{"repo_name": "linuxpdf", "file_name": "/linuxpdf/tinyemu/iomem.c", "inference_info": {"prefix_code": "/*\n * IO memory handling\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n\nstatic PhysMemoryRange *default_register_ram(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags);\nstatic void default_free_ram(PhysMemoryMap *s, PhysMemoryRange *pr);\nstatic const uint32_t *default_get_dirty_bits(PhysMemoryMap *map, PhysMemoryRange *pr);\nstatic void default_set_addr(PhysMemoryMap *map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled);\n\nPhysMemoryMap *phys_mem_map_init(void)\n{\n PhysMemoryMap *s;\n s = mallocz(sizeof(*s));\n s->register_ram = default_register_ram;\n s->free_ram = default_free_ram;\n s->get_dirty_bits = default_get_dirty_bits;\n s->set_ram_addr = default_set_addr;\n return s;\n}\n\nvoid phys_mem_map_end(PhysMemoryMap *s)\n{\n int i;\n PhysMemoryRange *pr;\n\n for(i = 0; i < s->n_phys_mem_range; i++) {\n pr = &s->phys_mem_range[i];\n if (pr->is_ram) {\n s->free_ram(s, pr);\n }\n }\n free(s);\n}\n\n/* return NULL if not found */\n/* XXX: optimize */\nPhysMemoryRange *get_phys_mem_range(PhysMemoryMap *s, uint64_t paddr)\n{\n PhysMemoryRange *pr;\n int i;\n for(i = 0; i < s->n_phys_mem_range; i++) {\n pr = &s->phys_mem_range[i];\n if (paddr >= pr->addr && paddr < pr->addr + pr->size)\n return pr;\n }\n return NULL;\n}\n\nPhysMemoryRange *register_ram_entry(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n\n assert(s->n_phys_mem_range < PHYS_MEM_RANGE_MAX);\n assert((size & (DEVRAM_PAGE_SIZE - 1)) == 0 && size != 0);\n pr = &s->phys_mem_range[s->n_phys_mem_range++];\n pr->map = s;\n pr->is_ram = TRUE;\n pr->devram_flags = devram_flags & ~DEVRAM_FLAG_DISABLED;\n pr->addr = addr;\n pr->org_size = size;\n if (devram_flags & DEVRAM_FLAG_DISABLED)\n pr->size = 0;\n else\n pr->size = pr->org_size;\n pr->phys_mem = NULL;\n pr->dirty_bits = NULL;\n return pr;\n}\n\nstatic PhysMemoryRange *default_register_ram(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n\n pr = register_ram_entry(s, addr, size, devram_flags);\n\n pr->phys_mem = mallocz(size);\n if (!pr->phys_mem) {\n fprintf(stderr, \"Could not allocate VM memory\\n\");\n exit(1);\n }\n\n if (devram_flags & DEVRAM_FLAG_DIRTY_BITS) {\n size_t nb_pages;\n int i;\n nb_pages = size >> DEVRAM_PAGE_SIZE_LOG2;\n pr->dirty_bits_size = ((nb_pages + 31) / 32) * sizeof(uint32_t);\n pr->dirty_bits_index = 0;\n for(i = 0; i < 2; i++) {\n pr->dirty_bits_tab[i] = mallocz(pr->dirty_bits_size);\n }\n pr->dirty_bits = pr->dirty_bits_tab[pr->dirty_bits_index];\n }\n return pr;\n}\n\n/* return a pointer to the bitmap of dirty bits and reset them */\n", "suffix_code": "\n\n/* reset the dirty bit of one page at 'offset' inside 'pr' */\nvoid phys_mem_reset_dirty_bit(PhysMemoryRange *pr, size_t offset)\n{\n size_t page_index;\n uint32_t mask, *dirty_bits_ptr;\n PhysMemoryMap *map;\n if (pr->dirty_bits) {\n page_index = offset >> DEVRAM_PAGE_SIZE_LOG2;\n mask = 1 << (page_index & 0x1f);\n dirty_bits_ptr = pr->dirty_bits + (page_index >> 5);\n if (*dirty_bits_ptr & mask) {\n *dirty_bits_ptr &= ~mask;\n /* invalidate the corresponding CPU write TLBs */\n map = pr->map;\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem + (offset & ~(DEVRAM_PAGE_SIZE - 1)),\n DEVRAM_PAGE_SIZE);\n }\n }\n}\n\nstatic void default_free_ram(PhysMemoryMap *s, PhysMemoryRange *pr)\n{\n free(pr->phys_mem);\n}\n\nPhysMemoryRange *cpu_register_device(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, void *opaque,\n DeviceReadFunc *read_func, DeviceWriteFunc *write_func,\n int devio_flags)\n{\n PhysMemoryRange *pr;\n assert(s->n_phys_mem_range < PHYS_MEM_RANGE_MAX);\n assert(size <= 0xffffffff);\n pr = &s->phys_mem_range[s->n_phys_mem_range++];\n pr->map = s;\n pr->addr = addr;\n pr->org_size = size;\n if (devio_flags & DEVIO_DISABLED)\n pr->size = 0;\n else\n pr->size = pr->org_size;\n pr->is_ram = FALSE;\n pr->opaque = opaque;\n pr->read_func = read_func;\n pr->write_func = write_func;\n pr->devio_flags = devio_flags;\n return pr;\n}\n\nstatic void default_set_addr(PhysMemoryMap *map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n if (enabled) {\n if (pr->size == 0 || pr->addr != addr) {\n /* enable or move mapping */\n if (pr->is_ram) {\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem, pr->org_size);\n }\n pr->addr = addr;\n pr->size = pr->org_size;\n }\n } else {\n if (pr->size != 0) {\n /* disable mapping */\n if (pr->is_ram) {\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem, pr->org_size);\n }\n pr->addr = 0;\n pr->size = 0;\n }\n }\n}\n\nvoid phys_mem_set_addr(PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n PhysMemoryMap *map = pr->map;\n if (!pr->is_ram) {\n default_set_addr(map, pr, addr, enabled);\n } else {\n return map->set_ram_addr(map, pr, addr, enabled);\n }\n}\n\n/* return NULL if no valid RAM page. The access can only be done in the page */\nuint8_t *phys_mem_get_ram_ptr(PhysMemoryMap *map, uint64_t paddr, BOOL is_rw)\n{\n PhysMemoryRange *pr = get_phys_mem_range(map, paddr);\n uintptr_t offset;\n if (!pr || !pr->is_ram)\n return NULL;\n offset = paddr - pr->addr;\n if (is_rw)\n phys_mem_set_dirty_bit(pr, offset);\n return pr->phys_mem + (uintptr_t)offset;\n}\n\n/* IRQ support */\n\nvoid irq_init(IRQSignal *irq, SetIRQFunc *set_irq, void *opaque, int irq_num)\n{\n irq->set_irq = set_irq;\n irq->opaque = opaque;\n irq->irq_num = irq_num;\n}\n", "middle_code": "static const uint32_t *default_get_dirty_bits(PhysMemoryMap *map,\n PhysMemoryRange *pr)\n{\n uint32_t *dirty_bits;\n BOOL has_dirty_bits;\n size_t n, i;\n dirty_bits = pr->dirty_bits;\n has_dirty_bits = FALSE;\n n = pr->dirty_bits_size / sizeof(uint32_t);\n for(i = 0; i < n; i++) {\n if (dirty_bits[i] != 0) {\n has_dirty_bits = TRUE;\n break;\n }\n }\n if (has_dirty_bits && pr->size != 0) {\n map->flush_tlb_write_range(map->opaque, pr->phys_mem, pr->org_size);\n }\n pr->dirty_bits_index ^= 1;\n pr->dirty_bits = pr->dirty_bits_tab[pr->dirty_bits_index];\n memset(pr->dirty_bits, 0, pr->dirty_bits_size);\n return dirty_bits;\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c", "sub_task_type": null}, "context_code": [["/linuxpdf/tinyemu/x86_machine.c", "/*\n * PC emulator\n * \n * Copyright (c) 2011-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"x86_cpu.h\"\n#include \"machine.h\"\n#include \"pci.h\"\n#include \"ide.h\"\n#include \"ps2.h\"\n\n#if defined(__linux__) && (defined(__i386__) || defined(__x86_64__))\n#define USE_KVM\n#endif\n\n#ifdef USE_KVM\n#include \n#include \n#include \n#include \n#include \n#endif\n\n//#define DEBUG_BIOS\n//#define DUMP_IOPORT\n\n/***********************************************************/\n/* cmos emulation */\n\n//#define DEBUG_CMOS\n\n#define RTC_SECONDS 0\n#define RTC_SECONDS_ALARM 1\n#define RTC_MINUTES 2\n#define RTC_MINUTES_ALARM 3\n#define RTC_HOURS 4\n#define RTC_HOURS_ALARM 5\n#define RTC_ALARM_DONT_CARE 0xC0\n\n#define RTC_DAY_OF_WEEK 6\n#define RTC_DAY_OF_MONTH 7\n#define RTC_MONTH 8\n#define RTC_YEAR 9\n\n#define RTC_REG_A 10\n#define RTC_REG_B 11\n#define RTC_REG_C 12\n#define RTC_REG_D 13\n\n#define REG_A_UIP 0x80\n\n#define REG_B_SET 0x80\n#define REG_B_PIE 0x40\n#define REG_B_AIE 0x20\n#define REG_B_UIE 0x10\n\ntypedef struct {\n uint8_t cmos_index;\n uint8_t cmos_data[128];\n IRQSignal *irq;\n BOOL use_local_time;\n /* used for the periodic irq */\n uint32_t irq_timeout;\n uint32_t irq_period;\n} CMOSState;\n\nstatic void cmos_write(void *opaque, uint32_t offset,\n uint32_t data, int size_log2);\nstatic uint32_t cmos_read(void *opaque, uint32_t offset, int size_log2);\n\nstatic int to_bcd(CMOSState *s, unsigned int a)\n{\n if (s->cmos_data[RTC_REG_B] & 0x04) {\n return a;\n } else {\n return ((a / 10) << 4) | (a % 10);\n }\n}\n\nstatic void cmos_update_time(CMOSState *s, BOOL set_century)\n{\n struct timeval tv;\n struct tm tm;\n time_t ti;\n int val;\n \n gettimeofday(&tv, NULL);\n ti = tv.tv_sec;\n if (s->use_local_time) {\n localtime_r(&ti, &tm);\n } else {\n gmtime_r(&ti, &tm);\n }\n \n s->cmos_data[RTC_SECONDS] = to_bcd(s, tm.tm_sec);\n s->cmos_data[RTC_MINUTES] = to_bcd(s, tm.tm_min);\n if (s->cmos_data[RTC_REG_B] & 0x02) {\n s->cmos_data[RTC_HOURS] = to_bcd(s, tm.tm_hour);\n } else {\n s->cmos_data[RTC_HOURS] = to_bcd(s, tm.tm_hour % 12);\n if (tm.tm_hour >= 12)\n s->cmos_data[RTC_HOURS] |= 0x80;\n }\n s->cmos_data[RTC_DAY_OF_WEEK] = to_bcd(s, tm.tm_wday);\n s->cmos_data[RTC_DAY_OF_MONTH] = to_bcd(s, tm.tm_mday);\n s->cmos_data[RTC_MONTH] = to_bcd(s, tm.tm_mon + 1);\n s->cmos_data[RTC_YEAR] = to_bcd(s, tm.tm_year % 100);\n\n if (set_century) {\n /* not set by the hardware, but easier to do it here */\n val = to_bcd(s, (tm.tm_year / 100) + 19);\n s->cmos_data[0x32] = val;\n s->cmos_data[0x37] = val;\n }\n \n /* update in progress flag: 8/32768 seconds after change */\n if (tv.tv_usec < 244) {\n s->cmos_data[RTC_REG_A] |= REG_A_UIP;\n } else {\n s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;\n }\n}\n\nCMOSState *cmos_init(PhysMemoryMap *port_map, int addr,\n IRQSignal *irq, BOOL use_local_time)\n{\n CMOSState *s;\n \n s = mallocz(sizeof(*s));\n s->use_local_time = use_local_time;\n \n s->cmos_index = 0;\n\n s->cmos_data[RTC_REG_A] = 0x26;\n s->cmos_data[RTC_REG_B] = 0x02;\n s->cmos_data[RTC_REG_C] = 0x00;\n s->cmos_data[RTC_REG_D] = 0x80;\n\n cmos_update_time(s, TRUE);\n \n s->irq = irq;\n \n cpu_register_device(port_map, addr, 2, s, cmos_read, cmos_write, \n DEVIO_SIZE8);\n return s;\n}\n\n#define CMOS_FREQ 32768\n\nstatic uint32_t cmos_get_timer(CMOSState *s)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint32_t)ts.tv_sec * CMOS_FREQ +\n ((uint64_t)ts.tv_nsec * CMOS_FREQ / 1000000000);\n}\n\nstatic void cmos_update_timer(CMOSState *s)\n{\n int period_code;\n\n period_code = s->cmos_data[RTC_REG_A] & 0x0f;\n if ((s->cmos_data[RTC_REG_B] & REG_B_PIE) &&\n period_code != 0) {\n if (period_code <= 2)\n period_code += 7;\n s->irq_period = 1 << (period_code - 1);\n s->irq_timeout = (cmos_get_timer(s) + s->irq_period) &\n ~(s->irq_period - 1);\n }\n}\n\n/* XXX: could return a delay, but we don't need high precision\n (Windows 2000 uses it for delay calibration) */\nstatic void cmos_update_irq(CMOSState *s)\n{\n uint32_t d;\n if (s->cmos_data[RTC_REG_B] & REG_B_PIE) {\n d = cmos_get_timer(s) - s->irq_timeout;\n if ((int32_t)d >= 0) {\n /* this is not what the real RTC does. Here we sent the IRQ\n immediately */\n s->cmos_data[RTC_REG_C] |= 0xc0;\n set_irq(s->irq, 1);\n /* update for the next irq */\n s->irq_timeout += s->irq_period;\n }\n }\n}\n\nstatic void cmos_write(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n CMOSState *s = opaque;\n\n if (offset == 0) {\n s->cmos_index = data & 0x7f;\n } else {\n#ifdef DEBUG_CMOS\n printf(\"cmos_write: reg=0x%02x val=0x%02x\\n\", s->cmos_index, data);\n#endif\n switch(s->cmos_index) {\n case RTC_REG_A:\n s->cmos_data[RTC_REG_A] = (data & ~REG_A_UIP) |\n (s->cmos_data[RTC_REG_A] & REG_A_UIP);\n cmos_update_timer(s);\n break;\n case RTC_REG_B:\n s->cmos_data[s->cmos_index] = data;\n cmos_update_timer(s);\n break;\n default:\n s->cmos_data[s->cmos_index] = data;\n break;\n }\n }\n}\n\nstatic uint32_t cmos_read(void *opaque, uint32_t offset, int size_log2)\n{\n CMOSState *s = opaque;\n int ret;\n\n if (offset == 0) {\n return 0xff;\n } else {\n switch(s->cmos_index) {\n case RTC_SECONDS:\n case RTC_MINUTES:\n case RTC_HOURS:\n case RTC_DAY_OF_WEEK:\n case RTC_DAY_OF_MONTH:\n case RTC_MONTH:\n case RTC_YEAR:\n case RTC_REG_A:\n cmos_update_time(s, FALSE);\n ret = s->cmos_data[s->cmos_index];\n break;\n case RTC_REG_C:\n ret = s->cmos_data[s->cmos_index];\n s->cmos_data[RTC_REG_C] = 0x00;\n set_irq(s->irq, 0);\n break;\n default:\n ret = s->cmos_data[s->cmos_index];\n }\n#ifdef DEBUG_CMOS\n printf(\"cmos_read: reg=0x%02x val=0x%02x\\n\", s->cmos_index, ret);\n#endif\n return ret;\n }\n}\n\n/***********************************************************/\n/* 8259 pic emulation */\n\n//#define DEBUG_PIC\n\ntypedef void PICUpdateIRQFunc(void *opaque);\n\ntypedef struct {\n uint8_t last_irr; /* edge detection */\n uint8_t irr; /* interrupt request register */\n uint8_t imr; /* interrupt mask register */\n uint8_t isr; /* interrupt service register */\n uint8_t priority_add; /* used to compute irq priority */\n uint8_t irq_base;\n uint8_t read_reg_select;\n uint8_t special_mask;\n uint8_t init_state;\n uint8_t auto_eoi;\n uint8_t rotate_on_autoeoi;\n uint8_t init4; /* true if 4 byte init */\n uint8_t elcr; /* PIIX edge/trigger selection*/\n uint8_t elcr_mask;\n PICUpdateIRQFunc *update_irq;\n void *opaque;\n} PICState;\n\nstatic void pic_reset(PICState *s);\nstatic void pic_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pic_read(void *opaque, uint32_t offset, int size_log2);\nstatic void pic_elcr_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pic_elcr_read(void *opaque, uint32_t offset, int size_log2);\n\nPICState *pic_init(PhysMemoryMap *port_map, int port, int elcr_port,\n int elcr_mask,\n PICUpdateIRQFunc *update_irq, void *opaque)\n{\n PICState *s;\n\n s = mallocz(sizeof(*s));\n s->elcr_mask = elcr_mask;\n s->update_irq = update_irq;\n s->opaque = opaque;\n cpu_register_device(port_map, port, 2, s,\n pic_read, pic_write, DEVIO_SIZE8);\n cpu_register_device(port_map, elcr_port, 1, s,\n pic_elcr_read, pic_elcr_write, DEVIO_SIZE8);\n pic_reset(s);\n return s;\n}\n\nstatic void pic_reset(PICState *s)\n{\n /* all 8 bit registers */\n s->last_irr = 0; /* edge detection */\n s->irr = 0; /* interrupt request register */\n s->imr = 0; /* interrupt mask register */\n s->isr = 0; /* interrupt service register */\n s->priority_add = 0; /* used to compute irq priority */\n s->irq_base = 0;\n s->read_reg_select = 0;\n s->special_mask = 0;\n s->init_state = 0;\n s->auto_eoi = 0;\n s->rotate_on_autoeoi = 0;\n s->init4 = 0; /* true if 4 byte init */\n}\n\n/* set irq level. If an edge is detected, then the IRR is set to 1 */\nstatic void pic_set_irq1(PICState *s, int irq, int level)\n{\n int mask;\n mask = 1 << irq;\n if (s->elcr & mask) {\n /* level triggered */\n if (level) {\n s->irr |= mask;\n s->last_irr |= mask;\n } else {\n s->irr &= ~mask;\n s->last_irr &= ~mask;\n }\n } else {\n /* edge triggered */\n if (level) {\n if ((s->last_irr & mask) == 0)\n s->irr |= mask;\n s->last_irr |= mask;\n } else {\n s->last_irr &= ~mask;\n }\n }\n}\n \nstatic int pic_get_priority(PICState *s, int mask)\n{\n int priority;\n if (mask == 0)\n return -1;\n priority = 7;\n while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)\n priority--;\n return priority;\n}\n\n/* return the pic wanted interrupt. return -1 if none */\nstatic int pic_get_irq(PICState *s)\n{\n int mask, cur_priority, priority;\n\n mask = s->irr & ~s->imr;\n priority = pic_get_priority(s, mask);\n if (priority < 0)\n return -1;\n /* compute current priority */\n cur_priority = pic_get_priority(s, s->isr);\n if (priority > cur_priority) {\n /* higher priority found: an irq should be generated */\n return priority;\n } else {\n return -1;\n }\n}\n \n/* acknowledge interrupt 'irq' */\nstatic void pic_intack(PICState *s, int irq)\n{\n if (s->auto_eoi) {\n if (s->rotate_on_autoeoi)\n s->priority_add = (irq + 1) & 7;\n } else {\n s->isr |= (1 << irq);\n }\n /* We don't clear a level sensitive interrupt here */\n if (!(s->elcr & (1 << irq)))\n s->irr &= ~(1 << irq);\n}\n\nstatic void pic_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PICState *s = opaque;\n int priority, addr;\n \n addr = offset & 1;\n#ifdef DEBUG_PIC\n console.log(\"pic_write: addr=\" + toHex2(addr) + \" val=\" + toHex2(val));\n#endif\n if (addr == 0) {\n if (val & 0x10) {\n /* init */\n pic_reset(s);\n s->init_state = 1;\n s->init4 = val & 1;\n if (val & 0x02)\n abort(); /* \"single mode not supported\" */\n if (val & 0x08)\n abort(); /* \"level sensitive irq not supported\" */\n } else if (val & 0x08) {\n if (val & 0x02)\n s->read_reg_select = val & 1;\n if (val & 0x40)\n s->special_mask = (val >> 5) & 1;\n } else {\n switch(val) {\n case 0x00:\n case 0x80:\n s->rotate_on_autoeoi = val >> 7;\n break;\n case 0x20: /* end of interrupt */\n case 0xa0:\n priority = pic_get_priority(s, s->isr);\n if (priority >= 0) {\n s->isr &= ~(1 << ((priority + s->priority_add) & 7));\n }\n if (val == 0xa0)\n s->priority_add = (s->priority_add + 1) & 7;\n break;\n case 0x60:\n case 0x61:\n case 0x62:\n case 0x63:\n case 0x64:\n case 0x65:\n case 0x66:\n case 0x67:\n priority = val & 7;\n s->isr &= ~(1 << priority);\n break;\n case 0xc0:\n case 0xc1:\n case 0xc2:\n case 0xc3:\n case 0xc4:\n case 0xc5:\n case 0xc6:\n case 0xc7:\n s->priority_add = (val + 1) & 7;\n break;\n case 0xe0:\n case 0xe1:\n case 0xe2:\n case 0xe3:\n case 0xe4:\n case 0xe5:\n case 0xe6:\n case 0xe7:\n priority = val & 7;\n s->isr &= ~(1 << priority);\n s->priority_add = (priority + 1) & 7;\n break;\n }\n }\n } else {\n switch(s->init_state) {\n case 0:\n /* normal mode */\n s->imr = val;\n s->update_irq(s->opaque);\n break;\n case 1:\n s->irq_base = val & 0xf8;\n s->init_state = 2;\n break;\n case 2:\n if (s->init4) {\n s->init_state = 3;\n } else {\n s->init_state = 0;\n }\n break;\n case 3:\n s->auto_eoi = (val >> 1) & 1;\n s->init_state = 0;\n break;\n }\n }\n}\n\nstatic uint32_t pic_read(void *opaque, uint32_t offset, int size_log2)\n{\n PICState *s = opaque;\n int addr, ret;\n\n addr = offset & 1;\n if (addr == 0) {\n if (s->read_reg_select)\n ret = s->isr;\n else\n ret = s->irr;\n } else {\n ret = s->imr;\n }\n#ifdef DEBUG_PIC\n console.log(\"pic_read: addr=\" + toHex2(addr1) + \" val=\" + toHex2(ret));\n#endif\n return ret;\n}\n\nstatic void pic_elcr_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PICState *s = opaque;\n s->elcr = val & s->elcr_mask;\n}\n\nstatic uint32_t pic_elcr_read(void *opaque, uint32_t offset, int size_log2)\n{\n PICState *s = opaque;\n return s->elcr;\n}\n\ntypedef struct {\n PICState *pics[2];\n int irq_requested;\n void (*cpu_set_irq)(void *opaque, int level);\n void *opaque;\n#if defined(DEBUG_PIC)\n uint8_t irq_level[16];\n#endif\n IRQSignal *irqs;\n} PIC2State;\n\nstatic void pic2_update_irq(void *opaque);\nstatic void pic2_set_irq(void *opaque, int irq, int level);\n\nPIC2State *pic2_init(PhysMemoryMap *port_map, uint32_t addr0, uint32_t addr1,\n uint32_t elcr_addr0, uint32_t elcr_addr1, \n void (*cpu_set_irq)(void *opaque, int level),\n void *opaque, IRQSignal *irqs)\n{\n PIC2State *s;\n int i;\n \n s = mallocz(sizeof(*s));\n\n for(i = 0; i < 16; i++) {\n irq_init(&irqs[i], pic2_set_irq, s, i);\n }\n s->cpu_set_irq = cpu_set_irq;\n s->opaque = opaque;\n s->pics[0] = pic_init(port_map, addr0, elcr_addr0, 0xf8, pic2_update_irq, s);\n s->pics[1] = pic_init(port_map, addr1, elcr_addr1, 0xde, pic2_update_irq, s);\n s->irq_requested = 0;\n return s;\n}\n\nvoid pic2_set_elcr(PIC2State *s, const uint8_t *elcr)\n{\n int i;\n for(i = 0; i < 2; i++) {\n s->pics[i]->elcr = elcr[i] & s->pics[i]->elcr_mask;\n }\n}\n\n/* raise irq to CPU if necessary. must be called every time the active\n irq may change */\nstatic void pic2_update_irq(void *opaque)\n{\n PIC2State *s = opaque;\n int irq2, irq;\n\n /* first look at slave pic */\n irq2 = pic_get_irq(s->pics[1]);\n if (irq2 >= 0) {\n /* if irq request by slave pic, signal master PIC */\n pic_set_irq1(s->pics[0], 2, 1);\n pic_set_irq1(s->pics[0], 2, 0);\n }\n /* look at requested irq */\n irq = pic_get_irq(s->pics[0]);\n#if 0\n console.log(\"irr=\" + toHex2(s->pics[0].irr) + \" imr=\" + toHex2(s->pics[0].imr) + \" isr=\" + toHex2(s->pics[0].isr) + \" irq=\"+ irq);\n#endif\n if (irq >= 0) {\n /* raise IRQ request on the CPU */\n s->cpu_set_irq(s->opaque, 1);\n } else {\n /* lower irq */\n s->cpu_set_irq(s->opaque, 0);\n }\n}\n\nstatic void pic2_set_irq(void *opaque, int irq, int level)\n{\n PIC2State *s = opaque;\n#if defined(DEBUG_PIC)\n if (irq != 0 && level != s->irq_level[irq]) {\n console.log(\"pic_set_irq: irq=\" + irq + \" level=\" + level);\n s->irq_level[irq] = level;\n }\n#endif\n pic_set_irq1(s->pics[irq >> 3], irq & 7, level);\n pic2_update_irq(s);\n}\n\n/* called from the CPU to get the hardware interrupt number */\nstatic int pic2_get_hard_intno(PIC2State *s)\n{\n int irq, irq2, intno;\n\n irq = pic_get_irq(s->pics[0]);\n if (irq >= 0) {\n pic_intack(s->pics[0], irq);\n if (irq == 2) {\n irq2 = pic_get_irq(s->pics[1]);\n if (irq2 >= 0) {\n pic_intack(s->pics[1], irq2);\n } else {\n /* spurious IRQ on slave controller */\n irq2 = 7;\n }\n intno = s->pics[1]->irq_base + irq2;\n irq = irq2 + 8;\n } else {\n intno = s->pics[0]->irq_base + irq;\n }\n } else {\n /* spurious IRQ on host controller */\n irq = 7;\n intno = s->pics[0]->irq_base + irq;\n }\n pic2_update_irq(s);\n\n#if defined(DEBUG_PIC)\n if (irq != 0 && irq != 14)\n printf(\"pic_interrupt: irq=%d\\n\", irq);\n#endif\n return intno;\n}\n\n/***********************************************************/\n/* 8253 PIT emulation */\n\n#define PIT_FREQ 1193182\n\n#define RW_STATE_LSB 0\n#define RW_STATE_MSB 1\n#define RW_STATE_WORD0 2\n#define RW_STATE_WORD1 3\n#define RW_STATE_LATCHED_WORD0 4\n#define RW_STATE_LATCHED_WORD1 5\n\n//#define DEBUG_PIT\n\ntypedef int64_t PITGetTicksFunc(void *opaque);\n\ntypedef struct PITState PITState;\n\ntypedef struct {\n PITState *pit_state;\n uint32_t count;\n uint32_t latched_count;\n uint8_t rw_state;\n uint8_t mode;\n uint8_t bcd;\n uint8_t gate;\n int64_t count_load_time;\n int64_t last_irq_time;\n} PITChannel;\n\nstruct PITState {\n PITChannel pit_channels[3];\n uint8_t speaker_data_on;\n PITGetTicksFunc *get_ticks;\n IRQSignal *irq;\n void *opaque;\n};\n\nstatic void pit_load_count(PITChannel *pc, int val);\nstatic void pit_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pit_read(void *opaque, uint32_t offset, int size_log2);\nstatic void speaker_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t speaker_read(void *opaque, uint32_t offset, int size_log2);\n\nPITState *pit_init(PhysMemoryMap *port_map, int addr0, int addr1,\n IRQSignal *irq,\n PITGetTicksFunc *get_ticks, void *opaque)\n{\n PITState *s;\n PITChannel *pc;\n int i;\n\n s = mallocz(sizeof(*s));\n\n s->irq = irq;\n s->get_ticks = get_ticks;\n s->opaque = opaque;\n \n for(i = 0; i < 3; i++) {\n pc = &s->pit_channels[i];\n pc->pit_state = s;\n pc->mode = 3;\n pc->gate = (i != 2) >> 0;\n pit_load_count(pc, 0);\n }\n s->speaker_data_on = 0;\n\n cpu_register_device(port_map, addr0, 4, s, pit_read, pit_write, \n DEVIO_SIZE8);\n\n cpu_register_device(port_map, addr1, 1, s, speaker_read, speaker_write, \n DEVIO_SIZE8);\n return s;\n}\n\n/* unit = PIT frequency */\nstatic int64_t pit_get_time(PITChannel *pc)\n{\n PITState *s = pc->pit_state;\n return s->get_ticks(s->opaque);\n}\n\nstatic uint32_t pit_get_count(PITChannel *pc)\n{\n uint32_t counter;\n uint64_t d;\n \n d = pit_get_time(pc) - pc->count_load_time;\n switch(pc->mode) {\n case 0:\n case 1:\n case 4:\n case 5:\n counter = (pc->count - d) & 0xffff;\n break;\n default:\n counter = pc->count - (d % pc->count);\n break;\n }\n return counter;\n}\n\n/* get pit output bit */\nstatic int pit_get_out(PITChannel *pc)\n{\n int out;\n int64_t d;\n \n d = pit_get_time(pc) - pc->count_load_time;\n switch(pc->mode) {\n default:\n case 0:\n out = (d >= pc->count) >> 0;\n break;\n case 1:\n out = (d < pc->count) >> 0;\n break;\n case 2:\n /* mode used by Linux */\n if ((d % pc->count) == 0 && d != 0)\n out = 1;\n else\n out = 0;\n break;\n case 3:\n out = ((d % pc->count) < (pc->count >> 1)) >> 0;\n break;\n case 4:\n case 5:\n out = (d == pc->count) >> 0;\n break;\n }\n return out;\n}\n\nstatic void pit_load_count(PITChannel *s, int val)\n{\n if (val == 0)\n val = 0x10000;\n s->count_load_time = pit_get_time(s);\n s->last_irq_time = 0;\n s->count = val;\n}\n\nstatic void pit_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PITState *pit = opaque;\n int channel, access, addr;\n PITChannel *s;\n\n addr = offset & 3;\n#ifdef DEBUG_PIT\n printf(\"pit_write: off=%d val=0x%02x\\n\", addr, val);\n#endif\n if (addr == 3) {\n channel = val >> 6;\n if (channel == 3)\n return;\n s = &pit->pit_channels[channel];\n access = (val >> 4) & 3;\n switch(access) {\n case 0:\n s->latched_count = pit_get_count(s);\n s->rw_state = RW_STATE_LATCHED_WORD0;\n break;\n default:\n s->mode = (val >> 1) & 7;\n s->bcd = val & 1;\n s->rw_state = access - 1 + RW_STATE_LSB;\n break;\n }\n } else {\n s = &pit->pit_channels[addr];\n switch(s->rw_state) {\n case RW_STATE_LSB:\n pit_load_count(s, val);\n break;\n case RW_STATE_MSB:\n pit_load_count(s, val << 8);\n break;\n case RW_STATE_WORD0:\n case RW_STATE_WORD1:\n if (s->rw_state & 1) {\n pit_load_count(s, (s->latched_count & 0xff) | (val << 8));\n } else {\n s->latched_count = val;\n }\n s->rw_state ^= 1;\n break;\n }\n }\n}\n\nstatic uint32_t pit_read(void *opaque, uint32_t offset, int size_log2)\n{\n PITState *pit = opaque;\n PITChannel *s;\n int ret, count, addr;\n \n addr = offset & 3;\n if (addr == 3)\n return 0xff;\n\n s = &pit->pit_channels[addr];\n switch(s->rw_state) {\n case RW_STATE_LSB:\n case RW_STATE_MSB:\n case RW_STATE_WORD0:\n case RW_STATE_WORD1:\n count = pit_get_count(s);\n if (s->rw_state & 1)\n ret = (count >> 8) & 0xff;\n else\n ret = count & 0xff;\n if (s->rw_state & 2)\n s->rw_state ^= 1;\n break;\n default:\n case RW_STATE_LATCHED_WORD0:\n case RW_STATE_LATCHED_WORD1:\n if (s->rw_state & 1)\n ret = s->latched_count >> 8;\n else\n ret = s->latched_count & 0xff;\n s->rw_state ^= 1;\n break;\n }\n#ifdef DEBUG_PIT\n printf(\"pit_read: off=%d val=0x%02x\\n\", addr, ret);\n#endif\n return ret;\n}\n\nstatic void speaker_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PITState *pit = opaque;\n pit->speaker_data_on = (val >> 1) & 1;\n pit->pit_channels[2].gate = val & 1;\n}\n\nstatic uint32_t speaker_read(void *opaque, uint32_t offset, int size_log2)\n{\n PITState *pit = opaque;\n PITChannel *s;\n int out, val;\n\n s = &pit->pit_channels[2];\n out = pit_get_out(s);\n val = (pit->speaker_data_on << 1) | s->gate | (out << 5);\n#ifdef DEBUG_PIT\n // console.log(\"speaker_read: addr=\" + toHex2(addr) + \" val=\" + toHex2(val));\n#endif\n return val;\n}\n\n/* set the IRQ if necessary and return the delay in ms until the next\n IRQ. Note: The code does not handle all the PIT configurations. */\nstatic int pit_update_irq(PITState *pit)\n{\n PITChannel *s;\n int64_t d, delay;\n \n s = &pit->pit_channels[0];\n \n delay = PIT_FREQ; /* could be infinity delay */\n \n d = pit_get_time(s) - s->count_load_time;\n switch(s->mode) {\n default:\n case 0:\n case 1:\n case 4:\n case 5:\n if (s->last_irq_time == 0) {\n delay = s->count - d;\n if (delay <= 0) {\n set_irq(pit->irq, 1);\n set_irq(pit->irq, 0);\n s->last_irq_time = d;\n }\n }\n break;\n case 2: /* mode used by Linux */\n case 3:\n delay = s->last_irq_time + s->count - d;\n if (delay <= 0) {\n set_irq(pit->irq, 1);\n set_irq(pit->irq, 0);\n s->last_irq_time += s->count;\n }\n break;\n }\n\n if (delay <= 0)\n return 0;\n else\n return delay / (PIT_FREQ / 1000);\n}\n \n/***********************************************************/\n/* serial port emulation */\n\n#define UART_LCR_DLAB\t0x80\t/* Divisor latch access bit */\n\n#define UART_IER_MSI\t0x08\t/* Enable Modem status interrupt */\n#define UART_IER_RLSI\t0x04\t/* Enable receiver line status interrupt */\n#define UART_IER_THRI\t0x02\t/* Enable Transmitter holding register int. */\n#define UART_IER_RDI\t0x01\t/* Enable receiver data interrupt */\n\n#define UART_IIR_NO_INT\t0x01\t/* No interrupts pending */\n#define UART_IIR_ID\t0x06\t/* Mask for the interrupt ID */\n\n#define UART_IIR_MSI\t0x00\t/* Modem status interrupt */\n#define UART_IIR_THRI\t0x02\t/* Transmitter holding register empty */\n#define UART_IIR_RDI\t0x04\t/* Receiver data interrupt */\n#define UART_IIR_RLSI\t0x06\t/* Receiver line status interrupt */\n#define UART_IIR_FE 0xC0 /* Fifo enabled */\n\n#define UART_LSR_TEMT\t0x40\t/* Transmitter empty */\n#define UART_LSR_THRE\t0x20\t/* Transmit-hold-register empty */\n#define UART_LSR_BI\t0x10\t/* Break interrupt indicator */\n#define UART_LSR_FE\t0x08\t/* Frame error indicator */\n#define UART_LSR_PE\t0x04\t/* Parity error indicator */\n#define UART_LSR_OE\t0x02\t/* Overrun error indicator */\n#define UART_LSR_DR\t0x01\t/* Receiver data ready */\n\n#define UART_FCR_XFR 0x04 /* XMIT Fifo Reset */\n#define UART_FCR_RFR 0x02 /* RCVR Fifo Reset */\n#define UART_FCR_FE 0x01 /* FIFO Enable */\n\n#define UART_FIFO_LENGTH 16 /* 16550A Fifo Length */\n\ntypedef struct {\n uint8_t divider; \n uint8_t rbr; /* receive register */\n uint8_t ier;\n uint8_t iir; /* read only */\n uint8_t lcr;\n uint8_t mcr;\n uint8_t lsr; /* read only */\n uint8_t msr;\n uint8_t scr;\n uint8_t fcr;\n IRQSignal *irq;\n void (*write_func)(void *opaque, const uint8_t *buf, int buf_len);\n void *opaque;\n} SerialState;\n\nstatic void serial_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t serial_read(void *opaque, uint32_t offset, int size_log2);\n\nSerialState *serial_init(PhysMemoryMap *port_map, int addr,\n IRQSignal *irq,\n void (*write_func)(void *opaque, const uint8_t *buf, int buf_len), void *opaque)\n{\n SerialState *s;\n s = mallocz(sizeof(*s));\n \n /* all 8 bit registers */\n s->divider = 0; \n s->rbr = 0; /* receive register */\n s->ier = 0;\n s->iir = UART_IIR_NO_INT; /* read only */\n s->lcr = 0;\n s->mcr = 0;\n s->lsr = UART_LSR_TEMT | UART_LSR_THRE; /* read only */\n s->msr = 0;\n s->scr = 0;\n s->fcr = 0;\n\n s->irq = irq;\n s->write_func = write_func;\n s->opaque = opaque;\n\n cpu_register_device(port_map, addr, 8, s, serial_read, serial_write, \n DEVIO_SIZE8);\n return s;\n}\n\nstatic void serial_update_irq(SerialState *s)\n{\n if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {\n s->iir = UART_IIR_RDI;\n } else if ((s->lsr & UART_LSR_THRE) && (s->ier & UART_IER_THRI)) {\n s->iir = UART_IIR_THRI;\n } else {\n s->iir = UART_IIR_NO_INT;\n }\n if (s->iir != UART_IIR_NO_INT) {\n set_irq(s->irq, 1);\n } else {\n set_irq(s->irq, 0);\n }\n}\n\n#if 0\n/* send remainining chars in fifo */\nSerial.prototype.write_tx_fifo = function()\n{\n if (s->tx_fifo != \"\") {\n s->write_func(s->tx_fifo);\n s->tx_fifo = \"\";\n \n s->lsr |= UART_LSR_THRE;\n s->lsr |= UART_LSR_TEMT;\n s->update_irq();\n }\n}\n#endif\n \nstatic void serial_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n SerialState *s = opaque;\n int addr;\n\n addr = offset & 7;\n switch(addr) {\n default:\n case 0:\n if (s->lcr & UART_LCR_DLAB) {\n s->divider = (s->divider & 0xff00) | val;\n } else {\n#if 0\n if (s->fcr & UART_FCR_FE) {\n s->tx_fifo += String.fromCharCode(val);\n s->lsr &= ~UART_LSR_THRE;\n serial_update_irq(s);\n if (s->tx_fifo.length >= UART_FIFO_LENGTH) {\n /* write to the terminal */\n s->write_tx_fifo();\n }\n } else\n#endif\n {\n uint8_t ch;\n s->lsr &= ~UART_LSR_THRE;\n serial_update_irq(s);\n \n /* write to the terminal */\n ch = val;\n s->write_func(s->opaque, &ch, 1);\n s->lsr |= UART_LSR_THRE;\n s->lsr |= UART_LSR_TEMT;\n serial_update_irq(s);\n }\n }\n break;\n case 1:\n if (s->lcr & UART_LCR_DLAB) {\n s->divider = (s->divider & 0x00ff) | (val << 8);\n } else {\n s->ier = val;\n serial_update_irq(s);\n }\n break;\n case 2:\n#if 0\n if ((s->fcr ^ val) & UART_FCR_FE) {\n /* clear fifos */\n val |= UART_FCR_XFR | UART_FCR_RFR;\n }\n if (val & UART_FCR_XFR)\n s->tx_fifo = \"\";\n if (val & UART_FCR_RFR)\n s->rx_fifo = \"\";\n s->fcr = val & UART_FCR_FE;\n#endif\n break;\n case 3:\n s->lcr = val;\n break;\n case 4:\n s->mcr = val;\n break;\n case 5:\n break;\n case 6:\n s->msr = val;\n break;\n case 7:\n s->scr = val;\n break;\n }\n}\n\nstatic uint32_t serial_read(void *opaque, uint32_t offset, int size_log2)\n{\n SerialState *s = opaque;\n int ret, addr;\n\n addr = offset & 7;\n switch(addr) {\n default:\n case 0:\n if (s->lcr & UART_LCR_DLAB) {\n ret = s->divider & 0xff; \n } else {\n ret = s->rbr;\n s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);\n serial_update_irq(s);\n#if 0\n /* try to receive next chars */\n s->send_char_from_fifo();\n#endif\n }\n break;\n case 1:\n if (s->lcr & UART_LCR_DLAB) {\n ret = (s->divider >> 8) & 0xff;\n } else {\n ret = s->ier;\n }\n break;\n case 2:\n ret = s->iir;\n if (s->fcr & UART_FCR_FE)\n ret |= UART_IIR_FE;\n break;\n case 3:\n ret = s->lcr;\n break;\n case 4:\n ret = s->mcr;\n break;\n case 5:\n ret = s->lsr;\n break;\n case 6:\n ret = s->msr;\n break;\n case 7:\n ret = s->scr;\n break;\n }\n return ret;\n}\n\nvoid serial_send_break(SerialState *s)\n{\n s->rbr = 0;\n s->lsr |= UART_LSR_BI | UART_LSR_DR;\n serial_update_irq(s);\n}\n\n#if 0\nstatic void serial_send_char(SerialState *s, int ch)\n{\n s->rbr = ch;\n s->lsr |= UART_LSR_DR;\n serial_update_irq(s);\n}\n\nSerial.prototype.send_char_from_fifo = function()\n{\n var fifo;\n\n fifo = s->rx_fifo;\n if (fifo != \"\" && !(s->lsr & UART_LSR_DR)) {\n s->send_char(fifo.charCodeAt(0));\n s->rx_fifo = fifo.substr(1, fifo.length - 1);\n }\n}\n\n/* queue the string in the UART receive fifo and send it ASAP */\nSerial.prototype.send_chars = function(str)\n{\n s->rx_fifo += str;\n s->send_char_from_fifo();\n}\n \n#endif\n\n#ifdef DEBUG_BIOS\nstatic void bios_debug_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n#ifdef EMSCRIPTEN\n static char line_buf[256];\n static int line_buf_index;\n line_buf[line_buf_index++] = val;\n if (val == '\\n' || line_buf_index >= sizeof(line_buf) - 1) {\n line_buf[line_buf_index] = '\\0';\n printf(\"%s\", line_buf);\n line_buf_index = 0;\n }\n#else\n putchar(val & 0xff);\n#endif\n}\n\nstatic uint32_t bios_debug_read(void *opaque, uint32_t offset, int size_log2)\n{\n return 0;\n}\n#endif\n\ntypedef struct PCMachine {\n VirtMachine common;\n uint64_t ram_size;\n PhysMemoryMap *mem_map;\n PhysMemoryMap *port_map;\n \n X86CPUState *cpu_state;\n PIC2State *pic_state;\n IRQSignal pic_irq[16];\n PITState *pit_state;\n I440FXState *i440fx_state;\n CMOSState *cmos_state;\n SerialState *serial_state;\n\n /* input */\n VIRTIODevice *keyboard_dev;\n VIRTIODevice *mouse_dev;\n KBDState *kbd_state;\n PS2MouseState *ps2_mouse;\n VMMouseState *vm_mouse;\n PS2KbdState *ps2_kbd;\n\n#ifdef USE_KVM\n BOOL kvm_enabled;\n int kvm_fd;\n int vm_fd;\n int vcpu_fd;\n int kvm_run_size;\n struct kvm_run *kvm_run;\n#endif\n} PCMachine;\n\nstatic void copy_kernel(PCMachine *s, const uint8_t *buf, int buf_len,\n const char *cmd_line);\n\nstatic void port80_write(void *opaque, uint32_t offset,\n uint32_t val64, int size_log2)\n{\n}\n\nstatic uint32_t port80_read(void *opaque, uint32_t offset, int size_log2)\n{\n return 0xff;\n}\n\nstatic void port92_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n}\n\nstatic uint32_t port92_read(void *opaque, uint32_t offset, int size_log2)\n{\n int a20 = 1; /* A20=0 is not supported */\n return a20 << 1;\n}\n\n#define VMPORT_MAGIC 0x564D5868\n#define REG_EAX 0\n#define REG_EBX 1\n#define REG_ECX 2\n#define REG_EDX 3\n#define REG_ESI 4\n#define REG_EDI 5\n\nstatic uint32_t vmport_read(void *opaque, uint32_t addr, int size_log2)\n{\n PCMachine *s = opaque;\n uint32_t regs[6];\n\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n struct kvm_regs r;\n\n ioctl(s->vcpu_fd, KVM_GET_REGS, &r);\n regs[REG_EAX] = r.rax;\n regs[REG_EBX] = r.rbx;\n regs[REG_ECX] = r.rcx;\n regs[REG_EDX] = r.rdx;\n regs[REG_ESI] = r.rsi;\n regs[REG_EDI] = r.rdi;\n\n if (regs[REG_EAX] == VMPORT_MAGIC) {\n \n vmmouse_handler(s->vm_mouse, regs);\n \n /* Note: in 64 bits the high parts are reset to zero\n in all cases. */\n r.rax = regs[REG_EAX];\n r.rbx = regs[REG_EBX];\n r.rcx = regs[REG_ECX];\n r.rdx = regs[REG_EDX];\n r.rsi = regs[REG_ESI];\n r.rdi = regs[REG_EDI];\n ioctl(s->vcpu_fd, KVM_SET_REGS, &r);\n }\n } else\n#endif\n {\n regs[REG_EAX] = x86_cpu_get_reg(s->cpu_state, 0);\n regs[REG_EBX] = x86_cpu_get_reg(s->cpu_state, 3);\n regs[REG_ECX] = x86_cpu_get_reg(s->cpu_state, 1);\n regs[REG_EDX] = x86_cpu_get_reg(s->cpu_state, 2);\n regs[REG_ESI] = x86_cpu_get_reg(s->cpu_state, 6);\n regs[REG_EDI] = x86_cpu_get_reg(s->cpu_state, 7);\n\n if (regs[REG_EAX] == VMPORT_MAGIC) {\n vmmouse_handler(s->vm_mouse, regs);\n\n x86_cpu_set_reg(s->cpu_state, 0, regs[REG_EAX]);\n x86_cpu_set_reg(s->cpu_state, 3, regs[REG_EBX]);\n x86_cpu_set_reg(s->cpu_state, 1, regs[REG_ECX]);\n x86_cpu_set_reg(s->cpu_state, 2, regs[REG_EDX]);\n x86_cpu_set_reg(s->cpu_state, 6, regs[REG_ESI]);\n x86_cpu_set_reg(s->cpu_state, 7, regs[REG_EDI]);\n }\n }\n return regs[REG_EAX];\n}\n\nstatic void vmport_write(void *opaque, uint32_t addr, uint32_t val,\n int size_log2)\n{\n}\n\nstatic void pic_set_irq_cb(void *opaque, int level)\n{\n PCMachine *s = opaque;\n x86_cpu_set_irq(s->cpu_state, level);\n}\n\nstatic void serial_write_cb(void *opaque, const uint8_t *buf, int buf_len)\n{\n PCMachine *s = opaque;\n if (s->common.console) {\n s->common.console->write_data(s->common.console->opaque, buf, buf_len);\n }\n}\n\nstatic int get_hard_intno_cb(void *opaque)\n{\n PCMachine *s = opaque;\n return pic2_get_hard_intno(s->pic_state);\n}\n\nstatic int64_t pit_get_ticks_cb(void *opaque)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * PIT_FREQ +\n ((uint64_t)ts.tv_nsec * PIT_FREQ / 1000000000);\n}\n\n#define FRAMEBUFFER_BASE_ADDR 0xf0400000\n\nstatic uint8_t *get_ram_ptr(PCMachine *s, uint64_t paddr)\n{\n PhysMemoryRange *pr;\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr || !pr->is_ram)\n return NULL;\n return pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n}\n\n#ifdef DUMP_IOPORT\nstatic BOOL dump_port(int port)\n{\n return !((port >= 0x1f0 && port <= 0x1f7) ||\n (port >= 0x20 && port <= 0x21) ||\n (port >= 0xa0 && port <= 0xa1));\n}\n#endif\n\nstatic void st_port(void *opaque, uint32_t port, uint32_t val, int size_log2)\n{\n PCMachine *s = opaque;\n PhysMemoryRange *pr;\n#ifdef DUMP_IOPORT\n if (dump_port(port))\n printf(\"write port=0x%x val=0x%x s=%d\\n\", port, val, 1 << size_log2);\n#endif\n pr = get_phys_mem_range(s->port_map, port);\n if (!pr) {\n return;\n }\n port -= pr->addr;\n if ((pr->devio_flags >> size_log2) & 1) {\n pr->write_func(pr->opaque, port, (uint32_t)val, size_log2);\n } else if (size_log2 == 1 && (pr->devio_flags & DEVIO_SIZE8)) {\n pr->write_func(pr->opaque, port, val & 0xff, 0);\n pr->write_func(pr->opaque, port + 1, (val >> 8) & 0xff, 0);\n }\n}\n\nstatic uint32_t ld_port(void *opaque, uint32_t port1, int size_log2)\n{\n PCMachine *s = opaque;\n PhysMemoryRange *pr;\n uint32_t val, port;\n \n port = port1;\n pr = get_phys_mem_range(s->port_map, port);\n if (!pr) {\n val = -1;\n } else {\n port -= pr->addr;\n if ((pr->devio_flags >> size_log2) & 1) {\n val = pr->read_func(pr->opaque, port, size_log2);\n } else if (size_log2 == 1 && (pr->devio_flags & DEVIO_SIZE8)) {\n val = pr->read_func(pr->opaque, port, 0) & 0xff;\n val |= (pr->read_func(pr->opaque, port + 1, 0) & 0xff) << 8;\n } else {\n val = -1;\n }\n }\n#ifdef DUMP_IOPORT\n if (dump_port(port1))\n printf(\"read port=0x%x val=0x%x s=%d\\n\", port1, val, 1 << size_log2);\n#endif\n return val;\n}\n\nstatic void pc_machine_set_defaults(VirtMachineParams *p)\n{\n p->accel_enable = TRUE;\n}\n\n#ifdef USE_KVM\n\nstatic void sigalrm_handler(int sig)\n{\n}\n\n#define CPUID_APIC (1 << 9)\n#define CPUID_ACPI (1 << 22)\n\nstatic void kvm_set_cpuid(PCMachine *s)\n{\n struct kvm_cpuid2 *kvm_cpuid;\n int n_ent_max, i;\n struct kvm_cpuid_entry2 *ent;\n \n n_ent_max = 128;\n kvm_cpuid = mallocz(sizeof(struct kvm_cpuid2) + n_ent_max * sizeof(kvm_cpuid->entries[0]));\n \n kvm_cpuid->nent = n_ent_max;\n if (ioctl(s->kvm_fd, KVM_GET_SUPPORTED_CPUID, kvm_cpuid) < 0) {\n perror(\"KVM_GET_SUPPORTED_CPUID\");\n exit(1);\n }\n\n for(i = 0; i < kvm_cpuid->nent; i++) {\n ent = &kvm_cpuid->entries[i];\n /* remove the APIC & ACPI to be in sync with the emulator */\n if (ent->function == 1 || ent->function == 0x80000001) {\n ent->edx &= ~(CPUID_APIC | CPUID_ACPI);\n }\n }\n \n if (ioctl(s->vcpu_fd, KVM_SET_CPUID2, kvm_cpuid) < 0) {\n perror(\"KVM_SET_CPUID2\");\n exit(1);\n }\n free(kvm_cpuid);\n}\n\n/* XXX: should check overlapping mappings */\nstatic void kvm_map_ram(PhysMemoryMap *mem_map, PhysMemoryRange *pr)\n{\n PCMachine *s = mem_map->opaque;\n struct kvm_userspace_memory_region region;\n int flags;\n\n region.slot = pr - mem_map->phys_mem_range;\n flags = 0;\n if (pr->devram_flags & DEVRAM_FLAG_ROM)\n flags |= KVM_MEM_READONLY;\n if (pr->devram_flags & DEVRAM_FLAG_DIRTY_BITS)\n flags |= KVM_MEM_LOG_DIRTY_PAGES;\n region.flags = flags;\n region.guest_phys_addr = pr->addr;\n region.memory_size = pr->size;\n#if 0\n printf(\"map slot %d: %08lx %08lx\\n\",\n region.slot, pr->addr, pr->size);\n#endif\n region.userspace_addr = (uintptr_t)pr->phys_mem;\n if (ioctl(s->vm_fd, KVM_SET_USER_MEMORY_REGION, ®ion) < 0) {\n perror(\"KVM_SET_USER_MEMORY_REGION\");\n exit(1);\n }\n}\n\n/* XXX: just for one region */\nstatic PhysMemoryRange *kvm_register_ram(PhysMemoryMap *mem_map, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n uint8_t *phys_mem;\n \n pr = register_ram_entry(mem_map, addr, size, devram_flags);\n\n phys_mem = mmap(NULL, size, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n if (!phys_mem)\n return NULL;\n pr->phys_mem = phys_mem;\n if (devram_flags & DEVRAM_FLAG_DIRTY_BITS) {\n int n_pages = size >> 12;\n pr->dirty_bits_size = ((n_pages + 63) / 64) * 8;\n pr->dirty_bits = mallocz(pr->dirty_bits_size);\n }\n\n if (pr->size != 0) {\n kvm_map_ram(mem_map, pr);\n }\n return pr;\n}\n\nstatic void kvm_set_ram_addr(PhysMemoryMap *mem_map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n if (enabled) {\n if (pr->size == 0 || addr != pr->addr) {\n /* move or create the region */\n pr->size = pr->org_size;\n pr->addr = addr;\n kvm_map_ram(mem_map, pr);\n }\n } else {\n if (pr->size != 0) {\n pr->addr = 0;\n pr->size = 0;\n /* map a zero size region to disable */\n kvm_map_ram(mem_map, pr);\n }\n }\n}\n\nstatic const uint32_t *kvm_get_dirty_bits(PhysMemoryMap *mem_map,\n PhysMemoryRange *pr)\n{\n PCMachine *s = mem_map->opaque;\n struct kvm_dirty_log dlog;\n \n if (pr->size == 0) {\n /* not mapped: we assume no modification was made */\n memset(pr->dirty_bits, 0, pr->dirty_bits_size);\n } else {\n dlog.slot = pr - mem_map->phys_mem_range;\n dlog.dirty_bitmap = pr->dirty_bits;\n if (ioctl(s->vm_fd, KVM_GET_DIRTY_LOG, &dlog) < 0) {\n perror(\"KVM_GET_DIRTY_LOG\");\n exit(1);\n }\n }\n return pr->dirty_bits;\n}\n\nstatic void kvm_free_ram(PhysMemoryMap *mem_map, PhysMemoryRange *pr)\n{\n /* XXX: do it */\n munmap(pr->phys_mem, pr->org_size);\n free(pr->dirty_bits);\n}\n\nstatic void kvm_pic_set_irq(void *opaque, int irq_num, int level)\n{\n PCMachine *s = opaque;\n struct kvm_irq_level irq_level;\n irq_level.irq = irq_num;\n irq_level.level = level;\n if (ioctl(s->vm_fd, KVM_IRQ_LINE, &irq_level) < 0) {\n perror(\"KVM_IRQ_LINE\");\n exit(1);\n }\n}\n\nstatic void kvm_init(PCMachine *s)\n{\n int ret, i;\n struct sigaction act;\n struct kvm_pit_config pit_config;\n uint64_t base_addr;\n \n s->kvm_enabled = FALSE;\n s->kvm_fd = open(\"/dev/kvm\", O_RDWR);\n if (s->kvm_fd < 0) {\n fprintf(stderr, \"KVM not available\\n\");\n return;\n }\n ret = ioctl(s->kvm_fd, KVM_GET_API_VERSION, 0);\n if (ret < 0) {\n perror(\"KVM_GET_API_VERSION\");\n exit(1);\n }\n if (ret != 12) {\n fprintf(stderr, \"Unsupported KVM version\\n\");\n close(s->kvm_fd);\n s->kvm_fd = -1;\n return;\n }\n s->vm_fd = ioctl(s->kvm_fd, KVM_CREATE_VM, 0);\n if (s->vm_fd < 0) {\n perror(\"KVM_CREATE_VM\");\n exit(1);\n }\n\n /* just before the BIOS */\n base_addr = 0xfffbc000;\n if (ioctl(s->vm_fd, KVM_SET_IDENTITY_MAP_ADDR, &base_addr) < 0) {\n perror(\"KVM_SET_IDENTITY_MAP_ADDR\");\n exit(1);\n }\n \n if (ioctl(s->vm_fd, KVM_SET_TSS_ADDR, (long)(base_addr + 0x1000)) < 0) {\n perror(\"KVM_SET_TSS_ADDR\");\n exit(1);\n }\n \n if (ioctl(s->vm_fd, KVM_CREATE_IRQCHIP, 0) < 0) {\n perror(\"KVM_CREATE_IRQCHIP\");\n exit(1);\n }\n\n memset(&pit_config, 0, sizeof(pit_config));\n pit_config.flags = KVM_PIT_SPEAKER_DUMMY;\n if (ioctl(s->vm_fd, KVM_CREATE_PIT2, &pit_config)) {\n perror(\"KVM_CREATE_PIT2\");\n exit(1);\n }\n \n s->vcpu_fd = ioctl(s->vm_fd, KVM_CREATE_VCPU, 0);\n if (s->vcpu_fd < 0) {\n perror(\"KVM_CREATE_VCPU\");\n exit(1);\n }\n\n kvm_set_cpuid(s);\n \n /* map the kvm_run structure */\n s->kvm_run_size = ioctl(s->kvm_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);\n if (s->kvm_run_size < 0) {\n perror(\"KVM_GET_VCPU_MMAP_SIZE\");\n exit(1);\n }\n\n s->kvm_run = mmap(NULL, s->kvm_run_size, PROT_READ | PROT_WRITE,\n MAP_SHARED, s->vcpu_fd, 0);\n if (!s->kvm_run) {\n perror(\"mmap kvm_run\");\n exit(1);\n }\n\n for(i = 0; i < 16; i++) {\n irq_init(&s->pic_irq[i], kvm_pic_set_irq, s, i);\n }\n\n act.sa_handler = sigalrm_handler;\n sigemptyset(&act.sa_mask);\n act.sa_flags = 0;\n sigaction(SIGALRM, &act, NULL);\n\n s->kvm_enabled = TRUE;\n\n s->mem_map->register_ram = kvm_register_ram;\n s->mem_map->free_ram = kvm_free_ram;\n s->mem_map->get_dirty_bits = kvm_get_dirty_bits;\n s->mem_map->set_ram_addr = kvm_set_ram_addr;\n s->mem_map->opaque = s;\n}\n\nstatic void kvm_exit_io(PCMachine *s, struct kvm_run *run)\n{\n uint8_t *ptr;\n int i;\n \n ptr = (uint8_t *)run + run->io.data_offset;\n // printf(\"port: addr=%04x\\n\", run->io.port);\n \n for(i = 0; i < run->io.count; i++) {\n if (run->io.direction == KVM_EXIT_IO_OUT) {\n switch(run->io.size) {\n case 1:\n st_port(s, run->io.port, *(uint8_t *)ptr, 0);\n break;\n case 2:\n st_port(s, run->io.port, *(uint16_t *)ptr, 1);\n break;\n case 4:\n st_port(s, run->io.port, *(uint32_t *)ptr, 2);\n break;\n default:\n abort();\n }\n } else {\n switch(run->io.size) {\n case 1:\n *(uint8_t *)ptr = ld_port(s, run->io.port, 0);\n break;\n case 2:\n *(uint16_t *)ptr = ld_port(s, run->io.port, 1);\n break;\n case 4:\n *(uint32_t *)ptr = ld_port(s, run->io.port, 2);\n break;\n default:\n abort();\n }\n }\n ptr += run->io.size;\n }\n}\n\nstatic void kvm_exit_mmio(PCMachine *s, struct kvm_run *run)\n{\n uint8_t *data = run->mmio.data;\n PhysMemoryRange *pr;\n uint64_t addr;\n \n pr = get_phys_mem_range(s->mem_map, run->mmio.phys_addr);\n if (run->mmio.is_write) {\n if (!pr || pr->is_ram)\n return;\n addr = run->mmio.phys_addr - pr->addr;\n switch(run->mmio.len) {\n case 1:\n if (pr->devio_flags & DEVIO_SIZE8) {\n pr->write_func(pr->opaque, addr, *(uint8_t *)data, 0);\n }\n break;\n case 2:\n if (pr->devio_flags & DEVIO_SIZE16) {\n pr->write_func(pr->opaque, addr, *(uint16_t *)data, 1);\n }\n break;\n case 4:\n if (pr->devio_flags & DEVIO_SIZE32) {\n pr->write_func(pr->opaque, addr, *(uint32_t *)data, 2);\n }\n break;\n case 8:\n if (pr->devio_flags & DEVIO_SIZE32) {\n pr->write_func(pr->opaque, addr, *(uint32_t *)data, 2);\n pr->write_func(pr->opaque, addr + 4, *(uint32_t *)(data + 4), 2);\n }\n break;\n default:\n abort();\n }\n } else {\n if (!pr || pr->is_ram)\n goto no_dev;\n addr = run->mmio.phys_addr - pr->addr;\n switch(run->mmio.len) {\n case 1:\n if (!(pr->devio_flags & DEVIO_SIZE8))\n goto no_dev;\n *(uint8_t *)data = pr->read_func(pr->opaque, addr, 0);\n break;\n case 2:\n if (!(pr->devio_flags & DEVIO_SIZE16))\n goto no_dev;\n *(uint16_t *)data = pr->read_func(pr->opaque, addr, 1);\n break;\n case 4:\n if (!(pr->devio_flags & DEVIO_SIZE32))\n goto no_dev;\n *(uint32_t *)data = pr->read_func(pr->opaque, addr, 2);\n break;\n case 8:\n if (pr->devio_flags & DEVIO_SIZE32) {\n *(uint32_t *)data =\n pr->read_func(pr->opaque, addr, 2);\n *(uint32_t *)(data + 4) =\n pr->read_func(pr->opaque, addr + 4, 2);\n } else {\n no_dev:\n memset(run->mmio.data, 0, run->mmio.len);\n }\n break;\n default:\n abort();\n }\n \n }\n}\n\nstatic void kvm_exec(PCMachine *s)\n{\n struct kvm_run *run = s->kvm_run;\n struct itimerval ival;\n int ret;\n \n /* Not efficient but simple: we use a timer to interrupt the\n execution after a given time */\n ival.it_interval.tv_sec = 0;\n ival.it_interval.tv_usec = 0;\n ival.it_value.tv_sec = 0;\n ival.it_value.tv_usec = 10 * 1000; /* 10 ms max */\n setitimer(ITIMER_REAL, &ival, NULL);\n\n ret = ioctl(s->vcpu_fd, KVM_RUN, 0);\n if (ret < 0) {\n if (errno == EINTR || errno == EAGAIN) {\n /* timeout */\n return;\n }\n perror(\"KVM_RUN\");\n exit(1);\n }\n // printf(\"exit=%d\\n\", run->exit_reason);\n switch(run->exit_reason) {\n case KVM_EXIT_HLT:\n break;\n case KVM_EXIT_IO:\n kvm_exit_io(s, run);\n break;\n case KVM_EXIT_MMIO:\n kvm_exit_mmio(s, run);\n break;\n case KVM_EXIT_FAIL_ENTRY:\n fprintf(stderr, \"KVM_EXIT_FAIL_ENTRY: reason=0x%\" PRIx64 \"\\n\",\n (uint64_t)run->fail_entry.hardware_entry_failure_reason);\n#if 0\n {\n struct kvm_regs regs;\n if (ioctl(s->vcpu_fd, KVM_GET_REGS, ®s) < 0) {\n perror(\"KVM_SET_REGS\");\n exit(1);\n }\n printf(\"RIP=%016\" PRIx64 \"\\n\", (uint64_t)regs.rip);\n }\n#endif\n exit(1);\n case KVM_EXIT_INTERNAL_ERROR:\n fprintf(stderr, \"KVM_EXIT_INTERNAL_ERROR: suberror=0x%x\\n\",\n (uint32_t)run->internal.suberror);\n exit(1);\n default:\n fprintf(stderr, \"KVM: unsupported exit_reason=%d\\n\", run->exit_reason);\n exit(1);\n }\n}\n#endif\n\n#if defined(EMSCRIPTEN)\n/* with Javascript clock_gettime() is not enough precise enough to\n have a reliable TSC counter. XXX: increment the cycles during the\n power down time */\nstatic uint64_t cpu_get_tsc(void *opaque)\n{\n PCMachine *s = opaque;\n uint64_t c;\n c = x86_cpu_get_cycles(s->cpu_state);\n return c;\n}\n#else\n\n#define TSC_FREQ 100000000\n\nstatic uint64_t cpu_get_tsc(void *opaque)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * TSC_FREQ +\n (ts.tv_nsec / (1000000000 / TSC_FREQ));\n}\n#endif\n\nstatic void pc_flush_tlb_write_range(void *opaque, uint8_t *ram_addr,\n size_t ram_size)\n{\n PCMachine *s = opaque;\n x86_cpu_flush_tlb_write_range_ram(s->cpu_state, ram_addr, ram_size);\n}\n\nstatic VirtMachine *pc_machine_init(const VirtMachineParams *p)\n{\n PCMachine *s;\n int i, piix3_devfn;\n PCIBus *pci_bus;\n VIRTIOBusDef vbus_s, *vbus = &vbus_s;\n \n if (strcmp(p->machine_name, \"pc\") != 0) {\n vm_error(\"unsupported machine: %s\\n\", p->machine_name);\n return NULL;\n }\n\n assert(p->ram_size >= (1 << 20));\n\n s = mallocz(sizeof(*s));\n s->common.vmc = p->vmc;\n s->ram_size = p->ram_size;\n \n s->port_map = phys_mem_map_init();\n s->mem_map = phys_mem_map_init();\n\n#ifdef USE_KVM\n if (p->accel_enable) {\n kvm_init(s);\n }\n#endif\n\n#ifdef USE_KVM\n if (!s->kvm_enabled)\n#endif\n {\n s->cpu_state = x86_cpu_init(s->mem_map);\n x86_cpu_set_get_tsc(s->cpu_state, cpu_get_tsc, s);\n x86_cpu_set_port_io(s->cpu_state, ld_port, st_port, s);\n \n /* needed to handle the RAM dirty bits */\n s->mem_map->opaque = s;\n s->mem_map->flush_tlb_write_range = pc_flush_tlb_write_range;\n }\n\n /* set the RAM mapping and leave the VGA addresses empty */\n cpu_register_ram(s->mem_map, 0xc0000, p->ram_size - 0xc0000, 0);\n cpu_register_ram(s->mem_map, 0, 0xa0000, 0);\n \n /* devices */\n cpu_register_device(s->port_map, 0x80, 2, s, port80_read, port80_write, \n DEVIO_SIZE8);\n cpu_register_device(s->port_map, 0x92, 2, s, port92_read, port92_write, \n DEVIO_SIZE8);\n \n /* setup the bios */\n if (p->files[VM_FILE_BIOS].len > 0) {\n int bios_size, bios_size1;\n uint8_t *bios_buf, *ptr;\n uint32_t bios_addr;\n \n bios_size = p->files[VM_FILE_BIOS].len;\n bios_buf = p->files[VM_FILE_BIOS].buf;\n assert((bios_size % 65536) == 0 && bios_size != 0);\n bios_addr = -bios_size;\n /* at the top of the 4GB memory */\n cpu_register_ram(s->mem_map, bios_addr, bios_size, DEVRAM_FLAG_ROM);\n ptr = get_ram_ptr(s, bios_addr);\n memcpy(ptr, bios_buf, bios_size);\n /* in the lower 1MB memory (currently set as RAM) */\n bios_size1 = min_int(bios_size, 128 * 1024);\n ptr = get_ram_ptr(s, 0x100000 - bios_size1);\n memcpy(ptr, bios_buf + bios_size - bios_size1, bios_size1);\n#ifdef DEBUG_BIOS\n cpu_register_device(s->port_map, 0x402, 2, s,\n bios_debug_read, bios_debug_write, \n DEVIO_SIZE8);\n#endif\n }\n\n#ifdef USE_KVM\n if (!s->kvm_enabled)\n#endif\n {\n s->pic_state = pic2_init(s->port_map, 0x20, 0xa0,\n 0x4d0, 0x4d1,\n pic_set_irq_cb, s,\n s->pic_irq);\n x86_cpu_set_get_hard_intno(s->cpu_state, get_hard_intno_cb, s);\n s->pit_state = pit_init(s->port_map, 0x40, 0x61, &s->pic_irq[0],\n pit_get_ticks_cb, s);\n }\n\n s->cmos_state = cmos_init(s->port_map, 0x70, &s->pic_irq[8],\n p->rtc_local_time);\n\n /* various cmos data */\n {\n int size;\n /* memory size */\n size = min_int((s->ram_size - (1 << 20)) >> 10, 65535);\n put_le16(s->cmos_state->cmos_data + 0x30, size);\n if (s->ram_size >= (16 << 20)) {\n size = min_int((s->ram_size - (16 << 20)) >> 16, 65535);\n put_le16(s->cmos_state->cmos_data + 0x34, size);\n }\n s->cmos_state->cmos_data[0x14] = 0x06; /* mouse + FPU present */\n }\n \n s->i440fx_state = i440fx_init(&pci_bus, &piix3_devfn, s->mem_map,\n s->port_map, s->pic_irq);\n \n s->common.console = p->console;\n /* serial console */\n if (0) {\n s->serial_state = serial_init(s->port_map, 0x3f8, &s->pic_irq[4],\n serial_write_cb, s);\n }\n \n memset(vbus, 0, sizeof(*vbus));\n vbus->pci_bus = pci_bus;\n\n if (p->console) {\n /* virtio console */\n s->common.console_dev = virtio_console_init(vbus, p->console);\n }\n \n /* block devices */\n for(i = 0; i < p->drive_count;) {\n const VMDriveEntry *de = &p->tab_drive[i];\n\n if (!de->device || !strcmp(de->device, \"virtio\")) {\n virtio_block_init(vbus, p->tab_drive[i].block_dev);\n i++;\n } else if (!strcmp(de->device, \"ide\")) {\n BlockDevice *tab_bs[2];\n \n tab_bs[0] = p->tab_drive[i++].block_dev;\n tab_bs[1] = NULL;\n if (i < p->drive_count)\n tab_bs[1] = p->tab_drive[i++].block_dev;\n ide_init(s->port_map, 0x1f0, 0x3f6, &s->pic_irq[14], tab_bs);\n piix3_ide_init(pci_bus, piix3_devfn + 1);\n }\n }\n \n /* virtio filesystem */\n for(i = 0; i < p->fs_count; i++) {\n virtio_9p_init(vbus, p->tab_fs[i].fs_dev,\n p->tab_fs[i].tag);\n }\n\n if (p->display_device) {\n FBDevice *fb_dev;\n\n fb_dev = mallocz(sizeof(*fb_dev));\n s->common.fb_dev = fb_dev;\n if (!strcmp(p->display_device, \"vga\")) {\n int bios_size;\n uint8_t *bios_buf;\n bios_size = p->files[VM_FILE_VGA_BIOS].len;\n bios_buf = p->files[VM_FILE_VGA_BIOS].buf;\n pci_vga_init(pci_bus, fb_dev, p->width, p->height,\n bios_buf, bios_size);\n } else if (!strcmp(p->display_device, \"simplefb\")) {\n simplefb_init(s->mem_map,\n FRAMEBUFFER_BASE_ADDR,\n fb_dev, p->width, p->height);\n } else {\n vm_error(\"unsupported display device: %s\\n\", p->display_device);\n exit(1);\n }\n }\n\n if (p->input_device) {\n if (!strcmp(p->input_device, \"virtio\")) {\n s->keyboard_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_KEYBOARD);\n \n s->mouse_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_TABLET);\n } else if (!strcmp(p->input_device, \"ps2\")) {\n s->kbd_state = i8042_init(&s->ps2_kbd, &s->ps2_mouse,\n s->port_map,\n &s->pic_irq[1], &s->pic_irq[12], 0x60);\n /* vmmouse */\n cpu_register_device(s->port_map, 0x5658, 1, s,\n vmport_read, vmport_write, \n DEVIO_SIZE32);\n s->vm_mouse = vmmouse_init(s->ps2_mouse);\n } else {\n vm_error(\"unsupported input device: %s\\n\", p->input_device);\n exit(1);\n }\n }\n \n /* virtio net device */\n for(i = 0; i < p->eth_count; i++) {\n virtio_net_init(vbus, p->tab_eth[i].net);\n s->common.net = p->tab_eth[i].net;\n }\n\n if (p->files[VM_FILE_KERNEL].buf) {\n copy_kernel(s, p->files[VM_FILE_KERNEL].buf,\n p->files[VM_FILE_KERNEL].len,\n p->cmdline ? p->cmdline : \"\");\n }\n\n return (VirtMachine *)s;\n}\n\nstatic void pc_machine_end(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n /* XXX: free all */\n if (s->cpu_state) {\n x86_cpu_end(s->cpu_state);\n }\n phys_mem_map_end(s->mem_map);\n phys_mem_map_end(s->port_map);\n free(s);\n}\n\nstatic void pc_vm_send_key_event(VirtMachine *s1, BOOL is_down, uint16_t key_code)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->keyboard_dev) {\n virtio_input_send_key_event(s->keyboard_dev, is_down, key_code);\n } else if (s->ps2_kbd) {\n ps2_put_keycode(s->ps2_kbd, is_down, key_code);\n }\n}\n\nstatic BOOL pc_vm_mouse_is_absolute(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->mouse_dev) {\n return TRUE;\n } else if (s->vm_mouse) {\n return vmmouse_is_absolute(s->vm_mouse);\n } else {\n return FALSE;\n }\n}\n\nstatic void pc_vm_send_mouse_event(VirtMachine *s1, int dx, int dy, int dz,\n unsigned int buttons)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->mouse_dev) {\n virtio_input_send_mouse_event(s->mouse_dev, dx, dy, dz, buttons);\n } else if (s->vm_mouse) {\n vmmouse_send_mouse_event(s->vm_mouse, dx, dy, dz, buttons);\n }\n}\n\nstruct screen_info {\n} __attribute__((packed));\n\n/* from plex86 (BSD license) */\nstruct __attribute__ ((packed)) linux_params {\n /* screen_info structure */\n uint8_t orig_x;\t\t/* 0x00 */\n uint8_t orig_y;\t\t/* 0x01 */\n uint16_t ext_mem_k;\t/* 0x02 */\n uint16_t orig_video_page;\t/* 0x04 */\n uint8_t orig_video_mode;\t/* 0x06 */\n uint8_t orig_video_cols;\t/* 0x07 */\n uint8_t flags;\t\t/* 0x08 */\n uint8_t unused2;\t\t/* 0x09 */\n uint16_t orig_video_ega_bx;/* 0x0a */\n uint16_t unused3;\t\t/* 0x0c */\n uint8_t orig_video_lines;\t/* 0x0e */\n uint8_t orig_video_isVGA;\t/* 0x0f */\n uint16_t orig_video_points;/* 0x10 */\n \n /* VESA graphic mode -- linear frame buffer */\n uint16_t lfb_width;\t/* 0x12 */\n uint16_t lfb_height;\t/* 0x14 */\n uint16_t lfb_depth;\t/* 0x16 */\n uint32_t lfb_base;\t\t/* 0x18 */\n uint32_t lfb_size;\t\t/* 0x1c */\n uint16_t cl_magic, cl_offset; /* 0x20 */\n uint16_t lfb_linelength;\t/* 0x24 */\n uint8_t red_size;\t\t/* 0x26 */\n uint8_t red_pos;\t\t/* 0x27 */\n uint8_t green_size;\t/* 0x28 */\n uint8_t green_pos;\t/* 0x29 */\n uint8_t blue_size;\t/* 0x2a */\n uint8_t blue_pos;\t\t/* 0x2b */\n uint8_t rsvd_size;\t/* 0x2c */\n uint8_t rsvd_pos;\t\t/* 0x2d */\n uint16_t vesapm_seg;\t/* 0x2e */\n uint16_t vesapm_off;\t/* 0x30 */\n uint16_t pages;\t\t/* 0x32 */\n uint16_t vesa_attributes;\t/* 0x34 */\n uint32_t capabilities; /* 0x36 */\n uint32_t ext_lfb_base;\t/* 0x3a */\n uint8_t _reserved[2];\t/* 0x3e */\n \n /* 0x040 */ uint8_t apm_bios_info[20]; // struct apm_bios_info\n /* 0x054 */ uint8_t pad2[0x80 - 0x54];\n\n // Following 2 from 'struct drive_info_struct' in drivers/block/cciss.h.\n // Might be truncated?\n /* 0x080 */ uint8_t hd0_info[16]; // hd0-disk-parameter from intvector 0x41\n /* 0x090 */ uint8_t hd1_info[16]; // hd1-disk-parameter from intvector 0x46\n\n // System description table truncated to 16 bytes\n // From 'struct sys_desc_table_struct' in linux/arch/i386/kernel/setup.c.\n /* 0x0a0 */ uint16_t sys_description_len;\n /* 0x0a2 */ uint8_t sys_description_table[14];\n // [0] machine id\n // [1] machine submodel id\n // [2] BIOS revision\n // [3] bit1: MCA bus\n\n /* 0x0b0 */ uint8_t pad3[0x1e0 - 0xb0];\n /* 0x1e0 */ uint32_t alt_mem_k;\n /* 0x1e4 */ uint8_t pad4[4];\n /* 0x1e8 */ uint8_t e820map_entries;\n /* 0x1e9 */ uint8_t eddbuf_entries; // EDD_NR\n /* 0x1ea */ uint8_t pad5[0x1f1 - 0x1ea];\n /* 0x1f1 */ uint8_t setup_sects; // size of setup.S, number of sectors\n /* 0x1f2 */ uint16_t mount_root_rdonly; // MOUNT_ROOT_RDONLY (if !=0)\n /* 0x1f4 */ uint16_t sys_size; // size of compressed kernel-part in the\n // (b)zImage-file (in 16 byte units, rounded up)\n /* 0x1f6 */ uint16_t swap_dev; // (unused AFAIK)\n /* 0x1f8 */ uint16_t ramdisk_flags;\n /* 0x1fa */ uint16_t vga_mode; // (old one)\n /* 0x1fc */ uint16_t orig_root_dev; // (high=Major, low=minor)\n /* 0x1fe */ uint8_t pad6[1];\n /* 0x1ff */ uint8_t aux_device_info;\n /* 0x200 */ uint16_t jump_setup; // Jump to start of setup code,\n // aka \"reserved\" field.\n /* 0x202 */ uint8_t setup_signature[4]; // Signature for SETUP-header, =\"HdrS\"\n /* 0x206 */ uint16_t header_format_version; // Version number of header format;\n /* 0x208 */ uint8_t setup_S_temp0[8]; // Used by setup.S for communication with\n // boot loaders, look there.\n /* 0x210 */ uint8_t loader_type;\n // 0 for old one.\n // else 0xTV:\n // T=0: LILO\n // T=1: Loadlin\n // T=2: bootsect-loader\n // T=3: SYSLINUX\n // T=4: ETHERBOOT\n // V=version\n /* 0x211 */ uint8_t loadflags;\n // bit0 = 1: kernel is loaded high (bzImage)\n // bit7 = 1: Heap and pointer (see below) set by boot\n // loader.\n /* 0x212 */ uint16_t setup_S_temp1;\n /* 0x214 */ uint32_t kernel_start;\n /* 0x218 */ uint32_t initrd_start;\n /* 0x21c */ uint32_t initrd_size;\n /* 0x220 */ uint8_t setup_S_temp2[4];\n /* 0x224 */ uint16_t setup_S_heap_end_pointer;\n /* 0x226 */ uint16_t pad70;\n /* 0x228 */ uint32_t cmd_line_ptr;\n /* 0x22c */ uint8_t pad7[0x2d0 - 0x22c];\n\n /* 0x2d0 : Int 15, ax=e820 memory map. */\n // (linux/include/asm-i386/e820.h, 'struct e820entry')\n#define E820MAX 32\n#define E820_RAM 1\n#define E820_RESERVED 2\n#define E820_ACPI 3 /* usable as RAM once ACPI tables have been read */\n#define E820_NVS 4\n struct {\n uint64_t addr;\n uint64_t size;\n uint32_t type;\n } e820map[E820MAX];\n\n /* 0x550 */ uint8_t pad8[0x600 - 0x550];\n\n // BIOS Enhanced Disk Drive Services.\n // (From linux/include/asm-i386/edd.h, 'struct edd_info')\n // Each 'struct edd_info is 78 bytes, times a max of 6 structs in array.\n /* 0x600 */ uint8_t eddbuf[0x7d4 - 0x600];\n\n /* 0x7d4 */ uint8_t pad9[0x800 - 0x7d4];\n /* 0x800 */ uint8_t commandline[0x800];\n\n uint64_t gdt_table[4];\n};\n\n#define KERNEL_PARAMS_ADDR 0x00090000\n\nstatic void copy_kernel(PCMachine *s, const uint8_t *buf, int buf_len,\n const char *cmd_line)\n{\n uint8_t *ram_ptr;\n int setup_sects, header_len, copy_len, setup_hdr_start, setup_hdr_end;\n uint32_t load_address;\n struct linux_params *params;\n FBDevice *fb_dev;\n \n if (buf_len < 1024) {\n too_small:\n fprintf(stderr, \"Kernel too small\\n\");\n exit(1);\n }\n if (buf[0x1fe] != 0x55 || buf[0x1ff] != 0xaa) {\n fprintf(stderr, \"Invalid kernel magic\\n\");\n exit(1);\n }\n setup_sects = buf[0x1f1];\n if (setup_sects == 0)\n setup_sects = 4;\n header_len = (setup_sects + 1) * 512;\n if (buf_len < header_len)\n goto too_small;\n if (memcmp(buf + 0x202, \"HdrS\", 4) != 0) {\n fprintf(stderr, \"Kernel too old\\n\");\n exit(1);\n }\n load_address = 0x100000; /* we don't support older protocols */\n\n ram_ptr = get_ram_ptr(s, load_address);\n copy_len = buf_len - header_len;\n if (copy_len > (s->ram_size - load_address)) {\n fprintf(stderr, \"Not enough RAM\\n\");\n exit(1);\n }\n memcpy(ram_ptr, buf + header_len, copy_len);\n\n params = (void *)get_ram_ptr(s, KERNEL_PARAMS_ADDR);\n \n memset(params, 0, sizeof(struct linux_params));\n\n /* copy the setup header */\n setup_hdr_start = 0x1f1;\n setup_hdr_end = 0x202 + buf[0x201];\n memcpy((uint8_t *)params + setup_hdr_start, buf + setup_hdr_start,\n setup_hdr_end - setup_hdr_start);\n\n strcpy((char *)params->commandline, cmd_line);\n\n params->mount_root_rdonly = 0;\n params->cmd_line_ptr = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, commandline);\n params->alt_mem_k = (s->ram_size / 1024) - 1024;\n params->loader_type = 0x01;\n#if 0\n if (initrd_size > 0) {\n params->initrd_start = INITRD_LOAD_ADDR;\n params->initrd_size = initrd_size;\n }\n#endif\n params->orig_video_lines = 0;\n params->orig_video_cols = 0;\n\n fb_dev = s->common.fb_dev;\n if (fb_dev) {\n \n params->orig_video_isVGA = 0x23; /* VIDEO_TYPE_VLFB */\n\n params->lfb_depth = 32;\n params->red_size = 8;\n params->red_pos = 16;\n params->green_size = 8;\n params->green_pos = 8;\n params->blue_size = 8;\n params->blue_pos = 0;\n params->rsvd_size = 8;\n params->rsvd_pos = 24;\n\n params->lfb_width = fb_dev->width;\n params->lfb_height = fb_dev->height;\n params->lfb_linelength = fb_dev->stride;\n params->lfb_size = fb_dev->fb_size;\n params->lfb_base = FRAMEBUFFER_BASE_ADDR;\n }\n \n params->gdt_table[2] = 0x00cf9b000000ffffLL; /* CS */\n params->gdt_table[3] = 0x00cf93000000ffffLL; /* DS */\n \n#ifdef USE_KVM\n if (s->kvm_enabled) {\n struct kvm_sregs sregs;\n struct kvm_segment seg;\n struct kvm_regs regs;\n \n /* init flat protected mode */\n\n if (ioctl(s->vcpu_fd, KVM_GET_SREGS, &sregs) < 0) {\n perror(\"KVM_GET_SREGS\");\n exit(1);\n }\n\n sregs.cr0 |= (1 << 0); /* CR0_PE */\n sregs.gdt.base = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, gdt_table);\n sregs.gdt.limit = sizeof(params->gdt_table) - 1;\n \n memset(&seg, 0, sizeof(seg));\n seg.limit = 0xffffffff;\n seg.present = 1;\n seg.db = 1;\n seg.s = 1; /* code/data */\n seg.g = 1; /* 4KB granularity */\n\n seg.type = 0xb; /* code */\n seg.selector = 2 << 3;\n sregs.cs = seg;\n\n seg.type = 0x3; /* data */\n seg.selector = 3 << 3;\n sregs.ds = seg;\n sregs.es = seg;\n sregs.ss = seg;\n sregs.fs = seg;\n sregs.gs = seg;\n \n if (ioctl(s->vcpu_fd, KVM_SET_SREGS, &sregs) < 0) {\n perror(\"KVM_SET_SREGS\");\n exit(1);\n }\n \n memset(®s, 0, sizeof(regs));\n regs.rip = load_address;\n regs.rsi = KERNEL_PARAMS_ADDR;\n regs.rflags = 0x2;\n if (ioctl(s->vcpu_fd, KVM_SET_REGS, ®s) < 0) {\n perror(\"KVM_SET_REGS\");\n exit(1);\n }\n } else\n#endif\n {\n int i;\n X86CPUSeg sd;\n uint32_t val;\n val = x86_cpu_get_reg(s->cpu_state, X86_CPU_REG_CR0);\n x86_cpu_set_reg(s->cpu_state, X86_CPU_REG_CR0, val | (1 << 0));\n \n sd.base = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, gdt_table);\n sd.limit = sizeof(params->gdt_table) - 1;\n x86_cpu_set_seg(s->cpu_state, X86_CPU_SEG_GDT, &sd);\n sd.sel = 2 << 3;\n sd.base = 0;\n sd.limit = 0xffffffff;\n sd.flags = 0xc09b;\n x86_cpu_set_seg(s->cpu_state, X86_CPU_SEG_CS, &sd);\n sd.sel = 3 << 3;\n sd.flags = 0xc093;\n for(i = 0; i < 6; i++) {\n if (i != X86_CPU_SEG_CS) {\n x86_cpu_set_seg(s->cpu_state, i, &sd);\n }\n }\n \n x86_cpu_set_reg(s->cpu_state, X86_CPU_REG_EIP, load_address);\n x86_cpu_set_reg(s->cpu_state, 6, KERNEL_PARAMS_ADDR); /* esi */\n }\n\n /* map PCI interrupts (no BIOS, so we must do it) */\n {\n uint8_t elcr[2];\n static const uint8_t pci_irqs[4] = { 9, 10, 11, 12 };\n\n i440fx_map_interrupts(s->i440fx_state, elcr, pci_irqs);\n /* XXX: KVM support */\n if (s->pic_state) {\n pic2_set_elcr(s->pic_state, elcr);\n }\n }\n}\n\n/* in ms */\nstatic int pc_machine_get_sleep_duration(VirtMachine *s1, int delay)\n{\n PCMachine *s = (PCMachine *)s1;\n\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n /* XXX: improve */\n cmos_update_irq(s->cmos_state);\n delay = 0;\n } else\n#endif\n {\n cmos_update_irq(s->cmos_state);\n delay = min_int(delay, pit_update_irq(s->pit_state));\n if (!x86_cpu_get_power_down(s->cpu_state))\n delay = 0;\n }\n return delay;\n}\n\nstatic void pc_machine_interp(VirtMachine *s1, int max_exec_cycles)\n{\n PCMachine *s = (PCMachine *)s1;\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n kvm_exec(s);\n } else \n#endif\n {\n x86_cpu_interp(s->cpu_state, max_exec_cycles);\n }\n}\n\nconst VirtMachineClass pc_machine_class = {\n \"pc\",\n pc_machine_set_defaults,\n pc_machine_init,\n pc_machine_end,\n pc_machine_get_sleep_duration,\n pc_machine_interp,\n pc_vm_mouse_is_absolute,\n pc_vm_send_mouse_event,\n pc_vm_send_key_event,\n};\n"], ["/linuxpdf/tinyemu/riscv_cpu.c", "/*\n * RISCV CPU emulator\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"riscv_cpu.h\"\n\n#ifndef MAX_XLEN\n#error MAX_XLEN must be defined\n#endif\n#ifndef CONFIG_RISCV_MAX_XLEN\n#error CONFIG_RISCV_MAX_XLEN must be defined\n#endif\n\n//#define DUMP_INVALID_MEM_ACCESS\n//#define DUMP_MMU_EXCEPTIONS\n//#define DUMP_INTERRUPTS\n//#define DUMP_INVALID_CSR\n//#define DUMP_EXCEPTIONS\n//#define DUMP_CSR\n//#define CONFIG_LOGFILE\n\n#include \"riscv_cpu_priv.h\"\n\n#if FLEN > 0\n#include \"softfp.h\"\n#endif\n\n#ifdef USE_GLOBAL_STATE\nstatic RISCVCPUState riscv_cpu_global_state;\n#endif\n#ifdef USE_GLOBAL_VARIABLES\n#define code_ptr s->__code_ptr\n#define code_end s->__code_end\n#define code_to_pc_addend s->__code_to_pc_addend\n#endif\n\n#ifdef CONFIG_LOGFILE\nstatic FILE *log_file;\n\nstatic void log_vprintf(const char *fmt, va_list ap)\n{\n if (!log_file)\n log_file = fopen(\"/tmp/riscemu.log\", \"wb\");\n vfprintf(log_file, fmt, ap);\n}\n#else\nstatic void log_vprintf(const char *fmt, va_list ap)\n{\n vprintf(fmt, ap);\n}\n#endif\n\nstatic void __attribute__((format(printf, 1, 2), unused)) log_printf(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n log_vprintf(fmt, ap);\n va_end(ap);\n}\n\n#if MAX_XLEN == 128\nstatic void fprint_target_ulong(FILE *f, target_ulong a)\n{\n fprintf(f, \"%016\" PRIx64 \"%016\" PRIx64, (uint64_t)(a >> 64), (uint64_t)a);\n}\n#else\nstatic void fprint_target_ulong(FILE *f, target_ulong a)\n{\n fprintf(f, \"%\" PR_target_ulong, a);\n}\n#endif\n\nstatic void print_target_ulong(target_ulong a)\n{\n fprint_target_ulong(stdout, a);\n}\n\nstatic char *reg_name[32] = {\n\"zero\", \"ra\", \"sp\", \"gp\", \"tp\", \"t0\", \"t1\", \"t2\",\n\"s0\", \"s1\", \"a0\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\",\n\"a6\", \"a7\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\", \"s7\",\n\"s8\", \"s9\", \"s10\", \"s11\", \"t3\", \"t4\", \"t5\", \"t6\"\n};\n\nstatic void dump_regs(RISCVCPUState *s)\n{\n int i, cols;\n const char priv_str[4] = \"USHM\";\n cols = 256 / MAX_XLEN;\n printf(\"pc =\");\n print_target_ulong(s->pc);\n printf(\" \");\n for(i = 1; i < 32; i++) {\n printf(\"%-3s=\", reg_name[i]);\n print_target_ulong(s->reg[i]);\n if ((i & (cols - 1)) == (cols - 1))\n printf(\"\\n\");\n else\n printf(\" \");\n }\n printf(\"priv=%c\", priv_str[s->priv]);\n printf(\" mstatus=\");\n print_target_ulong(s->mstatus);\n printf(\" cycles=%\" PRId64, s->insn_counter);\n printf(\"\\n\");\n#if 1\n printf(\" mideleg=\");\n print_target_ulong(s->mideleg);\n printf(\" mie=\");\n print_target_ulong(s->mie);\n printf(\" mip=\");\n print_target_ulong(s->mip);\n printf(\"\\n\");\n#endif\n}\n\nstatic __attribute__((unused)) void cpu_abort(RISCVCPUState *s)\n{\n dump_regs(s);\n abort();\n}\n\n/* addr must be aligned. Only RAM accesses are supported */\n#define PHYS_MEM_READ_WRITE(size, uint_type) \\\nstatic __maybe_unused inline void phys_write_u ## size(RISCVCPUState *s, target_ulong addr,\\\n uint_type val) \\\n{\\\n PhysMemoryRange *pr = get_phys_mem_range(s->mem_map, addr);\\\n if (!pr || !pr->is_ram)\\\n return;\\\n *(uint_type *)(pr->phys_mem + \\\n (uintptr_t)(addr - pr->addr)) = val;\\\n}\\\n\\\nstatic __maybe_unused inline uint_type phys_read_u ## size(RISCVCPUState *s, target_ulong addr) \\\n{\\\n PhysMemoryRange *pr = get_phys_mem_range(s->mem_map, addr);\\\n if (!pr || !pr->is_ram)\\\n return 0;\\\n return *(uint_type *)(pr->phys_mem + \\\n (uintptr_t)(addr - pr->addr)); \\\n}\n\nPHYS_MEM_READ_WRITE(8, uint8_t)\nPHYS_MEM_READ_WRITE(32, uint32_t)\nPHYS_MEM_READ_WRITE(64, uint64_t)\n\n#define PTE_V_MASK (1 << 0)\n#define PTE_U_MASK (1 << 4)\n#define PTE_A_MASK (1 << 6)\n#define PTE_D_MASK (1 << 7)\n\n#define ACCESS_READ 0\n#define ACCESS_WRITE 1\n#define ACCESS_CODE 2\n\n/* access = 0: read, 1 = write, 2 = code. Set the exception_pending\n field if necessary. return 0 if OK, -1 if translation error */\nstatic int get_phys_addr(RISCVCPUState *s,\n target_ulong *ppaddr, target_ulong vaddr,\n int access)\n{\n int mode, levels, pte_bits, pte_idx, pte_mask, pte_size_log2, xwr, priv;\n int need_write, vaddr_shift, i, pte_addr_bits;\n target_ulong pte_addr, pte, vaddr_mask, paddr;\n\n if ((s->mstatus & MSTATUS_MPRV) && access != ACCESS_CODE) {\n /* use previous priviledge */\n priv = (s->mstatus >> MSTATUS_MPP_SHIFT) & 3;\n } else {\n priv = s->priv;\n }\n\n if (priv == PRV_M) {\n if (s->cur_xlen < MAX_XLEN) {\n /* truncate virtual address */\n *ppaddr = vaddr & (((target_ulong)1 << s->cur_xlen) - 1);\n } else {\n *ppaddr = vaddr;\n }\n return 0;\n }\n#if MAX_XLEN == 32\n /* 32 bits */\n mode = s->satp >> 31;\n if (mode == 0) {\n /* bare: no translation */\n *ppaddr = vaddr;\n return 0;\n } else {\n /* sv32 */\n levels = 2;\n pte_size_log2 = 2;\n pte_addr_bits = 22;\n }\n#else\n mode = (s->satp >> 60) & 0xf;\n if (mode == 0) {\n /* bare: no translation */\n *ppaddr = vaddr;\n return 0;\n } else {\n /* sv39/sv48 */\n levels = mode - 8 + 3;\n pte_size_log2 = 3;\n vaddr_shift = MAX_XLEN - (PG_SHIFT + levels * 9);\n if ((((target_long)vaddr << vaddr_shift) >> vaddr_shift) != vaddr)\n return -1;\n pte_addr_bits = 44;\n }\n#endif\n pte_addr = (s->satp & (((target_ulong)1 << pte_addr_bits) - 1)) << PG_SHIFT;\n pte_bits = 12 - pte_size_log2;\n pte_mask = (1 << pte_bits) - 1;\n for(i = 0; i < levels; i++) {\n vaddr_shift = PG_SHIFT + pte_bits * (levels - 1 - i);\n pte_idx = (vaddr >> vaddr_shift) & pte_mask;\n pte_addr += pte_idx << pte_size_log2;\n if (pte_size_log2 == 2)\n pte = phys_read_u32(s, pte_addr);\n else\n pte = phys_read_u64(s, pte_addr);\n //printf(\"pte=0x%08\" PRIx64 \"\\n\", pte);\n if (!(pte & PTE_V_MASK))\n return -1; /* invalid PTE */\n paddr = (pte >> 10) << PG_SHIFT;\n xwr = (pte >> 1) & 7;\n if (xwr != 0) {\n if (xwr == 2 || xwr == 6)\n return -1;\n /* priviledge check */\n if (priv == PRV_S) {\n if ((pte & PTE_U_MASK) && !(s->mstatus & MSTATUS_SUM))\n return -1;\n } else {\n if (!(pte & PTE_U_MASK))\n return -1;\n }\n /* protection check */\n /* MXR allows read access to execute-only pages */\n if (s->mstatus & MSTATUS_MXR)\n xwr |= (xwr >> 2);\n\n if (((xwr >> access) & 1) == 0)\n return -1;\n need_write = !(pte & PTE_A_MASK) ||\n (!(pte & PTE_D_MASK) && access == ACCESS_WRITE);\n pte |= PTE_A_MASK;\n if (access == ACCESS_WRITE)\n pte |= PTE_D_MASK;\n if (need_write) {\n if (pte_size_log2 == 2)\n phys_write_u32(s, pte_addr, pte);\n else\n phys_write_u64(s, pte_addr, pte);\n }\n vaddr_mask = ((target_ulong)1 << vaddr_shift) - 1;\n *ppaddr = (vaddr & vaddr_mask) | (paddr & ~vaddr_mask);\n return 0;\n } else {\n pte_addr = paddr;\n }\n }\n return -1;\n}\n\n/* return 0 if OK, != 0 if exception */\nint target_read_slow(RISCVCPUState *s, mem_uint_t *pval,\n target_ulong addr, int size_log2)\n{\n int size, tlb_idx, err, al;\n target_ulong paddr, offset;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n mem_uint_t ret;\n\n /* first handle unaligned accesses */\n size = 1 << size_log2;\n al = addr & (size - 1);\n if (al != 0) {\n switch(size_log2) {\n case 1:\n {\n uint8_t v0, v1;\n err = target_read_u8(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u8(s, &v1, addr + 1);\n if (err)\n return err;\n ret = v0 | (v1 << 8);\n }\n break;\n case 2:\n {\n uint32_t v0, v1;\n addr -= al;\n err = target_read_u32(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u32(s, &v1, addr + 4);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (32 - al * 8));\n }\n break;\n#if MLEN >= 64\n case 3:\n {\n uint64_t v0, v1;\n addr -= al;\n err = target_read_u64(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u64(s, &v1, addr + 8);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (64 - al * 8));\n }\n break;\n#endif\n#if MLEN >= 128\n case 4:\n {\n uint128_t v0, v1;\n addr -= al;\n err = target_read_u128(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u128(s, &v1, addr + 16);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (128 - al * 8));\n }\n break;\n#endif\n default:\n abort();\n }\n } else {\n if (get_phys_addr(s, &paddr, addr, ACCESS_READ)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_LOAD_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr) {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"target_read_slow: invalid physical address 0x\");\n print_target_ulong(paddr);\n printf(\"\\n\");\n#endif\n return 0;\n } else if (pr->is_ram) {\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_read[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_read[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n switch(size_log2) {\n case 0:\n ret = *(uint8_t *)ptr;\n break;\n case 1:\n ret = *(uint16_t *)ptr;\n break;\n case 2:\n ret = *(uint32_t *)ptr;\n break;\n#if MLEN >= 64\n case 3:\n ret = *(uint64_t *)ptr;\n break;\n#endif\n#if MLEN >= 128\n case 4:\n ret = *(uint128_t *)ptr;\n break;\n#endif\n default:\n abort();\n }\n } else {\n offset = paddr - pr->addr;\n if (((pr->devio_flags >> size_log2) & 1) != 0) {\n ret = pr->read_func(pr->opaque, offset, size_log2);\n }\n#if MLEN >= 64\n else if ((pr->devio_flags & DEVIO_SIZE32) && size_log2 == 3) {\n /* emulate 64 bit access */\n ret = pr->read_func(pr->opaque, offset, 2);\n ret |= (uint64_t)pr->read_func(pr->opaque, offset + 4, 2) << 32;\n \n }\n#endif\n else {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"unsupported device read access: addr=0x\");\n print_target_ulong(paddr);\n printf(\" width=%d bits\\n\", 1 << (3 + size_log2));\n#endif\n ret = 0;\n }\n }\n }\n *pval = ret;\n return 0;\n}\n\n/* return 0 if OK, != 0 if exception */\nint target_write_slow(RISCVCPUState *s, target_ulong addr,\n mem_uint_t val, int size_log2)\n{\n int size, i, tlb_idx, err;\n target_ulong paddr, offset;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n \n /* first handle unaligned accesses */\n size = 1 << size_log2;\n if ((addr & (size - 1)) != 0) {\n /* XXX: should avoid modifying the memory in case of exception */\n for(i = 0; i < size; i++) {\n err = target_write_u8(s, addr + i, (val >> (8 * i)) & 0xff);\n if (err)\n return err;\n }\n } else {\n if (get_phys_addr(s, &paddr, addr, ACCESS_WRITE)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_STORE_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr) {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"target_write_slow: invalid physical address 0x\");\n print_target_ulong(paddr);\n printf(\"\\n\");\n#endif\n } else if (pr->is_ram) {\n phys_mem_set_dirty_bit(pr, paddr - pr->addr);\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_write[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_write[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n switch(size_log2) {\n case 0:\n *(uint8_t *)ptr = val;\n break;\n case 1:\n *(uint16_t *)ptr = val;\n break;\n case 2:\n *(uint32_t *)ptr = val;\n break;\n#if MLEN >= 64\n case 3:\n *(uint64_t *)ptr = val;\n break;\n#endif\n#if MLEN >= 128\n case 4:\n *(uint128_t *)ptr = val;\n break;\n#endif\n default:\n abort();\n }\n } else {\n offset = paddr - pr->addr;\n if (((pr->devio_flags >> size_log2) & 1) != 0) {\n pr->write_func(pr->opaque, offset, val, size_log2);\n }\n#if MLEN >= 64\n else if ((pr->devio_flags & DEVIO_SIZE32) && size_log2 == 3) {\n /* emulate 64 bit access */\n pr->write_func(pr->opaque, offset,\n val & 0xffffffff, 2);\n pr->write_func(pr->opaque, offset + 4,\n (val >> 32) & 0xffffffff, 2);\n }\n#endif\n else {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"unsupported device write access: addr=0x\");\n print_target_ulong(paddr);\n printf(\" width=%d bits\\n\", 1 << (3 + size_log2));\n#endif\n }\n }\n }\n return 0;\n}\n\nstruct __attribute__((packed)) unaligned_u32 {\n uint32_t u32;\n};\n\n/* unaligned access at an address known to be a multiple of 2 */\nstatic uint32_t get_insn32(uint8_t *ptr)\n{\n#if defined(EMSCRIPTEN)\n return ((uint16_t *)ptr)[0] | (((uint16_t *)ptr)[1] << 16);\n#else\n return ((struct unaligned_u32 *)ptr)->u32;\n#endif\n}\n\n/* return 0 if OK, != 0 if exception */\nstatic no_inline __exception int target_read_insn_slow(RISCVCPUState *s,\n uint8_t **pptr,\n target_ulong addr)\n{\n int tlb_idx;\n target_ulong paddr;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n \n if (get_phys_addr(s, &paddr, addr, ACCESS_CODE)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_FETCH_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr || !pr->is_ram) {\n /* XXX: we only access to execute code from RAM */\n s->pending_tval = addr;\n s->pending_exception = CAUSE_FAULT_FETCH;\n return -1;\n }\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_code[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_code[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n *pptr = ptr;\n return 0;\n}\n\n/* addr must be aligned */\nstatic inline __exception int target_read_insn_u16(RISCVCPUState *s, uint16_t *pinsn,\n target_ulong addr)\n{\n uint32_t tlb_idx;\n uint8_t *ptr;\n \n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n if (likely(s->tlb_code[tlb_idx].vaddr == (addr & ~PG_MASK))) {\n ptr = (uint8_t *)(s->tlb_code[tlb_idx].mem_addend +\n (uintptr_t)addr);\n } else {\n if (target_read_insn_slow(s, &ptr, addr))\n return -1;\n }\n *pinsn = *(uint16_t *)ptr;\n return 0;\n}\n\nstatic void tlb_init(RISCVCPUState *s)\n{\n int i;\n \n for(i = 0; i < TLB_SIZE; i++) {\n s->tlb_read[i].vaddr = -1;\n s->tlb_write[i].vaddr = -1;\n s->tlb_code[i].vaddr = -1;\n }\n}\n\nstatic void tlb_flush_all(RISCVCPUState *s)\n{\n tlb_init(s);\n}\n\nstatic void tlb_flush_vaddr(RISCVCPUState *s, target_ulong vaddr)\n{\n tlb_flush_all(s);\n}\n\n/* XXX: inefficient but not critical as long as it is seldom used */\nstatic void glue(riscv_cpu_flush_tlb_write_range_ram,\n MAX_XLEN)(RISCVCPUState *s,\n uint8_t *ram_ptr, size_t ram_size)\n{\n uint8_t *ptr, *ram_end;\n int i;\n \n ram_end = ram_ptr + ram_size;\n for(i = 0; i < TLB_SIZE; i++) {\n if (s->tlb_write[i].vaddr != -1) {\n ptr = (uint8_t *)(s->tlb_write[i].mem_addend +\n (uintptr_t)s->tlb_write[i].vaddr);\n if (ptr >= ram_ptr && ptr < ram_end) {\n s->tlb_write[i].vaddr = -1;\n }\n }\n }\n}\n\n\n#define SSTATUS_MASK0 (MSTATUS_UIE | MSTATUS_SIE | \\\n MSTATUS_UPIE | MSTATUS_SPIE | \\\n MSTATUS_SPP | \\\n MSTATUS_FS | MSTATUS_XS | \\\n MSTATUS_SUM | MSTATUS_MXR)\n#if MAX_XLEN >= 64\n#define SSTATUS_MASK (SSTATUS_MASK0 | MSTATUS_UXL_MASK)\n#else\n#define SSTATUS_MASK SSTATUS_MASK0\n#endif\n\n\n#define MSTATUS_MASK (MSTATUS_UIE | MSTATUS_SIE | MSTATUS_MIE | \\\n MSTATUS_UPIE | MSTATUS_SPIE | MSTATUS_MPIE | \\\n MSTATUS_SPP | MSTATUS_MPP | \\\n MSTATUS_FS | \\\n MSTATUS_MPRV | MSTATUS_SUM | MSTATUS_MXR)\n\n/* cycle and insn counters */\n#define COUNTEREN_MASK ((1 << 0) | (1 << 2))\n\n/* return the complete mstatus with the SD bit */\nstatic target_ulong get_mstatus(RISCVCPUState *s, target_ulong mask)\n{\n target_ulong val;\n BOOL sd;\n val = s->mstatus | (s->fs << MSTATUS_FS_SHIFT);\n val &= mask;\n sd = ((val & MSTATUS_FS) == MSTATUS_FS) |\n ((val & MSTATUS_XS) == MSTATUS_XS);\n if (sd)\n val |= (target_ulong)1 << (s->cur_xlen - 1);\n return val;\n}\n \nstatic int get_base_from_xlen(int xlen)\n{\n if (xlen == 32)\n return 1;\n else if (xlen == 64)\n return 2;\n else\n return 3;\n}\n\nstatic void set_mstatus(RISCVCPUState *s, target_ulong val)\n{\n target_ulong mod, mask;\n \n /* flush the TLBs if change of MMU config */\n mod = s->mstatus ^ val;\n if ((mod & (MSTATUS_MPRV | MSTATUS_SUM | MSTATUS_MXR)) != 0 ||\n ((s->mstatus & MSTATUS_MPRV) && (mod & MSTATUS_MPP) != 0)) {\n tlb_flush_all(s);\n }\n s->fs = (val >> MSTATUS_FS_SHIFT) & 3;\n\n mask = MSTATUS_MASK & ~MSTATUS_FS;\n#if MAX_XLEN >= 64\n {\n int uxl, sxl;\n uxl = (val >> MSTATUS_UXL_SHIFT) & 3;\n if (uxl >= 1 && uxl <= get_base_from_xlen(MAX_XLEN))\n mask |= MSTATUS_UXL_MASK;\n sxl = (val >> MSTATUS_UXL_SHIFT) & 3;\n if (sxl >= 1 && sxl <= get_base_from_xlen(MAX_XLEN))\n mask |= MSTATUS_SXL_MASK;\n }\n#endif\n s->mstatus = (s->mstatus & ~mask) | (val & mask);\n}\n\n/* return -1 if invalid CSR. 0 if OK. 'will_write' indicate that the\n csr will be written after (used for CSR access check) */\nstatic int csr_read(RISCVCPUState *s, target_ulong *pval, uint32_t csr,\n BOOL will_write)\n{\n target_ulong val;\n\n if (((csr & 0xc00) == 0xc00) && will_write)\n return -1; /* read-only CSR */\n if (s->priv < ((csr >> 8) & 3))\n return -1; /* not enough priviledge */\n \n switch(csr) {\n#if FLEN > 0\n case 0x001: /* fflags */\n if (s->fs == 0)\n return -1;\n val = s->fflags;\n break;\n case 0x002: /* frm */\n if (s->fs == 0)\n return -1;\n val = s->frm;\n break;\n case 0x003:\n if (s->fs == 0)\n return -1;\n val = s->fflags | (s->frm << 5);\n break;\n#endif\n case 0xc00: /* ucycle */\n case 0xc02: /* uinstret */\n {\n uint32_t counteren;\n if (s->priv < PRV_M) {\n if (s->priv < PRV_S)\n counteren = s->scounteren;\n else\n counteren = s->mcounteren;\n if (((counteren >> (csr & 0x1f)) & 1) == 0)\n goto invalid_csr;\n }\n }\n val = (int64_t)s->insn_counter;\n break;\n case 0xc80: /* mcycleh */\n case 0xc82: /* minstreth */\n if (s->cur_xlen != 32)\n goto invalid_csr;\n {\n uint32_t counteren;\n if (s->priv < PRV_M) {\n if (s->priv < PRV_S)\n counteren = s->scounteren;\n else\n counteren = s->mcounteren;\n if (((counteren >> (csr & 0x1f)) & 1) == 0)\n goto invalid_csr;\n }\n }\n val = s->insn_counter >> 32;\n break;\n \n case 0x100:\n val = get_mstatus(s, SSTATUS_MASK);\n break;\n case 0x104: /* sie */\n val = s->mie & s->mideleg;\n break;\n case 0x105:\n val = s->stvec;\n break;\n case 0x106:\n val = s->scounteren;\n break;\n case 0x140:\n val = s->sscratch;\n break;\n case 0x141:\n val = s->sepc;\n break;\n case 0x142:\n val = s->scause;\n break;\n case 0x143:\n val = s->stval;\n break;\n case 0x144: /* sip */\n val = s->mip & s->mideleg;\n break;\n case 0x180:\n val = s->satp;\n break;\n case 0x300:\n val = get_mstatus(s, (target_ulong)-1);\n break;\n case 0x301:\n val = s->misa;\n val |= (target_ulong)s->mxl << (s->cur_xlen - 2);\n break;\n case 0x302:\n val = s->medeleg;\n break;\n case 0x303:\n val = s->mideleg;\n break;\n case 0x304:\n val = s->mie;\n break;\n case 0x305:\n val = s->mtvec;\n break;\n case 0x306:\n val = s->mcounteren;\n break;\n case 0x340:\n val = s->mscratch;\n break;\n case 0x341:\n val = s->mepc;\n break;\n case 0x342:\n val = s->mcause;\n break;\n case 0x343:\n val = s->mtval;\n break;\n case 0x344:\n val = s->mip;\n break;\n case 0xb00: /* mcycle */\n case 0xb02: /* minstret */\n val = (int64_t)s->insn_counter;\n break;\n case 0xb80: /* mcycleh */\n case 0xb82: /* minstreth */\n if (s->cur_xlen != 32)\n goto invalid_csr;\n val = s->insn_counter >> 32;\n break;\n case 0xf14:\n val = s->mhartid;\n break;\n default:\n invalid_csr:\n#ifdef DUMP_INVALID_CSR\n /* the 'time' counter is usually emulated */\n if (csr != 0xc01 && csr != 0xc81) {\n printf(\"csr_read: invalid CSR=0x%x\\n\", csr);\n }\n#endif\n *pval = 0;\n return -1;\n }\n *pval = val;\n return 0;\n}\n\n#if FLEN > 0\nstatic void set_frm(RISCVCPUState *s, unsigned int val)\n{\n if (val >= 5)\n val = 0;\n s->frm = val;\n}\n\n/* return -1 if invalid roundind mode */\nstatic int get_insn_rm(RISCVCPUState *s, unsigned int rm)\n{\n if (rm == 7)\n return s->frm;\n if (rm >= 5)\n return -1;\n else\n return rm;\n}\n#endif\n\n/* return -1 if invalid CSR, 0 if OK, 1 if the interpreter loop must be\n exited (e.g. XLEN was modified), 2 if TLBs have been flushed. */\nstatic int csr_write(RISCVCPUState *s, uint32_t csr, target_ulong val)\n{\n target_ulong mask;\n\n#if defined(DUMP_CSR)\n printf(\"csr_write: csr=0x%03x val=0x\", csr);\n print_target_ulong(val);\n printf(\"\\n\");\n#endif\n switch(csr) {\n#if FLEN > 0\n case 0x001: /* fflags */\n s->fflags = val & 0x1f;\n s->fs = 3;\n break;\n case 0x002: /* frm */\n set_frm(s, val & 7);\n s->fs = 3;\n break;\n case 0x003: /* fcsr */\n set_frm(s, (val >> 5) & 7);\n s->fflags = val & 0x1f;\n s->fs = 3;\n break;\n#endif\n case 0x100: /* sstatus */\n set_mstatus(s, (s->mstatus & ~SSTATUS_MASK) | (val & SSTATUS_MASK));\n break;\n case 0x104: /* sie */\n mask = s->mideleg;\n s->mie = (s->mie & ~mask) | (val & mask);\n break;\n case 0x105:\n s->stvec = val & ~3;\n break;\n case 0x106:\n s->scounteren = val & COUNTEREN_MASK;\n break;\n case 0x140:\n s->sscratch = val;\n break;\n case 0x141:\n s->sepc = val & ~1;\n break;\n case 0x142:\n s->scause = val;\n break;\n case 0x143:\n s->stval = val;\n break;\n case 0x144: /* sip */\n mask = s->mideleg;\n s->mip = (s->mip & ~mask) | (val & mask);\n break;\n case 0x180:\n /* no ASID implemented */\n#if MAX_XLEN == 32\n {\n int new_mode;\n new_mode = (val >> 31) & 1;\n s->satp = (val & (((target_ulong)1 << 22) - 1)) |\n (new_mode << 31);\n }\n#else\n {\n int mode, new_mode;\n mode = s->satp >> 60;\n new_mode = (val >> 60) & 0xf;\n if (new_mode == 0 || (new_mode >= 8 && new_mode <= 9))\n mode = new_mode;\n s->satp = (val & (((uint64_t)1 << 44) - 1)) |\n ((uint64_t)mode << 60);\n }\n#endif\n tlb_flush_all(s);\n return 2;\n \n case 0x300:\n set_mstatus(s, val);\n break;\n case 0x301: /* misa */\n#if MAX_XLEN >= 64\n {\n int new_mxl;\n new_mxl = (val >> (s->cur_xlen - 2)) & 3;\n if (new_mxl >= 1 && new_mxl <= get_base_from_xlen(MAX_XLEN)) {\n /* Note: misa is only modified in M level, so cur_xlen\n = 2^(mxl + 4) */\n if (s->mxl != new_mxl) {\n s->mxl = new_mxl;\n s->cur_xlen = 1 << (new_mxl + 4);\n return 1;\n }\n }\n }\n#endif\n break;\n case 0x302:\n mask = (1 << (CAUSE_STORE_PAGE_FAULT + 1)) - 1;\n s->medeleg = (s->medeleg & ~mask) | (val & mask);\n break;\n case 0x303:\n mask = MIP_SSIP | MIP_STIP | MIP_SEIP;\n s->mideleg = (s->mideleg & ~mask) | (val & mask);\n break;\n case 0x304:\n mask = MIP_MSIP | MIP_MTIP | MIP_SSIP | MIP_STIP | MIP_SEIP;\n s->mie = (s->mie & ~mask) | (val & mask);\n break;\n case 0x305:\n s->mtvec = val & ~3;\n break;\n case 0x306:\n s->mcounteren = val & COUNTEREN_MASK;\n break;\n case 0x340:\n s->mscratch = val;\n break;\n case 0x341:\n s->mepc = val & ~1;\n break;\n case 0x342:\n s->mcause = val;\n break;\n case 0x343:\n s->mtval = val;\n break;\n case 0x344:\n mask = MIP_SSIP | MIP_STIP;\n s->mip = (s->mip & ~mask) | (val & mask);\n break;\n default:\n#ifdef DUMP_INVALID_CSR\n printf(\"csr_write: invalid CSR=0x%x\\n\", csr);\n#endif\n return -1;\n }\n return 0;\n}\n\nstatic void set_priv(RISCVCPUState *s, int priv)\n{\n if (s->priv != priv) {\n tlb_flush_all(s);\n#if MAX_XLEN >= 64\n /* change the current xlen */\n {\n int mxl;\n if (priv == PRV_S)\n mxl = (s->mstatus >> MSTATUS_SXL_SHIFT) & 3;\n else if (priv == PRV_U)\n mxl = (s->mstatus >> MSTATUS_UXL_SHIFT) & 3;\n else\n mxl = s->mxl;\n s->cur_xlen = 1 << (4 + mxl);\n }\n#endif\n s->priv = priv;\n }\n}\n\nstatic void raise_exception2(RISCVCPUState *s, uint32_t cause,\n target_ulong tval)\n{\n BOOL deleg;\n target_ulong causel;\n \n#if defined(DUMP_EXCEPTIONS) || defined(DUMP_MMU_EXCEPTIONS) || defined(DUMP_INTERRUPTS)\n {\n int flag;\n flag = 0;\n#ifdef DUMP_MMU_EXCEPTIONS\n if (cause == CAUSE_FAULT_FETCH ||\n cause == CAUSE_FAULT_LOAD ||\n cause == CAUSE_FAULT_STORE ||\n cause == CAUSE_FETCH_PAGE_FAULT ||\n cause == CAUSE_LOAD_PAGE_FAULT ||\n cause == CAUSE_STORE_PAGE_FAULT)\n flag = 1;\n#endif\n#ifdef DUMP_INTERRUPTS\n flag |= (cause & CAUSE_INTERRUPT) != 0;\n#endif\n#ifdef DUMP_EXCEPTIONS\n flag = 1;\n flag = (cause & CAUSE_INTERRUPT) == 0;\n if (cause == CAUSE_SUPERVISOR_ECALL || cause == CAUSE_ILLEGAL_INSTRUCTION)\n flag = 0;\n#endif\n if (flag) {\n log_printf(\"raise_exception: cause=0x%08x tval=0x\", cause);\n#ifdef CONFIG_LOGFILE\n fprint_target_ulong(log_file, tval);\n#else\n print_target_ulong(tval);\n#endif\n log_printf(\"\\n\");\n dump_regs(s);\n }\n }\n#endif\n\n if (s->priv <= PRV_S) {\n /* delegate the exception to the supervisor priviledge */\n if (cause & CAUSE_INTERRUPT)\n deleg = (s->mideleg >> (cause & (MAX_XLEN - 1))) & 1;\n else\n deleg = (s->medeleg >> cause) & 1;\n } else {\n deleg = 0;\n }\n \n causel = cause & 0x7fffffff;\n if (cause & CAUSE_INTERRUPT)\n causel |= (target_ulong)1 << (s->cur_xlen - 1);\n \n if (deleg) {\n s->scause = causel;\n s->sepc = s->pc;\n s->stval = tval;\n s->mstatus = (s->mstatus & ~MSTATUS_SPIE) |\n (((s->mstatus >> s->priv) & 1) << MSTATUS_SPIE_SHIFT);\n s->mstatus = (s->mstatus & ~MSTATUS_SPP) |\n (s->priv << MSTATUS_SPP_SHIFT);\n s->mstatus &= ~MSTATUS_SIE;\n set_priv(s, PRV_S);\n s->pc = s->stvec;\n } else {\n s->mcause = causel;\n s->mepc = s->pc;\n s->mtval = tval;\n s->mstatus = (s->mstatus & ~MSTATUS_MPIE) |\n (((s->mstatus >> s->priv) & 1) << MSTATUS_MPIE_SHIFT);\n s->mstatus = (s->mstatus & ~MSTATUS_MPP) |\n (s->priv << MSTATUS_MPP_SHIFT);\n s->mstatus &= ~MSTATUS_MIE;\n set_priv(s, PRV_M);\n s->pc = s->mtvec;\n }\n}\n\nstatic void raise_exception(RISCVCPUState *s, uint32_t cause)\n{\n raise_exception2(s, cause, 0);\n}\n\nstatic void handle_sret(RISCVCPUState *s)\n{\n int spp, spie;\n spp = (s->mstatus >> MSTATUS_SPP_SHIFT) & 1;\n /* set the IE state to previous IE state */\n spie = (s->mstatus >> MSTATUS_SPIE_SHIFT) & 1;\n s->mstatus = (s->mstatus & ~(1 << spp)) |\n (spie << spp);\n /* set SPIE to 1 */\n s->mstatus |= MSTATUS_SPIE;\n /* set SPP to U */\n s->mstatus &= ~MSTATUS_SPP;\n set_priv(s, spp);\n s->pc = s->sepc;\n}\n\nstatic void handle_mret(RISCVCPUState *s)\n{\n int mpp, mpie;\n mpp = (s->mstatus >> MSTATUS_MPP_SHIFT) & 3;\n /* set the IE state to previous IE state */\n mpie = (s->mstatus >> MSTATUS_MPIE_SHIFT) & 1;\n s->mstatus = (s->mstatus & ~(1 << mpp)) |\n (mpie << mpp);\n /* set MPIE to 1 */\n s->mstatus |= MSTATUS_MPIE;\n /* set MPP to U */\n s->mstatus &= ~MSTATUS_MPP;\n set_priv(s, mpp);\n s->pc = s->mepc;\n}\n\nstatic inline uint32_t get_pending_irq_mask(RISCVCPUState *s)\n{\n uint32_t pending_ints, enabled_ints;\n\n pending_ints = s->mip & s->mie;\n if (pending_ints == 0)\n return 0;\n\n enabled_ints = 0;\n switch(s->priv) {\n case PRV_M:\n if (s->mstatus & MSTATUS_MIE)\n enabled_ints = ~s->mideleg;\n break;\n case PRV_S:\n enabled_ints = ~s->mideleg;\n if (s->mstatus & MSTATUS_SIE)\n enabled_ints |= s->mideleg;\n break;\n default:\n case PRV_U:\n enabled_ints = -1;\n break;\n }\n return pending_ints & enabled_ints;\n}\n\nstatic __exception int raise_interrupt(RISCVCPUState *s)\n{\n uint32_t mask;\n int irq_num;\n\n mask = get_pending_irq_mask(s);\n if (mask == 0)\n return 0;\n irq_num = ctz32(mask);\n raise_exception(s, irq_num | CAUSE_INTERRUPT);\n return -1;\n}\n\nstatic inline int32_t sext(int32_t val, int n)\n{\n return (val << (32 - n)) >> (32 - n);\n}\n\nstatic inline uint32_t get_field1(uint32_t val, int src_pos, \n int dst_pos, int dst_pos_max)\n{\n int mask;\n assert(dst_pos_max >= dst_pos);\n mask = ((1 << (dst_pos_max - dst_pos + 1)) - 1) << dst_pos;\n if (dst_pos >= src_pos)\n return (val << (dst_pos - src_pos)) & mask;\n else\n return (val >> (src_pos - dst_pos)) & mask;\n}\n\n#define XLEN 32\n#include \"riscv_cpu_template.h\"\n\n#if MAX_XLEN >= 64\n#define XLEN 64\n#include \"riscv_cpu_template.h\"\n#endif\n\n#if MAX_XLEN >= 128\n#define XLEN 128\n#include \"riscv_cpu_template.h\"\n#endif\n\nstatic void glue(riscv_cpu_interp, MAX_XLEN)(RISCVCPUState *s, int n_cycles)\n{\n#ifdef USE_GLOBAL_STATE\n s = &riscv_cpu_global_state;\n#endif\n uint64_t timeout;\n\n timeout = s->insn_counter + n_cycles;\n while (!s->power_down_flag &&\n (int)(timeout - s->insn_counter) > 0) {\n n_cycles = timeout - s->insn_counter;\n switch(s->cur_xlen) {\n case 32:\n riscv_cpu_interp_x32(s, n_cycles);\n break;\n#if MAX_XLEN >= 64\n case 64:\n riscv_cpu_interp_x64(s, n_cycles);\n break;\n#endif\n#if MAX_XLEN >= 128\n case 128:\n riscv_cpu_interp_x128(s, n_cycles);\n break;\n#endif\n default:\n abort();\n }\n }\n}\n\n/* Note: the value is not accurate when called in riscv_cpu_interp() */\nstatic uint64_t glue(riscv_cpu_get_cycles, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->insn_counter;\n}\n\nstatic void glue(riscv_cpu_set_mip, MAX_XLEN)(RISCVCPUState *s, uint32_t mask)\n{\n s->mip |= mask;\n /* exit from power down if an interrupt is pending */\n if (s->power_down_flag && (s->mip & s->mie) != 0)\n s->power_down_flag = FALSE;\n}\n\nstatic void glue(riscv_cpu_reset_mip, MAX_XLEN)(RISCVCPUState *s, uint32_t mask)\n{\n s->mip &= ~mask;\n}\n\nstatic uint32_t glue(riscv_cpu_get_mip, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->mip;\n}\n\nstatic BOOL glue(riscv_cpu_get_power_down, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->power_down_flag;\n}\n\nstatic RISCVCPUState *glue(riscv_cpu_init, MAX_XLEN)(PhysMemoryMap *mem_map)\n{\n RISCVCPUState *s;\n \n#ifdef USE_GLOBAL_STATE\n s = &riscv_cpu_global_state;\n#else\n s = mallocz(sizeof(*s));\n#endif\n s->common.class_ptr = &glue(riscv_cpu_class, MAX_XLEN);\n s->mem_map = mem_map;\n s->pc = 0x1000;\n s->priv = PRV_M;\n s->cur_xlen = MAX_XLEN;\n s->mxl = get_base_from_xlen(MAX_XLEN);\n s->mstatus = ((uint64_t)s->mxl << MSTATUS_UXL_SHIFT) |\n ((uint64_t)s->mxl << MSTATUS_SXL_SHIFT);\n s->misa |= MCPUID_SUPER | MCPUID_USER | MCPUID_I | MCPUID_M | MCPUID_A;\n#if FLEN >= 32\n s->misa |= MCPUID_F;\n#endif\n#if FLEN >= 64\n s->misa |= MCPUID_D;\n#endif\n#if FLEN >= 128\n s->misa |= MCPUID_Q;\n#endif\n#ifdef CONFIG_EXT_C\n s->misa |= MCPUID_C;\n#endif\n tlb_init(s);\n return s;\n}\n\nstatic void glue(riscv_cpu_end, MAX_XLEN)(RISCVCPUState *s)\n{\n#ifdef USE_GLOBAL_STATE\n free(s);\n#endif\n}\n\nstatic uint32_t glue(riscv_cpu_get_misa, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->misa;\n}\n\nconst RISCVCPUClass glue(riscv_cpu_class, MAX_XLEN) = {\n glue(riscv_cpu_init, MAX_XLEN),\n glue(riscv_cpu_end, MAX_XLEN),\n glue(riscv_cpu_interp, MAX_XLEN),\n glue(riscv_cpu_get_cycles, MAX_XLEN),\n glue(riscv_cpu_set_mip, MAX_XLEN),\n glue(riscv_cpu_reset_mip, MAX_XLEN),\n glue(riscv_cpu_get_mip, MAX_XLEN),\n glue(riscv_cpu_get_power_down, MAX_XLEN),\n glue(riscv_cpu_get_misa, MAX_XLEN),\n glue(riscv_cpu_flush_tlb_write_range_ram, MAX_XLEN),\n};\n\n#if CONFIG_RISCV_MAX_XLEN == MAX_XLEN\nRISCVCPUState *riscv_cpu_init(PhysMemoryMap *mem_map, int max_xlen)\n{\n const RISCVCPUClass *c;\n switch(max_xlen) {\n /* with emscripten we compile a single CPU */\n#if defined(EMSCRIPTEN)\n case MAX_XLEN:\n c = &glue(riscv_cpu_class, MAX_XLEN);\n break;\n#else\n case 32:\n c = &riscv_cpu_class32;\n break;\n case 64:\n c = &riscv_cpu_class64;\n break;\n#if CONFIG_RISCV_MAX_XLEN == 128\n case 128:\n c = &riscv_cpu_class128;\n break;\n#endif\n#endif /* !EMSCRIPTEN */\n default:\n return NULL;\n }\n return c->riscv_cpu_init(mem_map);\n}\n#endif /* CONFIG_RISCV_MAX_XLEN == MAX_XLEN */\n\n"], ["/linuxpdf/tinyemu/simplefb.c", "/*\n * Simple frame buffer\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n//#define DEBUG_VBE\n\n#define FB_ALLOC_ALIGN 65536\n\nstruct SimpleFBState {\n FBDevice *fb_dev;\n int fb_page_count;\n PhysMemoryRange *mem_range;\n};\n\n#define MAX_MERGE_DISTANCE 3\n\nvoid simplefb_refresh(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque,\n PhysMemoryRange *mem_range,\n int fb_page_count)\n{\n const uint32_t *dirty_bits;\n uint32_t dirty_val;\n int y0, y1, page_y0, page_y1, byte_pos, page_index, bit_pos;\n\n dirty_bits = phys_mem_get_dirty_bits(mem_range);\n \n page_index = 0;\n y0 = y1 = 0;\n while (page_index < fb_page_count) {\n dirty_val = dirty_bits[page_index >> 5];\n if (dirty_val != 0) {\n bit_pos = 0;\n while (dirty_val != 0) {\n while (((dirty_val >> bit_pos) & 1) == 0)\n bit_pos++;\n dirty_val &= ~(1 << bit_pos);\n\n byte_pos = (page_index + bit_pos) * DEVRAM_PAGE_SIZE;\n page_y0 = byte_pos / fb_dev->stride;\n page_y1 = ((byte_pos + DEVRAM_PAGE_SIZE - 1) / fb_dev->stride) + 1;\n page_y1 = min_int(page_y1, fb_dev->height);\n if (y0 == y1) {\n y0 = page_y0;\n y1 = page_y1;\n } else if (page_y0 <= (y1 + MAX_MERGE_DISTANCE)) {\n /* union with current region */\n y1 = page_y1;\n } else {\n /* flush */\n redraw_func(fb_dev, opaque,\n 0, y0, fb_dev->width, y1 - y0);\n y0 = page_y0;\n y1 = page_y1;\n }\n }\n }\n page_index += 32;\n }\n\n if (y0 != y1) {\n redraw_func(fb_dev, opaque,\n 0, y0, fb_dev->width, y1 - y0);\n }\n}\n\nstatic void simplefb_refresh1(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n SimpleFBState *s = fb_dev->device_opaque;\n simplefb_refresh(fb_dev, redraw_func, opaque, s->mem_range,\n s->fb_page_count);\n}\n\nSimpleFBState *simplefb_init(PhysMemoryMap *map, uint64_t phys_addr,\n FBDevice *fb_dev, int width, int height)\n{\n SimpleFBState *s;\n \n s = mallocz(sizeof(*s));\n s->fb_dev = fb_dev;\n\n fb_dev->width = width;\n fb_dev->height = height;\n fb_dev->stride = width * 4;\n fb_dev->fb_size = (height * fb_dev->stride + FB_ALLOC_ALIGN - 1) & ~(FB_ALLOC_ALIGN - 1);\n s->fb_page_count = fb_dev->fb_size >> DEVRAM_PAGE_SIZE_LOG2;\n\n s->mem_range = cpu_register_ram(map, phys_addr, fb_dev->fb_size,\n DEVRAM_FLAG_DIRTY_BITS);\n \n fb_dev->fb_data = s->mem_range->phys_mem;\n fb_dev->device_opaque = s;\n fb_dev->refresh = simplefb_refresh1;\n return s;\n}\n"], ["/linuxpdf/tinyemu/vga.c", "/*\n * Dummy VGA device\n * \n * Copyright (c) 2003-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n//#define DEBUG_VBE\n\n#define MSR_COLOR_EMULATION 0x01\n#define MSR_PAGE_SELECT 0x20\n\n#define ST01_V_RETRACE 0x08\n#define ST01_DISP_ENABLE 0x01\n\n#define VBE_DISPI_INDEX_ID 0x0\n#define VBE_DISPI_INDEX_XRES 0x1\n#define VBE_DISPI_INDEX_YRES 0x2\n#define VBE_DISPI_INDEX_BPP 0x3\n#define VBE_DISPI_INDEX_ENABLE 0x4\n#define VBE_DISPI_INDEX_BANK 0x5\n#define VBE_DISPI_INDEX_VIRT_WIDTH 0x6\n#define VBE_DISPI_INDEX_VIRT_HEIGHT 0x7\n#define VBE_DISPI_INDEX_X_OFFSET 0x8\n#define VBE_DISPI_INDEX_Y_OFFSET 0x9\n#define VBE_DISPI_INDEX_VIDEO_MEMORY_64K 0xa\n#define VBE_DISPI_INDEX_NB 0xb\n\n#define VBE_DISPI_ID0 0xB0C0\n#define VBE_DISPI_ID1 0xB0C1\n#define VBE_DISPI_ID2 0xB0C2\n#define VBE_DISPI_ID3 0xB0C3\n#define VBE_DISPI_ID4 0xB0C4\n#define VBE_DISPI_ID5 0xB0C5\n\n#define VBE_DISPI_DISABLED 0x00\n#define VBE_DISPI_ENABLED 0x01\n#define VBE_DISPI_GETCAPS 0x02\n#define VBE_DISPI_8BIT_DAC 0x20\n#define VBE_DISPI_LFB_ENABLED 0x40\n#define VBE_DISPI_NOCLEARMEM 0x80\n\n#define FB_ALLOC_ALIGN (1 << 20)\n\n#define MAX_TEXT_WIDTH 132\n#define MAX_TEXT_HEIGHT 60\n\nstruct VGAState {\n FBDevice *fb_dev;\n int fb_page_count;\n PhysMemoryRange *mem_range;\n PhysMemoryRange *mem_range2;\n PCIDevice *pci_dev;\n PhysMemoryRange *rom_range;\n\n uint8_t *vga_ram; /* 128K at 0xa0000 */\n \n uint8_t sr_index;\n uint8_t sr[8];\n uint8_t gr_index;\n uint8_t gr[16];\n uint8_t ar_index;\n uint8_t ar[21];\n int ar_flip_flop;\n uint8_t cr_index;\n uint8_t cr[256]; /* CRT registers */\n uint8_t msr; /* Misc Output Register */\n uint8_t fcr; /* Feature Control Register */\n uint8_t st00; /* status 0 */\n uint8_t st01; /* status 1 */\n uint8_t dac_state;\n uint8_t dac_sub_index;\n uint8_t dac_read_index;\n uint8_t dac_write_index;\n uint8_t dac_cache[3]; /* used when writing */\n uint8_t palette[768];\n \n /* text mode state */\n uint32_t last_palette[16];\n uint16_t last_ch_attr[MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT];\n uint32_t last_width;\n uint32_t last_height;\n uint16_t last_line_offset;\n uint16_t last_start_addr;\n uint16_t last_cursor_offset;\n uint8_t last_cursor_start;\n uint8_t last_cursor_end;\n \n /* VBE extension */\n uint16_t vbe_index;\n uint16_t vbe_regs[VBE_DISPI_INDEX_NB];\n};\n\nstatic void vga_draw_glyph8(uint8_t *d, int linesize,\n const uint8_t *font_ptr, int h,\n uint32_t fgcol, uint32_t bgcol)\n{\n uint32_t font_data, xorcol;\n\n xorcol = bgcol ^ fgcol;\n do {\n font_data = font_ptr[0];\n ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol;\n ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[7] = (-((font_data >> 0) & 1) & xorcol) ^ bgcol;\n font_ptr++;\n d += linesize;\n } while (--h);\n}\n\nstatic void vga_draw_glyph9(uint8_t *d, int linesize,\n const uint8_t *font_ptr, int h,\n uint32_t fgcol, uint32_t bgcol,\n int dup9)\n{\n uint32_t font_data, xorcol, v;\n\n xorcol = bgcol ^ fgcol;\n do {\n font_data = font_ptr[0];\n ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol;\n ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol;\n v = (-((font_data >> 0) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[7] = v;\n if (dup9)\n ((uint32_t *)d)[8] = v;\n else\n ((uint32_t *)d)[8] = bgcol;\n font_ptr++;\n d += linesize;\n } while (--h);\n}\n\nstatic const uint8_t cursor_glyph[32] = {\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n};\n\nstatic inline int c6_to_8(int v)\n{\n int b;\n v &= 0x3f;\n b = v & 1;\n return (v << 2) | (b << 1) | b;\n}\n\nstatic int update_palette16(VGAState *s, uint32_t *palette)\n{\n int full_update, i;\n uint32_t v, col;\n\n full_update = 0;\n for(i = 0; i < 16; i++) {\n v = s->ar[i];\n if (s->ar[0x10] & 0x80)\n v = ((s->ar[0x14] & 0xf) << 4) | (v & 0xf);\n else\n v = ((s->ar[0x14] & 0xc) << 4) | (v & 0x3f);\n v = v * 3;\n col = (c6_to_8(s->palette[v]) << 16) |\n (c6_to_8(s->palette[v + 1]) << 8) |\n c6_to_8(s->palette[v + 2]);\n if (col != palette[i]) {\n full_update = 1;\n palette[i] = col;\n }\n }\n return full_update;\n}\n\n/* the text refresh is just for debugging and initial boot message, so\n it is very incomplete */\nstatic void vga_text_refresh(VGAState *s,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n FBDevice *fb_dev = s->fb_dev;\n int width, height, cwidth, cheight, cy, cx, x1, y1, width1, height1;\n int cx_min, cx_max, dup9;\n uint32_t ch_attr, line_offset, start_addr, ch_addr, ch_addr1, ch, cattr;\n uint8_t *vga_ram, *font_ptr, *dst;\n uint32_t fgcol, bgcol, cursor_offset, cursor_start, cursor_end;\n BOOL full_update;\n\n full_update = update_palette16(s, s->last_palette);\n\n vga_ram = s->vga_ram;\n \n line_offset = s->cr[0x13];\n line_offset <<= 3;\n line_offset >>= 1;\n\n start_addr = s->cr[0x0d] | (s->cr[0x0c] << 8);\n \n cheight = (s->cr[9] & 0x1f) + 1;\n cwidth = 8;\n if (!(s->sr[1] & 0x01))\n cwidth++;\n \n width = (s->cr[0x01] + 1);\n height = s->cr[0x12] |\n ((s->cr[0x07] & 0x02) << 7) |\n ((s->cr[0x07] & 0x40) << 3);\n height = (height + 1) / cheight;\n \n width1 = width * cwidth;\n height1 = height * cheight;\n if (fb_dev->width < width1 || fb_dev->height < height1 ||\n width > MAX_TEXT_WIDTH || height > MAX_TEXT_HEIGHT)\n return; /* not enough space */\n if (s->last_line_offset != line_offset ||\n s->last_start_addr != start_addr ||\n s->last_width != width ||\n s->last_height != height) {\n s->last_line_offset = line_offset;\n s->last_start_addr = start_addr;\n s->last_width = width;\n s->last_height = height;\n full_update = TRUE;\n }\n \n /* update cursor position */\n cursor_offset = ((s->cr[0x0e] << 8) | s->cr[0x0f]) - start_addr;\n cursor_start = s->cr[0xa];\n cursor_end = s->cr[0xb];\n if (cursor_offset != s->last_cursor_offset ||\n cursor_start != s->last_cursor_start ||\n cursor_end != s->last_cursor_end) {\n /* force refresh of characters with the cursor */\n if (s->last_cursor_offset < MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT)\n s->last_ch_attr[s->last_cursor_offset] = -1;\n if (cursor_offset < MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT)\n s->last_ch_attr[cursor_offset] = -1;\n s->last_cursor_offset = cursor_offset;\n s->last_cursor_start = cursor_start;\n s->last_cursor_end = cursor_end;\n }\n\n ch_addr1 = 0x18000 + (start_addr * 2);\n cursor_offset = 0x18000 + (start_addr + cursor_offset) * 2;\n \n x1 = (fb_dev->width - width1) / 2;\n y1 = (fb_dev->height - height1) / 2;\n#if 0\n printf(\"text refresh %dx%d font=%dx%d start_addr=0x%x line_offset=0x%x\\n\",\n width, height, cwidth, cheight, start_addr, line_offset);\n#endif\n for(cy = 0; cy < height; cy++) {\n ch_addr = ch_addr1;\n dst = fb_dev->fb_data + (y1 + cy * cheight) * fb_dev->stride + x1 * 4;\n cx_min = width;\n cx_max = -1;\n for(cx = 0; cx < width; cx++) {\n ch_attr = *(uint16_t *)(vga_ram + (ch_addr & 0x1fffe));\n if (full_update || ch_attr != s->last_ch_attr[cy * width + cx]) {\n s->last_ch_attr[cy * width + cx] = ch_attr;\n cx_min = min_int(cx_min, cx);\n cx_max = max_int(cx_max, cx);\n ch = ch_attr & 0xff;\n cattr = ch_attr >> 8;\n font_ptr = vga_ram + 32 * ch;\n bgcol = s->last_palette[cattr >> 4];\n fgcol = s->last_palette[cattr & 0x0f];\n if (cwidth == 8) {\n vga_draw_glyph8(dst, fb_dev->stride, font_ptr, cheight,\n fgcol, bgcol);\n } else {\n dup9 = 0;\n if (ch >= 0xb0 && ch <= 0xdf && (s->ar[0x10] & 0x04))\n dup9 = 1;\n vga_draw_glyph9(dst, fb_dev->stride, font_ptr, cheight,\n fgcol, bgcol, dup9);\n }\n /* cursor display */\n if (cursor_offset == ch_addr && !(cursor_start & 0x20)) {\n int line_start, line_last, h;\n uint8_t *dst1;\n line_start = cursor_start & 0x1f;\n line_last = min_int(cursor_end & 0x1f, cheight - 1);\n\n if (line_last >= line_start && line_start < cheight) {\n h = line_last - line_start + 1;\n dst1 = dst + fb_dev->stride * line_start;\n if (cwidth == 8) {\n vga_draw_glyph8(dst1, fb_dev->stride,\n cursor_glyph,\n h, fgcol, bgcol);\n } else {\n vga_draw_glyph9(dst1, fb_dev->stride,\n cursor_glyph,\n h, fgcol, bgcol, 1);\n }\n }\n }\n }\n ch_addr += 2;\n dst += 4 * cwidth;\n }\n if (cx_max >= cx_min) {\n // printf(\"redraw %d %d %d\\n\", cy, cx_min, cx_max);\n redraw_func(fb_dev, opaque,\n x1 + cx_min * cwidth, y1 + cy * cheight,\n (cx_max - cx_min + 1) * cwidth, cheight);\n }\n ch_addr1 += line_offset;\n }\n}\n\nstatic void vga_refresh(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n VGAState *s = fb_dev->device_opaque;\n\n if (!(s->ar_index & 0x20)) {\n /* blank */\n } else if (s->gr[0x06] & 1) {\n /* graphic mode (VBE) */\n simplefb_refresh(fb_dev, redraw_func, opaque, s->mem_range, s->fb_page_count);\n } else {\n /* text mode */\n vga_text_refresh(s, redraw_func, opaque);\n }\n}\n\n/* force some bits to zero */\nstatic const uint8_t sr_mask[8] = {\n (uint8_t)~0xfc,\n (uint8_t)~0xc2,\n (uint8_t)~0xf0,\n (uint8_t)~0xc0,\n (uint8_t)~0xf1,\n (uint8_t)~0xff,\n (uint8_t)~0xff,\n (uint8_t)~0x00,\n};\n\nstatic const uint8_t gr_mask[16] = {\n (uint8_t)~0xf0, /* 0x00 */\n (uint8_t)~0xf0, /* 0x01 */\n (uint8_t)~0xf0, /* 0x02 */\n (uint8_t)~0xe0, /* 0x03 */\n (uint8_t)~0xfc, /* 0x04 */\n (uint8_t)~0x84, /* 0x05 */\n (uint8_t)~0xf0, /* 0x06 */\n (uint8_t)~0xf0, /* 0x07 */\n (uint8_t)~0x00, /* 0x08 */\n (uint8_t)~0xff, /* 0x09 */\n (uint8_t)~0xff, /* 0x0a */\n (uint8_t)~0xff, /* 0x0b */\n (uint8_t)~0xff, /* 0x0c */\n (uint8_t)~0xff, /* 0x0d */\n (uint8_t)~0xff, /* 0x0e */\n (uint8_t)~0xff, /* 0x0f */\n};\n\nstatic uint32_t vga_ioport_read(VGAState *s, uint32_t addr)\n{\n int val, index;\n\n /* check port range access depending on color/monochrome mode */\n if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION)) ||\n (addr >= 0x3d0 && addr <= 0x3df && !(s->msr & MSR_COLOR_EMULATION))) {\n val = 0xff;\n } else {\n switch(addr) {\n case 0x3c0:\n if (s->ar_flip_flop == 0) {\n val = s->ar_index;\n } else {\n val = 0;\n }\n break;\n case 0x3c1:\n index = s->ar_index & 0x1f;\n if (index < 21)\n val = s->ar[index];\n else\n val = 0;\n break;\n case 0x3c2:\n val = s->st00;\n break;\n case 0x3c4:\n val = s->sr_index;\n break;\n case 0x3c5:\n val = s->sr[s->sr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n break;\n case 0x3c7:\n val = s->dac_state;\n break;\n\tcase 0x3c8:\n\t val = s->dac_write_index;\n\t break;\n case 0x3c9:\n val = s->palette[s->dac_read_index * 3 + s->dac_sub_index];\n if (++s->dac_sub_index == 3) {\n s->dac_sub_index = 0;\n s->dac_read_index++;\n }\n break;\n case 0x3ca:\n val = s->fcr;\n break;\n case 0x3cc:\n val = s->msr;\n break;\n case 0x3ce:\n val = s->gr_index;\n break;\n case 0x3cf:\n val = s->gr[s->gr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n break;\n case 0x3b4:\n case 0x3d4:\n val = s->cr_index;\n break;\n case 0x3b5:\n case 0x3d5:\n val = s->cr[s->cr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n break;\n case 0x3ba:\n case 0x3da:\n /* just toggle to fool polling */\n s->st01 ^= ST01_V_RETRACE | ST01_DISP_ENABLE;\n val = s->st01;\n s->ar_flip_flop = 0;\n break;\n default:\n val = 0x00;\n break;\n }\n }\n#if defined(DEBUG_VGA)\n printf(\"VGA: read addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n return val;\n}\n\nstatic void vga_ioport_write(VGAState *s, uint32_t addr, uint32_t val)\n{\n int index;\n\n /* check port range access depending on color/monochrome mode */\n if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION)) ||\n (addr >= 0x3d0 && addr <= 0x3df && !(s->msr & MSR_COLOR_EMULATION)))\n return;\n\n#ifdef DEBUG_VGA\n printf(\"VGA: write addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n\n switch(addr) {\n case 0x3c0:\n if (s->ar_flip_flop == 0) {\n val &= 0x3f;\n s->ar_index = val;\n } else {\n index = s->ar_index & 0x1f;\n switch(index) {\n case 0x00 ... 0x0f:\n s->ar[index] = val & 0x3f;\n break;\n case 0x10:\n s->ar[index] = val & ~0x10;\n break;\n case 0x11:\n s->ar[index] = val;\n break;\n case 0x12:\n s->ar[index] = val & ~0xc0;\n break;\n case 0x13:\n s->ar[index] = val & ~0xf0;\n break;\n case 0x14:\n s->ar[index] = val & ~0xf0;\n break;\n default:\n break;\n }\n }\n s->ar_flip_flop ^= 1;\n break;\n case 0x3c2:\n s->msr = val & ~0x10;\n break;\n case 0x3c4:\n s->sr_index = val & 7;\n break;\n case 0x3c5:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n s->sr[s->sr_index] = val & sr_mask[s->sr_index];\n break;\n case 0x3c7:\n s->dac_read_index = val;\n s->dac_sub_index = 0;\n s->dac_state = 3;\n break;\n case 0x3c8:\n s->dac_write_index = val;\n s->dac_sub_index = 0;\n s->dac_state = 0;\n break;\n case 0x3c9:\n s->dac_cache[s->dac_sub_index] = val;\n if (++s->dac_sub_index == 3) {\n memcpy(&s->palette[s->dac_write_index * 3], s->dac_cache, 3);\n s->dac_sub_index = 0;\n s->dac_write_index++;\n }\n break;\n case 0x3ce:\n s->gr_index = val & 0x0f;\n break;\n case 0x3cf:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n s->gr[s->gr_index] = val & gr_mask[s->gr_index];\n break;\n case 0x3b4:\n case 0x3d4:\n s->cr_index = val;\n break;\n case 0x3b5:\n case 0x3d5:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n /* handle CR0-7 protection */\n if ((s->cr[0x11] & 0x80) && s->cr_index <= 7) {\n /* can always write bit 4 of CR7 */\n if (s->cr_index == 7)\n s->cr[7] = (s->cr[7] & ~0x10) | (val & 0x10);\n return;\n }\n switch(s->cr_index) {\n case 0x01: /* horizontal display end */\n case 0x07:\n case 0x09:\n case 0x0c:\n case 0x0d:\n case 0x12: /* vertical display end */\n s->cr[s->cr_index] = val;\n break;\n default:\n s->cr[s->cr_index] = val;\n break;\n }\n break;\n case 0x3ba:\n case 0x3da:\n s->fcr = val & 0x10;\n break;\n }\n}\n\n#define VGA_IO(base) \\\nstatic uint32_t vga_read_ ## base(void *opaque, uint32_t addr, int size_log2)\\\n{\\\n return vga_ioport_read(opaque, base + addr);\\\n}\\\nstatic void vga_write_ ## base(void *opaque, uint32_t addr, uint32_t val, int size_log2)\\\n{\\\n return vga_ioport_write(opaque, base + addr, val);\\\n}\n\nVGA_IO(0x3c0)\nVGA_IO(0x3b4)\nVGA_IO(0x3d4)\nVGA_IO(0x3ba)\nVGA_IO(0x3da)\n\nstatic void vbe_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n VGAState *s = opaque;\n FBDevice *fb_dev = s->fb_dev;\n \n if (offset == 0) {\n s->vbe_index = val;\n } else {\n#ifdef DEBUG_VBE\n printf(\"VBE write: index=0x%04x val=0x%04x\\n\", s->vbe_index, val);\n#endif\n switch(s->vbe_index) {\n case VBE_DISPI_INDEX_ID:\n if (val >= VBE_DISPI_ID0 && val <= VBE_DISPI_ID5)\n s->vbe_regs[s->vbe_index] = val;\n break;\n case VBE_DISPI_INDEX_ENABLE:\n if ((val & VBE_DISPI_ENABLED) &&\n !(s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED)) {\n /* set graphic mode */\n /* XXX: resolution change not really supported */\n if (s->vbe_regs[VBE_DISPI_INDEX_XRES] <= 4096 &&\n s->vbe_regs[VBE_DISPI_INDEX_YRES] <= 4096 &&\n (s->vbe_regs[VBE_DISPI_INDEX_XRES] * 4 *\n s->vbe_regs[VBE_DISPI_INDEX_YRES]) <= fb_dev->fb_size) {\n fb_dev->width = s->vbe_regs[VBE_DISPI_INDEX_XRES];\n fb_dev->height = s->vbe_regs[VBE_DISPI_INDEX_YRES];\n fb_dev->stride = fb_dev->width * 4;\n }\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] =\n s->vbe_regs[VBE_DISPI_INDEX_XRES];\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_HEIGHT] =\n s->vbe_regs[VBE_DISPI_INDEX_YRES];\n s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET] = 0;\n s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET] = 0;\n }\n s->vbe_regs[s->vbe_index] = val;\n break;\n case VBE_DISPI_INDEX_XRES:\n case VBE_DISPI_INDEX_YRES:\n case VBE_DISPI_INDEX_BPP:\n case VBE_DISPI_INDEX_BANK:\n case VBE_DISPI_INDEX_VIRT_WIDTH:\n case VBE_DISPI_INDEX_VIRT_HEIGHT:\n case VBE_DISPI_INDEX_X_OFFSET:\n case VBE_DISPI_INDEX_Y_OFFSET:\n s->vbe_regs[s->vbe_index] = val;\n break;\n }\n }\n}\n\nstatic uint32_t vbe_read(void *opaque, uint32_t offset, int size_log2)\n{\n VGAState *s = opaque;\n uint32_t val;\n\n if (offset == 0) {\n val = s->vbe_index;\n } else {\n if (s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_GETCAPS) {\n switch(s->vbe_index) {\n case VBE_DISPI_INDEX_XRES:\n val = s->fb_dev->width;\n break;\n case VBE_DISPI_INDEX_YRES:\n val = s->fb_dev->height;\n break;\n case VBE_DISPI_INDEX_BPP:\n val = 32;\n break;\n default:\n goto read_reg;\n }\n } else {\n read_reg:\n if (s->vbe_index < VBE_DISPI_INDEX_NB)\n val = s->vbe_regs[s->vbe_index];\n else\n val = 0;\n }\n#ifdef DEBUG_VBE\n printf(\"VBE read: index=0x%04x val=0x%04x\\n\", s->vbe_index, val);\n#endif\n }\n return val;\n}\n\n\nstatic void simplefb_bar_set(void *opaque, int bar_num,\n uint32_t addr, BOOL enabled)\n{\n VGAState *s = opaque;\n if (bar_num == 0)\n phys_mem_set_addr(s->mem_range, addr, enabled);\n else\n phys_mem_set_addr(s->rom_range, addr, enabled);\n}\n\nVGAState *pci_vga_init(PCIBus *bus, FBDevice *fb_dev,\n int width, int height,\n const uint8_t *vga_rom_buf, int vga_rom_size)\n{\n VGAState *s;\n PCIDevice *d;\n uint32_t bar_size;\n PhysMemoryMap *mem_map, *port_map;\n \n d = pci_register_device(bus, \"VGA\", -1, 0x1234, 0x1111, 0x00, 0x0300);\n \n mem_map = pci_device_get_mem_map(d);\n port_map = pci_device_get_port_map(d);\n\n s = mallocz(sizeof(*s));\n s->fb_dev = fb_dev;\n \n fb_dev->width = width;\n fb_dev->height = height;\n fb_dev->stride = width * 4;\n\n fb_dev->fb_size = (height * fb_dev->stride + FB_ALLOC_ALIGN - 1) & ~(FB_ALLOC_ALIGN - 1);\n s->fb_page_count = fb_dev->fb_size >> DEVRAM_PAGE_SIZE_LOG2;\n\n s->mem_range =\n cpu_register_ram(mem_map, 0, fb_dev->fb_size,\n DEVRAM_FLAG_DIRTY_BITS | DEVRAM_FLAG_DISABLED);\n \n fb_dev->fb_data = s->mem_range->phys_mem;\n\n s->pci_dev = d;\n bar_size = 1;\n while (bar_size < fb_dev->fb_size)\n bar_size <<= 1;\n pci_register_bar(d, 0, bar_size, PCI_ADDRESS_SPACE_MEM, s,\n simplefb_bar_set);\n\n if (vga_rom_size > 0) {\n int rom_size;\n /* align to page size */\n rom_size = (vga_rom_size + DEVRAM_PAGE_SIZE - 1) & ~(DEVRAM_PAGE_SIZE - 1);\n s->rom_range = cpu_register_ram(mem_map, 0, rom_size,\n DEVRAM_FLAG_ROM | DEVRAM_FLAG_DISABLED);\n memcpy(s->rom_range->phys_mem, vga_rom_buf, vga_rom_size);\n\n bar_size = 1;\n while (bar_size < rom_size)\n bar_size <<= 1;\n pci_register_bar(d, PCI_ROM_SLOT, bar_size, PCI_ADDRESS_SPACE_MEM, s,\n simplefb_bar_set);\n }\n\n /* VGA memory (for simple text mode no need for callbacks) */\n s->mem_range2 = cpu_register_ram(mem_map, 0xa0000, 0x20000, 0);\n s->vga_ram = s->mem_range2->phys_mem;\n \n /* standard VGA ports */\n \n cpu_register_device(port_map, 0x3c0, 16, s, vga_read_0x3c0, vga_write_0x3c0,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3b4, 2, s, vga_read_0x3b4, vga_write_0x3b4,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3d4, 2, s, vga_read_0x3d4, vga_write_0x3d4,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3ba, 1, s, vga_read_0x3ba, vga_write_0x3ba,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3da, 1, s, vga_read_0x3da, vga_write_0x3da,\n DEVIO_SIZE8);\n \n /* VBE extension */\n cpu_register_device(port_map, 0x1ce, 2, s, vbe_read, vbe_write, \n DEVIO_SIZE16);\n \n s->vbe_regs[VBE_DISPI_INDEX_ID] = VBE_DISPI_ID5;\n s->vbe_regs[VBE_DISPI_INDEX_VIDEO_MEMORY_64K] = fb_dev->fb_size >> 16;\n\n fb_dev->device_opaque = s;\n fb_dev->refresh = vga_refresh;\n return s;\n}\n"], ["/linuxpdf/tinyemu/pci.c", "/*\n * Simple PCI bus driver\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"pci.h\"\n\n//#define DEBUG_CONFIG\n\ntypedef struct {\n uint32_t size; /* 0 means no mapping defined */\n uint8_t type;\n uint8_t enabled; /* true if mapping is enabled */\n void *opaque;\n PCIBarSetFunc *bar_set;\n} PCIIORegion;\n\nstruct PCIDevice {\n PCIBus *bus;\n uint8_t devfn;\n IRQSignal irq[4];\n uint8_t config[256];\n uint8_t next_cap_offset; /* offset of the next capability */\n char *name; /* for debug only */\n PCIIORegion io_regions[PCI_NUM_REGIONS];\n};\n\nstruct PCIBus {\n int bus_num;\n PCIDevice *device[256];\n PhysMemoryMap *mem_map;\n PhysMemoryMap *port_map;\n uint32_t irq_state[4][8]; /* one bit per device */\n IRQSignal irq[4];\n};\n\nstatic int bus_map_irq(PCIDevice *d, int irq_num)\n{\n int slot_addend;\n slot_addend = (d->devfn >> 3) - 1;\n return (irq_num + slot_addend) & 3;\n}\n\nstatic void pci_device_set_irq(void *opaque, int irq_num, int level)\n{\n PCIDevice *d = opaque;\n PCIBus *b = d->bus;\n uint32_t mask;\n int i, irq_level;\n \n // printf(\"%s: pci_device_seq_irq: %d %d\\n\", d->name, irq_num, level);\n irq_num = bus_map_irq(d, irq_num);\n mask = 1 << (d->devfn & 0x1f);\n if (level)\n b->irq_state[irq_num][d->devfn >> 5] |= mask;\n else\n b->irq_state[irq_num][d->devfn >> 5] &= ~mask;\n\n /* compute the IRQ state */\n mask = 0;\n for(i = 0; i < 8; i++)\n mask |= b->irq_state[irq_num][i];\n irq_level = (mask != 0);\n set_irq(&b->irq[irq_num], irq_level);\n}\n\nstatic int devfn_alloc(PCIBus *b)\n{\n int devfn;\n for(devfn = 0; devfn < 256; devfn += 8) {\n if (!b->device[devfn])\n return devfn;\n }\n return -1;\n}\n\n/* devfn < 0 means to allocate it */\nPCIDevice *pci_register_device(PCIBus *b, const char *name, int devfn,\n uint16_t vendor_id, uint16_t device_id,\n uint8_t revision, uint16_t class_id)\n{\n PCIDevice *d;\n int i;\n \n if (devfn < 0) {\n devfn = devfn_alloc(b);\n if (devfn < 0)\n return NULL;\n }\n if (b->device[devfn])\n return NULL;\n\n d = mallocz(sizeof(PCIDevice));\n d->bus = b;\n d->name = strdup(name);\n d->devfn = devfn;\n\n put_le16(d->config + 0x00, vendor_id);\n put_le16(d->config + 0x02, device_id);\n d->config[0x08] = revision;\n put_le16(d->config + 0x0a, class_id);\n d->config[0x0e] = 0x00; /* header type */\n d->next_cap_offset = 0x40;\n \n for(i = 0; i < 4; i++)\n irq_init(&d->irq[i], pci_device_set_irq, d, i);\n b->device[devfn] = d;\n\n return d;\n}\n\nIRQSignal *pci_device_get_irq(PCIDevice *d, unsigned int irq_num)\n{\n assert(irq_num < 4);\n return &d->irq[irq_num];\n}\n\nstatic uint32_t pci_device_config_read(PCIDevice *d, uint32_t addr,\n int size_log2)\n{\n uint32_t val;\n switch(size_log2) {\n case 0:\n val = *(uint8_t *)(d->config + addr);\n break;\n case 1:\n /* Note: may be unaligned */\n if (addr <= 0xfe)\n val = get_le16(d->config + addr);\n else\n val = *(uint8_t *)(d->config + addr);\n break;\n case 2:\n /* always aligned */\n val = get_le32(d->config + addr);\n break;\n default:\n abort();\n }\n#ifdef DEBUG_CONFIG\n printf(\"pci_config_read: dev=%s addr=0x%02x val=0x%x s=%d\\n\",\n d->name, addr, val, 1 << size_log2);\n#endif\n return val;\n}\n\nPhysMemoryMap *pci_device_get_mem_map(PCIDevice *d)\n{\n return d->bus->mem_map;\n}\n\nPhysMemoryMap *pci_device_get_port_map(PCIDevice *d)\n{\n return d->bus->port_map;\n}\n\nvoid pci_register_bar(PCIDevice *d, unsigned int bar_num,\n uint32_t size, int type,\n void *opaque, PCIBarSetFunc *bar_set)\n{\n PCIIORegion *r;\n uint32_t val, config_addr;\n \n assert(bar_num < PCI_NUM_REGIONS);\n assert((size & (size - 1)) == 0); /* power of two */\n assert(size >= 4);\n r = &d->io_regions[bar_num];\n assert(r->size == 0);\n r->size = size;\n r->type = type;\n r->enabled = FALSE;\n r->opaque = opaque;\n r->bar_set = bar_set;\n /* set the config value */\n val = 0;\n if (bar_num == PCI_ROM_SLOT) {\n config_addr = 0x30;\n } else {\n val |= r->type;\n config_addr = 0x10 + 4 * bar_num;\n }\n put_le32(&d->config[config_addr], val);\n}\n\nstatic void pci_update_mappings(PCIDevice *d)\n{\n int cmd, i, offset;\n uint32_t new_addr;\n BOOL new_enabled;\n PCIIORegion *r;\n \n cmd = get_le16(&d->config[PCI_COMMAND]);\n\n for(i = 0; i < PCI_NUM_REGIONS; i++) {\n r = &d->io_regions[i];\n if (i == PCI_ROM_SLOT) {\n offset = 0x30;\n } else {\n offset = 0x10 + i * 4;\n }\n new_addr = get_le32(&d->config[offset]);\n new_enabled = FALSE;\n if (r->size != 0) {\n if ((r->type & PCI_ADDRESS_SPACE_IO) &&\n (cmd & PCI_COMMAND_IO)) {\n new_enabled = TRUE;\n } else {\n if (cmd & PCI_COMMAND_MEMORY) {\n if (i == PCI_ROM_SLOT) {\n new_enabled = (new_addr & 1);\n } else {\n new_enabled = TRUE;\n }\n }\n }\n }\n if (new_enabled) {\n /* new address */\n new_addr = get_le32(&d->config[offset]) & ~(r->size - 1);\n r->bar_set(r->opaque, i, new_addr, TRUE);\n r->enabled = TRUE;\n } else if (r->enabled) {\n r->bar_set(r->opaque, i, 0, FALSE);\n r->enabled = FALSE;\n }\n }\n}\n\n/* return != 0 if write is not handled */\nstatic int pci_write_bar(PCIDevice *d, uint32_t addr,\n uint32_t val)\n{\n PCIIORegion *r;\n int reg;\n \n if (addr == 0x30)\n reg = PCI_ROM_SLOT;\n else\n reg = (addr - 0x10) >> 2;\n // printf(\"%s: write bar addr=%x data=%x\\n\", d->name, addr, val);\n r = &d->io_regions[reg];\n if (r->size == 0)\n return -1;\n if (reg == PCI_ROM_SLOT) {\n val = val & ((~(r->size - 1)) | 1);\n } else {\n val = (val & ~(r->size - 1)) | r->type;\n }\n put_le32(d->config + addr, val);\n pci_update_mappings(d);\n return 0;\n}\n\nstatic void pci_device_config_write8(PCIDevice *d, uint32_t addr,\n uint32_t data)\n{\n int can_write;\n\n if (addr == PCI_STATUS || addr == (PCI_STATUS + 1)) {\n /* write 1 reset bits */\n d->config[addr] &= ~data;\n return;\n }\n \n switch(d->config[0x0e]) {\n case 0x00:\n case 0x80:\n switch(addr) {\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x08:\n case 0x09:\n case 0x0a:\n case 0x0b:\n case 0x0e:\n case 0x10 ... 0x27: /* base */\n case 0x30 ... 0x33: /* rom */\n case 0x3d:\n can_write = 0;\n break;\n default:\n can_write = 1;\n break;\n }\n break;\n default:\n case 0x01:\n switch(addr) {\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x08:\n case 0x09:\n case 0x0a:\n case 0x0b:\n case 0x0e:\n case 0x38 ... 0x3b: /* rom */\n case 0x3d:\n can_write = 0;\n break;\n default:\n can_write = 1;\n break;\n }\n break;\n }\n if (can_write)\n d->config[addr] = data;\n}\n \n\nstatic void pci_device_config_write(PCIDevice *d, uint32_t addr,\n uint32_t data, int size_log2)\n{\n int size, i;\n uint32_t addr1;\n \n#ifdef DEBUG_CONFIG\n printf(\"pci_config_write: dev=%s addr=0x%02x val=0x%x s=%d\\n\",\n d->name, addr, data, 1 << size_log2);\n#endif\n if (size_log2 == 2 &&\n ((addr >= 0x10 && addr < 0x10 + 4 * 6) ||\n addr == 0x30)) {\n if (pci_write_bar(d, addr, data) == 0)\n return;\n }\n size = 1 << size_log2;\n for(i = 0; i < size; i++) {\n addr1 = addr + i;\n if (addr1 <= 0xff) {\n pci_device_config_write8(d, addr1, (data >> (i * 8)) & 0xff);\n }\n }\n if (PCI_COMMAND >= addr && PCI_COMMAND < addr + size) {\n pci_update_mappings(d);\n }\n}\n\n\nstatic void pci_data_write(PCIBus *s, uint32_t addr,\n uint32_t data, int size_log2)\n{\n PCIDevice *d;\n int bus_num, devfn, config_addr;\n \n bus_num = (addr >> 16) & 0xff;\n if (bus_num != s->bus_num)\n return;\n devfn = (addr >> 8) & 0xff;\n d = s->device[devfn];\n if (!d)\n return;\n config_addr = addr & 0xff;\n pci_device_config_write(d, config_addr, data, size_log2);\n}\n\nstatic const uint32_t val_ones[3] = { 0xff, 0xffff, 0xffffffff };\n\nstatic uint32_t pci_data_read(PCIBus *s, uint32_t addr, int size_log2)\n{\n PCIDevice *d;\n int bus_num, devfn, config_addr;\n \n bus_num = (addr >> 16) & 0xff;\n if (bus_num != s->bus_num)\n return val_ones[size_log2];\n devfn = (addr >> 8) & 0xff;\n d = s->device[devfn];\n if (!d)\n return val_ones[size_log2];\n config_addr = addr & 0xff;\n return pci_device_config_read(d, config_addr, size_log2);\n}\n\n/* warning: only valid for one DEVIO page. Return NULL if no memory at\n the given address */\nuint8_t *pci_device_get_dma_ptr(PCIDevice *d, uint64_t addr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(d->bus->mem_map, addr, is_rw);\n}\n\nvoid pci_device_set_config8(PCIDevice *d, uint8_t addr, uint8_t val)\n{\n d->config[addr] = val;\n}\n\nvoid pci_device_set_config16(PCIDevice *d, uint8_t addr, uint16_t val)\n{\n put_le16(&d->config[addr], val);\n}\n\nint pci_device_get_devfn(PCIDevice *d)\n{\n return d->devfn;\n}\n\n/* return the offset of the capability or < 0 if error. */\nint pci_add_capability(PCIDevice *d, const uint8_t *buf, int size)\n{\n int offset;\n \n offset = d->next_cap_offset;\n if ((offset + size) > 256)\n return -1;\n d->next_cap_offset += size;\n d->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;\n memcpy(d->config + offset, buf, size);\n d->config[offset + 1] = d->config[PCI_CAPABILITY_LIST];\n d->config[PCI_CAPABILITY_LIST] = offset;\n return offset;\n}\n\n/* i440FX host bridge */\n\nstruct I440FXState {\n PCIBus *pci_bus;\n PCIDevice *pci_dev;\n PCIDevice *piix3_dev;\n uint32_t config_reg;\n uint8_t pic_irq_state[16];\n IRQSignal *pic_irqs; /* 16 irqs */\n};\n\nstatic void i440fx_write_addr(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n I440FXState *s = opaque;\n s->config_reg = data;\n}\n\nstatic uint32_t i440fx_read_addr(void *opaque, uint32_t offset, int size_log2)\n{\n I440FXState *s = opaque;\n return s->config_reg;\n}\n\nstatic void i440fx_write_data(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n I440FXState *s = opaque;\n if (s->config_reg & 0x80000000) {\n if (size_log2 == 2) {\n /* it is simpler to assume 32 bit config accesses are\n always aligned */\n pci_data_write(s->pci_bus, s->config_reg & ~3, data, size_log2);\n } else {\n pci_data_write(s->pci_bus, s->config_reg | offset, data, size_log2);\n }\n }\n}\n\nstatic uint32_t i440fx_read_data(void *opaque, uint32_t offset, int size_log2)\n{\n I440FXState *s = opaque;\n if (!(s->config_reg & 0x80000000))\n return val_ones[size_log2];\n if (size_log2 == 2) {\n /* it is simpler to assume 32 bit config accesses are\n always aligned */\n return pci_data_read(s->pci_bus, s->config_reg & ~3, size_log2);\n } else {\n return pci_data_read(s->pci_bus, s->config_reg | offset, size_log2);\n }\n}\n\nstatic void i440fx_set_irq(void *opaque, int irq_num, int irq_level)\n{\n I440FXState *s = opaque;\n PCIDevice *hd = s->piix3_dev;\n int pic_irq;\n \n /* map to the PIC irq (different IRQs can be mapped to the same\n PIC irq) */\n hd->config[0x60 + irq_num] &= ~0x80;\n pic_irq = hd->config[0x60 + irq_num];\n if (pic_irq < 16) {\n if (irq_level)\n s->pic_irq_state[pic_irq] |= 1 << irq_num;\n else\n s->pic_irq_state[pic_irq] &= ~(1 << irq_num);\n set_irq(&s->pic_irqs[pic_irq], (s->pic_irq_state[pic_irq] != 0));\n }\n}\n\nI440FXState *i440fx_init(PCIBus **pbus, int *ppiix3_devfn,\n PhysMemoryMap *mem_map, PhysMemoryMap *port_map,\n IRQSignal *pic_irqs)\n{\n I440FXState *s;\n PCIBus *b;\n PCIDevice *d;\n int i;\n \n s = mallocz(sizeof(*s));\n \n b = mallocz(sizeof(PCIBus));\n b->bus_num = 0;\n b->mem_map = mem_map;\n b->port_map = port_map;\n\n s->pic_irqs = pic_irqs;\n for(i = 0; i < 4; i++) {\n irq_init(&b->irq[i], i440fx_set_irq, s, i);\n }\n \n cpu_register_device(port_map, 0xcf8, 1, s, i440fx_read_addr, i440fx_write_addr, \n DEVIO_SIZE32);\n cpu_register_device(port_map, 0xcfc, 4, s, i440fx_read_data, i440fx_write_data, \n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32);\n d = pci_register_device(b, \"i440FX\", 0, 0x8086, 0x1237, 0x02, 0x0600);\n put_le16(&d->config[PCI_SUBSYSTEM_VENDOR_ID], 0x1af4); /* Red Hat, Inc. */\n put_le16(&d->config[PCI_SUBSYSTEM_ID], 0x1100); /* QEMU virtual machine */\n \n s->pci_dev = d;\n s->pci_bus = b;\n\n s->piix3_dev = pci_register_device(b, \"PIIX3\", 8, 0x8086, 0x7000,\n 0x00, 0x0601);\n pci_device_set_config8(s->piix3_dev, 0x0e, 0x80); /* header type */\n\n *pbus = b;\n *ppiix3_devfn = s->piix3_dev->devfn;\n return s;\n}\n\n/* in case no BIOS is used, map the interrupts. */\nvoid i440fx_map_interrupts(I440FXState *s, uint8_t *elcr,\n const uint8_t *pci_irqs)\n{\n PCIBus *b = s->pci_bus;\n PCIDevice *d, *hd;\n int irq_num, pic_irq, devfn, i;\n \n /* set a default PCI IRQ mapping to PIC IRQs */\n hd = s->piix3_dev;\n\n elcr[0] = 0;\n elcr[1] = 0;\n for(i = 0; i < 4; i++) {\n irq_num = pci_irqs[i];\n hd->config[0x60 + i] = irq_num;\n elcr[irq_num >> 3] |= (1 << (irq_num & 7));\n }\n\n for(devfn = 0; devfn < 256; devfn++) {\n d = b->device[devfn];\n if (!d)\n continue;\n if (d->config[PCI_INTERRUPT_PIN]) {\n irq_num = 0;\n irq_num = bus_map_irq(d, irq_num);\n pic_irq = hd->config[0x60 + irq_num];\n if (pic_irq < 16) {\n d->config[PCI_INTERRUPT_LINE] = pic_irq;\n }\n }\n }\n}\n"], ["/linuxpdf/tinyemu/riscv_machine.c", "/*\n * RISCV machine\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"riscv_cpu.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n/* RISCV machine */\n\ntypedef struct RISCVMachine {\n VirtMachine common;\n PhysMemoryMap *mem_map;\n int max_xlen;\n RISCVCPUState *cpu_state;\n uint64_t ram_size;\n /* RTC */\n BOOL rtc_real_time;\n uint64_t rtc_start_time;\n uint64_t timecmp;\n /* PLIC */\n uint32_t plic_pending_irq, plic_served_irq;\n IRQSignal plic_irq[32]; /* IRQ 0 is not used */\n /* HTIF */\n uint64_t htif_tohost, htif_fromhost;\n\n VIRTIODevice *keyboard_dev;\n VIRTIODevice *mouse_dev;\n\n int virtio_count;\n} RISCVMachine;\n\n#define LOW_RAM_SIZE 0x00010000 /* 64KB */\n#define RAM_BASE_ADDR 0x80000000\n#define CLINT_BASE_ADDR 0x02000000\n#define CLINT_SIZE 0x000c0000\n#define HTIF_BASE_ADDR 0x40008000\n#define IDE_BASE_ADDR 0x40009000\n#define VIRTIO_BASE_ADDR 0x40010000\n#define VIRTIO_SIZE 0x1000\n#define VIRTIO_IRQ 1\n#define PLIC_BASE_ADDR 0x40100000\n#define PLIC_SIZE 0x00400000\n#define FRAMEBUFFER_BASE_ADDR 0x41000000\n\n#define RTC_FREQ 10000000\n#define RTC_FREQ_DIV 16 /* arbitrary, relative to CPU freq to have a\n 10 MHz frequency */\n\nstatic uint64_t rtc_get_real_time(RISCVMachine *s)\n{\n struct timespec ts;\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * RTC_FREQ +\n (ts.tv_nsec / (1000000000 / RTC_FREQ));\n}\n\nstatic uint64_t rtc_get_time(RISCVMachine *m)\n{\n uint64_t val;\n if (m->rtc_real_time) {\n val = rtc_get_real_time(m) - m->rtc_start_time;\n } else {\n val = riscv_cpu_get_cycles(m->cpu_state) / RTC_FREQ_DIV;\n }\n // printf(\"rtc_time=%\" PRId64 \"\\n\", val);\n return val;\n}\n\nstatic uint32_t htif_read(void *opaque, uint32_t offset,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n uint32_t val;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0:\n val = s->htif_tohost;\n break;\n case 4:\n val = s->htif_tohost >> 32;\n break;\n case 8:\n val = s->htif_fromhost;\n break;\n case 12:\n val = s->htif_fromhost >> 32;\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n\nstatic void htif_handle_cmd(RISCVMachine *s)\n{\n uint32_t device, cmd;\n\n device = s->htif_tohost >> 56;\n cmd = (s->htif_tohost >> 48) & 0xff;\n if (s->htif_tohost == 1) {\n /* shuthost */\n printf(\"\\nPower off.\\n\");\n exit(0);\n } else if (device == 1 && cmd == 1) {\n uint8_t buf[1];\n buf[0] = s->htif_tohost & 0xff;\n s->common.console->write_data(s->common.console->opaque, buf, 1);\n s->htif_tohost = 0;\n s->htif_fromhost = ((uint64_t)device << 56) | ((uint64_t)cmd << 48);\n } else if (device == 1 && cmd == 0) {\n /* request keyboard interrupt */\n s->htif_tohost = 0;\n } else {\n printf(\"HTIF: unsupported tohost=0x%016\" PRIx64 \"\\n\", s->htif_tohost);\n }\n}\n\nstatic void htif_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0:\n s->htif_tohost = (s->htif_tohost & ~0xffffffff) | val;\n break;\n case 4:\n s->htif_tohost = (s->htif_tohost & 0xffffffff) | ((uint64_t)val << 32);\n htif_handle_cmd(s);\n break;\n case 8:\n s->htif_fromhost = (s->htif_fromhost & ~0xffffffff) | val;\n break;\n case 12:\n s->htif_fromhost = (s->htif_fromhost & 0xffffffff) |\n (uint64_t)val << 32;\n break;\n default:\n break;\n }\n}\n\n#if 0\nstatic void htif_poll(RISCVMachine *s)\n{\n uint8_t buf[1];\n int ret;\n\n if (s->htif_fromhost == 0) {\n ret = s->console->read_data(s->console->opaque, buf, 1);\n if (ret == 1) {\n s->htif_fromhost = ((uint64_t)1 << 56) | ((uint64_t)0 << 48) |\n buf[0];\n }\n }\n}\n#endif\n\nstatic uint32_t clint_read(void *opaque, uint32_t offset, int size_log2)\n{\n RISCVMachine *m = opaque;\n uint32_t val;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0xbff8:\n val = rtc_get_time(m);\n break;\n case 0xbffc:\n val = rtc_get_time(m) >> 32;\n break;\n case 0x4000:\n val = m->timecmp;\n break;\n case 0x4004:\n val = m->timecmp >> 32;\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n \nstatic void clint_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *m = opaque;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0x4000:\n m->timecmp = (m->timecmp & ~0xffffffff) | val;\n riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP);\n break;\n case 0x4004:\n m->timecmp = (m->timecmp & 0xffffffff) | ((uint64_t)val << 32);\n riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP);\n break;\n default:\n break;\n }\n}\n\nstatic void plic_update_mip(RISCVMachine *s)\n{\n RISCVCPUState *cpu = s->cpu_state;\n uint32_t mask;\n mask = s->plic_pending_irq & ~s->plic_served_irq;\n if (mask) {\n riscv_cpu_set_mip(cpu, MIP_MEIP | MIP_SEIP);\n } else {\n riscv_cpu_reset_mip(cpu, MIP_MEIP | MIP_SEIP);\n }\n}\n\n#define PLIC_HART_BASE 0x200000\n#define PLIC_HART_SIZE 0x1000\n\nstatic uint32_t plic_read(void *opaque, uint32_t offset, int size_log2)\n{\n RISCVMachine *s = opaque;\n uint32_t val, mask;\n int i;\n assert(size_log2 == 2);\n switch(offset) {\n case PLIC_HART_BASE:\n val = 0;\n break;\n case PLIC_HART_BASE + 4:\n mask = s->plic_pending_irq & ~s->plic_served_irq;\n if (mask != 0) {\n i = ctz32(mask);\n s->plic_served_irq |= 1 << i;\n plic_update_mip(s);\n val = i + 1;\n } else {\n val = 0;\n }\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n\nstatic void plic_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n \n assert(size_log2 == 2);\n switch(offset) {\n case PLIC_HART_BASE + 4:\n val--;\n if (val < 32) {\n s->plic_served_irq &= ~(1 << val);\n plic_update_mip(s);\n }\n break;\n default:\n break;\n }\n}\n\nstatic void plic_set_irq(void *opaque, int irq_num, int state)\n{\n RISCVMachine *s = opaque;\n uint32_t mask;\n\n mask = 1 << (irq_num - 1);\n if (state) \n s->plic_pending_irq |= mask;\n else\n s->plic_pending_irq &= ~mask;\n plic_update_mip(s);\n}\n\nstatic uint8_t *get_ram_ptr(RISCVMachine *s, uint64_t paddr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(s->mem_map, paddr, is_rw);\n}\n\n/* FDT machine description */\n\n#define FDT_MAGIC\t0xd00dfeed\n#define FDT_VERSION\t17\n\nstruct fdt_header {\n uint32_t magic;\n uint32_t totalsize;\n uint32_t off_dt_struct;\n uint32_t off_dt_strings;\n uint32_t off_mem_rsvmap;\n uint32_t version;\n uint32_t last_comp_version; /* <= 17 */\n uint32_t boot_cpuid_phys;\n uint32_t size_dt_strings;\n uint32_t size_dt_struct;\n};\n\nstruct fdt_reserve_entry {\n uint64_t address;\n uint64_t size;\n};\n\n#define FDT_BEGIN_NODE\t1\n#define FDT_END_NODE\t2\n#define FDT_PROP\t3\n#define FDT_NOP\t\t4\n#define FDT_END\t\t9\n\ntypedef struct {\n uint32_t *tab;\n int tab_len;\n int tab_size;\n int open_node_count;\n \n char *string_table;\n int string_table_len;\n int string_table_size;\n} FDTState;\n\nstatic FDTState *fdt_init(void)\n{\n FDTState *s;\n s = mallocz(sizeof(*s));\n return s;\n}\n\nstatic void fdt_alloc_len(FDTState *s, int len)\n{\n int new_size;\n if (unlikely(len > s->tab_size)) {\n new_size = max_int(len, s->tab_size * 3 / 2);\n s->tab = realloc(s->tab, new_size * sizeof(uint32_t));\n s->tab_size = new_size;\n }\n}\n\nstatic void fdt_put32(FDTState *s, int v)\n{\n fdt_alloc_len(s, s->tab_len + 1);\n s->tab[s->tab_len++] = cpu_to_be32(v);\n}\n\n/* the data is zero padded */\nstatic void fdt_put_data(FDTState *s, const uint8_t *data, int len)\n{\n int len1;\n \n len1 = (len + 3) / 4;\n fdt_alloc_len(s, s->tab_len + len1);\n memcpy(s->tab + s->tab_len, data, len);\n memset((uint8_t *)(s->tab + s->tab_len) + len, 0, -len & 3);\n s->tab_len += len1;\n}\n\nstatic void fdt_begin_node(FDTState *s, const char *name)\n{\n fdt_put32(s, FDT_BEGIN_NODE);\n fdt_put_data(s, (uint8_t *)name, strlen(name) + 1);\n s->open_node_count++;\n}\n\nstatic void fdt_begin_node_num(FDTState *s, const char *name, uint64_t n)\n{\n char buf[256];\n snprintf(buf, sizeof(buf), \"%s@%\" PRIx64, name, n);\n fdt_begin_node(s, buf);\n}\n\nstatic void fdt_end_node(FDTState *s)\n{\n fdt_put32(s, FDT_END_NODE);\n s->open_node_count--;\n}\n\nstatic int fdt_get_string_offset(FDTState *s, const char *name)\n{\n int pos, new_size, name_size, new_len;\n\n pos = 0;\n while (pos < s->string_table_len) {\n if (!strcmp(s->string_table + pos, name))\n return pos;\n pos += strlen(s->string_table + pos) + 1;\n }\n /* add a new string */\n name_size = strlen(name) + 1;\n new_len = s->string_table_len + name_size;\n if (new_len > s->string_table_size) {\n new_size = max_int(new_len, s->string_table_size * 3 / 2);\n s->string_table = realloc(s->string_table, new_size);\n s->string_table_size = new_size;\n }\n pos = s->string_table_len;\n memcpy(s->string_table + pos, name, name_size);\n s->string_table_len = new_len;\n return pos;\n}\n\nstatic void fdt_prop(FDTState *s, const char *prop_name,\n const void *data, int data_len)\n{\n fdt_put32(s, FDT_PROP);\n fdt_put32(s, data_len);\n fdt_put32(s, fdt_get_string_offset(s, prop_name));\n fdt_put_data(s, data, data_len);\n}\n\nstatic void fdt_prop_tab_u32(FDTState *s, const char *prop_name,\n uint32_t *tab, int tab_len)\n{\n int i;\n fdt_put32(s, FDT_PROP);\n fdt_put32(s, tab_len * sizeof(uint32_t));\n fdt_put32(s, fdt_get_string_offset(s, prop_name));\n for(i = 0; i < tab_len; i++)\n fdt_put32(s, tab[i]);\n}\n\nstatic void fdt_prop_u32(FDTState *s, const char *prop_name, uint32_t val)\n{\n fdt_prop_tab_u32(s, prop_name, &val, 1);\n}\n\nstatic void fdt_prop_tab_u64(FDTState *s, const char *prop_name,\n uint64_t v0)\n{\n uint32_t tab[2];\n tab[0] = v0 >> 32;\n tab[1] = v0;\n fdt_prop_tab_u32(s, prop_name, tab, 2);\n}\n\nstatic void fdt_prop_tab_u64_2(FDTState *s, const char *prop_name,\n uint64_t v0, uint64_t v1)\n{\n uint32_t tab[4];\n tab[0] = v0 >> 32;\n tab[1] = v0;\n tab[2] = v1 >> 32;\n tab[3] = v1;\n fdt_prop_tab_u32(s, prop_name, tab, 4);\n}\n\nstatic void fdt_prop_str(FDTState *s, const char *prop_name,\n const char *str)\n{\n fdt_prop(s, prop_name, str, strlen(str) + 1);\n}\n\n/* NULL terminated string list */\nstatic void fdt_prop_tab_str(FDTState *s, const char *prop_name,\n ...)\n{\n va_list ap;\n int size, str_size;\n char *ptr, *tab;\n\n va_start(ap, prop_name);\n size = 0;\n for(;;) {\n ptr = va_arg(ap, char *);\n if (!ptr)\n break;\n str_size = strlen(ptr) + 1;\n size += str_size;\n }\n va_end(ap);\n \n tab = malloc(size);\n va_start(ap, prop_name);\n size = 0;\n for(;;) {\n ptr = va_arg(ap, char *);\n if (!ptr)\n break;\n str_size = strlen(ptr) + 1;\n memcpy(tab + size, ptr, str_size);\n size += str_size;\n }\n va_end(ap);\n \n fdt_prop(s, prop_name, tab, size);\n free(tab);\n}\n\n/* write the FDT to 'dst1'. return the FDT size in bytes */\nint fdt_output(FDTState *s, uint8_t *dst)\n{\n struct fdt_header *h;\n struct fdt_reserve_entry *re;\n int dt_struct_size;\n int dt_strings_size;\n int pos;\n\n assert(s->open_node_count == 0);\n \n fdt_put32(s, FDT_END);\n \n dt_struct_size = s->tab_len * sizeof(uint32_t);\n dt_strings_size = s->string_table_len;\n\n h = (struct fdt_header *)dst;\n h->magic = cpu_to_be32(FDT_MAGIC);\n h->version = cpu_to_be32(FDT_VERSION);\n h->last_comp_version = cpu_to_be32(16);\n h->boot_cpuid_phys = cpu_to_be32(0);\n h->size_dt_strings = cpu_to_be32(dt_strings_size);\n h->size_dt_struct = cpu_to_be32(dt_struct_size);\n\n pos = sizeof(struct fdt_header);\n\n h->off_dt_struct = cpu_to_be32(pos);\n memcpy(dst + pos, s->tab, dt_struct_size);\n pos += dt_struct_size;\n\n /* align to 8 */\n while ((pos & 7) != 0) {\n dst[pos++] = 0;\n }\n h->off_mem_rsvmap = cpu_to_be32(pos);\n re = (struct fdt_reserve_entry *)(dst + pos);\n re->address = 0; /* no reserved entry */\n re->size = 0;\n pos += sizeof(struct fdt_reserve_entry);\n\n h->off_dt_strings = cpu_to_be32(pos);\n memcpy(dst + pos, s->string_table, dt_strings_size);\n pos += dt_strings_size;\n\n /* align to 8, just in case */\n while ((pos & 7) != 0) {\n dst[pos++] = 0;\n }\n\n h->totalsize = cpu_to_be32(pos);\n return pos;\n}\n\nvoid fdt_end(FDTState *s)\n{\n free(s->tab);\n free(s->string_table);\n free(s);\n}\n\nstatic int riscv_build_fdt(RISCVMachine *m, uint8_t *dst,\n uint64_t kernel_start, uint64_t kernel_size,\n uint64_t initrd_start, uint64_t initrd_size,\n const char *cmd_line)\n{\n FDTState *s;\n int size, max_xlen, i, cur_phandle, intc_phandle, plic_phandle;\n char isa_string[128], *q;\n uint32_t misa;\n uint32_t tab[4];\n FBDevice *fb_dev;\n \n s = fdt_init();\n\n cur_phandle = 1;\n \n fdt_begin_node(s, \"\");\n fdt_prop_u32(s, \"#address-cells\", 2);\n fdt_prop_u32(s, \"#size-cells\", 2);\n fdt_prop_str(s, \"compatible\", \"ucbbar,riscvemu-bar_dev\");\n fdt_prop_str(s, \"model\", \"ucbbar,riscvemu-bare\");\n\n /* CPU list */\n fdt_begin_node(s, \"cpus\");\n fdt_prop_u32(s, \"#address-cells\", 1);\n fdt_prop_u32(s, \"#size-cells\", 0);\n fdt_prop_u32(s, \"timebase-frequency\", RTC_FREQ);\n\n /* cpu */\n fdt_begin_node_num(s, \"cpu\", 0);\n fdt_prop_str(s, \"device_type\", \"cpu\");\n fdt_prop_u32(s, \"reg\", 0);\n fdt_prop_str(s, \"status\", \"okay\");\n fdt_prop_str(s, \"compatible\", \"riscv\");\n\n max_xlen = m->max_xlen;\n misa = riscv_cpu_get_misa(m->cpu_state);\n q = isa_string;\n q += snprintf(isa_string, sizeof(isa_string), \"rv%d\", max_xlen);\n for(i = 0; i < 26; i++) {\n if (misa & (1 << i))\n *q++ = 'a' + i;\n }\n *q = '\\0';\n fdt_prop_str(s, \"riscv,isa\", isa_string);\n \n fdt_prop_str(s, \"mmu-type\", max_xlen <= 32 ? \"riscv,sv32\" : \"riscv,sv48\");\n fdt_prop_u32(s, \"clock-frequency\", 2000000000);\n\n fdt_begin_node(s, \"interrupt-controller\");\n fdt_prop_u32(s, \"#interrupt-cells\", 1);\n fdt_prop(s, \"interrupt-controller\", NULL, 0);\n fdt_prop_str(s, \"compatible\", \"riscv,cpu-intc\");\n intc_phandle = cur_phandle++;\n fdt_prop_u32(s, \"phandle\", intc_phandle);\n fdt_end_node(s); /* interrupt-controller */\n \n fdt_end_node(s); /* cpu */\n \n fdt_end_node(s); /* cpus */\n\n fdt_begin_node_num(s, \"memory\", RAM_BASE_ADDR);\n fdt_prop_str(s, \"device_type\", \"memory\");\n tab[0] = (uint64_t)RAM_BASE_ADDR >> 32;\n tab[1] = RAM_BASE_ADDR;\n tab[2] = m->ram_size >> 32;\n tab[3] = m->ram_size;\n fdt_prop_tab_u32(s, \"reg\", tab, 4);\n \n fdt_end_node(s); /* memory */\n\n fdt_begin_node(s, \"htif\");\n fdt_prop_str(s, \"compatible\", \"ucb,htif0\");\n fdt_end_node(s); /* htif */\n\n fdt_begin_node(s, \"soc\");\n fdt_prop_u32(s, \"#address-cells\", 2);\n fdt_prop_u32(s, \"#size-cells\", 2);\n fdt_prop_tab_str(s, \"compatible\",\n \"ucbbar,riscvemu-bar-soc\", \"simple-bus\", NULL);\n fdt_prop(s, \"ranges\", NULL, 0);\n\n fdt_begin_node_num(s, \"clint\", CLINT_BASE_ADDR);\n fdt_prop_str(s, \"compatible\", \"riscv,clint0\");\n\n tab[0] = intc_phandle;\n tab[1] = 3; /* M IPI irq */\n tab[2] = intc_phandle;\n tab[3] = 7; /* M timer irq */\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 4);\n\n fdt_prop_tab_u64_2(s, \"reg\", CLINT_BASE_ADDR, CLINT_SIZE);\n \n fdt_end_node(s); /* clint */\n\n fdt_begin_node_num(s, \"plic\", PLIC_BASE_ADDR);\n fdt_prop_u32(s, \"#interrupt-cells\", 1);\n fdt_prop(s, \"interrupt-controller\", NULL, 0);\n fdt_prop_str(s, \"compatible\", \"riscv,plic0\");\n fdt_prop_u32(s, \"riscv,ndev\", 31);\n fdt_prop_tab_u64_2(s, \"reg\", PLIC_BASE_ADDR, PLIC_SIZE);\n\n tab[0] = intc_phandle;\n tab[1] = 9; /* S ext irq */\n tab[2] = intc_phandle;\n tab[3] = 11; /* M ext irq */\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 4);\n\n plic_phandle = cur_phandle++;\n fdt_prop_u32(s, \"phandle\", plic_phandle);\n\n fdt_end_node(s); /* plic */\n \n for(i = 0; i < m->virtio_count; i++) {\n fdt_begin_node_num(s, \"virtio\", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE);\n fdt_prop_str(s, \"compatible\", \"virtio,mmio\");\n fdt_prop_tab_u64_2(s, \"reg\", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE,\n VIRTIO_SIZE);\n tab[0] = plic_phandle;\n tab[1] = VIRTIO_IRQ + i;\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 2);\n fdt_end_node(s); /* virtio */\n }\n\n fb_dev = m->common.fb_dev;\n if (fb_dev) {\n fdt_begin_node_num(s, \"framebuffer\", FRAMEBUFFER_BASE_ADDR);\n fdt_prop_str(s, \"compatible\", \"simple-framebuffer\");\n fdt_prop_tab_u64_2(s, \"reg\", FRAMEBUFFER_BASE_ADDR, fb_dev->fb_size);\n fdt_prop_u32(s, \"width\", fb_dev->width);\n fdt_prop_u32(s, \"height\", fb_dev->height);\n fdt_prop_u32(s, \"stride\", fb_dev->stride);\n fdt_prop_str(s, \"format\", \"a8r8g8b8\");\n fdt_end_node(s); /* framebuffer */\n }\n \n fdt_end_node(s); /* soc */\n\n fdt_begin_node(s, \"chosen\");\n fdt_prop_str(s, \"bootargs\", cmd_line ? cmd_line : \"\");\n if (kernel_size > 0) {\n fdt_prop_tab_u64(s, \"riscv,kernel-start\", kernel_start);\n fdt_prop_tab_u64(s, \"riscv,kernel-end\", kernel_start + kernel_size);\n }\n if (initrd_size > 0) {\n fdt_prop_tab_u64(s, \"linux,initrd-start\", initrd_start);\n fdt_prop_tab_u64(s, \"linux,initrd-end\", initrd_start + initrd_size);\n }\n \n\n fdt_end_node(s); /* chosen */\n \n fdt_end_node(s); /* / */\n\n size = fdt_output(s, dst);\n#if 0\n {\n FILE *f;\n f = fopen(\"/tmp/riscvemu.dtb\", \"wb\");\n fwrite(dst, 1, size, f);\n fclose(f);\n }\n#endif\n fdt_end(s);\n return size;\n}\n\nstatic void copy_bios(RISCVMachine *s, const uint8_t *buf, int buf_len,\n const uint8_t *kernel_buf, int kernel_buf_len,\n const uint8_t *initrd_buf, int initrd_buf_len,\n const char *cmd_line)\n{\n uint32_t fdt_addr, align, kernel_base, initrd_base;\n uint8_t *ram_ptr;\n uint32_t *q;\n\n if (buf_len > s->ram_size) {\n vm_error(\"BIOS too big\\n\");\n exit(1);\n }\n\n ram_ptr = get_ram_ptr(s, RAM_BASE_ADDR, TRUE);\n memcpy(ram_ptr, buf, buf_len);\n\n kernel_base = 0;\n if (kernel_buf_len > 0) {\n /* copy the kernel if present */\n if (s->max_xlen == 32)\n align = 4 << 20; /* 4 MB page align */\n else\n align = 2 << 20; /* 2 MB page align */\n kernel_base = (buf_len + align - 1) & ~(align - 1);\n memcpy(ram_ptr + kernel_base, kernel_buf, kernel_buf_len);\n if (kernel_buf_len + kernel_base > s->ram_size) {\n vm_error(\"kernel too big\");\n exit(1);\n }\n }\n\n initrd_base = 0;\n if (initrd_buf_len > 0) {\n /* same allocation as QEMU */\n initrd_base = s->ram_size / 2;\n if (initrd_base > (128 << 20))\n initrd_base = 128 << 20;\n memcpy(ram_ptr + initrd_base, initrd_buf, initrd_buf_len);\n if (initrd_buf_len + initrd_base > s->ram_size) {\n vm_error(\"initrd too big\");\n exit(1);\n }\n }\n \n ram_ptr = get_ram_ptr(s, 0, TRUE);\n \n fdt_addr = 0x1000 + 8 * 8;\n\n riscv_build_fdt(s, ram_ptr + fdt_addr,\n RAM_BASE_ADDR + kernel_base, kernel_buf_len,\n RAM_BASE_ADDR + initrd_base, initrd_buf_len,\n cmd_line);\n\n /* jump_addr = 0x80000000 */\n \n q = (uint32_t *)(ram_ptr + 0x1000);\n q[0] = 0x297 + 0x80000000 - 0x1000; /* auipc t0, jump_addr */\n q[1] = 0x597; /* auipc a1, dtb */\n q[2] = 0x58593 + ((fdt_addr - 4) << 20); /* addi a1, a1, dtb */\n q[3] = 0xf1402573; /* csrr a0, mhartid */\n q[4] = 0x00028067; /* jalr zero, t0, jump_addr */\n}\n\nstatic void riscv_flush_tlb_write_range(void *opaque, uint8_t *ram_addr,\n size_t ram_size)\n{\n RISCVMachine *s = opaque;\n riscv_cpu_flush_tlb_write_range_ram(s->cpu_state, ram_addr, ram_size);\n}\n\nstatic void riscv_machine_set_defaults(VirtMachineParams *p)\n{\n}\n\nstatic VirtMachine *riscv_machine_init(const VirtMachineParams *p)\n{\n RISCVMachine *s;\n VIRTIODevice *blk_dev;\n int irq_num, i, max_xlen, ram_flags;\n VIRTIOBusDef vbus_s, *vbus = &vbus_s;\n\n\n if (!strcmp(p->machine_name, \"riscv32\")) {\n max_xlen = 32;\n } else if (!strcmp(p->machine_name, \"riscv64\")) {\n max_xlen = 64;\n } else if (!strcmp(p->machine_name, \"riscv128\")) {\n max_xlen = 128;\n } else {\n vm_error(\"unsupported machine: %s\\n\", p->machine_name);\n return NULL;\n }\n \n s = mallocz(sizeof(*s));\n s->common.vmc = p->vmc;\n s->ram_size = p->ram_size;\n s->max_xlen = max_xlen;\n s->mem_map = phys_mem_map_init();\n /* needed to handle the RAM dirty bits */\n s->mem_map->opaque = s;\n s->mem_map->flush_tlb_write_range = riscv_flush_tlb_write_range;\n\n s->cpu_state = riscv_cpu_init(s->mem_map, max_xlen);\n if (!s->cpu_state) {\n vm_error(\"unsupported max_xlen=%d\\n\", max_xlen);\n /* XXX: should free resources */\n return NULL;\n }\n /* RAM */\n ram_flags = 0;\n cpu_register_ram(s->mem_map, RAM_BASE_ADDR, p->ram_size, ram_flags);\n cpu_register_ram(s->mem_map, 0x00000000, LOW_RAM_SIZE, 0);\n s->rtc_real_time = p->rtc_real_time;\n if (p->rtc_real_time) {\n s->rtc_start_time = rtc_get_real_time(s);\n }\n \n cpu_register_device(s->mem_map, CLINT_BASE_ADDR, CLINT_SIZE, s,\n clint_read, clint_write, DEVIO_SIZE32);\n cpu_register_device(s->mem_map, PLIC_BASE_ADDR, PLIC_SIZE, s,\n plic_read, plic_write, DEVIO_SIZE32);\n for(i = 1; i < 32; i++) {\n irq_init(&s->plic_irq[i], plic_set_irq, s, i);\n }\n\n cpu_register_device(s->mem_map, HTIF_BASE_ADDR, 16,\n s, htif_read, htif_write, DEVIO_SIZE32);\n s->common.console = p->console;\n\n memset(vbus, 0, sizeof(*vbus));\n vbus->mem_map = s->mem_map;\n vbus->addr = VIRTIO_BASE_ADDR;\n irq_num = VIRTIO_IRQ;\n \n /* virtio console */\n if (p->console) {\n vbus->irq = &s->plic_irq[irq_num];\n s->common.console_dev = virtio_console_init(vbus, p->console);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n \n /* virtio net device */\n for(i = 0; i < p->eth_count; i++) {\n vbus->irq = &s->plic_irq[irq_num];\n virtio_net_init(vbus, p->tab_eth[i].net);\n s->common.net = p->tab_eth[i].net;\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n /* virtio block device */\n for(i = 0; i < p->drive_count; i++) {\n vbus->irq = &s->plic_irq[irq_num];\n blk_dev = virtio_block_init(vbus, p->tab_drive[i].block_dev);\n (void)blk_dev;\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n /* virtio filesystem */\n for(i = 0; i < p->fs_count; i++) {\n VIRTIODevice *fs_dev;\n vbus->irq = &s->plic_irq[irq_num];\n fs_dev = virtio_9p_init(vbus, p->tab_fs[i].fs_dev,\n p->tab_fs[i].tag);\n (void)fs_dev;\n // virtio_set_debug(fs_dev, VIRTIO_DEBUG_9P);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n if (p->display_device) {\n FBDevice *fb_dev;\n fb_dev = mallocz(sizeof(*fb_dev));\n s->common.fb_dev = fb_dev;\n if (!strcmp(p->display_device, \"simplefb\")) {\n simplefb_init(s->mem_map,\n FRAMEBUFFER_BASE_ADDR,\n fb_dev,\n p->width, p->height);\n \n } else {\n vm_error(\"unsupported display device: %s\\n\", p->display_device);\n exit(1);\n }\n }\n\n if (p->input_device) {\n if (!strcmp(p->input_device, \"virtio\")) {\n vbus->irq = &s->plic_irq[irq_num];\n s->keyboard_dev = virtio_input_init(vbus,\n VIRTIO_INPUT_TYPE_KEYBOARD);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n\n vbus->irq = &s->plic_irq[irq_num];\n s->mouse_dev = virtio_input_init(vbus,\n VIRTIO_INPUT_TYPE_TABLET);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n } else {\n vm_error(\"unsupported input device: %s\\n\", p->input_device);\n exit(1);\n }\n }\n \n if (!p->files[VM_FILE_BIOS].buf) {\n vm_error(\"No bios found\");\n }\n\n copy_bios(s, p->files[VM_FILE_BIOS].buf, p->files[VM_FILE_BIOS].len,\n p->files[VM_FILE_KERNEL].buf, p->files[VM_FILE_KERNEL].len,\n p->files[VM_FILE_INITRD].buf, p->files[VM_FILE_INITRD].len,\n p->cmdline);\n \n return (VirtMachine *)s;\n}\n\nstatic void riscv_machine_end(VirtMachine *s1)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n /* XXX: stop all */\n riscv_cpu_end(s->cpu_state);\n phys_mem_map_end(s->mem_map);\n free(s);\n}\n\n/* in ms */\nstatic int riscv_machine_get_sleep_duration(VirtMachine *s1, int delay)\n{\n RISCVMachine *m = (RISCVMachine *)s1;\n RISCVCPUState *s = m->cpu_state;\n int64_t delay1;\n \n /* wait for an event: the only asynchronous event is the RTC timer */\n if (!(riscv_cpu_get_mip(s) & MIP_MTIP)) {\n delay1 = m->timecmp - rtc_get_time(m);\n if (delay1 <= 0) {\n riscv_cpu_set_mip(s, MIP_MTIP);\n delay = 0;\n } else {\n /* convert delay to ms */\n delay1 = delay1 / (RTC_FREQ / 1000);\n if (delay1 < delay)\n delay = delay1;\n }\n }\n if (!riscv_cpu_get_power_down(s))\n delay = 0;\n return delay;\n}\n\nstatic void riscv_machine_interp(VirtMachine *s1, int max_exec_cycle)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n riscv_cpu_interp(s->cpu_state, max_exec_cycle);\n}\n\nstatic void riscv_vm_send_key_event(VirtMachine *s1, BOOL is_down,\n uint16_t key_code)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n if (s->keyboard_dev) {\n virtio_input_send_key_event(s->keyboard_dev, is_down, key_code);\n }\n}\n\nstatic BOOL riscv_vm_mouse_is_absolute(VirtMachine *s)\n{\n return TRUE;\n}\n\nstatic void riscv_vm_send_mouse_event(VirtMachine *s1, int dx, int dy, int dz,\n unsigned int buttons)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n if (s->mouse_dev) {\n virtio_input_send_mouse_event(s->mouse_dev, dx, dy, dz, buttons);\n }\n}\n\nconst VirtMachineClass riscv_machine_class = {\n \"riscv32,riscv64,riscv128\",\n riscv_machine_set_defaults,\n riscv_machine_init,\n riscv_machine_end,\n riscv_machine_get_sleep_duration,\n riscv_machine_interp,\n riscv_vm_mouse_is_absolute,\n riscv_vm_send_mouse_event,\n riscv_vm_send_key_event,\n};\n"], ["/linuxpdf/tinyemu/virtio.c", "/*\n * VIRTIO driver\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"virtio.h\"\n\n//#define DEBUG_VIRTIO\n\n/* MMIO addresses - from the Linux kernel */\n#define VIRTIO_MMIO_MAGIC_VALUE\t\t0x000\n#define VIRTIO_MMIO_VERSION\t\t0x004\n#define VIRTIO_MMIO_DEVICE_ID\t\t0x008\n#define VIRTIO_MMIO_VENDOR_ID\t\t0x00c\n#define VIRTIO_MMIO_DEVICE_FEATURES\t0x010\n#define VIRTIO_MMIO_DEVICE_FEATURES_SEL\t0x014\n#define VIRTIO_MMIO_DRIVER_FEATURES\t0x020\n#define VIRTIO_MMIO_DRIVER_FEATURES_SEL\t0x024\n#define VIRTIO_MMIO_GUEST_PAGE_SIZE\t0x028 /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_SEL\t\t0x030\n#define VIRTIO_MMIO_QUEUE_NUM_MAX\t0x034\n#define VIRTIO_MMIO_QUEUE_NUM\t\t0x038\n#define VIRTIO_MMIO_QUEUE_ALIGN\t\t0x03c /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_PFN\t\t0x040 /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_READY\t\t0x044\n#define VIRTIO_MMIO_QUEUE_NOTIFY\t0x050\n#define VIRTIO_MMIO_INTERRUPT_STATUS\t0x060\n#define VIRTIO_MMIO_INTERRUPT_ACK\t0x064\n#define VIRTIO_MMIO_STATUS\t\t0x070\n#define VIRTIO_MMIO_QUEUE_DESC_LOW\t0x080\n#define VIRTIO_MMIO_QUEUE_DESC_HIGH\t0x084\n#define VIRTIO_MMIO_QUEUE_AVAIL_LOW\t0x090\n#define VIRTIO_MMIO_QUEUE_AVAIL_HIGH\t0x094\n#define VIRTIO_MMIO_QUEUE_USED_LOW\t0x0a0\n#define VIRTIO_MMIO_QUEUE_USED_HIGH\t0x0a4\n#define VIRTIO_MMIO_CONFIG_GENERATION\t0x0fc\n#define VIRTIO_MMIO_CONFIG\t\t0x100\n\n/* PCI registers */\n#define VIRTIO_PCI_DEVICE_FEATURE_SEL\t0x000\n#define VIRTIO_PCI_DEVICE_FEATURE\t0x004\n#define VIRTIO_PCI_GUEST_FEATURE_SEL\t0x008\n#define VIRTIO_PCI_GUEST_FEATURE\t0x00c\n#define VIRTIO_PCI_MSIX_CONFIG 0x010\n#define VIRTIO_PCI_NUM_QUEUES 0x012\n#define VIRTIO_PCI_DEVICE_STATUS 0x014\n#define VIRTIO_PCI_CONFIG_GENERATION 0x015\n#define VIRTIO_PCI_QUEUE_SEL\t\t0x016\n#define VIRTIO_PCI_QUEUE_SIZE\t 0x018\n#define VIRTIO_PCI_QUEUE_MSIX_VECTOR 0x01a\n#define VIRTIO_PCI_QUEUE_ENABLE 0x01c\n#define VIRTIO_PCI_QUEUE_NOTIFY_OFF 0x01e\n#define VIRTIO_PCI_QUEUE_DESC_LOW\t0x020\n#define VIRTIO_PCI_QUEUE_DESC_HIGH\t0x024\n#define VIRTIO_PCI_QUEUE_AVAIL_LOW\t0x028\n#define VIRTIO_PCI_QUEUE_AVAIL_HIGH\t0x02c\n#define VIRTIO_PCI_QUEUE_USED_LOW\t0x030\n#define VIRTIO_PCI_QUEUE_USED_HIGH\t0x034\n\n#define VIRTIO_PCI_CFG_OFFSET 0x0000\n#define VIRTIO_PCI_ISR_OFFSET 0x1000\n#define VIRTIO_PCI_CONFIG_OFFSET 0x2000\n#define VIRTIO_PCI_NOTIFY_OFFSET 0x3000\n\n#define VIRTIO_PCI_CAP_LEN 16\n\n#define MAX_QUEUE 8\n#define MAX_CONFIG_SPACE_SIZE 256\n#define MAX_QUEUE_NUM 16\n\ntypedef struct {\n uint32_t ready; /* 0 or 1 */\n uint32_t num;\n uint16_t last_avail_idx;\n virtio_phys_addr_t desc_addr;\n virtio_phys_addr_t avail_addr;\n virtio_phys_addr_t used_addr;\n BOOL manual_recv; /* if TRUE, the device_recv() callback is not called */\n} QueueState;\n\n#define VRING_DESC_F_NEXT\t1\n#define VRING_DESC_F_WRITE\t2\n#define VRING_DESC_F_INDIRECT\t4\n\ntypedef struct {\n uint64_t addr;\n uint32_t len;\n uint16_t flags; /* VRING_DESC_F_x */\n uint16_t next;\n} VIRTIODesc;\n\n/* return < 0 to stop the notification (it must be manually restarted\n later), 0 if OK */\ntypedef int VIRTIODeviceRecvFunc(VIRTIODevice *s1, int queue_idx,\n int desc_idx, int read_size,\n int write_size);\n\n/* return NULL if no RAM at this address. The mapping is valid for one page */\ntypedef uint8_t *VIRTIOGetRAMPtrFunc(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw);\n\nstruct VIRTIODevice {\n PhysMemoryMap *mem_map;\n PhysMemoryRange *mem_range;\n /* PCI only */\n PCIDevice *pci_dev;\n /* MMIO only */\n IRQSignal *irq;\n VIRTIOGetRAMPtrFunc *get_ram_ptr;\n int debug;\n\n uint32_t int_status;\n uint32_t status;\n uint32_t device_features_sel;\n uint32_t queue_sel; /* currently selected queue */\n QueueState queue[MAX_QUEUE];\n\n /* device specific */\n uint32_t device_id;\n uint32_t vendor_id;\n uint32_t device_features;\n VIRTIODeviceRecvFunc *device_recv;\n void (*config_write)(VIRTIODevice *s); /* called after the config\n is written */\n uint32_t config_space_size; /* in bytes, must be multiple of 4 */\n uint8_t config_space[MAX_CONFIG_SPACE_SIZE];\n};\n\nstatic uint32_t virtio_mmio_read(void *opaque, uint32_t offset1, int size_log2);\nstatic void virtio_mmio_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t virtio_pci_read(void *opaque, uint32_t offset, int size_log2);\nstatic void virtio_pci_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\n\nstatic void virtio_reset(VIRTIODevice *s)\n{\n int i;\n\n s->status = 0;\n s->queue_sel = 0;\n s->device_features_sel = 0;\n s->int_status = 0;\n for(i = 0; i < MAX_QUEUE; i++) {\n QueueState *qs = &s->queue[i];\n qs->ready = 0;\n qs->num = MAX_QUEUE_NUM;\n qs->desc_addr = 0;\n qs->avail_addr = 0;\n qs->used_addr = 0;\n qs->last_avail_idx = 0;\n }\n}\n\nstatic uint8_t *virtio_pci_get_ram_ptr(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw)\n{\n return pci_device_get_dma_ptr(s->pci_dev, paddr, is_rw);\n}\n\nstatic uint8_t *virtio_mmio_get_ram_ptr(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(s->mem_map, paddr, is_rw);\n}\n\nstatic void virtio_add_pci_capability(VIRTIODevice *s, int cfg_type,\n int bar, uint32_t offset, uint32_t len,\n uint32_t mult)\n{\n uint8_t cap[20];\n int cap_len;\n if (cfg_type == 2)\n cap_len = 20;\n else\n cap_len = 16;\n memset(cap, 0, cap_len);\n cap[0] = 0x09; /* vendor specific */\n cap[2] = cap_len; /* set by pci_add_capability() */\n cap[3] = cfg_type;\n cap[4] = bar;\n put_le32(cap + 8, offset);\n put_le32(cap + 12, len);\n if (cfg_type == 2)\n put_le32(cap + 16, mult);\n pci_add_capability(s->pci_dev, cap, cap_len);\n}\n\nstatic void virtio_pci_bar_set(void *opaque, int bar_num,\n uint32_t addr, BOOL enabled)\n{\n VIRTIODevice *s = opaque;\n phys_mem_set_addr(s->mem_range, addr, enabled);\n}\n\nstatic void virtio_init(VIRTIODevice *s, VIRTIOBusDef *bus,\n uint32_t device_id, int config_space_size,\n VIRTIODeviceRecvFunc *device_recv)\n{\n memset(s, 0, sizeof(*s));\n\n if (bus->pci_bus) {\n uint16_t pci_device_id, class_id;\n char name[32];\n int bar_num;\n \n switch(device_id) {\n case 1:\n pci_device_id = 0x1000; /* net */\n class_id = 0x0200;\n break;\n case 2:\n pci_device_id = 0x1001; /* block */\n class_id = 0x0100; /* XXX: check it */\n break;\n case 3:\n pci_device_id = 0x1003; /* console */\n class_id = 0x0780;\n break;\n case 9:\n pci_device_id = 0x1040 + device_id; /* use new device ID */\n class_id = 0x2;\n break;\n case 18:\n pci_device_id = 0x1040 + device_id; /* use new device ID */\n class_id = 0x0980;\n break;\n default:\n abort();\n }\n snprintf(name, sizeof(name), \"virtio_%04x\", pci_device_id);\n s->pci_dev = pci_register_device(bus->pci_bus, name, -1,\n 0x1af4, pci_device_id, 0x00,\n class_id);\n pci_device_set_config16(s->pci_dev, 0x2c, 0x1af4);\n pci_device_set_config16(s->pci_dev, 0x2e, device_id);\n pci_device_set_config8(s->pci_dev, PCI_INTERRUPT_PIN, 1);\n\n bar_num = 4;\n virtio_add_pci_capability(s, 1, bar_num,\n VIRTIO_PCI_CFG_OFFSET, 0x1000, 0); /* common */\n virtio_add_pci_capability(s, 3, bar_num,\n VIRTIO_PCI_ISR_OFFSET, 0x1000, 0); /* isr */\n virtio_add_pci_capability(s, 4, bar_num,\n VIRTIO_PCI_CONFIG_OFFSET, 0x1000, 0); /* config */\n virtio_add_pci_capability(s, 2, bar_num,\n VIRTIO_PCI_NOTIFY_OFFSET, 0x1000, 0); /* notify */\n \n s->get_ram_ptr = virtio_pci_get_ram_ptr;\n s->irq = pci_device_get_irq(s->pci_dev, 0);\n s->mem_map = pci_device_get_mem_map(s->pci_dev);\n s->mem_range = cpu_register_device(s->mem_map, 0, 0x4000, s,\n virtio_pci_read, virtio_pci_write,\n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32 | DEVIO_DISABLED);\n pci_register_bar(s->pci_dev, bar_num, 0x4000, PCI_ADDRESS_SPACE_MEM,\n s, virtio_pci_bar_set);\n } else {\n /* MMIO case */\n s->mem_map = bus->mem_map;\n s->irq = bus->irq;\n s->mem_range = cpu_register_device(s->mem_map, bus->addr, VIRTIO_PAGE_SIZE,\n s, virtio_mmio_read, virtio_mmio_write,\n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32);\n s->get_ram_ptr = virtio_mmio_get_ram_ptr;\n }\n\n s->device_id = device_id;\n s->vendor_id = 0xffff;\n s->config_space_size = config_space_size;\n s->device_recv = device_recv;\n virtio_reset(s);\n}\n\nstatic uint16_t virtio_read16(VIRTIODevice *s, virtio_phys_addr_t addr)\n{\n uint8_t *ptr;\n if (addr & 1)\n return 0; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, FALSE);\n if (!ptr)\n return 0;\n return *(uint16_t *)ptr;\n}\n\nstatic void virtio_write16(VIRTIODevice *s, virtio_phys_addr_t addr,\n uint16_t val)\n{\n uint8_t *ptr;\n if (addr & 1)\n return; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return;\n *(uint16_t *)ptr = val;\n}\n\nstatic void virtio_write32(VIRTIODevice *s, virtio_phys_addr_t addr,\n uint32_t val)\n{\n uint8_t *ptr;\n if (addr & 3)\n return; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return;\n *(uint32_t *)ptr = val;\n}\n\nstatic int virtio_memcpy_from_ram(VIRTIODevice *s, uint8_t *buf,\n virtio_phys_addr_t addr, int count)\n{\n uint8_t *ptr;\n int l;\n\n while (count > 0) {\n l = min_int(count, VIRTIO_PAGE_SIZE - (addr & (VIRTIO_PAGE_SIZE - 1)));\n ptr = s->get_ram_ptr(s, addr, FALSE);\n if (!ptr)\n return -1;\n memcpy(buf, ptr, l);\n addr += l;\n buf += l;\n count -= l;\n }\n return 0;\n}\n\nstatic int virtio_memcpy_to_ram(VIRTIODevice *s, virtio_phys_addr_t addr, \n const uint8_t *buf, int count)\n{\n uint8_t *ptr;\n int l;\n\n while (count > 0) {\n l = min_int(count, VIRTIO_PAGE_SIZE - (addr & (VIRTIO_PAGE_SIZE - 1)));\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return -1;\n memcpy(ptr, buf, l);\n addr += l;\n buf += l;\n count -= l;\n }\n return 0;\n}\n\nstatic int get_desc(VIRTIODevice *s, VIRTIODesc *desc, \n int queue_idx, int desc_idx)\n{\n QueueState *qs = &s->queue[queue_idx];\n return virtio_memcpy_from_ram(s, (void *)desc, qs->desc_addr +\n desc_idx * sizeof(VIRTIODesc),\n sizeof(VIRTIODesc));\n}\n\nstatic int memcpy_to_from_queue(VIRTIODevice *s, uint8_t *buf,\n int queue_idx, int desc_idx,\n int offset, int count, BOOL to_queue)\n{\n VIRTIODesc desc;\n int l, f_write_flag;\n\n if (count == 0)\n return 0;\n\n get_desc(s, &desc, queue_idx, desc_idx);\n\n if (to_queue) {\n f_write_flag = VRING_DESC_F_WRITE;\n /* find the first write descriptor */\n for(;;) {\n if ((desc.flags & VRING_DESC_F_WRITE) == f_write_flag)\n break;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n } else {\n f_write_flag = 0;\n }\n\n /* find the descriptor at offset */\n for(;;) {\n if ((desc.flags & VRING_DESC_F_WRITE) != f_write_flag)\n return -1;\n if (offset < desc.len)\n break;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n offset -= desc.len;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n\n for(;;) {\n l = min_int(count, desc.len - offset);\n if (to_queue)\n virtio_memcpy_to_ram(s, desc.addr + offset, buf, l);\n else\n virtio_memcpy_from_ram(s, buf, desc.addr + offset, l);\n count -= l;\n if (count == 0)\n break;\n offset += l;\n buf += l;\n if (offset == desc.len) {\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n if ((desc.flags & VRING_DESC_F_WRITE) != f_write_flag)\n return -1;\n offset = 0;\n }\n }\n return 0;\n}\n\nstatic int memcpy_from_queue(VIRTIODevice *s, void *buf,\n int queue_idx, int desc_idx,\n int offset, int count)\n{\n return memcpy_to_from_queue(s, buf, queue_idx, desc_idx, offset, count,\n FALSE);\n}\n\nstatic int memcpy_to_queue(VIRTIODevice *s,\n int queue_idx, int desc_idx,\n int offset, const void *buf, int count)\n{\n return memcpy_to_from_queue(s, (void *)buf, queue_idx, desc_idx, offset,\n count, TRUE);\n}\n\n/* signal that the descriptor has been consumed */\nstatic void virtio_consume_desc(VIRTIODevice *s,\n int queue_idx, int desc_idx, int desc_len)\n{\n QueueState *qs = &s->queue[queue_idx];\n virtio_phys_addr_t addr;\n uint32_t index;\n\n addr = qs->used_addr + 2;\n index = virtio_read16(s, addr);\n virtio_write16(s, addr, index + 1);\n\n addr = qs->used_addr + 4 + (index & (qs->num - 1)) * 8;\n virtio_write32(s, addr, desc_idx);\n virtio_write32(s, addr + 4, desc_len);\n\n s->int_status |= 1;\n set_irq(s->irq, 1);\n}\n\nstatic int get_desc_rw_size(VIRTIODevice *s, \n int *pread_size, int *pwrite_size,\n int queue_idx, int desc_idx)\n{\n VIRTIODesc desc;\n int read_size, write_size;\n\n read_size = 0;\n write_size = 0;\n get_desc(s, &desc, queue_idx, desc_idx);\n\n for(;;) {\n if (desc.flags & VRING_DESC_F_WRITE)\n break;\n read_size += desc.len;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n goto done;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n \n for(;;) {\n if (!(desc.flags & VRING_DESC_F_WRITE))\n return -1;\n write_size += desc.len;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n break;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n\n done:\n *pread_size = read_size;\n *pwrite_size = write_size;\n return 0;\n}\n\n/* XXX: test if the queue is ready ? */\nstatic void queue_notify(VIRTIODevice *s, int queue_idx)\n{\n QueueState *qs = &s->queue[queue_idx];\n uint16_t avail_idx;\n int desc_idx, read_size, write_size;\n\n if (qs->manual_recv)\n return;\n\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n while (qs->last_avail_idx != avail_idx) {\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (!get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx)) {\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"queue_notify: idx=%d read_size=%d write_size=%d\\n\",\n queue_idx, read_size, write_size);\n }\n#endif\n if (s->device_recv(s, queue_idx, desc_idx,\n read_size, write_size) < 0)\n break;\n }\n qs->last_avail_idx++;\n }\n}\n\nstatic uint32_t virtio_config_read(VIRTIODevice *s, uint32_t offset,\n int size_log2)\n{\n uint32_t val;\n switch(size_log2) {\n case 0:\n if (offset < s->config_space_size) {\n val = s->config_space[offset];\n } else {\n val = 0;\n }\n break;\n case 1:\n if (offset < (s->config_space_size - 1)) {\n val = get_le16(&s->config_space[offset]);\n } else {\n val = 0;\n }\n break;\n case 2:\n if (offset < (s->config_space_size - 3)) {\n val = get_le32(s->config_space + offset);\n } else {\n val = 0;\n }\n break;\n default:\n abort();\n }\n return val;\n}\n\nstatic void virtio_config_write(VIRTIODevice *s, uint32_t offset,\n uint32_t val, int size_log2)\n{\n switch(size_log2) {\n case 0:\n if (offset < s->config_space_size) {\n s->config_space[offset] = val;\n if (s->config_write)\n s->config_write(s);\n }\n break;\n case 1:\n if (offset < s->config_space_size - 1) {\n put_le16(s->config_space + offset, val);\n if (s->config_write)\n s->config_write(s);\n }\n break;\n case 2:\n if (offset < s->config_space_size - 3) {\n put_le32(s->config_space + offset, val);\n if (s->config_write)\n s->config_write(s);\n }\n break;\n }\n}\n\nstatic uint32_t virtio_mmio_read(void *opaque, uint32_t offset, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t val;\n\n if (offset >= VIRTIO_MMIO_CONFIG) {\n return virtio_config_read(s, offset - VIRTIO_MMIO_CONFIG, size_log2);\n }\n\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_MMIO_MAGIC_VALUE:\n val = 0x74726976;\n break;\n case VIRTIO_MMIO_VERSION:\n val = 2;\n break;\n case VIRTIO_MMIO_DEVICE_ID:\n val = s->device_id;\n break;\n case VIRTIO_MMIO_VENDOR_ID:\n val = s->vendor_id;\n break;\n case VIRTIO_MMIO_DEVICE_FEATURES:\n switch(s->device_features_sel) {\n case 0:\n val = s->device_features;\n break;\n case 1:\n val = 1; /* version 1 */\n break;\n default:\n val = 0;\n break;\n }\n break;\n case VIRTIO_MMIO_DEVICE_FEATURES_SEL:\n val = s->device_features_sel;\n break;\n case VIRTIO_MMIO_QUEUE_SEL:\n val = s->queue_sel;\n break;\n case VIRTIO_MMIO_QUEUE_NUM_MAX:\n val = MAX_QUEUE_NUM;\n break;\n case VIRTIO_MMIO_QUEUE_NUM:\n val = s->queue[s->queue_sel].num;\n break;\n case VIRTIO_MMIO_QUEUE_DESC_LOW:\n val = s->queue[s->queue_sel].desc_addr;\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_LOW:\n val = s->queue[s->queue_sel].avail_addr;\n break;\n case VIRTIO_MMIO_QUEUE_USED_LOW:\n val = s->queue[s->queue_sel].used_addr;\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_MMIO_QUEUE_DESC_HIGH:\n val = s->queue[s->queue_sel].desc_addr >> 32;\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_HIGH:\n val = s->queue[s->queue_sel].avail_addr >> 32;\n break;\n case VIRTIO_MMIO_QUEUE_USED_HIGH:\n val = s->queue[s->queue_sel].used_addr >> 32;\n break;\n#endif\n case VIRTIO_MMIO_QUEUE_READY:\n val = s->queue[s->queue_sel].ready;\n break;\n case VIRTIO_MMIO_INTERRUPT_STATUS:\n val = s->int_status;\n break;\n case VIRTIO_MMIO_STATUS:\n val = s->status;\n break;\n case VIRTIO_MMIO_CONFIG_GENERATION:\n val = 0;\n break;\n default:\n val = 0;\n break;\n }\n } else {\n val = 0;\n }\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_mmio_read: offset=0x%x val=0x%x size=%d\\n\", \n offset, val, 1 << size_log2);\n }\n#endif\n return val;\n}\n\n#if VIRTIO_ADDR_BITS == 64\nstatic void set_low32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = (*paddr & ~(virtio_phys_addr_t)0xffffffff) | val;\n}\n\nstatic void set_high32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = (*paddr & 0xffffffff) | ((virtio_phys_addr_t)val << 32);\n}\n#else\nstatic void set_low32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = val;\n}\n#endif\n\nstatic void virtio_mmio_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n VIRTIODevice *s = opaque;\n \n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_mmio_write: offset=0x%x val=0x%x size=%d\\n\",\n offset, val, 1 << size_log2);\n }\n#endif\n\n if (offset >= VIRTIO_MMIO_CONFIG) {\n virtio_config_write(s, offset - VIRTIO_MMIO_CONFIG, val, size_log2);\n return;\n }\n\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_MMIO_DEVICE_FEATURES_SEL:\n s->device_features_sel = val;\n break;\n case VIRTIO_MMIO_QUEUE_SEL:\n if (val < MAX_QUEUE)\n s->queue_sel = val;\n break;\n case VIRTIO_MMIO_QUEUE_NUM:\n if ((val & (val - 1)) == 0 && val > 0) {\n s->queue[s->queue_sel].num = val;\n }\n break;\n case VIRTIO_MMIO_QUEUE_DESC_LOW:\n set_low32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_LOW:\n set_low32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_USED_LOW:\n set_low32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_MMIO_QUEUE_DESC_HIGH:\n set_high32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_HIGH:\n set_high32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_USED_HIGH:\n set_high32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#endif\n case VIRTIO_MMIO_STATUS:\n s->status = val;\n if (val == 0) {\n /* reset */\n set_irq(s->irq, 0);\n virtio_reset(s);\n }\n break;\n case VIRTIO_MMIO_QUEUE_READY:\n s->queue[s->queue_sel].ready = val & 1;\n break;\n case VIRTIO_MMIO_QUEUE_NOTIFY:\n if (val < MAX_QUEUE)\n queue_notify(s, val);\n break;\n case VIRTIO_MMIO_INTERRUPT_ACK:\n s->int_status &= ~val;\n if (s->int_status == 0) {\n set_irq(s->irq, 0);\n }\n break;\n }\n }\n}\n\nstatic uint32_t virtio_pci_read(void *opaque, uint32_t offset1, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t offset;\n uint32_t val = 0;\n\n offset = offset1 & 0xfff;\n switch(offset1 >> 12) {\n case VIRTIO_PCI_CFG_OFFSET >> 12:\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_FEATURE:\n switch(s->device_features_sel) {\n case 0:\n val = s->device_features;\n break;\n case 1:\n val = 1; /* version 1 */\n break;\n default:\n val = 0;\n break;\n }\n break;\n case VIRTIO_PCI_DEVICE_FEATURE_SEL:\n val = s->device_features_sel;\n break;\n case VIRTIO_PCI_QUEUE_DESC_LOW:\n val = s->queue[s->queue_sel].desc_addr;\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_LOW:\n val = s->queue[s->queue_sel].avail_addr;\n break;\n case VIRTIO_PCI_QUEUE_USED_LOW:\n val = s->queue[s->queue_sel].used_addr;\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_PCI_QUEUE_DESC_HIGH:\n val = s->queue[s->queue_sel].desc_addr >> 32;\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_HIGH:\n val = s->queue[s->queue_sel].avail_addr >> 32;\n break;\n case VIRTIO_PCI_QUEUE_USED_HIGH:\n val = s->queue[s->queue_sel].used_addr >> 32;\n break;\n#endif\n }\n } else if (size_log2 == 1) {\n switch(offset) {\n case VIRTIO_PCI_NUM_QUEUES:\n val = MAX_QUEUE_NUM;\n break;\n case VIRTIO_PCI_QUEUE_SEL:\n val = s->queue_sel;\n break;\n case VIRTIO_PCI_QUEUE_SIZE:\n val = s->queue[s->queue_sel].num;\n break;\n case VIRTIO_PCI_QUEUE_ENABLE:\n val = s->queue[s->queue_sel].ready;\n break;\n case VIRTIO_PCI_QUEUE_NOTIFY_OFF:\n val = 0;\n break;\n }\n } else if (size_log2 == 0) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_STATUS:\n val = s->status;\n break;\n }\n }\n break;\n case VIRTIO_PCI_ISR_OFFSET >> 12:\n if (offset == 0 && size_log2 == 0) {\n val = s->int_status;\n s->int_status = 0;\n set_irq(s->irq, 0);\n }\n break;\n case VIRTIO_PCI_CONFIG_OFFSET >> 12:\n val = virtio_config_read(s, offset, size_log2);\n break;\n }\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_pci_read: offset=0x%x val=0x%x size=%d\\n\", \n offset1, val, 1 << size_log2);\n }\n#endif\n return val;\n}\n\nstatic void virtio_pci_write(void *opaque, uint32_t offset1,\n uint32_t val, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t offset;\n \n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_pci_write: offset=0x%x val=0x%x size=%d\\n\",\n offset1, val, 1 << size_log2);\n }\n#endif\n offset = offset1 & 0xfff;\n switch(offset1 >> 12) {\n case VIRTIO_PCI_CFG_OFFSET >> 12:\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_FEATURE_SEL:\n s->device_features_sel = val;\n break;\n case VIRTIO_PCI_QUEUE_DESC_LOW:\n set_low32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_LOW:\n set_low32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_USED_LOW:\n set_low32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_PCI_QUEUE_DESC_HIGH:\n set_high32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_HIGH:\n set_high32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_USED_HIGH:\n set_high32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#endif\n }\n } else if (size_log2 == 1) {\n switch(offset) {\n case VIRTIO_PCI_QUEUE_SEL:\n if (val < MAX_QUEUE)\n s->queue_sel = val;\n break;\n case VIRTIO_PCI_QUEUE_SIZE:\n if ((val & (val - 1)) == 0 && val > 0) {\n s->queue[s->queue_sel].num = val;\n }\n break;\n case VIRTIO_PCI_QUEUE_ENABLE:\n s->queue[s->queue_sel].ready = val & 1;\n break;\n }\n } else if (size_log2 == 0) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_STATUS:\n s->status = val;\n if (val == 0) {\n /* reset */\n set_irq(s->irq, 0);\n virtio_reset(s);\n }\n break;\n }\n }\n break;\n case VIRTIO_PCI_CONFIG_OFFSET >> 12:\n virtio_config_write(s, offset, val, size_log2);\n break;\n case VIRTIO_PCI_NOTIFY_OFFSET >> 12:\n if (val < MAX_QUEUE)\n queue_notify(s, val);\n break;\n }\n}\n\nvoid virtio_set_debug(VIRTIODevice *s, int debug)\n{\n s->debug = debug;\n}\n\nstatic void virtio_config_change_notify(VIRTIODevice *s)\n{\n /* INT_CONFIG interrupt */\n s->int_status |= 2;\n set_irq(s->irq, 1);\n}\n\n/*********************************************************************/\n/* block device */\n\ntypedef struct {\n uint32_t type;\n uint8_t *buf;\n int write_size;\n int queue_idx;\n int desc_idx;\n} BlockRequest;\n\ntypedef struct VIRTIOBlockDevice {\n VIRTIODevice common;\n BlockDevice *bs;\n\n BOOL req_in_progress;\n BlockRequest req; /* request in progress */\n} VIRTIOBlockDevice;\n\ntypedef struct {\n uint32_t type;\n uint32_t ioprio;\n uint64_t sector_num;\n} BlockRequestHeader;\n\n#define VIRTIO_BLK_T_IN 0\n#define VIRTIO_BLK_T_OUT 1\n#define VIRTIO_BLK_T_FLUSH 4\n#define VIRTIO_BLK_T_FLUSH_OUT 5\n\n#define VIRTIO_BLK_S_OK 0\n#define VIRTIO_BLK_S_IOERR 1\n#define VIRTIO_BLK_S_UNSUPP 2\n\n#define SECTOR_SIZE 512\n\nstatic void virtio_block_req_end(VIRTIODevice *s, int ret)\n{\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n int write_size;\n int queue_idx = s1->req.queue_idx;\n int desc_idx = s1->req.desc_idx;\n uint8_t *buf, buf1[1];\n\n switch(s1->req.type) {\n case VIRTIO_BLK_T_IN:\n write_size = s1->req.write_size;\n buf = s1->req.buf;\n if (ret < 0) {\n buf[write_size - 1] = VIRTIO_BLK_S_IOERR;\n } else {\n buf[write_size - 1] = VIRTIO_BLK_S_OK;\n }\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, write_size);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, write_size);\n break;\n case VIRTIO_BLK_T_OUT:\n if (ret < 0)\n buf1[0] = VIRTIO_BLK_S_IOERR;\n else\n buf1[0] = VIRTIO_BLK_S_OK;\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf1, sizeof(buf1));\n virtio_consume_desc(s, queue_idx, desc_idx, 1);\n break;\n default:\n abort();\n }\n}\n\nstatic void virtio_block_req_cb(void *opaque, int ret)\n{\n VIRTIODevice *s = opaque;\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n\n virtio_block_req_end(s, ret);\n \n s1->req_in_progress = FALSE;\n\n /* handle next requests */\n queue_notify((VIRTIODevice *)s, s1->req.queue_idx);\n}\n\n/* XXX: handle async I/O */\nstatic int virtio_block_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n BlockDevice *bs = s1->bs;\n BlockRequestHeader h;\n uint8_t *buf;\n int len, ret;\n\n if (s1->req_in_progress)\n return -1;\n \n if (memcpy_from_queue(s, &h, queue_idx, desc_idx, 0, sizeof(h)) < 0)\n return 0;\n s1->req.type = h.type;\n s1->req.queue_idx = queue_idx;\n s1->req.desc_idx = desc_idx;\n switch(h.type) {\n case VIRTIO_BLK_T_IN:\n s1->req.buf = malloc(write_size);\n s1->req.write_size = write_size;\n ret = bs->read_async(bs, h.sector_num, s1->req.buf, \n (write_size - 1) / SECTOR_SIZE,\n virtio_block_req_cb, s);\n if (ret > 0) {\n /* asyncronous read */\n s1->req_in_progress = TRUE;\n } else {\n virtio_block_req_end(s, ret);\n }\n break;\n case VIRTIO_BLK_T_OUT:\n assert(write_size >= 1);\n len = read_size - sizeof(h);\n buf = malloc(len);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, sizeof(h), len);\n ret = bs->write_async(bs, h.sector_num, buf, len / SECTOR_SIZE,\n virtio_block_req_cb, s);\n free(buf);\n if (ret > 0) {\n /* asyncronous write */\n s1->req_in_progress = TRUE;\n } else {\n virtio_block_req_end(s, ret);\n }\n break;\n default:\n break;\n }\n return 0;\n}\n\nVIRTIODevice *virtio_block_init(VIRTIOBusDef *bus, BlockDevice *bs)\n{\n VIRTIOBlockDevice *s;\n uint64_t nb_sectors;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 2, 8, virtio_block_recv_request);\n s->bs = bs;\n \n nb_sectors = bs->get_sector_count(bs);\n put_le32(s->common.config_space, nb_sectors);\n put_le32(s->common.config_space + 4, nb_sectors >> 32);\n\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* network device */\n\ntypedef struct VIRTIONetDevice {\n VIRTIODevice common;\n EthernetDevice *es;\n int header_size;\n} VIRTIONetDevice;\n\ntypedef struct {\n uint8_t flags;\n uint8_t gso_type;\n uint16_t hdr_len;\n uint16_t gso_size;\n uint16_t csum_start;\n uint16_t csum_offset;\n uint16_t num_buffers;\n} VIRTIONetHeader;\n\nstatic int virtio_net_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIONetDevice *s1 = (VIRTIONetDevice *)s;\n EthernetDevice *es = s1->es;\n VIRTIONetHeader h;\n uint8_t *buf;\n int len;\n\n if (queue_idx == 1) {\n /* send to network */\n if (memcpy_from_queue(s, &h, queue_idx, desc_idx, 0, s1->header_size) < 0)\n return 0;\n len = read_size - s1->header_size;\n buf = malloc(len);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, s1->header_size, len);\n es->write_packet(es, buf, len);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\nstatic BOOL virtio_net_can_write_packet(EthernetDevice *es)\n{\n VIRTIODevice *s = es->device_opaque;\n QueueState *qs = &s->queue[0];\n uint16_t avail_idx;\n\n if (!qs->ready)\n return FALSE;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n return qs->last_avail_idx != avail_idx;\n}\n\nstatic void virtio_net_write_packet(EthernetDevice *es, const uint8_t *buf, int buf_len)\n{\n VIRTIODevice *s = es->device_opaque;\n VIRTIONetDevice *s1 = (VIRTIONetDevice *)s;\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n VIRTIONetHeader h;\n int len, read_size, write_size;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx))\n return;\n len = s1->header_size + buf_len; \n if (len > write_size)\n return;\n memset(&h, 0, s1->header_size);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, &h, s1->header_size);\n memcpy_to_queue(s, queue_idx, desc_idx, s1->header_size, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, len);\n qs->last_avail_idx++;\n}\n\nstatic void virtio_net_set_carrier(EthernetDevice *es, BOOL carrier_state)\n{\n#if 0\n VIRTIODevice *s1 = es->device_opaque;\n VIRTIONetDevice *s = (VIRTIONetDevice *)s1;\n int cur_carrier_state;\n\n // printf(\"virtio_net_set_carrier: %d\\n\", carrier_state);\n cur_carrier_state = s->common.config_space[6] & 1;\n if (cur_carrier_state != carrier_state) {\n s->common.config_space[6] = (carrier_state << 0);\n virtio_config_change_notify(s1);\n }\n#endif\n}\n\nVIRTIODevice *virtio_net_init(VIRTIOBusDef *bus, EthernetDevice *es)\n{\n VIRTIONetDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 1, 6 + 2, virtio_net_recv_request);\n /* VIRTIO_NET_F_MAC, VIRTIO_NET_F_STATUS */\n s->common.device_features = (1 << 5) /* | (1 << 16) */;\n s->common.queue[0].manual_recv = TRUE;\n s->es = es;\n memcpy(s->common.config_space, es->mac_addr, 6);\n /* status */\n s->common.config_space[6] = 0;\n s->common.config_space[7] = 0;\n\n s->header_size = sizeof(VIRTIONetHeader);\n \n es->device_opaque = s;\n es->device_can_write_packet = virtio_net_can_write_packet;\n es->device_write_packet = virtio_net_write_packet;\n es->device_set_carrier = virtio_net_set_carrier;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* console device */\n\ntypedef struct VIRTIOConsoleDevice {\n VIRTIODevice common;\n CharacterDevice *cs;\n} VIRTIOConsoleDevice;\n\nstatic int virtio_console_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIOConsoleDevice *s1 = (VIRTIOConsoleDevice *)s;\n CharacterDevice *cs = s1->cs;\n uint8_t *buf;\n\n if (queue_idx == 1) {\n /* send to console */\n buf = malloc(read_size);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, 0, read_size);\n cs->write_data(cs->opaque, buf, read_size);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\nBOOL virtio_console_can_write_data(VIRTIODevice *s)\n{\n QueueState *qs = &s->queue[0];\n uint16_t avail_idx;\n\n if (!qs->ready)\n return FALSE;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n return qs->last_avail_idx != avail_idx;\n}\n\nint virtio_console_get_write_len(VIRTIODevice *s)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n int read_size, write_size;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return 0;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return 0;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx))\n return 0;\n return write_size;\n}\n\nint virtio_console_write_data(VIRTIODevice *s, const uint8_t *buf, int buf_len)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return 0;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return 0;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, buf_len);\n qs->last_avail_idx++;\n return buf_len;\n}\n\n/* send a resize event */\nvoid virtio_console_resize_event(VIRTIODevice *s, int width, int height)\n{\n /* indicate the console size */\n put_le16(s->config_space + 0, width);\n put_le16(s->config_space + 2, height);\n\n virtio_config_change_notify(s);\n}\n\nVIRTIODevice *virtio_console_init(VIRTIOBusDef *bus, CharacterDevice *cs)\n{\n VIRTIOConsoleDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 3, 4, virtio_console_recv_request);\n s->common.device_features = (1 << 0); /* VIRTIO_CONSOLE_F_SIZE */\n s->common.queue[0].manual_recv = TRUE;\n \n s->cs = cs;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* input device */\n\nenum {\n VIRTIO_INPUT_CFG_UNSET = 0x00,\n VIRTIO_INPUT_CFG_ID_NAME = 0x01,\n VIRTIO_INPUT_CFG_ID_SERIAL = 0x02,\n VIRTIO_INPUT_CFG_ID_DEVIDS = 0x03,\n VIRTIO_INPUT_CFG_PROP_BITS = 0x10,\n VIRTIO_INPUT_CFG_EV_BITS = 0x11,\n VIRTIO_INPUT_CFG_ABS_INFO = 0x12,\n};\n\n#define VIRTIO_INPUT_EV_SYN 0x00\n#define VIRTIO_INPUT_EV_KEY 0x01\n#define VIRTIO_INPUT_EV_REL 0x02\n#define VIRTIO_INPUT_EV_ABS 0x03\n#define VIRTIO_INPUT_EV_REP 0x14\n\n#define BTN_LEFT 0x110\n#define BTN_RIGHT 0x111\n#define BTN_MIDDLE 0x112\n#define BTN_GEAR_DOWN 0x150\n#define BTN_GEAR_UP 0x151\n\n#define REL_X 0x00\n#define REL_Y 0x01\n#define REL_Z 0x02\n#define REL_WHEEL 0x08\n\n#define ABS_X 0x00\n#define ABS_Y 0x01\n#define ABS_Z 0x02\n\ntypedef struct VIRTIOInputDevice {\n VIRTIODevice common;\n VirtioInputTypeEnum type;\n uint32_t buttons_state;\n} VIRTIOInputDevice;\n\nstatic const uint16_t buttons_list[] = {\n BTN_LEFT, BTN_RIGHT, BTN_MIDDLE\n};\n\nstatic int virtio_input_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n if (queue_idx == 1) {\n /* led & keyboard updates */\n // printf(\"%s: write_size=%d\\n\", __func__, write_size);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\n/* return < 0 if could not send key event */\nstatic int virtio_input_queue_event(VIRTIODevice *s,\n uint16_t type, uint16_t code,\n uint32_t value)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx, buf_len;\n uint16_t avail_idx;\n uint8_t buf[8];\n\n if (!qs->ready)\n return -1;\n\n put_le16(buf, type);\n put_le16(buf + 2, code);\n put_le32(buf + 4, value);\n buf_len = 8;\n \n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return -1;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n // printf(\"send: queue_idx=%d desc_idx=%d\\n\", queue_idx, desc_idx);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, buf_len);\n qs->last_avail_idx++;\n return 0;\n}\n\nint virtio_input_send_key_event(VIRTIODevice *s, BOOL is_down,\n uint16_t key_code)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n int ret;\n \n if (s1->type != VIRTIO_INPUT_TYPE_KEYBOARD)\n return -1;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_KEY, key_code, is_down);\n if (ret)\n return ret;\n return virtio_input_queue_event(s, VIRTIO_INPUT_EV_SYN, 0, 0);\n}\n\n/* also used for the tablet */\nint virtio_input_send_mouse_event(VIRTIODevice *s, int dx, int dy, int dz,\n unsigned int buttons)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n int ret, i, b, last_b;\n\n if (s1->type != VIRTIO_INPUT_TYPE_MOUSE &&\n s1->type != VIRTIO_INPUT_TYPE_TABLET)\n return -1;\n if (s1->type == VIRTIO_INPUT_TYPE_MOUSE) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_X, dx);\n if (ret != 0)\n return ret;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_Y, dy);\n if (ret != 0)\n return ret;\n } else {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_ABS, ABS_X, dx);\n if (ret != 0)\n return ret;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_ABS, ABS_Y, dy);\n if (ret != 0)\n return ret;\n }\n if (dz != 0) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_WHEEL, dz);\n if (ret != 0)\n return ret;\n }\n\n if (buttons != s1->buttons_state) {\n for(i = 0; i < countof(buttons_list); i++) {\n b = (buttons >> i) & 1;\n last_b = (s1->buttons_state >> i) & 1;\n if (b != last_b) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_KEY,\n buttons_list[i], b);\n if (ret != 0)\n return ret;\n }\n }\n s1->buttons_state = buttons;\n }\n\n return virtio_input_queue_event(s, VIRTIO_INPUT_EV_SYN, 0, 0);\n}\n\nstatic void set_bit(uint8_t *tab, int k)\n{\n tab[k >> 3] |= 1 << (k & 7);\n}\n\nstatic void virtio_input_config_write(VIRTIODevice *s)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n uint8_t *config = s->config_space;\n int i;\n \n // printf(\"config_write: %02x %02x\\n\", config[0], config[1]);\n switch(config[0]) {\n case VIRTIO_INPUT_CFG_UNSET:\n break;\n case VIRTIO_INPUT_CFG_ID_NAME:\n {\n const char *name;\n int len;\n switch(s1->type) {\n case VIRTIO_INPUT_TYPE_KEYBOARD:\n name = \"virtio_keyboard\";\n break;\n case VIRTIO_INPUT_TYPE_MOUSE:\n name = \"virtio_mouse\";\n break;\n case VIRTIO_INPUT_TYPE_TABLET:\n name = \"virtio_tablet\";\n break;\n default:\n abort();\n }\n len = strlen(name);\n config[2] = len;\n memcpy(config + 8, name, len);\n }\n break;\n default:\n case VIRTIO_INPUT_CFG_ID_SERIAL:\n case VIRTIO_INPUT_CFG_ID_DEVIDS:\n case VIRTIO_INPUT_CFG_PROP_BITS:\n config[2] = 0; /* size of reply */\n break;\n case VIRTIO_INPUT_CFG_EV_BITS:\n config[2] = 0;\n switch(s1->type) {\n case VIRTIO_INPUT_TYPE_KEYBOARD:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 128 / 8;\n memset(config + 8, 0xff, 128 / 8); /* bitmap */\n break;\n case VIRTIO_INPUT_EV_REP: /* allow key repetition */\n config[2] = 1;\n break;\n default:\n break;\n }\n break;\n case VIRTIO_INPUT_TYPE_MOUSE:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 512 / 8;\n memset(config + 8, 0, 512 / 8); /* bitmap */\n for(i = 0; i < countof(buttons_list); i++)\n set_bit(config + 8, buttons_list[i]);\n break;\n case VIRTIO_INPUT_EV_REL:\n config[2] = 2;\n config[8] = 0;\n config[9] = 0;\n set_bit(config + 8, REL_X);\n set_bit(config + 8, REL_Y);\n set_bit(config + 8, REL_WHEEL);\n break;\n default:\n break;\n }\n break;\n case VIRTIO_INPUT_TYPE_TABLET:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 512 / 8;\n memset(config + 8, 0, 512 / 8); /* bitmap */\n for(i = 0; i < countof(buttons_list); i++)\n set_bit(config + 8, buttons_list[i]);\n break;\n case VIRTIO_INPUT_EV_REL:\n config[2] = 2;\n config[8] = 0;\n config[9] = 0;\n set_bit(config + 8, REL_WHEEL);\n break;\n case VIRTIO_INPUT_EV_ABS:\n config[2] = 1;\n config[8] = 0;\n set_bit(config + 8, ABS_X);\n set_bit(config + 8, ABS_Y);\n break;\n default:\n break;\n }\n break;\n default:\n abort();\n }\n break;\n case VIRTIO_INPUT_CFG_ABS_INFO:\n if (s1->type == VIRTIO_INPUT_TYPE_TABLET && config[1] <= 1) {\n /* for ABS_X and ABS_Y */\n config[2] = 5 * 4;\n put_le32(config + 8, 0); /* min */\n put_le32(config + 12, VIRTIO_INPUT_ABS_SCALE - 1) ; /* max */\n put_le32(config + 16, 0); /* fuzz */\n put_le32(config + 20, 0); /* flat */\n put_le32(config + 24, 0); /* res */\n }\n break;\n }\n}\n\nVIRTIODevice *virtio_input_init(VIRTIOBusDef *bus, VirtioInputTypeEnum type)\n{\n VIRTIOInputDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 18, 256, virtio_input_recv_request);\n s->common.queue[0].manual_recv = TRUE;\n s->common.device_features = 0;\n s->common.config_write = virtio_input_config_write;\n s->type = type;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* 9p filesystem device */\n\ntypedef struct {\n struct list_head link;\n uint32_t fid;\n FSFile *fd;\n} FIDDesc;\n\ntypedef struct VIRTIO9PDevice {\n VIRTIODevice common;\n FSDevice *fs;\n int msize; /* maximum message size */\n struct list_head fid_list; /* list of FIDDesc */\n BOOL req_in_progress;\n} VIRTIO9PDevice;\n\nstatic FIDDesc *fid_find1(VIRTIO9PDevice *s, uint32_t fid)\n{\n struct list_head *el;\n FIDDesc *f;\n\n list_for_each(el, &s->fid_list) {\n f = list_entry(el, FIDDesc, link);\n if (f->fid == fid)\n return f;\n }\n return NULL;\n}\n\nstatic FSFile *fid_find(VIRTIO9PDevice *s, uint32_t fid)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (!f)\n return NULL;\n return f->fd;\n}\n\nstatic void fid_delete(VIRTIO9PDevice *s, uint32_t fid)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (f) {\n s->fs->fs_delete(s->fs, f->fd);\n list_del(&f->link);\n free(f);\n }\n}\n\nstatic void fid_set(VIRTIO9PDevice *s, uint32_t fid, FSFile *fd)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (f) {\n s->fs->fs_delete(s->fs, f->fd);\n f->fd = fd;\n } else {\n f = malloc(sizeof(*f));\n f->fid = fid;\n f->fd = fd;\n list_add(&f->link, &s->fid_list);\n }\n}\n\n#ifdef DEBUG_VIRTIO\n\ntypedef struct {\n uint8_t tag;\n const char *name;\n} Virtio9POPName;\n\nstatic const Virtio9POPName virtio_9p_op_names[] = {\n { 8, \"statfs\" },\n { 12, \"lopen\" },\n { 14, \"lcreate\" },\n { 16, \"symlink\" },\n { 18, \"mknod\" },\n { 22, \"readlink\" },\n { 24, \"getattr\" },\n { 26, \"setattr\" },\n { 30, \"xattrwalk\" },\n { 40, \"readdir\" },\n { 50, \"fsync\" },\n { 52, \"lock\" },\n { 54, \"getlock\" },\n { 70, \"link\" },\n { 72, \"mkdir\" },\n { 74, \"renameat\" },\n { 76, \"unlinkat\" },\n { 100, \"version\" },\n { 104, \"attach\" },\n { 108, \"flush\" },\n { 110, \"walk\" },\n { 116, \"read\" },\n { 118, \"write\" },\n { 120, \"clunk\" },\n { 0, NULL },\n};\n\nstatic const char *get_9p_op_name(int tag)\n{\n const Virtio9POPName *p;\n for(p = virtio_9p_op_names; p->name != NULL; p++) {\n if (p->tag == tag)\n return p->name;\n }\n return NULL;\n}\n\n#endif /* DEBUG_VIRTIO */\n\nstatic int marshall(VIRTIO9PDevice *s, \n uint8_t *buf1, int max_len, const char *fmt, ...)\n{\n va_list ap;\n int c;\n uint32_t val;\n uint64_t val64;\n uint8_t *buf, *buf_end;\n\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" ->\");\n#endif\n va_start(ap, fmt);\n buf = buf1;\n buf_end = buf1 + max_len;\n for(;;) {\n c = *fmt++;\n if (c == '\\0')\n break;\n switch(c) {\n case 'b':\n assert(buf + 1 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" b=%d\", val);\n#endif\n buf[0] = val;\n buf += 1;\n break;\n case 'h':\n assert(buf + 2 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" h=%d\", val);\n#endif\n put_le16(buf, val);\n buf += 2;\n break;\n case 'w':\n assert(buf + 4 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" w=%d\", val);\n#endif\n put_le32(buf, val);\n buf += 4;\n break;\n case 'd':\n assert(buf + 8 <= buf_end);\n val64 = va_arg(ap, uint64_t);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" d=%\" PRId64, val64);\n#endif\n put_le64(buf, val64);\n buf += 8;\n break;\n case 's':\n {\n char *str;\n int len;\n str = va_arg(ap, char *);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" s=\\\"%s\\\"\", str);\n#endif\n len = strlen(str);\n assert(len <= 65535);\n assert(buf + 2 + len <= buf_end);\n put_le16(buf, len);\n buf += 2;\n memcpy(buf, str, len);\n buf += len;\n }\n break;\n case 'Q':\n {\n FSQID *qid;\n assert(buf + 13 <= buf_end);\n qid = va_arg(ap, FSQID *);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" Q=%d:%d:%\" PRIu64, qid->type, qid->version, qid->path);\n#endif\n buf[0] = qid->type;\n put_le32(buf + 1, qid->version);\n put_le64(buf + 5, qid->path);\n buf += 13;\n }\n break;\n default:\n abort();\n }\n }\n va_end(ap);\n return buf - buf1;\n}\n\n/* return < 0 if error */\n/* XXX: free allocated strings in case of error */\nstatic int unmarshall(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, int *poffset, const char *fmt, ...)\n{\n VIRTIODevice *s1 = (VIRTIODevice *)s;\n va_list ap;\n int offset, c;\n uint8_t buf[16];\n\n offset = *poffset;\n va_start(ap, fmt);\n for(;;) {\n c = *fmt++;\n if (c == '\\0')\n break;\n switch(c) {\n case 'b':\n {\n uint8_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 1))\n return -1;\n ptr = va_arg(ap, uint8_t *);\n *ptr = buf[0];\n offset += 1;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" b=%d\", *ptr);\n#endif\n }\n break;\n case 'h':\n {\n uint16_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 2))\n return -1;\n ptr = va_arg(ap, uint16_t *);\n *ptr = get_le16(buf);\n offset += 2;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" h=%d\", *ptr);\n#endif\n }\n break;\n case 'w':\n {\n uint32_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 4))\n return -1;\n ptr = va_arg(ap, uint32_t *);\n *ptr = get_le32(buf);\n offset += 4;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" w=%d\", *ptr);\n#endif\n }\n break;\n case 'd':\n {\n uint64_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 8))\n return -1;\n ptr = va_arg(ap, uint64_t *);\n *ptr = get_le64(buf);\n offset += 8;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" d=%\" PRId64, *ptr);\n#endif\n }\n break;\n case 's':\n {\n char *str, **ptr;\n int len;\n\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 2))\n return -1;\n len = get_le16(buf);\n offset += 2;\n str = malloc(len + 1);\n if (memcpy_from_queue(s1, str, queue_idx, desc_idx, offset, len))\n return -1;\n str[len] = '\\0';\n offset += len;\n ptr = va_arg(ap, char **);\n *ptr = str;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" s=\\\"%s\\\"\", *ptr);\n#endif\n }\n break;\n default:\n abort();\n }\n }\n va_end(ap);\n *poffset = offset;\n return 0;\n}\n\nstatic void virtio_9p_send_reply(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, uint8_t id, uint16_t tag, \n uint8_t *buf, int buf_len)\n{\n uint8_t *buf1;\n int len;\n\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P) {\n if (id == 6)\n printf(\" (error)\");\n printf(\"\\n\");\n }\n#endif\n len = buf_len + 7;\n buf1 = malloc(len);\n put_le32(buf1, len);\n buf1[4] = id + 1;\n put_le16(buf1 + 5, tag);\n memcpy(buf1 + 7, buf, buf_len);\n memcpy_to_queue((VIRTIODevice *)s, queue_idx, desc_idx, 0, buf1, len);\n virtio_consume_desc((VIRTIODevice *)s, queue_idx, desc_idx, len);\n free(buf1);\n}\n\nstatic void virtio_9p_send_error(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, uint16_t tag, uint32_t error)\n{\n uint8_t buf[4];\n int buf_len;\n\n buf_len = marshall(s, buf, sizeof(buf), \"w\", -error);\n virtio_9p_send_reply(s, queue_idx, desc_idx, 6, tag, buf, buf_len);\n}\n\ntypedef struct {\n VIRTIO9PDevice *dev;\n int queue_idx;\n int desc_idx;\n uint16_t tag;\n} P9OpenInfo;\n\nstatic void virtio_9p_open_reply(FSDevice *fs, FSQID *qid, int err,\n P9OpenInfo *oi)\n{\n VIRTIO9PDevice *s = oi->dev;\n uint8_t buf[32];\n int buf_len;\n \n if (err < 0) {\n virtio_9p_send_error(s, oi->queue_idx, oi->desc_idx, oi->tag, err);\n } else {\n buf_len = marshall(s, buf, sizeof(buf),\n \"Qw\", qid, s->msize - 24);\n virtio_9p_send_reply(s, oi->queue_idx, oi->desc_idx, 12, oi->tag,\n buf, buf_len);\n }\n free(oi);\n}\n\nstatic void virtio_9p_open_cb(FSDevice *fs, FSQID *qid, int err,\n void *opaque)\n{\n P9OpenInfo *oi = opaque;\n VIRTIO9PDevice *s = oi->dev;\n int queue_idx = oi->queue_idx;\n \n virtio_9p_open_reply(fs, qid, err, oi);\n\n s->req_in_progress = FALSE;\n\n /* handle next requests */\n queue_notify((VIRTIODevice *)s, queue_idx);\n}\n\nstatic int virtio_9p_recv_request(VIRTIODevice *s1, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIO9PDevice *s = (VIRTIO9PDevice *)s1;\n int offset, header_len;\n uint8_t id;\n uint16_t tag;\n uint8_t buf[1024];\n int buf_len, err;\n FSDevice *fs = s->fs;\n\n if (queue_idx != 0)\n return 0;\n \n if (s->req_in_progress)\n return -1;\n \n offset = 0;\n header_len = 4 + 1 + 2;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, header_len)) {\n tag = 0;\n goto protocol_error;\n }\n //size = get_le32(buf);\n id = buf[4];\n tag = get_le16(buf + 5);\n offset += header_len;\n \n#ifdef DEBUG_VIRTIO\n if (s1->debug & VIRTIO_DEBUG_9P) {\n const char *name;\n name = get_9p_op_name(id);\n printf(\"9p: op=\");\n if (name)\n printf(\"%s\", name);\n else\n printf(\"%d\", id);\n }\n#endif\n /* Note: same subset as JOR1K */\n switch(id) {\n case 8: /* statfs */\n {\n FSStatFS st;\n\n fs->fs_statfs(fs, &st);\n buf_len = marshall(s, buf, sizeof(buf),\n \"wwddddddw\", \n 0,\n st.f_bsize,\n st.f_blocks,\n st.f_bfree,\n st.f_bavail,\n st.f_files,\n st.f_ffree,\n 0, /* id */\n 256 /* max filename length */\n );\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 12: /* lopen */\n {\n uint32_t fid, flags;\n FSFile *f;\n FSQID qid;\n P9OpenInfo *oi;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"ww\", &fid, &flags))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n oi = malloc(sizeof(*oi));\n oi->dev = s;\n oi->queue_idx = queue_idx;\n oi->desc_idx = desc_idx;\n oi->tag = tag;\n err = fs->fs_open(fs, &qid, f, flags, virtio_9p_open_cb, oi);\n if (err <= 0) {\n virtio_9p_open_reply(fs, &qid, err, oi);\n } else {\n s->req_in_progress = TRUE;\n }\n }\n break;\n case 14: /* lcreate */\n {\n uint32_t fid, flags, mode, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wswww\", &fid, &name, &flags, &mode, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_create(fs, &qid, f, name, flags, mode, gid);\n }\n free(name);\n if (err) \n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Qw\", &qid, s->msize - 24);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 16: /* symlink */\n {\n uint32_t fid, gid;\n char *name, *symgt;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wssw\", &fid, &name, &symgt, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_symlink(fs, &qid, f, name, symgt, gid);\n }\n free(name);\n free(symgt);\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 18: /* mknod */\n {\n uint32_t fid, mode, major, minor, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wswwww\", &fid, &name, &mode, &major, &minor, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_mknod(fs, &qid, f, name, mode, major, minor, gid);\n }\n free(name);\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 22: /* readlink */\n {\n uint32_t fid;\n char buf1[1024];\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"w\", &fid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_readlink(fs, buf1, sizeof(buf1), f);\n }\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"s\", buf1);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 24: /* getattr */\n {\n uint32_t fid;\n uint64_t mask;\n FSFile *f;\n FSStat st;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wd\", &fid, &mask))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_stat(fs, f, &st);\n if (err)\n goto error;\n\n buf_len = marshall(s, buf, sizeof(buf),\n \"dQwwwddddddddddddddd\", \n mask, &st.qid,\n st.st_mode, st.st_uid, st.st_gid,\n st.st_nlink, st.st_rdev, st.st_size,\n st.st_blksize, st.st_blocks,\n st.st_atime_sec, (uint64_t)st.st_atime_nsec,\n st.st_mtime_sec, (uint64_t)st.st_mtime_nsec,\n st.st_ctime_sec, (uint64_t)st.st_ctime_nsec,\n (uint64_t)0, (uint64_t)0,\n (uint64_t)0, (uint64_t)0);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 26: /* setattr */\n {\n uint32_t fid, mask, mode, uid, gid;\n uint64_t size, atime_sec, atime_nsec, mtime_sec, mtime_nsec;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wwwwwddddd\", &fid, &mask, &mode, &uid, &gid,\n &size, &atime_sec, &atime_nsec, \n &mtime_sec, &mtime_nsec))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_setattr(fs, f, mask, mode, uid, gid, size, atime_sec,\n atime_nsec, mtime_sec, mtime_nsec);\n if (err)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 30: /* xattrwalk */\n {\n /* not supported yet */\n err = -P9_ENOTSUP;\n goto error;\n }\n break;\n case 40: /* readdir */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf = malloc(count + 4);\n n = fs->fs_readdir(fs, f, offs, buf + 4, count);\n if (n < 0) {\n err = n;\n goto error;\n }\n put_le32(buf, n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, n + 4);\n free(buf);\n }\n break;\n case 50: /* fsync */\n {\n uint32_t fid;\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"w\", &fid))\n goto protocol_error;\n /* ignored */\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 52: /* lock */\n {\n uint32_t fid;\n FSFile *f;\n FSLock lock;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wbwddws\", &fid, &lock.type, &lock.flags,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n err = -P9_EPROTO;\n else\n err = fs->fs_lock(fs, f, &lock);\n free(lock.client_id);\n if (err < 0)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"b\", err);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 54: /* getlock */\n {\n uint32_t fid;\n FSFile *f;\n FSLock lock;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wbddws\", &fid, &lock.type,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n err = -P9_EPROTO;\n else\n err = fs->fs_getlock(fs, f, &lock);\n if (err < 0) {\n free(lock.client_id);\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"bddws\",\n &lock.type,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id);\n free(lock.client_id);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 70: /* link */\n {\n uint32_t dfid, fid;\n char *name;\n FSFile *f, *df;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wws\", &dfid, &fid, &name))\n goto protocol_error;\n df = fid_find(s, dfid);\n f = fid_find(s, fid);\n if (!df || !f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_link(fs, df, f, name);\n }\n free(name);\n if (err)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 72: /* mkdir */\n {\n uint32_t fid, mode, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsww\", &fid, &name, &mode, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_mkdir(fs, &qid, f, name, mode, gid);\n if (err != 0)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 74: /* renameat */\n {\n uint32_t fid, new_fid;\n char *name, *new_name;\n FSFile *f, *new_f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsws\", &fid, &name, &new_fid, &new_name))\n goto protocol_error;\n f = fid_find(s, fid);\n new_f = fid_find(s, new_fid);\n if (!f || !new_f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_renameat(fs, f, name, new_f, new_name);\n }\n free(name);\n free(new_name);\n if (err != 0)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 76: /* unlinkat */\n {\n uint32_t fid, flags;\n char *name;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsw\", &fid, &name, &flags))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_unlinkat(fs, f, name);\n }\n free(name);\n if (err != 0)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 100: /* version */\n {\n uint32_t msize;\n char *version;\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"ws\", &msize, &version))\n goto protocol_error;\n s->msize = msize;\n // printf(\"version: msize=%d version=%s\\n\", msize, version);\n free(version);\n buf_len = marshall(s, buf, sizeof(buf), \"ws\", s->msize, \"9P2000.L\");\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 104: /* attach */\n {\n uint32_t fid, afid, uid;\n char *uname, *aname;\n FSQID qid;\n FSFile *f;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"wwssw\", &fid, &afid, &uname, &aname, &uid))\n goto protocol_error;\n err = fs->fs_attach(fs, &f, &qid, uid, uname, aname);\n if (err != 0)\n goto error;\n fid_set(s, fid, f);\n free(uname);\n free(aname);\n buf_len = marshall(s, buf, sizeof(buf), \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 108: /* flush */\n {\n uint16_t oldtag;\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"h\", &oldtag))\n goto protocol_error;\n /* ignored */\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 110: /* walk */\n {\n uint32_t fid, newfid;\n uint16_t nwname;\n FSQID *qids;\n char **names;\n FSFile *f;\n int i;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"wwh\", &fid, &newfid, &nwname))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n names = mallocz(sizeof(names[0]) * nwname);\n qids = malloc(sizeof(qids[0]) * nwname);\n for(i = 0; i < nwname; i++) {\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"s\", &names[i])) {\n err = -P9_EPROTO;\n goto walk_done;\n }\n }\n err = fs->fs_walk(fs, &f, qids, f, nwname, names);\n walk_done:\n for(i = 0; i < nwname; i++) {\n free(names[i]);\n }\n free(names);\n if (err < 0) {\n free(qids);\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"h\", err);\n for(i = 0; i < err; i++) {\n buf_len += marshall(s, buf + buf_len, sizeof(buf) - buf_len,\n \"Q\", &qids[i]);\n }\n free(qids);\n fid_set(s, newfid, f);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 116: /* read */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf = malloc(count + 4);\n n = fs->fs_read(fs, f, offs, buf + 4, count);\n if (n < 0) {\n err = n;\n free(buf);\n goto error;\n }\n put_le32(buf, n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, n + 4);\n free(buf);\n }\n break;\n case 118: /* write */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf1;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf1 = malloc(count);\n if (memcpy_from_queue(s1, buf1, queue_idx, desc_idx, offset,\n count)) {\n free(buf1);\n goto protocol_error;\n }\n n = fs->fs_write(fs, f, offs, buf1, count);\n free(buf1);\n if (n < 0) {\n err = n;\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"w\", n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 120: /* clunk */\n {\n uint32_t fid;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"w\", &fid))\n goto protocol_error;\n fid_delete(s, fid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n default:\n printf(\"9p: unsupported operation id=%d\\n\", id);\n goto protocol_error;\n }\n return 0;\n error:\n virtio_9p_send_error(s, queue_idx, desc_idx, tag, err);\n return 0;\n protocol_error:\n fid_not_found:\n err = -P9_EPROTO;\n goto error;\n}\n\nVIRTIODevice *virtio_9p_init(VIRTIOBusDef *bus, FSDevice *fs,\n const char *mount_tag)\n\n{\n VIRTIO9PDevice *s;\n int len;\n uint8_t *cfg;\n\n len = strlen(mount_tag);\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 9, 2 + len, virtio_9p_recv_request);\n s->common.device_features = 1 << 0;\n\n /* set the mount tag */\n cfg = s->common.config_space;\n cfg[0] = len;\n cfg[1] = len >> 8;\n memcpy(cfg + 2, mount_tag, len);\n\n s->fs = fs;\n s->msize = 8192;\n init_list_head(&s->fid_list);\n \n return (VIRTIODevice *)s;\n}\n\n"], ["/linuxpdf/tinyemu/ide.c", "/*\n * IDE emulation\n * \n * Copyright (c) 2003-2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"ide.h\"\n\n//#define DEBUG_IDE\n\n/* Bits of HD_STATUS */\n#define ERR_STAT\t\t0x01\n#define INDEX_STAT\t\t0x02\n#define ECC_STAT\t\t0x04\t/* Corrected error */\n#define DRQ_STAT\t\t0x08\n#define SEEK_STAT\t\t0x10\n#define SRV_STAT\t\t0x10\n#define WRERR_STAT\t\t0x20\n#define READY_STAT\t\t0x40\n#define BUSY_STAT\t\t0x80\n\n/* Bits for HD_ERROR */\n#define MARK_ERR\t\t0x01\t/* Bad address mark */\n#define TRK0_ERR\t\t0x02\t/* couldn't find track 0 */\n#define ABRT_ERR\t\t0x04\t/* Command aborted */\n#define MCR_ERR\t\t\t0x08\t/* media change request */\n#define ID_ERR\t\t\t0x10\t/* ID field not found */\n#define MC_ERR\t\t\t0x20\t/* media changed */\n#define ECC_ERR\t\t\t0x40\t/* Uncorrectable ECC error */\n#define BBD_ERR\t\t\t0x80\t/* pre-EIDE meaning: block marked bad */\n#define ICRC_ERR\t\t0x80\t/* new meaning: CRC error during transfer */\n\n/* Bits of HD_NSECTOR */\n#define CD\t\t\t0x01\n#define IO\t\t\t0x02\n#define REL\t\t\t0x04\n#define TAG_MASK\t\t0xf8\n\n#define IDE_CMD_RESET 0x04\n#define IDE_CMD_DISABLE_IRQ 0x02\n\n/* ATA/ATAPI Commands pre T13 Spec */\n#define WIN_NOP\t\t\t\t0x00\n/*\n *\t0x01->0x02 Reserved\n */\n#define CFA_REQ_EXT_ERROR_CODE\t\t0x03 /* CFA Request Extended Error Code */\n/*\n *\t0x04->0x07 Reserved\n */\n#define WIN_SRST\t\t\t0x08 /* ATAPI soft reset command */\n#define WIN_DEVICE_RESET\t\t0x08\n/*\n *\t0x09->0x0F Reserved\n */\n#define WIN_RECAL\t\t\t0x10\n#define WIN_RESTORE\t\t\tWIN_RECAL\n/*\n *\t0x10->0x1F Reserved\n */\n#define WIN_READ\t\t\t0x20 /* 28-Bit */\n#define WIN_READ_ONCE\t\t\t0x21 /* 28-Bit without retries */\n#define WIN_READ_LONG\t\t\t0x22 /* 28-Bit */\n#define WIN_READ_LONG_ONCE\t\t0x23 /* 28-Bit without retries */\n#define WIN_READ_EXT\t\t\t0x24 /* 48-Bit */\n#define WIN_READDMA_EXT\t\t\t0x25 /* 48-Bit */\n#define WIN_READDMA_QUEUED_EXT\t\t0x26 /* 48-Bit */\n#define WIN_READ_NATIVE_MAX_EXT\t\t0x27 /* 48-Bit */\n/*\n *\t0x28\n */\n#define WIN_MULTREAD_EXT\t\t0x29 /* 48-Bit */\n/*\n *\t0x2A->0x2F Reserved\n */\n#define WIN_WRITE\t\t\t0x30 /* 28-Bit */\n#define WIN_WRITE_ONCE\t\t\t0x31 /* 28-Bit without retries */\n#define WIN_WRITE_LONG\t\t\t0x32 /* 28-Bit */\n#define WIN_WRITE_LONG_ONCE\t\t0x33 /* 28-Bit without retries */\n#define WIN_WRITE_EXT\t\t\t0x34 /* 48-Bit */\n#define WIN_WRITEDMA_EXT\t\t0x35 /* 48-Bit */\n#define WIN_WRITEDMA_QUEUED_EXT\t\t0x36 /* 48-Bit */\n#define WIN_SET_MAX_EXT\t\t\t0x37 /* 48-Bit */\n#define CFA_WRITE_SECT_WO_ERASE\t\t0x38 /* CFA Write Sectors without erase */\n#define WIN_MULTWRITE_EXT\t\t0x39 /* 48-Bit */\n/*\n *\t0x3A->0x3B Reserved\n */\n#define WIN_WRITE_VERIFY\t\t0x3C /* 28-Bit */\n/*\n *\t0x3D->0x3F Reserved\n */\n#define WIN_VERIFY\t\t\t0x40 /* 28-Bit - Read Verify Sectors */\n#define WIN_VERIFY_ONCE\t\t\t0x41 /* 28-Bit - without retries */\n#define WIN_VERIFY_EXT\t\t\t0x42 /* 48-Bit */\n/*\n *\t0x43->0x4F Reserved\n */\n#define WIN_FORMAT\t\t\t0x50\n/*\n *\t0x51->0x5F Reserved\n */\n#define WIN_INIT\t\t\t0x60\n/*\n *\t0x61->0x5F Reserved\n */\n#define WIN_SEEK\t\t\t0x70 /* 0x70-0x7F Reserved */\n#define CFA_TRANSLATE_SECTOR\t\t0x87 /* CFA Translate Sector */\n#define WIN_DIAGNOSE\t\t\t0x90\n#define WIN_SPECIFY\t\t\t0x91 /* set drive geometry translation */\n#define WIN_DOWNLOAD_MICROCODE\t\t0x92\n#define WIN_STANDBYNOW2\t\t\t0x94\n#define WIN_STANDBY2\t\t\t0x96\n#define WIN_SETIDLE2\t\t\t0x97\n#define WIN_CHECKPOWERMODE2\t\t0x98\n#define WIN_SLEEPNOW2\t\t\t0x99\n/*\n *\t0x9A VENDOR\n */\n#define WIN_PACKETCMD\t\t\t0xA0 /* Send a packet command. */\n#define WIN_PIDENTIFY\t\t\t0xA1 /* identify ATAPI device\t*/\n#define WIN_QUEUED_SERVICE\t\t0xA2\n#define WIN_SMART\t\t\t0xB0 /* self-monitoring and reporting */\n#define CFA_ERASE_SECTORS \t0xC0\n#define WIN_MULTREAD\t\t\t0xC4 /* read sectors using multiple mode*/\n#define WIN_MULTWRITE\t\t\t0xC5 /* write sectors using multiple mode */\n#define WIN_SETMULT\t\t\t0xC6 /* enable/disable multiple mode */\n#define WIN_READDMA_QUEUED\t\t0xC7 /* read sectors using Queued DMA transfers */\n#define WIN_READDMA\t\t\t0xC8 /* read sectors using DMA transfers */\n#define WIN_READDMA_ONCE\t\t0xC9 /* 28-Bit - without retries */\n#define WIN_WRITEDMA\t\t\t0xCA /* write sectors using DMA transfers */\n#define WIN_WRITEDMA_ONCE\t\t0xCB /* 28-Bit - without retries */\n#define WIN_WRITEDMA_QUEUED\t\t0xCC /* write sectors using Queued DMA transfers */\n#define CFA_WRITE_MULTI_WO_ERASE\t0xCD /* CFA Write multiple without erase */\n#define WIN_GETMEDIASTATUS\t\t0xDA\t\n#define WIN_ACKMEDIACHANGE\t\t0xDB /* ATA-1, ATA-2 vendor */\n#define WIN_POSTBOOT\t\t\t0xDC\n#define WIN_PREBOOT\t\t\t0xDD\n#define WIN_DOORLOCK\t\t\t0xDE /* lock door on removable drives */\n#define WIN_DOORUNLOCK\t\t\t0xDF /* unlock door on removable drives */\n#define WIN_STANDBYNOW1\t\t\t0xE0\n#define WIN_IDLEIMMEDIATE\t\t0xE1 /* force drive to become \"ready\" */\n#define WIN_STANDBY \t0xE2 /* Set device in Standby Mode */\n#define WIN_SETIDLE1\t\t\t0xE3\n#define WIN_READ_BUFFER\t\t\t0xE4 /* force read only 1 sector */\n#define WIN_CHECKPOWERMODE1\t\t0xE5\n#define WIN_SLEEPNOW1\t\t\t0xE6\n#define WIN_FLUSH_CACHE\t\t\t0xE7\n#define WIN_WRITE_BUFFER\t\t0xE8 /* force write only 1 sector */\n#define WIN_WRITE_SAME\t\t\t0xE9 /* read ata-2 to use */\n\t/* SET_FEATURES 0x22 or 0xDD */\n#define WIN_FLUSH_CACHE_EXT\t\t0xEA /* 48-Bit */\n#define WIN_IDENTIFY\t\t\t0xEC /* ask drive to identify itself\t*/\n#define WIN_MEDIAEJECT\t\t\t0xED\n#define WIN_IDENTIFY_DMA\t\t0xEE /* same as WIN_IDENTIFY, but DMA */\n#define WIN_SETFEATURES\t\t\t0xEF /* set special drive features */\n#define EXABYTE_ENABLE_NEST\t\t0xF0\n#define WIN_SECURITY_SET_PASS\t\t0xF1\n#define WIN_SECURITY_UNLOCK\t\t0xF2\n#define WIN_SECURITY_ERASE_PREPARE\t0xF3\n#define WIN_SECURITY_ERASE_UNIT\t\t0xF4\n#define WIN_SECURITY_FREEZE_LOCK\t0xF5\n#define WIN_SECURITY_DISABLE\t\t0xF6\n#define WIN_READ_NATIVE_MAX\t\t0xF8 /* return the native maximum address */\n#define WIN_SET_MAX\t\t\t0xF9\n#define DISABLE_SEAGATE\t\t\t0xFB\n\n#define MAX_MULT_SECTORS 128\n\ntypedef struct IDEState IDEState;\n\ntypedef void EndTransferFunc(IDEState *);\n\nstruct IDEState {\n IDEIFState *ide_if;\n BlockDevice *bs;\n int cylinders, heads, sectors;\n int mult_sectors;\n int64_t nb_sectors;\n\n /* ide regs */\n uint8_t feature;\n uint8_t error;\n uint16_t nsector; /* 0 is 256 to ease computations */\n uint8_t sector;\n uint8_t lcyl;\n uint8_t hcyl;\n uint8_t select;\n uint8_t status;\n\n int io_nb_sectors;\n int req_nb_sectors;\n EndTransferFunc *end_transfer_func;\n \n int data_index;\n int data_end;\n uint8_t io_buffer[MAX_MULT_SECTORS*512 + 4];\n};\n\nstruct IDEIFState {\n IRQSignal *irq;\n IDEState *cur_drive;\n IDEState *drives[2];\n /* 0x3f6 command */\n uint8_t cmd;\n};\n\nstatic void ide_sector_read_cb(void *opaque, int ret);\nstatic void ide_sector_read_cb_end(IDEState *s);\nstatic void ide_sector_write_cb2(void *opaque, int ret);\n\nstatic void padstr(char *str, const char *src, int len)\n{\n int i, v;\n for(i = 0; i < len; i++) {\n if (*src)\n v = *src++;\n else\n v = ' ';\n *(char *)((long)str ^ 1) = v;\n str++;\n }\n}\n\n/* little endian assume */\nstatic void stw(uint16_t *buf, int v)\n{\n *buf = v;\n}\n\nstatic void ide_identify(IDEState *s)\n{\n uint16_t *tab;\n uint32_t oldsize;\n \n tab = (uint16_t *)s->io_buffer;\n\n memset(tab, 0, 512 * 2);\n\n stw(tab + 0, 0x0040);\n stw(tab + 1, s->cylinders); \n stw(tab + 3, s->heads);\n stw(tab + 4, 512 * s->sectors); /* sectors */\n stw(tab + 5, 512); /* sector size */\n stw(tab + 6, s->sectors); \n stw(tab + 20, 3); /* buffer type */\n stw(tab + 21, 512); /* cache size in sectors */\n stw(tab + 22, 4); /* ecc bytes */\n padstr((char *)(tab + 27), \"RISCVEMU HARDDISK\", 40);\n stw(tab + 47, 0x8000 | MAX_MULT_SECTORS);\n stw(tab + 48, 0); /* dword I/O */\n stw(tab + 49, 1 << 9); /* LBA supported, no DMA */\n stw(tab + 51, 0x200); /* PIO transfer cycle */\n stw(tab + 52, 0x200); /* DMA transfer cycle */\n stw(tab + 54, s->cylinders);\n stw(tab + 55, s->heads);\n stw(tab + 56, s->sectors);\n oldsize = s->cylinders * s->heads * s->sectors;\n stw(tab + 57, oldsize);\n stw(tab + 58, oldsize >> 16);\n if (s->mult_sectors)\n stw(tab + 59, 0x100 | s->mult_sectors);\n stw(tab + 60, s->nb_sectors);\n stw(tab + 61, s->nb_sectors >> 16);\n stw(tab + 80, (1 << 1) | (1 << 2));\n stw(tab + 82, (1 << 14));\n stw(tab + 83, (1 << 14));\n stw(tab + 84, (1 << 14));\n stw(tab + 85, (1 << 14));\n stw(tab + 86, 0);\n stw(tab + 87, (1 << 14));\n}\n\nstatic void ide_set_signature(IDEState *s) \n{\n s->select &= 0xf0;\n s->nsector = 1;\n s->sector = 1;\n s->lcyl = 0;\n s->hcyl = 0;\n}\n\nstatic void ide_abort_command(IDEState *s) \n{\n s->status = READY_STAT | ERR_STAT;\n s->error = ABRT_ERR;\n}\n\nstatic void ide_set_irq(IDEState *s) \n{\n IDEIFState *ide_if = s->ide_if;\n if (!(ide_if->cmd & IDE_CMD_DISABLE_IRQ)) {\n set_irq(ide_if->irq, 1);\n }\n}\n\n/* prepare data transfer and tell what to do after */\nstatic void ide_transfer_start(IDEState *s, int size,\n EndTransferFunc *end_transfer_func)\n{\n s->end_transfer_func = end_transfer_func;\n s->data_index = 0;\n s->data_end = size;\n}\n\nstatic void ide_transfer_stop(IDEState *s)\n{\n s->end_transfer_func = ide_transfer_stop;\n s->data_index = 0;\n s->data_end = 0;\n}\n\nstatic int64_t ide_get_sector(IDEState *s)\n{\n int64_t sector_num;\n if (s->select & 0x40) {\n /* lba */\n sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) |\n (s->lcyl << 8) | s->sector;\n } else {\n sector_num = ((s->hcyl << 8) | s->lcyl) * \n s->heads * s->sectors +\n (s->select & 0x0f) * s->sectors + (s->sector - 1);\n }\n return sector_num;\n}\n\nstatic void ide_set_sector(IDEState *s, int64_t sector_num)\n{\n unsigned int cyl, r;\n if (s->select & 0x40) {\n s->select = (s->select & 0xf0) | ((sector_num >> 24) & 0x0f);\n s->hcyl = (sector_num >> 16) & 0xff;\n s->lcyl = (sector_num >> 8) & 0xff;\n s->sector = sector_num & 0xff;\n } else {\n cyl = sector_num / (s->heads * s->sectors);\n r = sector_num % (s->heads * s->sectors);\n s->hcyl = (cyl >> 8) & 0xff;\n s->lcyl = cyl & 0xff;\n s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f);\n s->sector = (r % s->sectors) + 1;\n }\n}\n\nstatic void ide_sector_read(IDEState *s)\n{\n int64_t sector_num;\n int ret, n;\n\n sector_num = ide_get_sector(s);\n n = s->nsector;\n if (n == 0) \n n = 256;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n#if defined(DEBUG_IDE)\n printf(\"read sector=%\" PRId64 \" count=%d\\n\", sector_num, n);\n#endif\n s->io_nb_sectors = n;\n ret = s->bs->read_async(s->bs, sector_num, s->io_buffer, n, \n ide_sector_read_cb, s);\n if (ret < 0) {\n /* error */\n ide_abort_command(s);\n ide_set_irq(s);\n } else if (ret == 0) {\n /* synchronous case (needed for performance) */\n ide_sector_read_cb(s, 0);\n } else {\n /* async case */\n s->status = READY_STAT | SEEK_STAT | BUSY_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n }\n}\n\nstatic void ide_sector_read_cb(void *opaque, int ret)\n{\n IDEState *s = opaque;\n int n;\n EndTransferFunc *func;\n \n n = s->io_nb_sectors;\n ide_set_sector(s, ide_get_sector(s) + n);\n s->nsector = (s->nsector - n) & 0xff;\n if (s->nsector == 0)\n func = ide_sector_read_cb_end;\n else\n func = ide_sector_read;\n ide_transfer_start(s, 512 * n, func);\n ide_set_irq(s);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n}\n\nstatic void ide_sector_read_cb_end(IDEState *s)\n{\n /* no more sector to read from disk */\n s->status = READY_STAT | SEEK_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n ide_transfer_stop(s);\n}\n\nstatic void ide_sector_write_cb1(IDEState *s)\n{\n int64_t sector_num;\n int ret;\n\n ide_transfer_stop(s);\n sector_num = ide_get_sector(s);\n#if defined(DEBUG_IDE)\n printf(\"write sector=%\" PRId64 \" count=%d\\n\",\n sector_num, s->io_nb_sectors);\n#endif\n ret = s->bs->write_async(s->bs, sector_num, s->io_buffer, s->io_nb_sectors, \n ide_sector_write_cb2, s);\n if (ret < 0) {\n /* error */\n ide_abort_command(s);\n ide_set_irq(s);\n } else if (ret == 0) {\n /* synchronous case (needed for performance) */\n ide_sector_write_cb2(s, 0);\n } else {\n /* async case */\n s->status = READY_STAT | SEEK_STAT | BUSY_STAT;\n }\n}\n\nstatic void ide_sector_write_cb2(void *opaque, int ret)\n{\n IDEState *s = opaque;\n int n;\n\n n = s->io_nb_sectors;\n ide_set_sector(s, ide_get_sector(s) + n);\n s->nsector = (s->nsector - n) & 0xff;\n if (s->nsector == 0) {\n /* no more sectors to write */\n s->status = READY_STAT | SEEK_STAT;\n } else {\n n = s->nsector;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n s->io_nb_sectors = n;\n ide_transfer_start(s, 512 * n, ide_sector_write_cb1);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n }\n ide_set_irq(s);\n}\n\nstatic void ide_sector_write(IDEState *s)\n{\n int n;\n n = s->nsector;\n if (n == 0)\n n = 256;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n s->io_nb_sectors = n;\n ide_transfer_start(s, 512 * n, ide_sector_write_cb1);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n}\n\nstatic void ide_identify_cb(IDEState *s)\n{\n ide_transfer_stop(s);\n s->status = READY_STAT;\n}\n\nstatic void ide_exec_cmd(IDEState *s, int val)\n{\n#if defined(DEBUG_IDE)\n printf(\"ide: exec_cmd=0x%02x\\n\", val);\n#endif\n switch(val) {\n case WIN_IDENTIFY:\n ide_identify(s);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n ide_transfer_start(s, 512, ide_identify_cb);\n ide_set_irq(s);\n break;\n case WIN_SPECIFY:\n case WIN_RECAL:\n s->error = 0;\n s->status = READY_STAT | SEEK_STAT;\n ide_set_irq(s);\n break;\n case WIN_SETMULT:\n if (s->nsector > MAX_MULT_SECTORS || \n (s->nsector & (s->nsector - 1)) != 0) {\n ide_abort_command(s);\n } else {\n s->mult_sectors = s->nsector;\n#if defined(DEBUG_IDE)\n printf(\"ide: setmult=%d\\n\", s->mult_sectors);\n#endif\n s->status = READY_STAT;\n }\n ide_set_irq(s);\n break;\n case WIN_READ:\n case WIN_READ_ONCE:\n s->req_nb_sectors = 1;\n ide_sector_read(s);\n break;\n case WIN_WRITE:\n case WIN_WRITE_ONCE:\n s->req_nb_sectors = 1;\n ide_sector_write(s);\n break;\n case WIN_MULTREAD:\n if (!s->mult_sectors) {\n ide_abort_command(s);\n ide_set_irq(s);\n } else {\n s->req_nb_sectors = s->mult_sectors;\n ide_sector_read(s);\n }\n break;\n case WIN_MULTWRITE:\n if (!s->mult_sectors) {\n ide_abort_command(s);\n ide_set_irq(s);\n } else {\n s->req_nb_sectors = s->mult_sectors;\n ide_sector_write(s);\n }\n break;\n case WIN_READ_NATIVE_MAX:\n ide_set_sector(s, s->nb_sectors - 1);\n s->status = READY_STAT;\n ide_set_irq(s);\n break;\n default:\n ide_abort_command(s);\n ide_set_irq(s);\n break;\n }\n}\n\nstatic void ide_ioport_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int addr = offset + 1;\n \n#ifdef DEBUG_IDE\n printf(\"ide: write addr=0x%02x val=0x%02x\\n\", addr, val);\n#endif\n switch(addr) {\n case 0:\n break;\n case 1:\n if (s) {\n s->feature = val;\n }\n break;\n case 2:\n if (s) {\n s->nsector = val;\n }\n break;\n case 3:\n if (s) {\n s->sector = val;\n }\n break;\n case 4:\n if (s) {\n s->lcyl = val;\n }\n break;\n case 5:\n if (s) {\n s->hcyl = val;\n }\n break;\n case 6:\n /* select drive */\n s = s1->cur_drive = s1->drives[(val >> 4) & 1];\n if (s) {\n s->select = val;\n }\n break;\n default:\n case 7:\n /* command */\n if (s) {\n ide_exec_cmd(s, val);\n }\n break;\n }\n}\n\nstatic uint32_t ide_ioport_read(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int ret, addr = offset + 1;\n\n if (!s) {\n ret = 0x00;\n } else {\n switch(addr) {\n case 0:\n ret = 0xff;\n break;\n case 1:\n ret = s->error;\n break;\n case 2:\n ret = s->nsector;\n break;\n case 3:\n ret = s->sector;\n break;\n case 4:\n ret = s->lcyl;\n break;\n case 5:\n ret = s->hcyl;\n break;\n case 6:\n ret = s->select;\n break;\n default:\n case 7:\n ret = s->status;\n set_irq(s1->irq, 0);\n break;\n }\n }\n#ifdef DEBUG_IDE\n printf(\"ide: read addr=0x%02x val=0x%02x\\n\", addr, ret);\n#endif\n return ret;\n}\n\nstatic uint32_t ide_status_read(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int ret;\n\n if (s) {\n ret = s->status;\n } else {\n ret = 0;\n }\n#ifdef DEBUG_IDE\n printf(\"ide: read status=0x%02x\\n\", ret);\n#endif\n return ret;\n}\n\nstatic void ide_cmd_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s;\n int i;\n \n#ifdef DEBUG_IDE\n printf(\"ide: cmd write=0x%02x\\n\", val);\n#endif\n if (!(s1->cmd & IDE_CMD_RESET) && (val & IDE_CMD_RESET)) {\n /* low to high */\n for(i = 0; i < 2; i++) {\n s = s1->drives[i];\n if (s) {\n s->status = BUSY_STAT | SEEK_STAT;\n s->error = 0x01;\n }\n }\n } else if ((s1->cmd & IDE_CMD_RESET) && !(val & IDE_CMD_RESET)) {\n /* high to low */\n for(i = 0; i < 2; i++) {\n s = s1->drives[i];\n if (s) {\n s->status = READY_STAT | SEEK_STAT;\n ide_set_signature(s);\n }\n }\n }\n s1->cmd = val;\n}\n\nstatic void ide_data_writew(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int p;\n uint8_t *tab;\n \n if (!s)\n return;\n p = s->data_index;\n tab = s->io_buffer;\n tab[p] = val & 0xff;\n tab[p + 1] = (val >> 8) & 0xff;\n p += 2;\n s->data_index = p;\n if (p >= s->data_end)\n s->end_transfer_func(s);\n}\n\nstatic uint32_t ide_data_readw(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int p, ret;\n uint8_t *tab;\n \n if (!s) {\n ret = 0;\n } else {\n p = s->data_index;\n tab = s->io_buffer;\n ret = tab[p] | (tab[p + 1] << 8);\n p += 2;\n s->data_index = p;\n if (p >= s->data_end)\n s->end_transfer_func(s);\n }\n return ret;\n}\n\nstatic IDEState *ide_drive_init(IDEIFState *ide_if, BlockDevice *bs)\n{\n IDEState *s;\n uint32_t cylinders;\n uint64_t nb_sectors;\n\n s = malloc(sizeof(*s));\n memset(s, 0, sizeof(*s));\n\n s->ide_if = ide_if;\n s->bs = bs;\n\n nb_sectors = s->bs->get_sector_count(s->bs);\n cylinders = nb_sectors / (16 * 63);\n if (cylinders > 16383)\n cylinders = 16383;\n else if (cylinders < 2)\n cylinders = 2;\n s->cylinders = cylinders;\n s->heads = 16;\n s->sectors = 63;\n s->nb_sectors = nb_sectors;\n\n s->mult_sectors = MAX_MULT_SECTORS;\n /* ide regs */\n s->feature = 0;\n s->error = 0;\n s->nsector = 0;\n s->sector = 0;\n s->lcyl = 0;\n s->hcyl = 0;\n s->select = 0xa0;\n s->status = READY_STAT | SEEK_STAT;\n\n /* init I/O buffer */\n s->data_index = 0;\n s->data_end = 0;\n s->end_transfer_func = ide_transfer_stop;\n\n s->req_nb_sectors = 0; /* temp for read/write */\n s->io_nb_sectors = 0; /* temp for read/write */\n return s;\n}\n\nIDEIFState *ide_init(PhysMemoryMap *port_map, uint32_t addr, uint32_t addr2,\n IRQSignal *irq, BlockDevice **tab_bs)\n{\n int i;\n IDEIFState *s;\n \n s = malloc(sizeof(IDEIFState));\n memset(s, 0, sizeof(*s));\n \n s->irq = irq;\n s->cmd = 0;\n\n cpu_register_device(port_map, addr, 1, s, ide_data_readw, ide_data_writew, \n DEVIO_SIZE16);\n cpu_register_device(port_map, addr + 1, 7, s, ide_ioport_read, ide_ioport_write, \n DEVIO_SIZE8);\n if (addr2) {\n cpu_register_device(port_map, addr2, 1, s, ide_status_read, ide_cmd_write, \n DEVIO_SIZE8);\n }\n \n for(i = 0; i < 2; i++) {\n if (tab_bs[i])\n s->drives[i] = ide_drive_init(s, tab_bs[i]);\n }\n s->cur_drive = s->drives[0];\n return s;\n}\n\n/* dummy PCI device for the IDE */\nPCIDevice *piix3_ide_init(PCIBus *pci_bus, int devfn)\n{\n PCIDevice *d;\n d = pci_register_device(pci_bus, \"PIIX3 IDE\", devfn, 0x8086, 0x7010, 0x00, 0x0101);\n pci_device_set_config8(d, 0x09, 0x00); /* ISA IDE ports, no DMA */\n return d;\n}\n"], ["/linuxpdf/tinyemu/temu.c", "/*\n * TinyEMU\n * \n * Copyright (c) 2016-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifndef _WIN32\n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#ifdef CONFIG_FS_NET\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n#endif\n#ifdef CONFIG_SLIRP\n#include \"slirp/libslirp.h\"\n#endif\n\n#ifndef _WIN32\n\ntypedef struct {\n int stdin_fd;\n int console_esc_state;\n BOOL resize_pending;\n} STDIODevice;\n\nstatic struct termios oldtty;\nstatic int old_fd0_flags;\nstatic STDIODevice *global_stdio_device;\n\nstatic void term_exit(void)\n{\n tcsetattr (0, TCSANOW, &oldtty);\n fcntl(0, F_SETFL, old_fd0_flags);\n}\n\nstatic void term_init(BOOL allow_ctrlc)\n{\n struct termios tty;\n\n memset(&tty, 0, sizeof(tty));\n tcgetattr (0, &tty);\n oldtty = tty;\n old_fd0_flags = fcntl(0, F_GETFL);\n\n tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP\n |INLCR|IGNCR|ICRNL|IXON);\n tty.c_oflag |= OPOST;\n tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);\n if (!allow_ctrlc)\n tty.c_lflag &= ~ISIG;\n tty.c_cflag &= ~(CSIZE|PARENB);\n tty.c_cflag |= CS8;\n tty.c_cc[VMIN] = 1;\n tty.c_cc[VTIME] = 0;\n\n tcsetattr (0, TCSANOW, &tty);\n\n atexit(term_exit);\n}\n\nstatic void console_write(void *opaque, const uint8_t *buf, int len)\n{\n fwrite(buf, 1, len, stdout);\n fflush(stdout);\n}\n\nstatic int console_read(void *opaque, uint8_t *buf, int len)\n{\n STDIODevice *s = opaque;\n int ret, i, j;\n uint8_t ch;\n \n if (len <= 0)\n return 0;\n\n ret = read(s->stdin_fd, buf, len);\n if (ret < 0)\n return 0;\n if (ret == 0) {\n /* EOF */\n exit(1);\n }\n\n j = 0;\n for(i = 0; i < ret; i++) {\n ch = buf[i];\n if (s->console_esc_state) {\n s->console_esc_state = 0;\n switch(ch) {\n case 'x':\n printf(\"Terminated\\n\");\n exit(0);\n case 'h':\n printf(\"\\n\"\n \"C-a h print this help\\n\"\n \"C-a x exit emulator\\n\"\n \"C-a C-a send C-a\\n\"\n );\n break;\n case 1:\n goto output_char;\n default:\n break;\n }\n } else {\n if (ch == 1) {\n s->console_esc_state = 1;\n } else {\n output_char:\n buf[j++] = ch;\n }\n }\n }\n return j;\n}\n\nstatic void term_resize_handler(int sig)\n{\n if (global_stdio_device)\n global_stdio_device->resize_pending = TRUE;\n}\n\nstatic void console_get_size(STDIODevice *s, int *pw, int *ph)\n{\n struct winsize ws;\n int width, height;\n /* default values */\n width = 80;\n height = 25;\n if (ioctl(s->stdin_fd, TIOCGWINSZ, &ws) == 0 &&\n ws.ws_col >= 4 && ws.ws_row >= 4) {\n width = ws.ws_col;\n height = ws.ws_row;\n }\n *pw = width;\n *ph = height;\n}\n\nCharacterDevice *console_init(BOOL allow_ctrlc)\n{\n CharacterDevice *dev;\n STDIODevice *s;\n struct sigaction sig;\n\n term_init(allow_ctrlc);\n\n dev = mallocz(sizeof(*dev));\n s = mallocz(sizeof(*s));\n s->stdin_fd = 0;\n /* Note: the glibc does not properly tests the return value of\n write() in printf, so some messages on stdout may be lost */\n fcntl(s->stdin_fd, F_SETFL, O_NONBLOCK);\n\n s->resize_pending = TRUE;\n global_stdio_device = s;\n \n /* use a signal to get the host terminal resize events */\n sig.sa_handler = term_resize_handler;\n sigemptyset(&sig.sa_mask);\n sig.sa_flags = 0;\n sigaction(SIGWINCH, &sig, NULL);\n \n dev->opaque = s;\n dev->write_data = console_write;\n dev->read_data = console_read;\n return dev;\n}\n\n#endif /* !_WIN32 */\n\ntypedef enum {\n BF_MODE_RO,\n BF_MODE_RW,\n BF_MODE_SNAPSHOT,\n} BlockDeviceModeEnum;\n\n#define SECTOR_SIZE 512\n\ntypedef struct BlockDeviceFile {\n FILE *f;\n int64_t nb_sectors;\n BlockDeviceModeEnum mode;\n uint8_t **sector_table;\n} BlockDeviceFile;\n\nstatic int64_t bf_get_sector_count(BlockDevice *bs)\n{\n BlockDeviceFile *bf = bs->opaque;\n return bf->nb_sectors;\n}\n\n//#define DUMP_BLOCK_READ\n\nstatic int bf_read_async(BlockDevice *bs,\n uint64_t sector_num, uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceFile *bf = bs->opaque;\n // printf(\"bf_read_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n#ifdef DUMP_BLOCK_READ\n {\n static FILE *f;\n if (!f)\n f = fopen(\"/tmp/read_sect.txt\", \"wb\");\n fprintf(f, \"%\" PRId64 \" %d\\n\", sector_num, n);\n }\n#endif\n if (!bf->f)\n return -1;\n if (bf->mode == BF_MODE_SNAPSHOT) {\n int i;\n for(i = 0; i < n; i++) {\n if (!bf->sector_table[sector_num]) {\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fread(buf, 1, SECTOR_SIZE, bf->f);\n } else {\n memcpy(buf, bf->sector_table[sector_num], SECTOR_SIZE);\n }\n sector_num++;\n buf += SECTOR_SIZE;\n }\n } else {\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fread(buf, 1, n * SECTOR_SIZE, bf->f);\n }\n /* synchronous read */\n return 0;\n}\n\nstatic int bf_write_async(BlockDevice *bs,\n uint64_t sector_num, const uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceFile *bf = bs->opaque;\n int ret;\n\n switch(bf->mode) {\n case BF_MODE_RO:\n ret = -1; /* error */\n break;\n case BF_MODE_RW:\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fwrite(buf, 1, n * SECTOR_SIZE, bf->f);\n ret = 0;\n break;\n case BF_MODE_SNAPSHOT:\n {\n int i;\n if ((sector_num + n) > bf->nb_sectors)\n return -1;\n for(i = 0; i < n; i++) {\n if (!bf->sector_table[sector_num]) {\n bf->sector_table[sector_num] = malloc(SECTOR_SIZE);\n }\n memcpy(bf->sector_table[sector_num], buf, SECTOR_SIZE);\n sector_num++;\n buf += SECTOR_SIZE;\n }\n ret = 0;\n }\n break;\n default:\n abort();\n }\n\n return ret;\n}\n\nstatic BlockDevice *block_device_init(const char *filename,\n BlockDeviceModeEnum mode)\n{\n BlockDevice *bs;\n BlockDeviceFile *bf;\n int64_t file_size;\n FILE *f;\n const char *mode_str;\n\n if (mode == BF_MODE_RW) {\n mode_str = \"r+b\";\n } else {\n mode_str = \"rb\";\n }\n \n f = fopen(filename, mode_str);\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n file_size = ftello(f);\n\n bs = mallocz(sizeof(*bs));\n bf = mallocz(sizeof(*bf));\n\n bf->mode = mode;\n bf->nb_sectors = file_size / 512;\n bf->f = f;\n\n if (mode == BF_MODE_SNAPSHOT) {\n bf->sector_table = mallocz(sizeof(bf->sector_table[0]) *\n bf->nb_sectors);\n }\n \n bs->opaque = bf;\n bs->get_sector_count = bf_get_sector_count;\n bs->read_async = bf_read_async;\n bs->write_async = bf_write_async;\n return bs;\n}\n\n#ifndef _WIN32\n\ntypedef struct {\n int fd;\n BOOL select_filled;\n} TunState;\n\nstatic void tun_write_packet(EthernetDevice *net,\n const uint8_t *buf, int len)\n{\n TunState *s = net->opaque;\n write(s->fd, buf, len);\n}\n\nstatic void tun_select_fill(EthernetDevice *net, int *pfd_max,\n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *pdelay)\n{\n TunState *s = net->opaque;\n int net_fd = s->fd;\n\n s->select_filled = net->device_can_write_packet(net);\n if (s->select_filled) {\n FD_SET(net_fd, rfds);\n *pfd_max = max_int(*pfd_max, net_fd);\n }\n}\n\nstatic void tun_select_poll(EthernetDevice *net, \n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int select_ret)\n{\n TunState *s = net->opaque;\n int net_fd = s->fd;\n uint8_t buf[2048];\n int ret;\n \n if (select_ret <= 0)\n return;\n if (s->select_filled && FD_ISSET(net_fd, rfds)) {\n ret = read(net_fd, buf, sizeof(buf));\n if (ret > 0)\n net->device_write_packet(net, buf, ret);\n }\n \n}\n\n/* configure with:\n# bridge configuration (connect tap0 to bridge interface br0)\n ip link add br0 type bridge\n ip tuntap add dev tap0 mode tap [user x] [group x]\n ip link set tap0 master br0\n ip link set dev br0 up\n ip link set dev tap0 up\n\n# NAT configuration (eth1 is the interface connected to internet)\n ifconfig br0 192.168.3.1\n echo 1 > /proc/sys/net/ipv4/ip_forward\n iptables -D FORWARD 1\n iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE\n\n In the VM:\n ifconfig eth0 192.168.3.2\n route add -net 0.0.0.0 netmask 0.0.0.0 gw 192.168.3.1\n*/\nstatic EthernetDevice *tun_open(const char *ifname)\n{\n struct ifreq ifr;\n int fd, ret;\n EthernetDevice *net;\n TunState *s;\n \n fd = open(\"/dev/net/tun\", O_RDWR);\n if (fd < 0) {\n fprintf(stderr, \"Error: could not open /dev/net/tun\\n\");\n return NULL;\n }\n memset(&ifr, 0, sizeof(ifr));\n ifr.ifr_flags = IFF_TAP | IFF_NO_PI;\n pstrcpy(ifr.ifr_name, sizeof(ifr.ifr_name), ifname);\n ret = ioctl(fd, TUNSETIFF, (void *) &ifr);\n if (ret != 0) {\n fprintf(stderr, \"Error: could not configure /dev/net/tun\\n\");\n close(fd);\n return NULL;\n }\n fcntl(fd, F_SETFL, O_NONBLOCK);\n\n net = mallocz(sizeof(*net));\n net->mac_addr[0] = 0x02;\n net->mac_addr[1] = 0x00;\n net->mac_addr[2] = 0x00;\n net->mac_addr[3] = 0x00;\n net->mac_addr[4] = 0x00;\n net->mac_addr[5] = 0x01;\n s = mallocz(sizeof(*s));\n s->fd = fd;\n net->opaque = s;\n net->write_packet = tun_write_packet;\n net->select_fill = tun_select_fill;\n net->select_poll = tun_select_poll;\n return net;\n}\n\n#endif /* !_WIN32 */\n\n#ifdef CONFIG_SLIRP\n\n/*******************************************************/\n/* slirp */\n\nstatic Slirp *slirp_state;\n\nstatic void slirp_write_packet(EthernetDevice *net,\n const uint8_t *buf, int len)\n{\n Slirp *slirp_state = net->opaque;\n slirp_input(slirp_state, buf, len);\n}\n\nint slirp_can_output(void *opaque)\n{\n EthernetDevice *net = opaque;\n return net->device_can_write_packet(net);\n}\n\nvoid slirp_output(void *opaque, const uint8_t *pkt, int pkt_len)\n{\n EthernetDevice *net = opaque;\n return net->device_write_packet(net, pkt, pkt_len);\n}\n\nstatic void slirp_select_fill1(EthernetDevice *net, int *pfd_max,\n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *pdelay)\n{\n Slirp *slirp_state = net->opaque;\n slirp_select_fill(slirp_state, pfd_max, rfds, wfds, efds);\n}\n\nstatic void slirp_select_poll1(EthernetDevice *net, \n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int select_ret)\n{\n Slirp *slirp_state = net->opaque;\n slirp_select_poll(slirp_state, rfds, wfds, efds, (select_ret <= 0));\n}\n\nstatic EthernetDevice *slirp_open(void)\n{\n EthernetDevice *net;\n struct in_addr net_addr = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */\n struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */\n struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */\n struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */\n struct in_addr dns = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */\n const char *bootfile = NULL;\n const char *vhostname = NULL;\n int restricted = 0;\n \n if (slirp_state) {\n fprintf(stderr, \"Only a single slirp instance is allowed\\n\");\n return NULL;\n }\n net = mallocz(sizeof(*net));\n\n slirp_state = slirp_init(restricted, net_addr, mask, host, vhostname,\n \"\", bootfile, dhcp, dns, net);\n \n net->mac_addr[0] = 0x02;\n net->mac_addr[1] = 0x00;\n net->mac_addr[2] = 0x00;\n net->mac_addr[3] = 0x00;\n net->mac_addr[4] = 0x00;\n net->mac_addr[5] = 0x01;\n net->opaque = slirp_state;\n net->write_packet = slirp_write_packet;\n net->select_fill = slirp_select_fill1;\n net->select_poll = slirp_select_poll1;\n \n return net;\n}\n\n#endif /* CONFIG_SLIRP */\n\n#define MAX_EXEC_CYCLE 500000\n#define MAX_SLEEP_TIME 10 /* in ms */\n\nvoid virt_machine_run(VirtMachine *m)\n{\n fd_set rfds, wfds, efds;\n int fd_max, ret, delay;\n struct timeval tv;\n#ifndef _WIN32\n int stdin_fd;\n#endif\n \n delay = virt_machine_get_sleep_duration(m, MAX_SLEEP_TIME);\n \n /* wait for an event */\n FD_ZERO(&rfds);\n FD_ZERO(&wfds);\n FD_ZERO(&efds);\n fd_max = -1;\n#ifndef _WIN32\n if (m->console_dev && virtio_console_can_write_data(m->console_dev)) {\n STDIODevice *s = m->console->opaque;\n stdin_fd = s->stdin_fd;\n FD_SET(stdin_fd, &rfds);\n fd_max = stdin_fd;\n\n if (s->resize_pending) {\n int width, height;\n console_get_size(s, &width, &height);\n virtio_console_resize_event(m->console_dev, width, height);\n s->resize_pending = FALSE;\n }\n }\n#endif\n if (m->net) {\n m->net->select_fill(m->net, &fd_max, &rfds, &wfds, &efds, &delay);\n }\n#ifdef CONFIG_FS_NET\n fs_net_set_fdset(&fd_max, &rfds, &wfds, &efds, &delay);\n#endif\n tv.tv_sec = delay / 1000;\n tv.tv_usec = (delay % 1000) * 1000;\n ret = select(fd_max + 1, &rfds, &wfds, &efds, &tv);\n if (m->net) {\n m->net->select_poll(m->net, &rfds, &wfds, &efds, ret);\n }\n if (ret > 0) {\n#ifndef _WIN32\n if (m->console_dev && FD_ISSET(stdin_fd, &rfds)) {\n uint8_t buf[128];\n int ret, len;\n len = virtio_console_get_write_len(m->console_dev);\n len = min_int(len, sizeof(buf));\n ret = m->console->read_data(m->console->opaque, buf, len);\n if (ret > 0) {\n virtio_console_write_data(m->console_dev, buf, ret);\n }\n }\n#endif\n }\n\n#ifdef CONFIG_SDL\n sdl_refresh(m);\n#endif\n \n virt_machine_interp(m, MAX_EXEC_CYCLE);\n}\n\n/*******************************************************/\n\nstatic struct option options[] = {\n { \"help\", no_argument, NULL, 'h' },\n { \"ctrlc\", no_argument },\n { \"rw\", no_argument },\n { \"ro\", no_argument },\n { \"append\", required_argument },\n { \"no-accel\", no_argument },\n { \"build-preload\", required_argument },\n { NULL },\n};\n\nvoid help(void)\n{\n printf(\"temu version \" CONFIG_VERSION \", Copyright (c) 2016-2018 Fabrice Bellard\\n\"\n \"usage: riscvemu [options] config_file\\n\"\n \"options are:\\n\"\n \"-m ram_size set the RAM size in MB\\n\"\n \"-rw allow write access to the disk image (default=snapshot)\\n\"\n \"-ctrlc the C-c key stops the emulator instead of being sent to the\\n\"\n \" emulated software\\n\"\n \"-append cmdline append cmdline to the kernel command line\\n\"\n \"-no-accel disable VM acceleration (KVM, x86 machine only)\\n\"\n \"\\n\"\n \"Console keys:\\n\"\n \"Press C-a x to exit the emulator, C-a h to get some help.\\n\");\n exit(1);\n}\n\n#ifdef CONFIG_FS_NET\nstatic BOOL net_completed;\n\nstatic void net_start_cb(void *arg)\n{\n net_completed = TRUE;\n}\n\nstatic BOOL net_poll_cb(void *arg)\n{\n return net_completed;\n}\n\n#endif\n\nint main(int argc, char **argv)\n{\n VirtMachine *s;\n const char *path, *cmdline, *build_preload_file;\n int c, option_index, i, ram_size, accel_enable;\n BOOL allow_ctrlc;\n BlockDeviceModeEnum drive_mode;\n VirtMachineParams p_s, *p = &p_s;\n\n ram_size = -1;\n allow_ctrlc = FALSE;\n (void)allow_ctrlc;\n drive_mode = BF_MODE_SNAPSHOT;\n accel_enable = -1;\n cmdline = NULL;\n build_preload_file = NULL;\n for(;;) {\n c = getopt_long_only(argc, argv, \"hm:\", options, &option_index);\n if (c == -1)\n break;\n switch(c) {\n case 0:\n switch(option_index) {\n case 1: /* ctrlc */\n allow_ctrlc = TRUE;\n break;\n case 2: /* rw */\n drive_mode = BF_MODE_RW;\n break;\n case 3: /* ro */\n drive_mode = BF_MODE_RO;\n break;\n case 4: /* append */\n cmdline = optarg;\n break;\n case 5: /* no-accel */\n accel_enable = FALSE;\n break;\n case 6: /* build-preload */\n build_preload_file = optarg;\n break;\n default:\n fprintf(stderr, \"unknown option index: %d\\n\", option_index);\n exit(1);\n }\n break;\n case 'h':\n help();\n break;\n case 'm':\n ram_size = strtoul(optarg, NULL, 0);\n break;\n default:\n exit(1);\n }\n }\n\n if (optind >= argc) {\n help();\n }\n\n path = argv[optind++];\n\n virt_machine_set_defaults(p);\n#ifdef CONFIG_FS_NET\n fs_wget_init();\n#endif\n virt_machine_load_config_file(p, path, NULL, NULL);\n#ifdef CONFIG_FS_NET\n fs_net_event_loop(NULL, NULL);\n#endif\n\n /* override some config parameters */\n\n if (ram_size > 0) {\n p->ram_size = (uint64_t)ram_size << 20;\n }\n if (accel_enable != -1)\n p->accel_enable = accel_enable;\n if (cmdline) {\n vm_add_cmdline(p, cmdline);\n }\n \n /* open the files & devices */\n for(i = 0; i < p->drive_count; i++) {\n BlockDevice *drive;\n char *fname;\n fname = get_file_path(p->cfg_filename, p->tab_drive[i].filename);\n#ifdef CONFIG_FS_NET\n if (is_url(fname)) {\n net_completed = FALSE;\n drive = block_device_init_http(fname, 128 * 1024,\n net_start_cb, NULL);\n /* wait until the drive is initialized */\n fs_net_event_loop(net_poll_cb, NULL);\n } else\n#endif\n {\n drive = block_device_init(fname, drive_mode);\n }\n free(fname);\n p->tab_drive[i].block_dev = drive;\n }\n\n for(i = 0; i < p->fs_count; i++) {\n FSDevice *fs;\n const char *path;\n path = p->tab_fs[i].filename;\n#ifdef CONFIG_FS_NET\n if (is_url(path)) {\n fs = fs_net_init(path, NULL, NULL);\n if (!fs)\n exit(1);\n if (build_preload_file)\n fs_dump_cache_load(fs, build_preload_file);\n fs_net_event_loop(NULL, NULL);\n } else\n#endif\n {\n#ifdef _WIN32\n fprintf(stderr, \"Filesystem access not supported yet\\n\");\n exit(1);\n#else\n char *fname;\n fname = get_file_path(p->cfg_filename, path);\n fs = fs_disk_init(fname);\n if (!fs) {\n fprintf(stderr, \"%s: must be a directory\\n\", fname);\n exit(1);\n }\n free(fname);\n#endif\n }\n p->tab_fs[i].fs_dev = fs;\n }\n\n for(i = 0; i < p->eth_count; i++) {\n#ifdef CONFIG_SLIRP\n if (!strcmp(p->tab_eth[i].driver, \"user\")) {\n p->tab_eth[i].net = slirp_open();\n if (!p->tab_eth[i].net)\n exit(1);\n } else\n#endif\n#ifndef _WIN32\n if (!strcmp(p->tab_eth[i].driver, \"tap\")) {\n p->tab_eth[i].net = tun_open(p->tab_eth[i].ifname);\n if (!p->tab_eth[i].net)\n exit(1);\n } else\n#endif\n {\n fprintf(stderr, \"Unsupported network driver '%s'\\n\",\n p->tab_eth[i].driver);\n exit(1);\n }\n }\n \n#ifdef CONFIG_SDL\n if (p->display_device) {\n sdl_init(p->width, p->height);\n } else\n#endif\n {\n#ifdef _WIN32\n fprintf(stderr, \"Console not supported yet\\n\");\n exit(1);\n#else\n p->console = console_init(allow_ctrlc);\n#endif\n }\n p->rtc_real_time = TRUE;\n\n s = virt_machine_init(p);\n if (!s)\n exit(1);\n \n virt_machine_free_config(p);\n\n if (s->net) {\n s->net->device_set_carrier(s->net, TRUE);\n }\n \n for(;;) {\n virt_machine_run(s);\n }\n virt_machine_end(s);\n return 0;\n}\n"], ["/linuxpdf/tinyemu/fs_net.c", "/*\n * Networked Filesystem using HTTP\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n#include \"fbuf.h\"\n\n#if defined(EMSCRIPTEN)\n#include \n#endif\n\n/*\n TODO:\n - implement fs_lock/fs_getlock\n - update fs_size with links ?\n - limit fs_size in dirent creation\n - limit filename length\n*/\n\n//#define DEBUG_CACHE\n#if !defined(EMSCRIPTEN)\n#define DUMP_CACHE_LOAD\n#endif\n\n#if defined(EMSCRIPTEN)\n#define DEFAULT_INODE_CACHE_SIZE (64 * 1024 * 1024)\n#else\n#define DEFAULT_INODE_CACHE_SIZE (256 * 1024 * 1024)\n#endif\n\ntypedef enum {\n FT_FIFO = 1,\n FT_CHR = 2,\n FT_DIR = 4,\n FT_BLK = 6,\n FT_REG = 8,\n FT_LNK = 10,\n FT_SOCK = 12,\n} FSINodeTypeEnum;\n\ntypedef enum {\n REG_STATE_LOCAL, /* local content */\n REG_STATE_UNLOADED, /* content not loaded */\n REG_STATE_LOADING, /* content is being loaded */\n REG_STATE_LOADED, /* loaded, not modified, stored in cached_inode_list */\n} FSINodeRegStateEnum;\n\ntypedef struct FSBaseURL {\n struct list_head link;\n int ref_count;\n char *base_url_id;\n char *url;\n char *user;\n char *password;\n BOOL encrypted;\n AES_KEY aes_state;\n} FSBaseURL;\n\ntypedef struct FSINode {\n struct list_head link;\n uint64_t inode_num; /* inode number */\n int32_t refcount;\n int32_t open_count;\n FSINodeTypeEnum type;\n uint32_t mode;\n uint32_t uid;\n uint32_t gid;\n uint32_t mtime_sec;\n uint32_t ctime_sec;\n uint32_t mtime_nsec;\n uint32_t ctime_nsec;\n union {\n struct {\n FSINodeRegStateEnum state;\n size_t size; /* real file size */\n FileBuffer fbuf;\n FSBaseURL *base_url;\n FSFileID file_id; /* network file ID */\n struct list_head link;\n struct FSOpenInfo *open_info; /* used in LOADING state */\n BOOL is_fscmd;\n#ifdef DUMP_CACHE_LOAD\n char *filename;\n#endif\n } reg;\n struct {\n struct list_head de_list; /* list of FSDirEntry */\n int size;\n } dir;\n struct {\n uint32_t major;\n uint32_t minor;\n } dev;\n struct {\n char *name;\n } symlink;\n } u;\n} FSINode;\n\ntypedef struct {\n struct list_head link;\n FSINode *inode;\n uint8_t mark; /* temporary use only */\n char name[0];\n} FSDirEntry;\n\ntypedef enum {\n FS_CMD_XHR,\n FS_CMD_PBKDF2,\n} FSCMDRequestEnum;\n\n#define FS_CMD_REPLY_LEN_MAX 64\n\ntypedef struct {\n FSCMDRequestEnum type;\n struct CmdXHRState *xhr_state;\n int reply_len;\n uint8_t reply_buf[FS_CMD_REPLY_LEN_MAX];\n} FSCMDRequest;\n\nstruct FSFile {\n uint32_t uid;\n FSINode *inode;\n BOOL is_opened;\n uint32_t open_flags;\n FSCMDRequest *req;\n};\n\ntypedef struct {\n struct list_head link;\n BOOL is_archive;\n const char *name;\n} PreloadFile;\n\ntypedef struct {\n struct list_head link;\n FSFileID file_id;\n struct list_head file_list; /* list of PreloadFile.link */\n} PreloadEntry;\n\ntypedef struct {\n struct list_head link;\n FSFileID file_id;\n uint64_t size;\n const char *name;\n} PreloadArchiveFile;\n\ntypedef struct {\n struct list_head link;\n const char *name;\n struct list_head file_list; /* list of PreloadArchiveFile.link */\n} PreloadArchive;\n\ntypedef struct FSDeviceMem {\n FSDevice common;\n\n struct list_head inode_list; /* list of FSINode */\n int64_t inode_count; /* current number of inodes */\n uint64_t inode_limit;\n int64_t fs_blocks;\n uint64_t fs_max_blocks;\n uint64_t inode_num_alloc;\n int block_size_log2;\n uint32_t block_size; /* for stat/statfs */\n FSINode *root_inode;\n struct list_head inode_cache_list; /* list of FSINode.u.reg.link */\n int64_t inode_cache_size;\n int64_t inode_cache_size_limit;\n struct list_head preload_list; /* list of PreloadEntry.link */\n struct list_head preload_archive_list; /* list of PreloadArchive.link */\n /* network */\n struct list_head base_url_list; /* list of FSBaseURL.link */\n char *import_dir;\n#ifdef DUMP_CACHE_LOAD\n BOOL dump_cache_load;\n BOOL dump_started;\n char *dump_preload_dir;\n FILE *dump_preload_file;\n FILE *dump_preload_archive_file;\n\n char *dump_archive_name;\n uint64_t dump_archive_size;\n FILE *dump_archive_file;\n\n int dump_archive_num;\n struct list_head dump_preload_list; /* list of PreloadFile.link */\n struct list_head dump_exclude_list; /* list of PreloadFile.link */\n#endif\n} FSDeviceMem;\n\ntypedef enum {\n FS_OPEN_WGET_REG,\n FS_OPEN_WGET_ARCHIVE,\n FS_OPEN_WGET_ARCHIVE_FILE,\n} FSOpenWgetEnum;\n\ntypedef struct FSOpenInfo {\n FSDevice *fs;\n FSOpenWgetEnum open_type;\n\n /* used for FS_OPEN_WGET_REG, FS_OPEN_WGET_ARCHIVE */\n XHRState *xhr;\n FSINode *n;\n DecryptFileState *dec_state;\n size_t cur_pos;\n\n struct list_head archive_link; /* FS_OPEN_WGET_ARCHIVE_FILE */\n uint64_t archive_offset; /* FS_OPEN_WGET_ARCHIVE_FILE */\n struct list_head archive_file_list; /* FS_OPEN_WGET_ARCHIVE */\n \n /* the following is set in case there is a fs_open callback */\n FSFile *f;\n FSOpenCompletionFunc *cb;\n void *opaque;\n} FSOpenInfo;\n\nstatic void fs_close(FSDevice *fs, FSFile *f);\nstatic void inode_decref(FSDevice *fs1, FSINode *n);\nstatic int fs_cmd_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int buf_len);\nstatic int fs_cmd_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int buf_len);\nstatic int fs_truncate(FSDevice *fs1, FSINode *n, uint64_t size);\nstatic void fs_open_end(FSOpenInfo *oi);\nstatic void fs_base_url_decref(FSDevice *fs, FSBaseURL *bu);\nstatic FSBaseURL *fs_net_set_base_url(FSDevice *fs1,\n const char *base_url_id,\n const char *url,\n const char *user, const char *password,\n AES_KEY *aes_state);\nstatic void fs_cmd_close(FSDevice *fs, FSFile *f);\nstatic void fs_error_archive(FSOpenInfo *oi);\n#ifdef DUMP_CACHE_LOAD\nstatic void dump_loaded_file(FSDevice *fs1, FSINode *n);\n#endif\n\n#if !defined(EMSCRIPTEN)\n/* file buffer (the content of the buffer can be stored elsewhere) */\nvoid file_buffer_init(FileBuffer *bs)\n{\n bs->data = NULL;\n bs->allocated_size = 0;\n}\n\nvoid file_buffer_reset(FileBuffer *bs)\n{\n free(bs->data);\n file_buffer_init(bs);\n}\n\nint file_buffer_resize(FileBuffer *bs, size_t new_size)\n{\n uint8_t *new_data;\n new_data = realloc(bs->data, new_size);\n if (!new_data && new_size != 0)\n return -1;\n bs->data = new_data;\n bs->allocated_size = new_size;\n return 0;\n}\n\nvoid file_buffer_write(FileBuffer *bs, size_t offset, const uint8_t *buf,\n size_t size)\n{\n memcpy(bs->data + offset, buf, size);\n}\n\nvoid file_buffer_set(FileBuffer *bs, size_t offset, int val, size_t size)\n{\n memset(bs->data + offset, val, size);\n}\n\nvoid file_buffer_read(FileBuffer *bs, size_t offset, uint8_t *buf,\n size_t size)\n{\n memcpy(buf, bs->data + offset, size);\n}\n#endif\n\nstatic int64_t to_blocks(FSDeviceMem *fs, uint64_t size)\n{\n return (size + fs->block_size - 1) >> fs->block_size_log2;\n}\n\nstatic FSINode *inode_incref(FSDevice *fs, FSINode *n)\n{\n n->refcount++;\n return n;\n}\n\nstatic FSINode *inode_inc_open(FSDevice *fs, FSINode *n)\n{\n n->open_count++;\n return n;\n}\n\nstatic void inode_free(FSDevice *fs1, FSINode *n)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n // printf(\"inode_free=%\" PRId64 \"\\n\", n->inode_num);\n assert(n->refcount == 0);\n assert(n->open_count == 0);\n switch(n->type) {\n case FT_REG:\n fs->fs_blocks -= to_blocks(fs, n->u.reg.size);\n assert(fs->fs_blocks >= 0);\n file_buffer_reset(&n->u.reg.fbuf);\n#ifdef DUMP_CACHE_LOAD\n free(n->u.reg.filename);\n#endif\n switch(n->u.reg.state) {\n case REG_STATE_LOADED:\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n fs_base_url_decref(fs1, n->u.reg.base_url);\n break;\n case REG_STATE_LOADING:\n {\n FSOpenInfo *oi = n->u.reg.open_info;\n if (oi->xhr)\n fs_wget_free(oi->xhr);\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE) {\n fs_error_archive(oi);\n }\n fs_open_end(oi);\n fs_base_url_decref(fs1, n->u.reg.base_url);\n }\n break;\n case REG_STATE_UNLOADED:\n fs_base_url_decref(fs1, n->u.reg.base_url);\n break;\n case REG_STATE_LOCAL:\n break;\n default:\n abort();\n }\n break;\n case FT_LNK:\n free(n->u.symlink.name);\n break;\n case FT_DIR:\n assert(list_empty(&n->u.dir.de_list));\n break;\n default:\n break;\n }\n list_del(&n->link);\n free(n);\n fs->inode_count--;\n assert(fs->inode_count >= 0);\n}\n\nstatic void inode_decref(FSDevice *fs1, FSINode *n)\n{\n assert(n->refcount >= 1);\n if (--n->refcount <= 0 && n->open_count <= 0) {\n inode_free(fs1, n);\n }\n}\n\nstatic void inode_dec_open(FSDevice *fs1, FSINode *n)\n{\n assert(n->open_count >= 1);\n if (--n->open_count <= 0 && n->refcount <= 0) {\n inode_free(fs1, n);\n }\n}\n\nstatic void inode_update_mtime(FSDevice *fs, FSINode *n)\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n n->mtime_sec = tv.tv_sec;\n n->mtime_nsec = tv.tv_usec * 1000;\n}\n\nstatic FSINode *inode_new(FSDevice *fs1, FSINodeTypeEnum type,\n uint32_t mode, uint32_t uid, uint32_t gid)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n;\n\n n = mallocz(sizeof(*n));\n n->refcount = 1;\n n->open_count = 0;\n n->inode_num = fs->inode_num_alloc;\n fs->inode_num_alloc++;\n n->type = type;\n n->mode = mode & 0xfff;\n n->uid = uid;\n n->gid = gid;\n\n switch(type) {\n case FT_REG:\n file_buffer_init(&n->u.reg.fbuf);\n break;\n case FT_DIR:\n init_list_head(&n->u.dir.de_list);\n break;\n default:\n break;\n }\n\n list_add(&n->link, &fs->inode_list);\n fs->inode_count++;\n\n inode_update_mtime(fs1, n);\n n->ctime_sec = n->mtime_sec;\n n->ctime_nsec = n->mtime_nsec;\n\n return n;\n}\n\n/* warning: the refcount of 'n1' is not incremented by this function */\n/* XXX: test FS max size */\nstatic FSDirEntry *inode_dir_add(FSDevice *fs1, FSINode *n, const char *name,\n FSINode *n1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSDirEntry *de;\n int name_len, dirent_size, new_size;\n assert(n->type == FT_DIR);\n\n name_len = strlen(name);\n de = mallocz(sizeof(*de) + name_len + 1);\n de->inode = n1;\n memcpy(de->name, name, name_len + 1);\n dirent_size = sizeof(*de) + name_len + 1;\n new_size = n->u.dir.size + dirent_size;\n fs->fs_blocks += to_blocks(fs, new_size) - to_blocks(fs, n->u.dir.size);\n n->u.dir.size = new_size;\n list_add_tail(&de->link, &n->u.dir.de_list);\n return de;\n}\n\nstatic FSDirEntry *inode_search(FSINode *n, const char *name)\n{\n struct list_head *el;\n FSDirEntry *de;\n \n if (n->type != FT_DIR)\n return NULL;\n\n list_for_each(el, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n if (!strcmp(de->name, name))\n return de;\n }\n return NULL;\n}\n\nstatic FSINode *inode_search_path1(FSDevice *fs, FSINode *n, const char *path)\n{\n char name[1024];\n const char *p, *p1;\n int len;\n FSDirEntry *de;\n \n p = path;\n if (*p == '/')\n p++;\n if (*p == '\\0')\n return n;\n for(;;) {\n p1 = strchr(p, '/');\n if (!p1) {\n len = strlen(p);\n } else {\n len = p1 - p;\n p1++;\n }\n if (len > sizeof(name) - 1)\n return NULL;\n memcpy(name, p, len);\n name[len] = '\\0';\n if (n->type != FT_DIR)\n return NULL;\n de = inode_search(n, name);\n if (!de)\n return NULL;\n n = de->inode;\n p = p1;\n if (!p)\n break;\n }\n return n;\n}\n\nstatic FSINode *inode_search_path(FSDevice *fs1, const char *path)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (!fs1)\n return NULL;\n return inode_search_path1(fs1, fs->root_inode, path);\n}\n\nstatic BOOL is_empty_dir(FSDevice *fs, FSINode *n)\n{\n struct list_head *el;\n FSDirEntry *de;\n\n list_for_each(el, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n if (strcmp(de->name, \".\") != 0 &&\n strcmp(de->name, \"..\") != 0)\n return FALSE;\n }\n return TRUE;\n}\n\nstatic void inode_dirent_delete_no_decref(FSDevice *fs1, FSINode *n, FSDirEntry *de)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int dirent_size, new_size;\n dirent_size = sizeof(*de) + strlen(de->name) + 1;\n\n new_size = n->u.dir.size - dirent_size;\n fs->fs_blocks += to_blocks(fs, new_size) - to_blocks(fs, n->u.dir.size);\n n->u.dir.size = new_size;\n assert(n->u.dir.size >= 0);\n assert(fs->fs_blocks >= 0);\n list_del(&de->link);\n free(de);\n}\n\nstatic void inode_dirent_delete(FSDevice *fs, FSINode *n, FSDirEntry *de)\n{\n FSINode *n1;\n n1 = de->inode;\n inode_dirent_delete_no_decref(fs, n, de);\n inode_decref(fs, n1);\n}\n\nstatic void flush_dir(FSDevice *fs, FSINode *n)\n{\n struct list_head *el, *el1;\n FSDirEntry *de;\n list_for_each_safe(el, el1, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n inode_dirent_delete(fs, n, de);\n }\n assert(n->u.dir.size == 0);\n}\n\nstatic void fs_delete(FSDevice *fs, FSFile *f)\n{\n fs_close(fs, f);\n inode_dec_open(fs, f->inode);\n free(f);\n}\n\nstatic FSFile *fid_create(FSDevice *fs1, FSINode *n, uint32_t uid)\n{\n FSFile *f;\n\n f = mallocz(sizeof(*f));\n f->inode = inode_inc_open(fs1, n);\n f->uid = uid;\n return f;\n}\n\nstatic void inode_to_qid(FSQID *qid, FSINode *n)\n{\n if (n->type == FT_DIR)\n qid->type = P9_QTDIR;\n else if (n->type == FT_LNK)\n qid->type = P9_QTSYMLINK;\n else\n qid->type = P9_QTFILE;\n qid->version = 0; /* no caching on client */\n qid->path = n->inode_num;\n}\n\nstatic void fs_statfs(FSDevice *fs1, FSStatFS *st)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n st->f_bsize = 1024;\n st->f_blocks = fs->fs_max_blocks <<\n (fs->block_size_log2 - 10);\n st->f_bfree = (fs->fs_max_blocks - fs->fs_blocks) <<\n (fs->block_size_log2 - 10);\n st->f_bavail = st->f_bfree;\n st->f_files = fs->inode_limit;\n st->f_ffree = fs->inode_limit - fs->inode_count;\n}\n\nstatic int fs_attach(FSDevice *fs1, FSFile **pf, FSQID *qid, uint32_t uid,\n const char *uname, const char *aname)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n *pf = fid_create(fs1, fs->root_inode, uid);\n inode_to_qid(qid, fs->root_inode);\n return 0;\n}\n\nstatic int fs_walk(FSDevice *fs, FSFile **pf, FSQID *qids,\n FSFile *f, int count, char **names)\n{\n int i;\n FSINode *n;\n FSDirEntry *de;\n\n n = f->inode;\n for(i = 0; i < count; i++) {\n de = inode_search(n, names[i]);\n if (!de)\n break;\n n = de->inode;\n inode_to_qid(&qids[i], n);\n }\n *pf = fid_create(fs, n, f->uid);\n return i;\n}\n\nstatic int fs_mkdir(FSDevice *fs, FSQID *qid, FSFile *f,\n const char *name, uint32_t mode, uint32_t gid)\n{\n FSINode *n, *n1;\n\n n = f->inode;\n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n if (inode_search(n, name))\n return -P9_EEXIST;\n n1 = inode_new(fs, FT_DIR, mode, f->uid, gid);\n inode_dir_add(fs, n1, \".\", inode_incref(fs, n1));\n inode_dir_add(fs, n1, \"..\", inode_incref(fs, n));\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\n/* remove elements in the cache considering that 'added_size' will be\n added */\nstatic void fs_trim_cache(FSDevice *fs1, int64_t added_size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el, *el1;\n FSINode *n;\n\n if ((fs->inode_cache_size + added_size) <= fs->inode_cache_size_limit)\n return;\n list_for_each_prev_safe(el, el1, &fs->inode_cache_list) {\n n = list_entry(el, FSINode, u.reg.link);\n assert(n->u.reg.state == REG_STATE_LOADED);\n /* cannot remove open files */\n // printf(\"open_count=%d\\n\", n->open_count);\n if (n->open_count != 0)\n continue;\n#ifdef DEBUG_CACHE\n printf(\"fs_trim_cache: remove '%s' size=%ld\\n\",\n n->u.reg.filename, (long)n->u.reg.size);\n#endif\n file_buffer_reset(&n->u.reg.fbuf);\n n->u.reg.state = REG_STATE_UNLOADED;\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n if ((fs->inode_cache_size + added_size) <= fs->inode_cache_size_limit)\n break;\n }\n}\n\nstatic void fs_open_end(FSOpenInfo *oi)\n{\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE_FILE) {\n list_del(&oi->archive_link);\n }\n if (oi->dec_state)\n decrypt_file_end(oi->dec_state);\n free(oi);\n}\n\nstatic int fs_open_write_cb(void *opaque, const uint8_t *data, size_t size)\n{\n FSOpenInfo *oi = opaque;\n size_t len;\n FSINode *n = oi->n;\n \n /* we ignore extraneous data */\n len = n->u.reg.size - oi->cur_pos;\n if (size < len)\n len = size;\n file_buffer_write(&n->u.reg.fbuf, oi->cur_pos, data, len);\n oi->cur_pos += len;\n return 0;\n}\n\nstatic void fs_wget_set_loaded(FSINode *n)\n{\n FSOpenInfo *oi;\n FSDeviceMem *fs;\n FSFile *f;\n FSQID qid;\n\n assert(n->u.reg.state == REG_STATE_LOADING);\n oi = n->u.reg.open_info;\n fs = (FSDeviceMem *)oi->fs;\n n->u.reg.state = REG_STATE_LOADED;\n list_add(&n->u.reg.link, &fs->inode_cache_list);\n fs->inode_cache_size += n->u.reg.size;\n \n if (oi->cb) {\n f = oi->f;\n f->is_opened = TRUE;\n inode_to_qid(&qid, n);\n oi->cb(oi->fs, &qid, 0, oi->opaque);\n }\n fs_open_end(oi);\n}\n\nstatic void fs_wget_set_error(FSINode *n)\n{\n FSOpenInfo *oi;\n assert(n->u.reg.state == REG_STATE_LOADING);\n oi = n->u.reg.open_info;\n n->u.reg.state = REG_STATE_UNLOADED;\n file_buffer_reset(&n->u.reg.fbuf);\n if (oi->cb) {\n oi->cb(oi->fs, NULL, -P9_EIO, oi->opaque);\n }\n fs_open_end(oi);\n}\n\nstatic void fs_read_archive(FSOpenInfo *oi)\n{\n FSINode *n = oi->n;\n uint64_t pos, pos1, l;\n uint8_t buf[1024];\n FSINode *n1;\n FSOpenInfo *oi1;\n struct list_head *el, *el1;\n \n list_for_each_safe(el, el1, &oi->archive_file_list) {\n oi1 = list_entry(el, FSOpenInfo, archive_link);\n n1 = oi1->n;\n /* copy the archive data to the file */\n pos = oi1->archive_offset;\n pos1 = 0;\n while (pos1 < n1->u.reg.size) {\n l = n1->u.reg.size - pos1;\n if (l > sizeof(buf))\n l = sizeof(buf);\n file_buffer_read(&n->u.reg.fbuf, pos, buf, l);\n file_buffer_write(&n1->u.reg.fbuf, pos1, buf, l);\n pos += l;\n pos1 += l;\n }\n fs_wget_set_loaded(n1);\n }\n}\n\nstatic void fs_error_archive(FSOpenInfo *oi)\n{\n FSOpenInfo *oi1;\n struct list_head *el, *el1;\n \n list_for_each_safe(el, el1, &oi->archive_file_list) {\n oi1 = list_entry(el, FSOpenInfo, archive_link);\n fs_wget_set_error(oi1->n);\n }\n}\n\nstatic void fs_open_cb(void *opaque, int err, void *data, size_t size)\n{\n FSOpenInfo *oi = opaque;\n FSINode *n = oi->n;\n \n // printf(\"open_cb: err=%d size=%ld\\n\", err, size);\n if (err < 0) {\n error:\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE)\n fs_error_archive(oi);\n fs_wget_set_error(n);\n } else {\n if (oi->dec_state) {\n if (decrypt_file(oi->dec_state, data, size) < 0)\n goto error;\n if (err == 0) {\n if (decrypt_file_flush(oi->dec_state) < 0)\n goto error;\n }\n } else {\n fs_open_write_cb(oi, data, size);\n }\n\n if (err == 0) {\n /* end of transfer */\n if (oi->cur_pos != n->u.reg.size)\n goto error;\n#ifdef DUMP_CACHE_LOAD\n dump_loaded_file(oi->fs, n);\n#endif\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE)\n fs_read_archive(oi);\n fs_wget_set_loaded(n);\n }\n }\n}\n\n\nstatic int fs_open_wget(FSDevice *fs1, FSINode *n, FSOpenWgetEnum open_type)\n{\n char *url;\n FSOpenInfo *oi;\n char fname[FILEID_SIZE_MAX];\n FSBaseURL *bu;\n\n assert(n->u.reg.state == REG_STATE_UNLOADED);\n \n fs_trim_cache(fs1, n->u.reg.size);\n \n if (file_buffer_resize(&n->u.reg.fbuf, n->u.reg.size) < 0)\n return -P9_EIO;\n n->u.reg.state = REG_STATE_LOADING;\n oi = mallocz(sizeof(*oi));\n oi->cur_pos = 0;\n oi->fs = fs1;\n oi->n = n;\n oi->open_type = open_type;\n if (open_type != FS_OPEN_WGET_ARCHIVE_FILE) {\n if (open_type == FS_OPEN_WGET_ARCHIVE)\n init_list_head(&oi->archive_file_list);\n file_id_to_filename(fname, n->u.reg.file_id);\n bu = n->u.reg.base_url;\n url = compose_path(bu->url, fname);\n if (bu->encrypted) {\n oi->dec_state = decrypt_file_init(&bu->aes_state, fs_open_write_cb, oi);\n }\n oi->xhr = fs_wget(url, bu->user, bu->password, oi, fs_open_cb, FALSE);\n }\n n->u.reg.open_info = oi;\n return 0;\n}\n\n\nstatic void fs_preload_file(FSDevice *fs1, const char *filename)\n{\n FSINode *n;\n\n n = inode_search_path(fs1, filename);\n if (n && n->type == FT_REG && n->u.reg.state == REG_STATE_UNLOADED) {\n#if defined(DEBUG_CACHE)\n printf(\"preload: %s\\n\", filename);\n#endif\n fs_open_wget(fs1, n, FS_OPEN_WGET_REG);\n }\n}\n\nstatic PreloadArchive *find_preload_archive(FSDeviceMem *fs,\n const char *filename)\n{\n PreloadArchive *pa;\n struct list_head *el;\n list_for_each(el, &fs->preload_archive_list) {\n pa = list_entry(el, PreloadArchive, link);\n if (!strcmp(pa->name, filename))\n return pa;\n }\n return NULL;\n}\n\nstatic void fs_preload_archive(FSDevice *fs1, const char *filename)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n PreloadArchive *pa;\n PreloadArchiveFile *paf;\n struct list_head *el;\n FSINode *n, *n1;\n uint64_t offset;\n BOOL has_unloaded;\n \n pa = find_preload_archive(fs, filename);\n if (!pa)\n return;\n#if defined(DEBUG_CACHE)\n printf(\"preload archive: %s\\n\", filename);\n#endif\n n = inode_search_path(fs1, filename);\n if (n && n->type == FT_REG && n->u.reg.state == REG_STATE_UNLOADED) {\n /* if all the files are loaded, no need to load the archive */\n offset = 0;\n has_unloaded = FALSE;\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n n1 = inode_search_path(fs1, paf->name);\n if (n1 && n1->type == FT_REG &&\n n1->u.reg.state == REG_STATE_UNLOADED) {\n has_unloaded = TRUE;\n }\n offset += paf->size;\n }\n if (!has_unloaded) {\n#if defined(DEBUG_CACHE)\n printf(\"archive files already loaded\\n\");\n#endif\n return;\n }\n /* check archive size consistency */\n if (offset != n->u.reg.size) {\n#if defined(DEBUG_CACHE)\n printf(\" inconsistent archive size: %\" PRId64 \" %\" PRId64 \"\\n\",\n offset, n->u.reg.size);\n#endif\n goto load_fallback;\n }\n\n /* start loading the archive */\n fs_open_wget(fs1, n, FS_OPEN_WGET_ARCHIVE);\n \n /* indicate that all the archive files are being loaded. Also\n check consistency of size and file id */\n offset = 0;\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n n1 = inode_search_path(fs1, paf->name);\n if (n1 && n1->type == FT_REG &&\n n1->u.reg.state == REG_STATE_UNLOADED) {\n if (n1->u.reg.size == paf->size &&\n n1->u.reg.file_id == paf->file_id) {\n fs_open_wget(fs1, n1, FS_OPEN_WGET_ARCHIVE_FILE);\n list_add_tail(&n1->u.reg.open_info->archive_link,\n &n->u.reg.open_info->archive_file_list);\n n1->u.reg.open_info->archive_offset = offset;\n } else {\n#if defined(DEBUG_CACHE)\n printf(\" inconsistent archive file: %s\\n\", paf->name);\n#endif\n /* fallback to file preload */\n fs_preload_file(fs1, paf->name);\n }\n }\n offset += paf->size;\n }\n } else {\n load_fallback:\n /* if the archive is already loaded or not loaded, we load the\n files separately (XXX: not optimal if the archive is\n already loaded, but it should not happen often) */\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n fs_preload_file(fs1, paf->name);\n }\n }\n}\n\nstatic void fs_preload_files(FSDevice *fs1, FSFileID file_id)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el;\n PreloadEntry *pe;\n PreloadFile *pf;\n \n list_for_each(el, &fs->preload_list) {\n pe = list_entry(el, PreloadEntry, link);\n if (pe->file_id == file_id)\n goto found;\n }\n return;\n found:\n list_for_each(el, &pe->file_list) {\n pf = list_entry(el, PreloadFile, link);\n if (pf->is_archive)\n fs_preload_archive(fs1, pf->name);\n else\n fs_preload_file(fs1, pf->name);\n }\n}\n\n/* return < 0 if error, 0 if OK, 1 if asynchronous completion */\n/* XXX: we don't support several simultaneous asynchronous open on the\n same inode */\nstatic int fs_open(FSDevice *fs1, FSQID *qid, FSFile *f, uint32_t flags,\n FSOpenCompletionFunc *cb, void *opaque)\n{\n FSINode *n = f->inode;\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int ret;\n \n fs_close(fs1, f);\n\n if (flags & P9_O_DIRECTORY) {\n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n } else {\n if (n->type != FT_REG && n->type != FT_DIR)\n return -P9_EINVAL; /* XXX */\n }\n f->open_flags = flags;\n if (n->type == FT_REG) {\n if ((flags & P9_O_TRUNC) && (flags & P9_O_NOACCESS) != P9_O_RDONLY) {\n fs_truncate(fs1, n, 0);\n }\n\n switch(n->u.reg.state) {\n case REG_STATE_UNLOADED:\n {\n FSOpenInfo *oi;\n /* need to load the file */\n fs_preload_files(fs1, n->u.reg.file_id);\n /* The state can be modified by the fs_preload_files */\n if (n->u.reg.state == REG_STATE_LOADING)\n goto handle_loading;\n ret = fs_open_wget(fs1, n, FS_OPEN_WGET_REG);\n if (ret)\n return ret;\n oi = n->u.reg.open_info;\n oi->f = f;\n oi->cb = cb;\n oi->opaque = opaque;\n return 1; /* completion callback will be called later */\n }\n break;\n case REG_STATE_LOADING:\n handle_loading:\n {\n FSOpenInfo *oi;\n /* we only handle the case where the file is being preloaded */\n oi = n->u.reg.open_info;\n if (oi->cb)\n return -P9_EIO;\n oi = n->u.reg.open_info;\n oi->f = f;\n oi->cb = cb;\n oi->opaque = opaque;\n return 1; /* completion callback will be called later */\n }\n break;\n case REG_STATE_LOCAL:\n goto do_open;\n case REG_STATE_LOADED:\n /* move to front */\n list_del(&n->u.reg.link);\n list_add(&n->u.reg.link, &fs->inode_cache_list);\n goto do_open;\n default:\n abort();\n }\n } else {\n do_open:\n f->is_opened = TRUE;\n inode_to_qid(qid, n);\n return 0;\n }\n}\n\nstatic int fs_create(FSDevice *fs, FSQID *qid, FSFile *f, const char *name, \n uint32_t flags, uint32_t mode, uint32_t gid)\n{\n FSINode *n1, *n = f->inode;\n \n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n if (inode_search(n, name)) {\n /* XXX: support it, but Linux does not seem to use this case */\n return -P9_EEXIST;\n } else {\n fs_close(fs, f);\n \n n1 = inode_new(fs, FT_REG, mode, f->uid, gid);\n inode_dir_add(fs, n, name, n1);\n \n inode_dec_open(fs, f->inode);\n f->inode = inode_inc_open(fs, n1);\n f->is_opened = TRUE;\n f->open_flags = flags;\n inode_to_qid(qid, n1);\n return 0;\n }\n}\n\nstatic int fs_readdir(FSDevice *fs, FSFile *f, uint64_t offset1,\n uint8_t *buf, int count)\n{\n FSINode *n1, *n = f->inode;\n int len, pos, name_len, type;\n struct list_head *el;\n FSDirEntry *de;\n uint64_t offset;\n\n if (!f->is_opened || n->type != FT_DIR)\n return -P9_EPROTO;\n \n el = n->u.dir.de_list.next;\n offset = 0;\n while (offset < offset1) {\n if (el == &n->u.dir.de_list)\n return 0; /* no more entries */\n offset++;\n el = el->next;\n }\n \n pos = 0;\n for(;;) {\n if (el == &n->u.dir.de_list)\n break;\n de = list_entry(el, FSDirEntry, link);\n name_len = strlen(de->name);\n len = 13 + 8 + 1 + 2 + name_len;\n if ((pos + len) > count)\n break;\n offset++;\n n1 = de->inode;\n if (n1->type == FT_DIR)\n type = P9_QTDIR;\n else if (n1->type == FT_LNK)\n type = P9_QTSYMLINK;\n else\n type = P9_QTFILE;\n buf[pos++] = type;\n put_le32(buf + pos, 0); /* version */\n pos += 4;\n put_le64(buf + pos, n1->inode_num);\n pos += 8;\n put_le64(buf + pos, offset);\n pos += 8;\n buf[pos++] = n1->type;\n put_le16(buf + pos, name_len);\n pos += 2;\n memcpy(buf + pos, de->name, name_len);\n pos += name_len;\n el = el->next;\n }\n return pos;\n}\n\nstatic int fs_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n FSINode *n = f->inode;\n uint64_t count1;\n\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n if ((f->open_flags & P9_O_NOACCESS) == P9_O_WRONLY)\n return -P9_EIO;\n if (n->u.reg.is_fscmd)\n return fs_cmd_read(fs, f, offset, buf, count);\n if (offset >= n->u.reg.size)\n return 0;\n count1 = n->u.reg.size - offset;\n if (count1 < count)\n count = count1;\n file_buffer_read(&n->u.reg.fbuf, offset, buf, count);\n return count;\n}\n\nstatic int fs_truncate(FSDevice *fs1, FSINode *n, uint64_t size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n intptr_t diff, diff_blocks;\n size_t new_allocated_size;\n \n if (n->type != FT_REG)\n return -P9_EINVAL;\n if (size > UINTPTR_MAX)\n return -P9_ENOSPC;\n diff = size - n->u.reg.size;\n if (diff == 0)\n return 0;\n diff_blocks = to_blocks(fs, size) - to_blocks(fs, n->u.reg.size);\n /* currently cannot resize while loading */\n switch(n->u.reg.state) {\n case REG_STATE_LOADING:\n return -P9_EIO;\n case REG_STATE_UNLOADED:\n if (size == 0) {\n /* now local content */\n n->u.reg.state = REG_STATE_LOCAL;\n }\n break;\n case REG_STATE_LOADED:\n case REG_STATE_LOCAL:\n if (diff > 0) {\n if ((fs->fs_blocks + diff_blocks) > fs->fs_max_blocks)\n return -P9_ENOSPC;\n if (size > n->u.reg.fbuf.allocated_size) {\n new_allocated_size = n->u.reg.fbuf.allocated_size * 5 / 4;\n if (size > new_allocated_size)\n new_allocated_size = size;\n if (file_buffer_resize(&n->u.reg.fbuf, new_allocated_size) < 0)\n return -P9_ENOSPC;\n }\n file_buffer_set(&n->u.reg.fbuf, n->u.reg.size, 0, diff);\n } else {\n new_allocated_size = n->u.reg.fbuf.allocated_size * 4 / 5;\n if (size <= new_allocated_size) {\n if (file_buffer_resize(&n->u.reg.fbuf, new_allocated_size) < 0)\n return -P9_ENOSPC;\n }\n }\n /* file is modified, so it is now local */\n if (n->u.reg.state == REG_STATE_LOADED) {\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n n->u.reg.state = REG_STATE_LOCAL;\n }\n break;\n default:\n abort();\n }\n fs->fs_blocks += diff_blocks;\n assert(fs->fs_blocks >= 0);\n n->u.reg.size = size;\n return 0;\n}\n\nstatic int fs_write(FSDevice *fs1, FSFile *f, uint64_t offset,\n const uint8_t *buf, int count)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n = f->inode;\n uint64_t end;\n int err;\n \n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n if ((f->open_flags & P9_O_NOACCESS) == P9_O_RDONLY)\n return -P9_EIO;\n if (count == 0)\n return 0;\n if (n->u.reg.is_fscmd) {\n return fs_cmd_write(fs1, f, offset, buf, count);\n }\n end = offset + count;\n if (end > n->u.reg.size) {\n err = fs_truncate(fs1, n, end);\n if (err)\n return err;\n }\n inode_update_mtime(fs1, n);\n /* file is modified, so it is now local */\n if (n->u.reg.state == REG_STATE_LOADED) {\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n n->u.reg.state = REG_STATE_LOCAL;\n }\n file_buffer_write(&n->u.reg.fbuf, offset, buf, count);\n return count;\n}\n\nstatic void fs_close(FSDevice *fs, FSFile *f)\n{\n if (f->is_opened) {\n f->is_opened = FALSE;\n }\n if (f->req)\n fs_cmd_close(fs, f);\n}\n\nstatic int fs_stat(FSDevice *fs1, FSFile *f, FSStat *st)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n = f->inode;\n\n inode_to_qid(&st->qid, n);\n st->st_mode = n->mode | (n->type << 12);\n st->st_uid = n->uid;\n st->st_gid = n->gid;\n st->st_nlink = n->refcount;\n if (n->type == FT_BLK || n->type == FT_CHR) {\n /* XXX: check */\n st->st_rdev = (n->u.dev.major << 8) | n->u.dev.minor;\n } else {\n st->st_rdev = 0;\n }\n st->st_blksize = fs->block_size;\n if (n->type == FT_REG) {\n st->st_size = n->u.reg.size;\n } else if (n->type == FT_LNK) {\n st->st_size = strlen(n->u.symlink.name);\n } else if (n->type == FT_DIR) {\n st->st_size = n->u.dir.size;\n } else {\n st->st_size = 0;\n }\n /* in 512 byte blocks */\n st->st_blocks = to_blocks(fs, st->st_size) << (fs->block_size_log2 - 9);\n \n /* Note: atime is not supported */\n st->st_atime_sec = n->mtime_sec;\n st->st_atime_nsec = n->mtime_nsec;\n st->st_mtime_sec = n->mtime_sec;\n st->st_mtime_nsec = n->mtime_nsec;\n st->st_ctime_sec = n->ctime_sec;\n st->st_ctime_nsec = n->ctime_nsec;\n return 0;\n}\n\nstatic int fs_setattr(FSDevice *fs1, FSFile *f, uint32_t mask,\n uint32_t mode, uint32_t uid, uint32_t gid,\n uint64_t size, uint64_t atime_sec, uint64_t atime_nsec,\n uint64_t mtime_sec, uint64_t mtime_nsec)\n{\n FSINode *n = f->inode;\n int ret;\n \n if (mask & P9_SETATTR_MODE) {\n n->mode = mode;\n }\n if (mask & P9_SETATTR_UID) {\n n->uid = uid;\n }\n if (mask & P9_SETATTR_GID) {\n n->gid = gid;\n }\n if (mask & P9_SETATTR_SIZE) {\n ret = fs_truncate(fs1, n, size);\n if (ret)\n return ret;\n }\n if (mask & P9_SETATTR_MTIME) {\n if (mask & P9_SETATTR_MTIME_SET) {\n n->mtime_sec = mtime_sec;\n n->mtime_nsec = mtime_nsec;\n } else {\n inode_update_mtime(fs1, n);\n }\n }\n if (mask & P9_SETATTR_CTIME) {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n n->ctime_sec = tv.tv_sec;\n n->ctime_nsec = tv.tv_usec * 1000;\n }\n return 0;\n}\n\nstatic int fs_link(FSDevice *fs, FSFile *df, FSFile *f, const char *name)\n{\n FSINode *n = df->inode;\n \n if (f->inode->type == FT_DIR)\n return -P9_EPERM;\n if (inode_search(n, name))\n return -P9_EEXIST;\n inode_dir_add(fs, n, name, inode_incref(fs, f->inode));\n return 0;\n}\n\nstatic int fs_symlink(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, const char *symgt, uint32_t gid)\n{\n FSINode *n1, *n = f->inode;\n \n if (inode_search(n, name))\n return -P9_EEXIST;\n\n n1 = inode_new(fs, FT_LNK, 0777, f->uid, gid);\n n1->u.symlink.name = strdup(symgt);\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\nstatic int fs_mknod(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, uint32_t mode, uint32_t major,\n uint32_t minor, uint32_t gid)\n{\n int type;\n FSINode *n1, *n = f->inode;\n\n type = (mode & P9_S_IFMT) >> 12;\n /* XXX: add FT_DIR support */\n if (type != FT_FIFO && type != FT_CHR && type != FT_BLK &&\n type != FT_REG && type != FT_SOCK)\n return -P9_EINVAL;\n if (inode_search(n, name))\n return -P9_EEXIST;\n n1 = inode_new(fs, type, mode, f->uid, gid);\n if (type == FT_CHR || type == FT_BLK) {\n n1->u.dev.major = major;\n n1->u.dev.minor = minor;\n }\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\nstatic int fs_readlink(FSDevice *fs, char *buf, int buf_size, FSFile *f)\n{\n FSINode *n = f->inode;\n int len;\n if (n->type != FT_LNK)\n return -P9_EIO;\n len = min_int(strlen(n->u.symlink.name), buf_size - 1);\n memcpy(buf, n->u.symlink.name, len);\n buf[len] = '\\0';\n return 0;\n}\n\nstatic int fs_renameat(FSDevice *fs, FSFile *f, const char *name, \n FSFile *new_f, const char *new_name)\n{\n FSDirEntry *de, *de1;\n FSINode *n1;\n \n de = inode_search(f->inode, name);\n if (!de)\n return -P9_ENOENT;\n de1 = inode_search(new_f->inode, new_name);\n n1 = NULL;\n if (de1) {\n n1 = de1->inode;\n if (n1->type == FT_DIR)\n return -P9_EEXIST; /* XXX: handle the case */\n inode_dirent_delete_no_decref(fs, new_f->inode, de1);\n }\n inode_dir_add(fs, new_f->inode, new_name, inode_incref(fs, de->inode));\n inode_dirent_delete(fs, f->inode, de);\n if (n1)\n inode_decref(fs, n1);\n return 0;\n}\n\nstatic int fs_unlinkat(FSDevice *fs, FSFile *f, const char *name)\n{\n FSDirEntry *de;\n FSINode *n;\n\n if (!strcmp(name, \".\") || !strcmp(name, \"..\"))\n return -P9_ENOENT;\n de = inode_search(f->inode, name);\n if (!de)\n return -P9_ENOENT;\n n = de->inode;\n if (n->type == FT_DIR) {\n if (!is_empty_dir(fs, n))\n return -P9_ENOTEMPTY;\n flush_dir(fs, n);\n }\n inode_dirent_delete(fs, f->inode, de);\n return 0;\n}\n\nstatic int fs_lock(FSDevice *fs, FSFile *f, const FSLock *lock)\n{\n FSINode *n = f->inode;\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n /* XXX: implement it */\n return P9_LOCK_SUCCESS;\n}\n\nstatic int fs_getlock(FSDevice *fs, FSFile *f, FSLock *lock)\n{\n FSINode *n = f->inode;\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n /* XXX: implement it */\n return 0;\n}\n\n/* XXX: only used with file lists, so not all the data is released */\nstatic void fs_mem_end(FSDevice *fs1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el, *el1, *el2, *el3;\n FSINode *n;\n FSDirEntry *de;\n\n list_for_each_safe(el, el1, &fs->inode_list) {\n n = list_entry(el, FSINode, link);\n n->refcount = 0;\n if (n->type == FT_DIR) {\n list_for_each_safe(el2, el3, &n->u.dir.de_list) {\n de = list_entry(el2, FSDirEntry, link);\n list_del(&de->link);\n free(de);\n }\n init_list_head(&n->u.dir.de_list);\n }\n inode_free(fs1, n);\n }\n assert(list_empty(&fs->inode_cache_list));\n free(fs->import_dir);\n}\n\nFSDevice *fs_mem_init(void)\n{\n FSDeviceMem *fs;\n FSDevice *fs1;\n FSINode *n;\n\n fs = mallocz(sizeof(*fs));\n fs1 = &fs->common;\n\n fs->common.fs_end = fs_mem_end;\n fs->common.fs_delete = fs_delete;\n fs->common.fs_statfs = fs_statfs;\n fs->common.fs_attach = fs_attach;\n fs->common.fs_walk = fs_walk;\n fs->common.fs_mkdir = fs_mkdir;\n fs->common.fs_open = fs_open;\n fs->common.fs_create = fs_create;\n fs->common.fs_stat = fs_stat;\n fs->common.fs_setattr = fs_setattr;\n fs->common.fs_close = fs_close;\n fs->common.fs_readdir = fs_readdir;\n fs->common.fs_read = fs_read;\n fs->common.fs_write = fs_write;\n fs->common.fs_link = fs_link;\n fs->common.fs_symlink = fs_symlink;\n fs->common.fs_mknod = fs_mknod;\n fs->common.fs_readlink = fs_readlink;\n fs->common.fs_renameat = fs_renameat;\n fs->common.fs_unlinkat = fs_unlinkat;\n fs->common.fs_lock = fs_lock;\n fs->common.fs_getlock = fs_getlock;\n\n init_list_head(&fs->inode_list);\n fs->inode_num_alloc = 1;\n fs->block_size_log2 = FS_BLOCK_SIZE_LOG2;\n fs->block_size = 1 << fs->block_size_log2;\n fs->inode_limit = 1 << 20; /* arbitrary */\n fs->fs_max_blocks = 1 << (30 - fs->block_size_log2); /* arbitrary */\n\n init_list_head(&fs->inode_cache_list);\n fs->inode_cache_size_limit = DEFAULT_INODE_CACHE_SIZE;\n\n init_list_head(&fs->preload_list);\n init_list_head(&fs->preload_archive_list);\n\n init_list_head(&fs->base_url_list);\n\n /* create the root inode */\n n = inode_new(fs1, FT_DIR, 0777, 0, 0);\n inode_dir_add(fs1, n, \".\", inode_incref(fs1, n));\n inode_dir_add(fs1, n, \"..\", inode_incref(fs1, n));\n fs->root_inode = n;\n\n return (FSDevice *)fs;\n}\n\nstatic BOOL fs_is_net(FSDevice *fs)\n{\n return (fs->fs_end == fs_mem_end);\n}\n\nstatic FSBaseURL *fs_find_base_url(FSDevice *fs1,\n const char *base_url_id)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el;\n FSBaseURL *bu;\n \n list_for_each(el, &fs->base_url_list) {\n bu = list_entry(el, FSBaseURL, link);\n if (!strcmp(bu->base_url_id, base_url_id))\n return bu;\n }\n return NULL;\n}\n\nstatic void fs_base_url_decref(FSDevice *fs, FSBaseURL *bu)\n{\n assert(bu->ref_count >= 1);\n if (--bu->ref_count == 0) {\n free(bu->base_url_id);\n free(bu->url);\n free(bu->user);\n free(bu->password);\n list_del(&bu->link);\n free(bu);\n }\n}\n\nstatic FSBaseURL *fs_net_set_base_url(FSDevice *fs1,\n const char *base_url_id,\n const char *url,\n const char *user, const char *password,\n AES_KEY *aes_state)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSBaseURL *bu;\n \n assert(fs_is_net(fs1));\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu) {\n bu = mallocz(sizeof(*bu));\n bu->base_url_id = strdup(base_url_id);\n bu->ref_count = 1;\n list_add_tail(&bu->link, &fs->base_url_list);\n } else {\n free(bu->url);\n free(bu->user);\n free(bu->password);\n }\n\n bu->url = strdup(url);\n if (user)\n bu->user = strdup(user);\n else\n bu->user = NULL;\n if (password)\n bu->password = strdup(password);\n else\n bu->password = NULL;\n if (aes_state) {\n bu->encrypted = TRUE;\n bu->aes_state = *aes_state;\n } else {\n bu->encrypted = FALSE;\n }\n return bu;\n}\n\nstatic int fs_net_reset_base_url(FSDevice *fs1,\n const char *base_url_id)\n{\n FSBaseURL *bu;\n \n assert(fs_is_net(fs1));\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu)\n return -P9_ENOENT;\n fs_base_url_decref(fs1, bu);\n return 0;\n}\n\nstatic void fs_net_set_fs_max_size(FSDevice *fs1, uint64_t fs_max_size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n assert(fs_is_net(fs1));\n fs->fs_max_blocks = to_blocks(fs, fs_max_size);\n}\n\nstatic int fs_net_set_url(FSDevice *fs1, FSINode *n,\n const char *base_url_id, FSFileID file_id, uint64_t size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSBaseURL *bu;\n\n assert(fs_is_net(fs1));\n\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu)\n return -P9_ENOENT;\n\n /* XXX: could accept more state */\n if (n->type != FT_REG ||\n n->u.reg.state != REG_STATE_LOCAL ||\n n->u.reg.fbuf.allocated_size != 0)\n return -P9_EIO;\n \n if (size > 0) {\n n->u.reg.state = REG_STATE_UNLOADED;\n n->u.reg.base_url = bu;\n bu->ref_count++;\n n->u.reg.size = size;\n fs->fs_blocks += to_blocks(fs, size);\n n->u.reg.file_id = file_id;\n }\n return 0;\n}\n\n#ifdef DUMP_CACHE_LOAD\n\n#include \"json.h\"\n\n#define ARCHIVE_SIZE_MAX (4 << 20)\n\nstatic void fs_dump_add_file(struct list_head *head, const char *name)\n{\n PreloadFile *pf;\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(name);\n list_add_tail(&pf->link, head);\n}\n\nstatic PreloadFile *fs_dump_find_file(struct list_head *head, const char *name)\n{\n PreloadFile *pf;\n struct list_head *el;\n list_for_each(el, head) {\n pf = list_entry(el, PreloadFile, link);\n if (!strcmp(pf->name, name))\n return pf;\n }\n return NULL;\n}\n\nstatic void dump_close_archive(FSDevice *fs1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (fs->dump_archive_file) {\n fclose(fs->dump_archive_file);\n }\n fs->dump_archive_file = NULL;\n fs->dump_archive_size = 0;\n}\n\nstatic void dump_loaded_file(FSDevice *fs1, FSINode *n)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char filename[1024];\n const char *fname, *p;\n \n if (!fs->dump_cache_load || !n->u.reg.filename)\n return;\n fname = n->u.reg.filename;\n \n if (fs_dump_find_file(&fs->dump_preload_list, fname)) {\n dump_close_archive(fs1);\n p = strrchr(fname, '/');\n if (!p)\n p = fname;\n else\n p++;\n free(fs->dump_archive_name);\n fs->dump_archive_name = strdup(p);\n fs->dump_started = TRUE;\n fs->dump_archive_num = 0;\n\n fprintf(fs->dump_preload_file, \"\\n%s :\\n\", fname);\n }\n if (!fs->dump_started)\n return;\n \n if (!fs->dump_archive_file) {\n snprintf(filename, sizeof(filename), \"%s/%s%d\",\n fs->dump_preload_dir, fs->dump_archive_name,\n fs->dump_archive_num);\n fs->dump_archive_file = fopen(filename, \"wb\");\n if (!fs->dump_archive_file) {\n perror(filename);\n exit(1);\n }\n fprintf(fs->dump_preload_archive_file, \"\\n@.preload2/%s%d :\\n\",\n fs->dump_archive_name, fs->dump_archive_num);\n fprintf(fs->dump_preload_file, \" @.preload2/%s%d\\n\",\n fs->dump_archive_name, fs->dump_archive_num);\n fflush(fs->dump_preload_file);\n fs->dump_archive_num++;\n }\n\n if (n->u.reg.size >= ARCHIVE_SIZE_MAX) {\n /* exclude large files from archive */\n /* add indicative size */\n fprintf(fs->dump_preload_file, \" %s %\" PRId64 \"\\n\",\n fname, n->u.reg.size);\n fflush(fs->dump_preload_file);\n } else {\n fprintf(fs->dump_preload_archive_file, \" %s %\" PRId64 \" %\" PRIx64 \"\\n\",\n n->u.reg.filename, n->u.reg.size, n->u.reg.file_id);\n fflush(fs->dump_preload_archive_file);\n fwrite(n->u.reg.fbuf.data, 1, n->u.reg.size, fs->dump_archive_file);\n fflush(fs->dump_archive_file);\n fs->dump_archive_size += n->u.reg.size;\n if (fs->dump_archive_size >= ARCHIVE_SIZE_MAX) {\n dump_close_archive(fs1);\n }\n }\n}\n\nstatic JSONValue json_load(const char *filename)\n{\n FILE *f;\n JSONValue val;\n size_t size;\n char *buf;\n \n f = fopen(filename, \"rb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n size = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = malloc(size + 1);\n fread(buf, 1, size, f);\n fclose(f);\n val = json_parse_value_len(buf, size);\n free(buf);\n return val;\n}\n\nvoid fs_dump_cache_load(FSDevice *fs1, const char *cfg_filename)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n JSONValue cfg, val, array;\n char *fname;\n const char *preload_dir, *name;\n int i;\n \n if (!fs_is_net(fs1))\n return;\n cfg = json_load(cfg_filename);\n if (json_is_error(cfg)) {\n fprintf(stderr, \"%s\\n\", json_get_error(cfg));\n exit(1);\n }\n\n val = json_object_get(cfg, \"preload_dir\");\n if (json_is_undefined(cfg)) {\n config_error:\n exit(1);\n }\n preload_dir = json_get_str(val);\n if (!preload_dir) {\n fprintf(stderr, \"expecting preload_filename\\n\");\n goto config_error;\n }\n fs->dump_preload_dir = strdup(preload_dir);\n \n init_list_head(&fs->dump_preload_list);\n init_list_head(&fs->dump_exclude_list);\n\n array = json_object_get(cfg, \"preload\");\n if (array.type != JSON_ARRAY) {\n fprintf(stderr, \"expecting preload array\\n\");\n goto config_error;\n }\n for(i = 0; i < array.u.array->len; i++) {\n val = json_array_get(array, i);\n name = json_get_str(val);\n if (!name) {\n fprintf(stderr, \"expecting a string\\n\");\n goto config_error;\n }\n fs_dump_add_file(&fs->dump_preload_list, name);\n }\n json_free(cfg);\n\n fname = compose_path(fs->dump_preload_dir, \"preload.txt\");\n fs->dump_preload_file = fopen(fname, \"w\");\n if (!fs->dump_preload_file) {\n perror(fname);\n exit(1);\n }\n free(fname);\n\n fname = compose_path(fs->dump_preload_dir, \"preload_archive.txt\");\n fs->dump_preload_archive_file = fopen(fname, \"w\");\n if (!fs->dump_preload_archive_file) {\n perror(fname);\n exit(1);\n }\n free(fname);\n\n fs->dump_cache_load = TRUE;\n}\n#else\nvoid fs_dump_cache_load(FSDevice *fs1, const char *cfg_filename)\n{\n}\n#endif\n\n/***********************************************/\n/* file list processing */\n\nstatic int filelist_load_rec(FSDevice *fs1, const char **pp, FSINode *dir,\n const char *path)\n{\n // FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char fname[1024], lname[1024];\n int ret;\n const char *p;\n FSINodeTypeEnum type;\n uint32_t mode, uid, gid;\n uint64_t size;\n FSINode *n;\n\n p = *pp;\n for(;;) {\n /* skip comments or empty lines */\n if (*p == '\\0')\n break;\n if (*p == '#') {\n skip_line(&p);\n continue;\n }\n /* end of directory */\n if (*p == '.') {\n p++;\n skip_line(&p);\n break;\n }\n if (parse_uint32_base(&mode, &p, 8) < 0) {\n fprintf(stderr, \"invalid mode\\n\");\n return -1;\n }\n type = mode >> 12;\n mode &= 0xfff;\n \n if (parse_uint32(&uid, &p) < 0) {\n fprintf(stderr, \"invalid uid\\n\");\n return -1;\n }\n\n if (parse_uint32(&gid, &p) < 0) {\n fprintf(stderr, \"invalid gid\\n\");\n return -1;\n }\n\n n = inode_new(fs1, type, mode, uid, gid);\n \n size = 0;\n switch(type) {\n case FT_CHR:\n case FT_BLK:\n if (parse_uint32(&n->u.dev.major, &p) < 0) {\n fprintf(stderr, \"invalid major\\n\");\n return -1;\n }\n if (parse_uint32(&n->u.dev.minor, &p) < 0) {\n fprintf(stderr, \"invalid minor\\n\");\n return -1;\n }\n break;\n case FT_REG:\n if (parse_uint64(&size, &p) < 0) {\n fprintf(stderr, \"invalid size\\n\");\n return -1;\n }\n break;\n case FT_DIR:\n inode_dir_add(fs1, n, \".\", inode_incref(fs1, n));\n inode_dir_add(fs1, n, \"..\", inode_incref(fs1, dir));\n break;\n default:\n break;\n }\n \n /* modification time */\n if (parse_time(&n->mtime_sec, &n->mtime_nsec, &p) < 0) {\n fprintf(stderr, \"invalid mtime\\n\");\n return -1;\n }\n\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return -1;\n }\n inode_dir_add(fs1, dir, fname, n);\n \n if (type == FT_LNK) {\n if (parse_fname(lname, sizeof(lname), &p) < 0) {\n fprintf(stderr, \"invalid symlink name\\n\");\n return -1;\n }\n n->u.symlink.name = strdup(lname);\n } else if (type == FT_REG && size > 0) {\n FSFileID file_id;\n if (parse_file_id(&file_id, &p) < 0) {\n fprintf(stderr, \"invalid file id\\n\");\n return -1;\n }\n fs_net_set_url(fs1, n, \"/\", file_id, size);\n#ifdef DUMP_CACHE_LOAD\n {\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (fs->dump_cache_load\n#ifdef DEBUG_CACHE\n || 1\n#endif\n ) {\n n->u.reg.filename = compose_path(path, fname);\n } else {\n n->u.reg.filename = NULL;\n }\n }\n#endif\n }\n\n skip_line(&p);\n \n if (type == FT_DIR) {\n char *path1;\n path1 = compose_path(path, fname);\n ret = filelist_load_rec(fs1, &p, n, path1);\n free(path1);\n if (ret)\n return ret;\n }\n }\n *pp = p;\n return 0;\n}\n\nstatic int filelist_load(FSDevice *fs1, const char *str)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int ret;\n const char *p;\n \n if (parse_tag_version(str) != 1)\n return -1;\n p = skip_header(str);\n if (!p)\n return -1;\n ret = filelist_load_rec(fs1, &p, fs->root_inode, \"\");\n return ret;\n}\n\n/************************************************************/\n/* FS init from network */\n\nstatic void __attribute__((format(printf, 1, 2))) fatal_error(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n fprintf(stderr, \"Error: \");\n vfprintf(stderr, fmt, ap);\n fprintf(stderr, \"\\n\");\n va_end(ap);\n exit(1);\n}\n\nstatic void fs_create_cmd(FSDevice *fs)\n{\n FSFile *root_fd;\n FSQID qid;\n FSINode *n;\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\"));\n assert(!fs->fs_create(fs, &qid, root_fd, FSCMD_NAME, P9_O_RDWR | P9_O_TRUNC,\n 0666, 0));\n n = root_fd->inode;\n n->u.reg.is_fscmd = TRUE;\n fs->fs_delete(fs, root_fd);\n}\n\ntypedef struct {\n FSDevice *fs;\n char *url;\n void (*start_cb)(void *opaque);\n void *start_opaque;\n \n FSFile *root_fd;\n FSFile *fd;\n int file_index;\n \n} FSNetInitState;\n\nstatic void fs_initial_sync(FSDevice *fs,\n const char *url, void (*start_cb)(void *opaque),\n void *start_opaque);\nstatic void head_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque);\nstatic void filelist_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque);\nstatic void kernel_load_cb(FSDevice *fs, FSQID *qid, int err,\n void *opaque);\nstatic int preload_parse(FSDevice *fs, const char *fname, BOOL is_new);\n\n#ifdef EMSCRIPTEN\nstatic FSDevice *fs_import_fs;\n#endif\n\n#define DEFAULT_IMPORT_FILE_PATH \"/tmp\"\n\nFSDevice *fs_net_init(const char *url, void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n FSDevice *fs;\n FSDeviceMem *fs1;\n \n fs_wget_init();\n \n fs = fs_mem_init();\n#ifdef EMSCRIPTEN\n if (!fs_import_fs)\n fs_import_fs = fs;\n#endif\n fs1 = (FSDeviceMem *)fs;\n fs1->import_dir = strdup(DEFAULT_IMPORT_FILE_PATH);\n \n fs_create_cmd(fs);\n\n if (url) {\n fs_initial_sync(fs, url, start_cb, start_opaque);\n }\n return fs;\n}\n\nstatic void fs_initial_sync(FSDevice *fs,\n const char *url, void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n FSNetInitState *s;\n FSFile *head_fd;\n FSQID qid;\n char *head_url;\n char buf[128];\n struct timeval tv;\n \n s = mallocz(sizeof(*s));\n s->fs = fs;\n s->url = strdup(url);\n s->start_cb = start_cb;\n s->start_opaque = start_opaque;\n assert(!fs->fs_attach(fs, &s->root_fd, &qid, 0, \"\", \"\"));\n \n /* avoid using cached version */\n gettimeofday(&tv, NULL);\n snprintf(buf, sizeof(buf), HEAD_FILENAME \"?nocache=%\" PRId64,\n (int64_t)tv.tv_sec * 1000000 + tv.tv_usec);\n head_url = compose_url(s->url, buf);\n head_fd = fs_dup(fs, s->root_fd);\n assert(!fs->fs_create(fs, &qid, head_fd, \".head\",\n P9_O_RDWR | P9_O_TRUNC, 0644, 0));\n fs_wget_file2(fs, head_fd, head_url, NULL, NULL, NULL, 0,\n head_loaded, s, NULL);\n free(head_url);\n}\n\nstatic void head_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque)\n{\n FSNetInitState *s = opaque;\n char *buf, *root_url, *url;\n char fname[FILEID_SIZE_MAX];\n FSFileID root_id;\n FSFile *new_filelist_fd;\n FSQID qid;\n uint64_t fs_max_size;\n \n if (size < 0)\n fatal_error(\"could not load 'head' file (HTTP error=%d)\", -(int)size);\n \n buf = malloc(size + 1);\n fs->fs_read(fs, f, 0, (uint8_t *)buf, size);\n buf[size] = '\\0';\n fs->fs_delete(fs, f);\n fs->fs_unlinkat(fs, s->root_fd, \".head\");\n\n if (parse_tag_version(buf) != 1)\n fatal_error(\"invalid head version\");\n\n if (parse_tag_file_id(&root_id, buf, \"RootID\") < 0)\n fatal_error(\"expected RootID tag\");\n\n if (parse_tag_uint64(&fs_max_size, buf, \"FSMaxSize\") == 0 &&\n fs_max_size >= ((uint64_t)1 << 20)) {\n fs_net_set_fs_max_size(fs, fs_max_size);\n }\n \n /* set the Root URL in the filesystem */\n root_url = compose_url(s->url, ROOT_FILENAME);\n fs_net_set_base_url(fs, \"/\", root_url, NULL, NULL, NULL);\n \n new_filelist_fd = fs_dup(fs, s->root_fd);\n assert(!fs->fs_create(fs, &qid, new_filelist_fd, \".filelist.txt\",\n P9_O_RDWR | P9_O_TRUNC, 0644, 0));\n\n file_id_to_filename(fname, root_id);\n url = compose_url(root_url, fname);\n fs_wget_file2(fs, new_filelist_fd, url, NULL, NULL, NULL, 0,\n filelist_loaded, s, NULL);\n free(root_url);\n free(url);\n}\n\nstatic void filelist_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque)\n{\n FSNetInitState *s = opaque;\n uint8_t *buf;\n\n if (size < 0)\n fatal_error(\"could not load file list (HTTP error=%d)\", -(int)size);\n \n buf = malloc(size + 1);\n fs->fs_read(fs, f, 0, buf, size);\n buf[size] = '\\0';\n fs->fs_delete(fs, f);\n fs->fs_unlinkat(fs, s->root_fd, \".filelist.txt\");\n \n if (filelist_load(fs, (char *)buf) != 0)\n fatal_error(\"error while parsing file list\");\n\n /* try to load the kernel and the preload file */\n s->file_index = 0;\n kernel_load_cb(fs, NULL, 0, s);\n}\n\n\n#define FILE_LOAD_COUNT 2\n\nstatic const char *kernel_file_list[FILE_LOAD_COUNT] = {\n \".preload\",\n \".preload2/preload.txt\",\n};\n\nstatic void kernel_load_cb(FSDevice *fs, FSQID *qid1, int err,\n void *opaque)\n{\n FSNetInitState *s = opaque;\n FSQID qid;\n\n#ifdef DUMP_CACHE_LOAD\n /* disable preloading if dumping cache load */\n if (((FSDeviceMem *)fs)->dump_cache_load)\n return;\n#endif\n\n if (s->fd) {\n fs->fs_delete(fs, s->fd);\n s->fd = NULL;\n }\n \n if (s->file_index >= FILE_LOAD_COUNT) {\n /* all files are loaded */\n if (preload_parse(fs, \".preload2/preload.txt\", TRUE) < 0) { \n preload_parse(fs, \".preload\", FALSE);\n }\n fs->fs_delete(fs, s->root_fd);\n if (s->start_cb)\n s->start_cb(s->start_opaque);\n free(s);\n } else {\n s->fd = fs_walk_path(fs, s->root_fd, kernel_file_list[s->file_index++]);\n if (!s->fd)\n goto done;\n err = fs->fs_open(fs, &qid, s->fd, P9_O_RDONLY, kernel_load_cb, s);\n if (err <= 0) {\n done:\n kernel_load_cb(fs, NULL, 0, s);\n }\n }\n}\n\nstatic void preload_parse_str_old(FSDevice *fs1, const char *p)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char fname[1024];\n PreloadEntry *pe;\n PreloadFile *pf;\n FSINode *n;\n\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\n') {\n p++;\n continue;\n }\n if (*p == '\\0')\n break;\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n // printf(\"preload file='%s\\n\", fname);\n n = inode_search_path(fs1, fname);\n if (!n || n->type != FT_REG || n->u.reg.state == REG_STATE_LOCAL) {\n fprintf(stderr, \"invalid preload file: '%s'\\n\", fname);\n while (*p != '\\n' && *p != '\\0')\n p++;\n } else {\n pe = mallocz(sizeof(*pe));\n pe->file_id = n->u.reg.file_id;\n init_list_head(&pe->file_list);\n list_add_tail(&pe->link, &fs->preload_list);\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\0' || *p == '\\n')\n break;\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n // printf(\" adding '%s'\\n\", fname);\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(fname);\n list_add_tail(&pf->link, &pe->file_list); \n }\n }\n }\n}\n\nstatic void preload_parse_str(FSDevice *fs1, const char *p)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n PreloadEntry *pe;\n PreloadArchive *pa;\n FSINode *n;\n BOOL is_archive;\n char fname[1024];\n \n pe = NULL;\n pa = NULL;\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\n') {\n pe = NULL;\n p++;\n continue;\n }\n if (*p == '#')\n continue; /* comment */\n if (*p == '\\0')\n break;\n\n is_archive = FALSE;\n if (*p == '@') {\n is_archive = TRUE;\n p++;\n }\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n while (isspace_nolf(*p))\n p++;\n if (*p == ':') {\n p++;\n // printf(\"preload file='%s' archive=%d\\n\", fname, is_archive);\n n = inode_search_path(fs1, fname);\n pe = NULL;\n pa = NULL;\n if (!n || n->type != FT_REG || n->u.reg.state == REG_STATE_LOCAL) {\n fprintf(stderr, \"invalid preload file: '%s'\\n\", fname);\n while (*p != '\\n' && *p != '\\0')\n p++;\n } else if (is_archive) {\n pa = mallocz(sizeof(*pa));\n pa->name = strdup(fname);\n init_list_head(&pa->file_list);\n list_add_tail(&pa->link, &fs->preload_archive_list);\n } else {\n pe = mallocz(sizeof(*pe));\n pe->file_id = n->u.reg.file_id;\n init_list_head(&pe->file_list);\n list_add_tail(&pe->link, &fs->preload_list);\n }\n } else {\n if (!pe && !pa) {\n fprintf(stderr, \"filename without target: %s\\n\", fname);\n return;\n }\n if (pa) {\n PreloadArchiveFile *paf;\n FSFileID file_id;\n uint64_t size;\n\n if (parse_uint64(&size, &p) < 0) {\n fprintf(stderr, \"invalid size\\n\");\n return;\n }\n\n if (parse_file_id(&file_id, &p) < 0) {\n fprintf(stderr, \"invalid file id\\n\");\n return;\n }\n\n paf = mallocz(sizeof(*paf));\n paf->name = strdup(fname);\n paf->file_id = file_id;\n paf->size = size;\n list_add_tail(&paf->link, &pa->file_list);\n } else {\n PreloadFile *pf;\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(fname);\n pf->is_archive = is_archive;\n list_add_tail(&pf->link, &pe->file_list);\n }\n }\n /* skip the rest of the line */\n while (*p != '\\n' && *p != '\\0')\n p++;\n if (*p == '\\n')\n p++;\n }\n}\n\nstatic int preload_parse(FSDevice *fs, const char *fname, BOOL is_new)\n{\n FSINode *n;\n char *buf;\n size_t size;\n \n n = inode_search_path(fs, fname);\n if (!n || n->type != FT_REG || n->u.reg.state != REG_STATE_LOADED)\n return -1;\n /* transform to zero terminated string */\n size = n->u.reg.size;\n buf = malloc(size + 1);\n file_buffer_read(&n->u.reg.fbuf, 0, (uint8_t *)buf, size);\n buf[size] = '\\0';\n if (is_new)\n preload_parse_str(fs, buf);\n else\n preload_parse_str_old(fs, buf);\n free(buf);\n return 0;\n}\n\n\n\n/************************************************************/\n/* FS user interface */\n\ntypedef struct CmdXHRState {\n FSFile *req_fd;\n FSFile *root_fd;\n FSFile *fd;\n FSFile *post_fd;\n AES_KEY aes_state;\n} CmdXHRState;\n\nstatic void fs_cmd_xhr_on_load(FSDevice *fs, FSFile *f, int64_t size,\n void *opaque);\n\nstatic int parse_hex_buf(uint8_t *buf, int buf_size, const char **pp)\n{\n char buf1[1024];\n int len;\n \n if (parse_fname(buf1, sizeof(buf1), pp) < 0)\n return -1;\n len = strlen(buf1);\n if ((len & 1) != 0)\n return -1;\n len >>= 1;\n if (len > buf_size)\n return -1;\n if (decode_hex(buf, buf1, len) < 0)\n return -1;\n return len;\n}\n\nstatic int fs_cmd_xhr(FSDevice *fs, FSFile *f,\n const char *p, uint32_t uid, uint32_t gid)\n{\n char url[1024], post_filename[1024], filename[1024];\n char user_buf[128], *user;\n char password_buf[128], *password;\n FSQID qid;\n FSFile *fd, *root_fd, *post_fd;\n uint64_t post_data_len;\n int err, aes_key_len;\n CmdXHRState *s;\n char *name;\n AES_KEY *paes_state;\n uint8_t aes_key[FS_KEY_LEN];\n uint32_t flags;\n FSCMDRequest *req;\n\n /* a request is already done or in progress */\n if (f->req != NULL)\n return -P9_EIO;\n\n if (parse_fname(url, sizeof(url), &p) < 0)\n goto fail;\n if (parse_fname(user_buf, sizeof(user_buf), &p) < 0)\n goto fail;\n if (parse_fname(password_buf, sizeof(password_buf), &p) < 0)\n goto fail;\n if (parse_fname(post_filename, sizeof(post_filename), &p) < 0)\n goto fail;\n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n aes_key_len = parse_hex_buf(aes_key, FS_KEY_LEN, &p);\n if (aes_key_len < 0)\n goto fail;\n if (parse_uint32(&flags, &p) < 0)\n goto fail;\n if (aes_key_len != 0 && aes_key_len != FS_KEY_LEN)\n goto fail;\n\n if (user_buf[0] != '\\0')\n user = user_buf;\n else\n user = NULL;\n if (password_buf[0] != '\\0')\n password = password_buf;\n else\n password = NULL;\n\n // printf(\"url='%s' '%s' '%s' filename='%s'\\n\", url, user, password, filename);\n assert(!fs->fs_attach(fs, &root_fd, &qid, uid, \"\", \"\"));\n post_fd = NULL;\n\n fd = fs_walk_path1(fs, root_fd, filename, &name);\n if (!fd) {\n err = -P9_ENOENT;\n goto fail1;\n }\n /* XXX: until fs_create is fixed */\n fs->fs_unlinkat(fs, fd, name);\n\n err = fs->fs_create(fs, &qid, fd, name,\n P9_O_RDWR | P9_O_TRUNC, 0600, gid);\n if (err < 0) {\n goto fail1;\n }\n\n if (post_filename[0] != '\\0') {\n FSINode *n;\n \n post_fd = fs_walk_path(fs, root_fd, post_filename);\n if (!post_fd) {\n err = -P9_ENOENT;\n goto fail1;\n }\n err = fs->fs_open(fs, &qid, post_fd, P9_O_RDONLY, NULL, NULL);\n if (err < 0)\n goto fail1;\n n = post_fd->inode;\n assert(n->type == FT_REG && n->u.reg.state == REG_STATE_LOCAL);\n post_data_len = n->u.reg.size;\n } else {\n post_data_len = 0;\n }\n\n s = mallocz(sizeof(*s));\n s->root_fd = root_fd;\n s->fd = fd;\n s->post_fd = post_fd;\n if (aes_key_len != 0) {\n AES_set_decrypt_key(aes_key, FS_KEY_LEN * 8, &s->aes_state);\n paes_state = &s->aes_state;\n } else {\n paes_state = NULL;\n }\n\n req = mallocz(sizeof(*req));\n req->type = FS_CMD_XHR;\n req->reply_len = 0;\n req->xhr_state = s;\n s->req_fd = f;\n f->req = req;\n \n fs_wget_file2(fs, fd, url, user, password, post_fd, post_data_len,\n fs_cmd_xhr_on_load, s, paes_state);\n return 0;\n fail1:\n if (fd)\n fs->fs_delete(fs, fd);\n if (post_fd)\n fs->fs_delete(fs, post_fd);\n fs->fs_delete(fs, root_fd);\n return err;\n fail:\n return -P9_EIO;\n}\n\nstatic void fs_cmd_xhr_on_load(FSDevice *fs, FSFile *f, int64_t size,\n void *opaque)\n{\n CmdXHRState *s = opaque;\n FSCMDRequest *req;\n int ret;\n \n // printf(\"fs_cmd_xhr_on_load: size=%d\\n\", (int)size);\n\n if (s->fd)\n fs->fs_delete(fs, s->fd);\n if (s->post_fd)\n fs->fs_delete(fs, s->post_fd);\n fs->fs_delete(fs, s->root_fd);\n \n if (s->req_fd) {\n req = s->req_fd->req;\n if (size < 0) {\n ret = size;\n } else {\n ret = 0;\n }\n put_le32(req->reply_buf, ret);\n req->reply_len = sizeof(ret);\n req->xhr_state = NULL;\n }\n free(s);\n}\n\nstatic int fs_cmd_set_base_url(FSDevice *fs, const char *p)\n{\n // FSDeviceMem *fs1 = (FSDeviceMem *)fs;\n char url[1024], base_url_id[1024];\n char user_buf[128], *user;\n char password_buf[128], *password;\n AES_KEY aes_state, *paes_state;\n uint8_t aes_key[FS_KEY_LEN];\n int aes_key_len;\n \n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n if (parse_fname(url, sizeof(url), &p) < 0)\n goto fail;\n if (parse_fname(user_buf, sizeof(user_buf), &p) < 0)\n goto fail;\n if (parse_fname(password_buf, sizeof(password_buf), &p) < 0)\n goto fail;\n aes_key_len = parse_hex_buf(aes_key, FS_KEY_LEN, &p);\n if (aes_key_len < 0)\n goto fail;\n\n if (user_buf[0] != '\\0')\n user = user_buf;\n else\n user = NULL;\n if (password_buf[0] != '\\0')\n password = password_buf;\n else\n password = NULL;\n\n if (aes_key_len != 0) {\n if (aes_key_len != FS_KEY_LEN)\n goto fail;\n AES_set_decrypt_key(aes_key, FS_KEY_LEN * 8, &aes_state);\n paes_state = &aes_state;\n } else {\n paes_state = NULL;\n }\n\n fs_net_set_base_url(fs, base_url_id, url, user, password,\n paes_state);\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_reset_base_url(FSDevice *fs, const char *p)\n{\n char base_url_id[1024];\n \n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n fs_net_reset_base_url(fs, base_url_id);\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_set_url(FSDevice *fs, const char *p)\n{\n char base_url_id[1024];\n char filename[1024];\n FSFileID file_id;\n uint64_t size;\n FSINode *n;\n \n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n if (parse_file_id(&file_id, &p) < 0)\n goto fail;\n if (parse_uint64(&size, &p) < 0)\n goto fail;\n \n n = inode_search_path(fs, filename);\n if (!n) {\n return -P9_ENOENT;\n }\n return fs_net_set_url(fs, n, base_url_id, file_id, size);\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_export_file(FSDevice *fs, const char *p)\n{\n char filename[1024];\n FSINode *n;\n const char *name;\n uint8_t *buf;\n \n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n n = inode_search_path(fs, filename);\n if (!n)\n return -P9_ENOENT;\n if (n->type != FT_REG ||\n (n->u.reg.state != REG_STATE_LOCAL &&\n n->u.reg.state != REG_STATE_LOADED))\n goto fail;\n name = strrchr(filename, '/');\n if (name)\n name++;\n else\n name = filename;\n /* XXX: pass the buffer to JS to avoid the allocation */\n buf = malloc(n->u.reg.size);\n file_buffer_read(&n->u.reg.fbuf, 0, buf, n->u.reg.size);\n fs_export_file(name, buf, n->u.reg.size);\n free(buf);\n return 0;\n fail:\n return -P9_EIO;\n}\n\n/* PBKDF2 crypto acceleration */\nstatic int fs_cmd_pbkdf2(FSDevice *fs, FSFile *f, const char *p)\n{\n uint8_t pwd[1024];\n uint8_t salt[128];\n uint32_t iter, key_len;\n int pwd_len, salt_len;\n FSCMDRequest *req;\n \n /* a request is already done or in progress */\n if (f->req != NULL)\n return -P9_EIO;\n\n pwd_len = parse_hex_buf(pwd, sizeof(pwd), &p);\n if (pwd_len < 0)\n goto fail;\n salt_len = parse_hex_buf(salt, sizeof(salt), &p);\n if (pwd_len < 0)\n goto fail;\n if (parse_uint32(&iter, &p) < 0)\n goto fail;\n if (parse_uint32(&key_len, &p) < 0)\n goto fail;\n if (key_len > FS_CMD_REPLY_LEN_MAX ||\n key_len == 0)\n goto fail;\n req = mallocz(sizeof(*req));\n req->type = FS_CMD_PBKDF2;\n req->reply_len = key_len;\n pbkdf2_hmac_sha256(pwd, pwd_len, salt, salt_len, iter, key_len,\n req->reply_buf);\n f->req = req;\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_set_import_dir(FSDevice *fs, FSFile *f, const char *p)\n{\n FSDeviceMem *fs1 = (FSDeviceMem *)fs;\n char filename[1024];\n\n if (parse_fname(filename, sizeof(filename), &p) < 0)\n return -P9_EINVAL;\n free(fs1->import_dir);\n fs1->import_dir = strdup(filename);\n return 0;\n}\n\nstatic int fs_cmd_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int buf_len)\n{\n char *buf1;\n const char *p;\n char cmd[64];\n int err;\n \n /* transform into a string */\n buf1 = malloc(buf_len + 1);\n memcpy(buf1, buf, buf_len);\n buf1[buf_len] = '\\0';\n \n err = 0;\n p = buf1;\n if (parse_fname(cmd, sizeof(cmd), &p) < 0)\n goto fail;\n if (!strcmp(cmd, \"xhr\")) {\n err = fs_cmd_xhr(fs, f, p, f->uid, 0);\n } else if (!strcmp(cmd, \"set_base_url\")) {\n err = fs_cmd_set_base_url(fs, p);\n } else if (!strcmp(cmd, \"reset_base_url\")) {\n err = fs_cmd_reset_base_url(fs, p);\n } else if (!strcmp(cmd, \"set_url\")) {\n err = fs_cmd_set_url(fs, p);\n } else if (!strcmp(cmd, \"export_file\")) {\n err = fs_cmd_export_file(fs, p);\n } else if (!strcmp(cmd, \"pbkdf2\")) {\n err = fs_cmd_pbkdf2(fs, f, p);\n } else if (!strcmp(cmd, \"set_import_dir\")) {\n err = fs_cmd_set_import_dir(fs, f, p);\n } else {\n printf(\"unknown command: '%s'\\n\", cmd);\n fail:\n err = -P9_EIO;\n }\n free(buf1);\n if (err == 0)\n return buf_len;\n else\n return err;\n}\n\nstatic int fs_cmd_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int buf_len)\n{\n FSCMDRequest *req;\n int l;\n \n req = f->req;\n if (!req)\n return -P9_EIO;\n l = min_int(req->reply_len, buf_len);\n memcpy(buf, req->reply_buf, l);\n return l;\n}\n\nstatic void fs_cmd_close(FSDevice *fs, FSFile *f)\n{\n FSCMDRequest *req;\n req = f->req;\n\n if (req) {\n if (req->xhr_state) {\n req->xhr_state->req_fd = NULL;\n }\n free(req);\n f->req = NULL;\n }\n}\n\n/* Create a .fscmd_pwd file to avoid passing the password thru the\n Linux command line */\nvoid fs_net_set_pwd(FSDevice *fs, const char *pwd)\n{\n FSFile *root_fd;\n FSQID qid;\n \n assert(fs_is_net(fs));\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\"));\n assert(!fs->fs_create(fs, &qid, root_fd, \".fscmd_pwd\", P9_O_RDWR | P9_O_TRUNC,\n 0600, 0));\n fs->fs_write(fs, root_fd, 0, (uint8_t *)pwd, strlen(pwd));\n fs->fs_delete(fs, root_fd);\n}\n\n/* external file import */\n\n#ifdef EMSCRIPTEN\n\nvoid fs_import_file(const char *filename, uint8_t *buf, int buf_len)\n{\n FSDevice *fs;\n FSDeviceMem *fs1;\n FSFile *fd, *root_fd;\n FSQID qid;\n \n // printf(\"importing file: %s len=%d\\n\", filename, buf_len);\n fs = fs_import_fs;\n if (!fs) {\n free(buf);\n return;\n }\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 1000, \"\", \"\"));\n fs1 = (FSDeviceMem *)fs;\n fd = fs_walk_path(fs, root_fd, fs1->import_dir);\n if (!fd)\n goto fail;\n fs_unlinkat(fs, root_fd, filename);\n if (fs->fs_create(fs, &qid, fd, filename, P9_O_RDWR | P9_O_TRUNC,\n 0600, 0) < 0)\n goto fail;\n fs->fs_write(fs, fd, 0, buf, buf_len);\n fail:\n if (fd)\n fs->fs_delete(fs, fd);\n if (root_fd)\n fs->fs_delete(fs, root_fd);\n free(buf);\n}\n\n#else\n\nvoid fs_export_file(const char *filename,\n const uint8_t *buf, int buf_len)\n{\n}\n\n#endif\n"], ["/linuxpdf/tinyemu/x86_cpu.c", "/*\n * x86 CPU emulator stub\n * \n * Copyright (c) 2011-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"x86_cpu.h\"\n\nX86CPUState *x86_cpu_init(PhysMemoryMap *mem_map)\n{\n fprintf(stderr, \"x86 emulator is not supported\\n\");\n exit(1);\n}\n\nvoid x86_cpu_end(X86CPUState *s)\n{\n}\n\nvoid x86_cpu_interp(X86CPUState *s, int max_cycles1)\n{\n}\n\nvoid x86_cpu_set_irq(X86CPUState *s, BOOL set)\n{\n}\n\nvoid x86_cpu_set_reg(X86CPUState *s, int reg, uint32_t val)\n{\n}\n\nuint32_t x86_cpu_get_reg(X86CPUState *s, int reg)\n{\n return 0;\n}\n\nvoid x86_cpu_set_seg(X86CPUState *s, int seg, const X86CPUSeg *sd)\n{\n}\n\nvoid x86_cpu_set_get_hard_intno(X86CPUState *s,\n int (*get_hard_intno)(void *opaque),\n void *opaque)\n{\n}\n\nvoid x86_cpu_set_get_tsc(X86CPUState *s,\n uint64_t (*get_tsc)(void *opaque),\n void *opaque)\n{\n}\n\nvoid x86_cpu_set_port_io(X86CPUState *s, \n DeviceReadFunc *port_read, DeviceWriteFunc *port_write,\n void *opaque)\n{\n}\n\nint64_t x86_cpu_get_cycles(X86CPUState *s)\n{\n return 0;\n}\n\nBOOL x86_cpu_get_power_down(X86CPUState *s)\n{\n return FALSE;\n}\n\nvoid x86_cpu_flush_tlb_write_range_ram(X86CPUState *s,\n uint8_t *ram_ptr, size_t ram_size)\n{\n}\n"], ["/linuxpdf/tinyemu/pckbd.c", "/*\n * QEMU PC keyboard emulation\n *\n * Copyright (c) 2003 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n/* debug PC keyboard */\n//#define DEBUG_KBD\n\n/* debug PC keyboard : only mouse */\n//#define DEBUG_MOUSE\n\n/*\tKeyboard Controller Commands */\n#define KBD_CCMD_READ_MODE\t0x20\t/* Read mode bits */\n#define KBD_CCMD_WRITE_MODE\t0x60\t/* Write mode bits */\n#define KBD_CCMD_GET_VERSION\t0xA1\t/* Get controller version */\n#define KBD_CCMD_MOUSE_DISABLE\t0xA7\t/* Disable mouse interface */\n#define KBD_CCMD_MOUSE_ENABLE\t0xA8\t/* Enable mouse interface */\n#define KBD_CCMD_TEST_MOUSE\t0xA9\t/* Mouse interface test */\n#define KBD_CCMD_SELF_TEST\t0xAA\t/* Controller self test */\n#define KBD_CCMD_KBD_TEST\t0xAB\t/* Keyboard interface test */\n#define KBD_CCMD_KBD_DISABLE\t0xAD\t/* Keyboard interface disable */\n#define KBD_CCMD_KBD_ENABLE\t0xAE\t/* Keyboard interface enable */\n#define KBD_CCMD_READ_INPORT 0xC0 /* read input port */\n#define KBD_CCMD_READ_OUTPORT\t0xD0 /* read output port */\n#define KBD_CCMD_WRITE_OUTPORT\t0xD1 /* write output port */\n#define KBD_CCMD_WRITE_OBUF\t0xD2\n#define KBD_CCMD_WRITE_AUX_OBUF\t0xD3 /* Write to output buffer as if\n\t\t\t\t\t initiated by the auxiliary device */\n#define KBD_CCMD_WRITE_MOUSE\t0xD4\t/* Write the following byte to the mouse */\n#define KBD_CCMD_DISABLE_A20 0xDD /* HP vectra only ? */\n#define KBD_CCMD_ENABLE_A20 0xDF /* HP vectra only ? */\n#define KBD_CCMD_RESET\t 0xFE\n\n/* Status Register Bits */\n#define KBD_STAT_OBF \t\t0x01\t/* Keyboard output buffer full */\n#define KBD_STAT_IBF \t\t0x02\t/* Keyboard input buffer full */\n#define KBD_STAT_SELFTEST\t0x04\t/* Self test successful */\n#define KBD_STAT_CMD\t\t0x08\t/* Last write was a command write (0=data) */\n#define KBD_STAT_UNLOCKED\t0x10\t/* Zero if keyboard locked */\n#define KBD_STAT_MOUSE_OBF\t0x20\t/* Mouse output buffer full */\n#define KBD_STAT_GTO \t\t0x40\t/* General receive/xmit timeout */\n#define KBD_STAT_PERR \t\t0x80\t/* Parity error */\n\n/* Controller Mode Register Bits */\n#define KBD_MODE_KBD_INT\t0x01\t/* Keyboard data generate IRQ1 */\n#define KBD_MODE_MOUSE_INT\t0x02\t/* Mouse data generate IRQ12 */\n#define KBD_MODE_SYS \t\t0x04\t/* The system flag (?) */\n#define KBD_MODE_NO_KEYLOCK\t0x08\t/* The keylock doesn't affect the keyboard if set */\n#define KBD_MODE_DISABLE_KBD\t0x10\t/* Disable keyboard interface */\n#define KBD_MODE_DISABLE_MOUSE\t0x20\t/* Disable mouse interface */\n#define KBD_MODE_KCC \t\t0x40\t/* Scan code conversion to PC format */\n#define KBD_MODE_RFU\t\t0x80\n\n#define KBD_PENDING_KBD 1\n#define KBD_PENDING_AUX 2\n\nstruct KBDState {\n uint8_t write_cmd; /* if non zero, write data to port 60 is expected */\n uint8_t status;\n uint8_t mode;\n /* Bitmask of devices with data available. */\n uint8_t pending;\n PS2KbdState *kbd;\n PS2MouseState *mouse;\n\n IRQSignal *irq_kbd;\n IRQSignal *irq_mouse;\n};\n\nstatic void qemu_system_reset_request(void)\n{\n printf(\"system_reset_request\\n\");\n exit(1);\n /* XXX */\n}\n\nstatic void ioport_set_a20(int val)\n{\n}\n\nstatic int ioport_get_a20(void)\n{\n return 1;\n}\n\n/* update irq and KBD_STAT_[MOUSE_]OBF */\n/* XXX: not generating the irqs if KBD_MODE_DISABLE_KBD is set may be\n incorrect, but it avoids having to simulate exact delays */\nstatic void kbd_update_irq(KBDState *s)\n{\n int irq_kbd_level, irq_mouse_level;\n\n irq_kbd_level = 0;\n irq_mouse_level = 0;\n s->status &= ~(KBD_STAT_OBF | KBD_STAT_MOUSE_OBF);\n if (s->pending) {\n s->status |= KBD_STAT_OBF;\n /* kbd data takes priority over aux data. */\n if (s->pending == KBD_PENDING_AUX) {\n s->status |= KBD_STAT_MOUSE_OBF;\n if (s->mode & KBD_MODE_MOUSE_INT)\n irq_mouse_level = 1;\n } else {\n if ((s->mode & KBD_MODE_KBD_INT) &&\n !(s->mode & KBD_MODE_DISABLE_KBD))\n irq_kbd_level = 1;\n }\n }\n set_irq(s->irq_kbd, irq_kbd_level);\n set_irq(s->irq_mouse, irq_mouse_level);\n}\n\nstatic void kbd_update_kbd_irq(void *opaque, int level)\n{\n KBDState *s = (KBDState *)opaque;\n\n if (level)\n s->pending |= KBD_PENDING_KBD;\n else\n s->pending &= ~KBD_PENDING_KBD;\n kbd_update_irq(s);\n}\n\nstatic void kbd_update_aux_irq(void *opaque, int level)\n{\n KBDState *s = (KBDState *)opaque;\n\n if (level)\n s->pending |= KBD_PENDING_AUX;\n else\n s->pending &= ~KBD_PENDING_AUX;\n kbd_update_irq(s);\n}\n\nstatic uint32_t kbd_read_status(void *opaque, uint32_t addr, int size_log2)\n{\n KBDState *s = opaque;\n int val;\n val = s->status;\n#if defined(DEBUG_KBD)\n printf(\"kbd: read status=0x%02x\\n\", val);\n#endif\n return val;\n}\n\nstatic void kbd_queue(KBDState *s, int b, int aux)\n{\n if (aux)\n ps2_queue(s->mouse, b);\n else\n ps2_queue(s->kbd, b);\n}\n\nstatic void kbd_write_command(void *opaque, uint32_t addr, uint32_t val,\n int size_log2)\n{\n KBDState *s = opaque;\n\n#if defined(DEBUG_KBD)\n printf(\"kbd: write cmd=0x%02x\\n\", val);\n#endif\n switch(val) {\n case KBD_CCMD_READ_MODE:\n kbd_queue(s, s->mode, 1);\n break;\n case KBD_CCMD_WRITE_MODE:\n case KBD_CCMD_WRITE_OBUF:\n case KBD_CCMD_WRITE_AUX_OBUF:\n case KBD_CCMD_WRITE_MOUSE:\n case KBD_CCMD_WRITE_OUTPORT:\n s->write_cmd = val;\n break;\n case KBD_CCMD_MOUSE_DISABLE:\n s->mode |= KBD_MODE_DISABLE_MOUSE;\n break;\n case KBD_CCMD_MOUSE_ENABLE:\n s->mode &= ~KBD_MODE_DISABLE_MOUSE;\n break;\n case KBD_CCMD_TEST_MOUSE:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_SELF_TEST:\n s->status |= KBD_STAT_SELFTEST;\n kbd_queue(s, 0x55, 0);\n break;\n case KBD_CCMD_KBD_TEST:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_KBD_DISABLE:\n s->mode |= KBD_MODE_DISABLE_KBD;\n kbd_update_irq(s);\n break;\n case KBD_CCMD_KBD_ENABLE:\n s->mode &= ~KBD_MODE_DISABLE_KBD;\n kbd_update_irq(s);\n break;\n case KBD_CCMD_READ_INPORT:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_READ_OUTPORT:\n /* XXX: check that */\n val = 0x01 | (ioport_get_a20() << 1);\n if (s->status & KBD_STAT_OBF)\n val |= 0x10;\n if (s->status & KBD_STAT_MOUSE_OBF)\n val |= 0x20;\n kbd_queue(s, val, 0);\n break;\n case KBD_CCMD_ENABLE_A20:\n ioport_set_a20(1);\n break;\n case KBD_CCMD_DISABLE_A20:\n ioport_set_a20(0);\n break;\n case KBD_CCMD_RESET:\n qemu_system_reset_request();\n break;\n case 0xff:\n /* ignore that - I don't know what is its use */\n break;\n default:\n fprintf(stderr, \"qemu: unsupported keyboard cmd=0x%02x\\n\", val);\n break;\n }\n}\n\nstatic uint32_t kbd_read_data(void *opaque, uint32_t addr, int size_log2)\n{\n KBDState *s = opaque;\n uint32_t val;\n if (s->pending == KBD_PENDING_AUX)\n val = ps2_read_data(s->mouse);\n else\n val = ps2_read_data(s->kbd);\n#ifdef DEBUG_KBD\n printf(\"kbd: read data=0x%02x\\n\", val);\n#endif\n return val;\n}\n\nstatic void kbd_write_data(void *opaque, uint32_t addr, uint32_t val, int size_log2)\n{\n KBDState *s = opaque;\n\n#ifdef DEBUG_KBD\n printf(\"kbd: write data=0x%02x\\n\", val);\n#endif\n\n switch(s->write_cmd) {\n case 0:\n ps2_write_keyboard(s->kbd, val);\n break;\n case KBD_CCMD_WRITE_MODE:\n s->mode = val;\n ps2_keyboard_set_translation(s->kbd, (s->mode & KBD_MODE_KCC) != 0);\n /* ??? */\n kbd_update_irq(s);\n break;\n case KBD_CCMD_WRITE_OBUF:\n kbd_queue(s, val, 0);\n break;\n case KBD_CCMD_WRITE_AUX_OBUF:\n kbd_queue(s, val, 1);\n break;\n case KBD_CCMD_WRITE_OUTPORT:\n ioport_set_a20((val >> 1) & 1);\n if (!(val & 1)) {\n qemu_system_reset_request();\n }\n break;\n case KBD_CCMD_WRITE_MOUSE:\n ps2_write_mouse(s->mouse, val);\n break;\n default:\n break;\n }\n s->write_cmd = 0;\n}\n\nstatic void kbd_reset(void *opaque)\n{\n KBDState *s = opaque;\n\n s->mode = KBD_MODE_KBD_INT | KBD_MODE_MOUSE_INT;\n s->status = KBD_STAT_CMD | KBD_STAT_UNLOCKED;\n}\n\nKBDState *i8042_init(PS2KbdState **pkbd,\n PS2MouseState **pmouse,\n PhysMemoryMap *port_map,\n IRQSignal *kbd_irq, IRQSignal *mouse_irq, uint32_t io_base)\n{\n KBDState *s;\n \n s = mallocz(sizeof(*s));\n \n s->irq_kbd = kbd_irq;\n s->irq_mouse = mouse_irq;\n\n kbd_reset(s);\n cpu_register_device(port_map, io_base, 1, s, kbd_read_data, kbd_write_data, \n DEVIO_SIZE8);\n cpu_register_device(port_map, io_base + 4, 1, s, kbd_read_status, kbd_write_command, \n DEVIO_SIZE8);\n\n s->kbd = ps2_kbd_init(kbd_update_kbd_irq, s);\n s->mouse = ps2_mouse_init(kbd_update_aux_irq, s);\n\n *pkbd = s->kbd;\n *pmouse = s->mouse;\n return s;\n}\n"], ["/linuxpdf/tinyemu/block_net.c", "/*\n * HTTP block device\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"virtio.h\"\n#include \"fs_wget.h\"\n#include \"list.h\"\n#include \"fbuf.h\"\n#include \"machine.h\"\n\ntypedef enum {\n CBLOCK_LOADING,\n CBLOCK_LOADED,\n} CachedBlockStateEnum;\n\ntypedef struct CachedBlock {\n struct list_head link;\n struct BlockDeviceHTTP *bf;\n unsigned int block_num;\n CachedBlockStateEnum state;\n FileBuffer fbuf;\n} CachedBlock;\n\n#define BLK_FMT \"%sblk%09u.bin\"\n#define GROUP_FMT \"%sgrp%09u.bin\"\n#define PREFETCH_GROUP_LEN_MAX 32\n\ntypedef struct {\n struct BlockDeviceHTTP *bf;\n int group_num;\n int n_block_num;\n CachedBlock *tab_block[PREFETCH_GROUP_LEN_MAX];\n} PrefetchGroupRequest;\n\n/* modified data is stored per cluster (smaller than cached blocks to\n avoid losing space) */\ntypedef struct Cluster {\n FileBuffer fbuf;\n} Cluster;\n\ntypedef struct BlockDeviceHTTP {\n BlockDevice *bs;\n int max_cache_size_kb;\n char url[1024];\n int prefetch_count;\n void (*start_cb)(void *opaque);\n void *start_opaque;\n \n int64_t nb_sectors;\n int block_size; /* in sectors, power of two */\n int nb_blocks;\n struct list_head cached_blocks; /* list of CachedBlock */\n int n_cached_blocks;\n int n_cached_blocks_max;\n\n /* write support */\n int sectors_per_cluster; /* power of two */\n Cluster **clusters; /* NULL if no written data */\n int n_clusters;\n int n_allocated_clusters;\n \n /* statistics */\n int64_t n_read_sectors;\n int64_t n_read_blocks;\n int64_t n_write_sectors;\n\n /* current read request */\n BOOL is_write;\n uint64_t sector_num;\n int cur_block_num;\n int sector_index, sector_count;\n BlockDeviceCompletionFunc *cb;\n void *opaque;\n uint8_t *io_buf;\n\n /* prefetch */\n int prefetch_group_len;\n} BlockDeviceHTTP;\n\nstatic void bf_update_block(CachedBlock *b, const uint8_t *data);\nstatic void bf_read_onload(void *opaque, int err, void *data, size_t size);\nstatic void bf_init_onload(void *opaque, int err, void *data, size_t size);\nstatic void bf_prefetch_group_onload(void *opaque, int err, void *data,\n size_t size);\n\nstatic CachedBlock *bf_find_block(BlockDeviceHTTP *bf, unsigned int block_num)\n{\n CachedBlock *b;\n struct list_head *el;\n \n list_for_each(el, &bf->cached_blocks) {\n b = list_entry(el, CachedBlock, link);\n if (b->block_num == block_num) {\n /* move to front */\n if (bf->cached_blocks.next != el) {\n list_del(&b->link);\n list_add(&b->link, &bf->cached_blocks);\n }\n return b;\n }\n }\n return NULL;\n}\n\nstatic void bf_free_block(BlockDeviceHTTP *bf, CachedBlock *b)\n{\n bf->n_cached_blocks--;\n file_buffer_reset(&b->fbuf);\n list_del(&b->link);\n free(b);\n}\n\nstatic CachedBlock *bf_add_block(BlockDeviceHTTP *bf, unsigned int block_num)\n{\n CachedBlock *b;\n if (bf->n_cached_blocks >= bf->n_cached_blocks_max) {\n struct list_head *el, *el1;\n /* start by looking at the least unused blocks */\n list_for_each_prev_safe(el, el1, &bf->cached_blocks) {\n b = list_entry(el, CachedBlock, link);\n if (b->state == CBLOCK_LOADED) {\n bf_free_block(bf, b);\n if (bf->n_cached_blocks < bf->n_cached_blocks_max)\n break;\n }\n }\n }\n b = mallocz(sizeof(CachedBlock));\n b->bf = bf;\n b->block_num = block_num;\n b->state = CBLOCK_LOADING;\n file_buffer_init(&b->fbuf);\n file_buffer_resize(&b->fbuf, bf->block_size * 512);\n list_add(&b->link, &bf->cached_blocks);\n bf->n_cached_blocks++;\n return b;\n}\n\nstatic int64_t bf_get_sector_count(BlockDevice *bs)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n return bf->nb_sectors;\n}\n\nstatic void bf_start_load_block(BlockDevice *bs, int block_num)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n char filename[1024];\n CachedBlock *b;\n b = bf_add_block(bf, block_num);\n bf->n_read_blocks++;\n /* make a XHR to read the block */\n#if 0\n printf(\"%u,\\n\", block_num);\n#endif\n#if 0\n printf(\"load_blk=%d cached=%d read=%d KB (%d KB) write=%d KB (%d KB)\\n\",\n block_num, bf->n_cached_blocks,\n (int)(bf->n_read_sectors / 2),\n (int)(bf->n_read_blocks * bf->block_size / 2),\n (int)(bf->n_write_sectors / 2),\n (int)(bf->n_allocated_clusters * bf->sectors_per_cluster / 2));\n#endif\n snprintf(filename, sizeof(filename), BLK_FMT, bf->url, block_num);\n // printf(\"wget %s\\n\", filename);\n fs_wget(filename, NULL, NULL, b, bf_read_onload, TRUE);\n}\n\nstatic void bf_start_load_prefetch_group(BlockDevice *bs, int group_num,\n const int *tab_block_num,\n int n_block_num)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n CachedBlock *b;\n PrefetchGroupRequest *req;\n char filename[1024];\n BOOL req_flag;\n int i;\n \n req_flag = FALSE;\n req = malloc(sizeof(*req));\n req->bf = bf;\n req->group_num = group_num;\n req->n_block_num = n_block_num;\n for(i = 0; i < n_block_num; i++) {\n b = bf_find_block(bf, tab_block_num[i]);\n if (!b) {\n b = bf_add_block(bf, tab_block_num[i]);\n req_flag = TRUE;\n } else {\n /* no need to read the block if it is already loading or\n loaded */\n b = NULL;\n }\n req->tab_block[i] = b;\n }\n\n if (req_flag) {\n snprintf(filename, sizeof(filename), GROUP_FMT, bf->url, group_num);\n // printf(\"wget %s\\n\", filename);\n fs_wget(filename, NULL, NULL, req, bf_prefetch_group_onload, TRUE);\n /* XXX: should add request in a list to free it for clean exit */\n } else {\n free(req);\n }\n}\n\nstatic void bf_prefetch_group_onload(void *opaque, int err, void *data,\n size_t size)\n{\n PrefetchGroupRequest *req = opaque;\n BlockDeviceHTTP *bf = req->bf;\n CachedBlock *b;\n int block_bytes, i;\n \n if (err < 0) {\n fprintf(stderr, \"Could not load group %u\\n\", req->group_num);\n exit(1);\n }\n block_bytes = bf->block_size * 512;\n assert(size == block_bytes * req->n_block_num);\n for(i = 0; i < req->n_block_num; i++) {\n b = req->tab_block[i];\n if (b) {\n bf_update_block(b, (const uint8_t *)data + block_bytes * i);\n }\n }\n free(req);\n}\n\nstatic int bf_rw_async1(BlockDevice *bs, BOOL is_sync)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n int offset, block_num, n, cluster_num;\n CachedBlock *b;\n Cluster *c;\n \n for(;;) {\n n = bf->sector_count - bf->sector_index;\n if (n == 0)\n break;\n cluster_num = bf->sector_num / bf->sectors_per_cluster;\n c = bf->clusters[cluster_num];\n if (c) {\n offset = bf->sector_num % bf->sectors_per_cluster;\n n = min_int(n, bf->sectors_per_cluster - offset);\n if (bf->is_write) {\n file_buffer_write(&c->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n } else {\n file_buffer_read(&c->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n }\n bf->sector_index += n;\n bf->sector_num += n;\n } else {\n block_num = bf->sector_num / bf->block_size;\n offset = bf->sector_num % bf->block_size;\n n = min_int(n, bf->block_size - offset);\n bf->cur_block_num = block_num;\n \n b = bf_find_block(bf, block_num);\n if (b) {\n if (b->state == CBLOCK_LOADING) {\n /* wait until the block is loaded */\n return 1;\n } else {\n if (bf->is_write) {\n int cluster_size, cluster_offset;\n uint8_t *buf;\n /* allocate a new cluster */\n c = mallocz(sizeof(Cluster));\n cluster_size = bf->sectors_per_cluster * 512;\n buf = malloc(cluster_size);\n file_buffer_init(&c->fbuf);\n file_buffer_resize(&c->fbuf, cluster_size);\n bf->clusters[cluster_num] = c;\n /* copy the cached block data to the cluster */\n cluster_offset = (cluster_num * bf->sectors_per_cluster) &\n (bf->block_size - 1);\n file_buffer_read(&b->fbuf, cluster_offset * 512,\n buf, cluster_size);\n file_buffer_write(&c->fbuf, 0, buf, cluster_size);\n free(buf);\n bf->n_allocated_clusters++;\n continue; /* write to the allocated cluster */\n } else {\n file_buffer_read(&b->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n }\n bf->sector_index += n;\n bf->sector_num += n;\n }\n } else {\n bf_start_load_block(bs, block_num);\n return 1;\n }\n bf->cur_block_num = -1;\n }\n }\n\n if (!is_sync) {\n // printf(\"end of request\\n\");\n /* end of request */\n bf->cb(bf->opaque, 0);\n } \n return 0;\n}\n\nstatic void bf_update_block(CachedBlock *b, const uint8_t *data)\n{\n BlockDeviceHTTP *bf = b->bf;\n BlockDevice *bs = bf->bs;\n\n assert(b->state == CBLOCK_LOADING);\n file_buffer_write(&b->fbuf, 0, data, bf->block_size * 512);\n b->state = CBLOCK_LOADED;\n \n /* continue I/O read/write if necessary */\n if (b->block_num == bf->cur_block_num) {\n bf_rw_async1(bs, FALSE);\n }\n}\n\nstatic void bf_read_onload(void *opaque, int err, void *data, size_t size)\n{\n CachedBlock *b = opaque;\n BlockDeviceHTTP *bf = b->bf;\n\n if (err < 0) {\n fprintf(stderr, \"Could not load block %u\\n\", b->block_num);\n exit(1);\n }\n \n assert(size == bf->block_size * 512);\n bf_update_block(b, data);\n}\n\nstatic int bf_read_async(BlockDevice *bs,\n uint64_t sector_num, uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n // printf(\"bf_read_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n bf->is_write = FALSE;\n bf->sector_num = sector_num;\n bf->io_buf = buf;\n bf->sector_count = n;\n bf->sector_index = 0;\n bf->cb = cb;\n bf->opaque = opaque;\n bf->n_read_sectors += n;\n return bf_rw_async1(bs, TRUE);\n}\n\nstatic int bf_write_async(BlockDevice *bs,\n uint64_t sector_num, const uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n // printf(\"bf_write_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n bf->is_write = TRUE;\n bf->sector_num = sector_num;\n bf->io_buf = (uint8_t *)buf;\n bf->sector_count = n;\n bf->sector_index = 0;\n bf->cb = cb;\n bf->opaque = opaque;\n bf->n_write_sectors += n;\n return bf_rw_async1(bs, TRUE);\n}\n\nBlockDevice *block_device_init_http(const char *url,\n int max_cache_size_kb,\n void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n BlockDevice *bs;\n BlockDeviceHTTP *bf;\n char *p;\n\n bs = mallocz(sizeof(*bs));\n bf = mallocz(sizeof(*bf));\n strcpy(bf->url, url);\n /* get the path with the trailing '/' */\n p = strrchr(bf->url, '/');\n if (!p)\n p = bf->url;\n else\n p++;\n *p = '\\0';\n\n init_list_head(&bf->cached_blocks);\n bf->max_cache_size_kb = max_cache_size_kb;\n bf->start_cb = start_cb;\n bf->start_opaque = start_opaque;\n bf->bs = bs;\n \n bs->opaque = bf;\n bs->get_sector_count = bf_get_sector_count;\n bs->read_async = bf_read_async;\n bs->write_async = bf_write_async;\n \n fs_wget(url, NULL, NULL, bs, bf_init_onload, TRUE);\n return bs;\n}\n\nstatic void bf_init_onload(void *opaque, int err, void *data, size_t size)\n{\n BlockDevice *bs = opaque;\n BlockDeviceHTTP *bf = bs->opaque;\n int block_size_kb, block_num;\n JSONValue cfg, array;\n \n if (err < 0) {\n fprintf(stderr, \"Could not load block device file (err=%d)\\n\", -err);\n exit(1);\n }\n\n /* parse the disk image info */\n cfg = json_parse_value_len(data, size);\n if (json_is_error(cfg)) {\n vm_error(\"error: %s\\n\", json_get_error(cfg));\n config_error:\n json_free(cfg);\n exit(1);\n }\n\n if (vm_get_int(cfg, \"block_size\", &block_size_kb) < 0)\n goto config_error;\n bf->block_size = block_size_kb * 2;\n if (bf->block_size <= 0 ||\n (bf->block_size & (bf->block_size - 1)) != 0) {\n vm_error(\"invalid block_size\\n\");\n goto config_error;\n }\n if (vm_get_int(cfg, \"n_block\", &bf->nb_blocks) < 0)\n goto config_error;\n if (bf->nb_blocks <= 0) {\n vm_error(\"invalid n_block\\n\");\n goto config_error;\n }\n\n bf->nb_sectors = bf->block_size * (uint64_t)bf->nb_blocks;\n bf->n_cached_blocks = 0;\n bf->n_cached_blocks_max = max_int(1, bf->max_cache_size_kb / block_size_kb);\n bf->cur_block_num = -1; /* no request in progress */\n \n bf->sectors_per_cluster = 8; /* 4 KB */\n bf->n_clusters = (bf->nb_sectors + bf->sectors_per_cluster - 1) / bf->sectors_per_cluster;\n bf->clusters = mallocz(sizeof(bf->clusters[0]) * bf->n_clusters);\n\n if (vm_get_int_opt(cfg, \"prefetch_group_len\",\n &bf->prefetch_group_len, 1) < 0)\n goto config_error;\n if (bf->prefetch_group_len > PREFETCH_GROUP_LEN_MAX) {\n vm_error(\"prefetch_group_len is too large\");\n goto config_error;\n }\n \n array = json_object_get(cfg, \"prefetch\");\n if (!json_is_undefined(array)) {\n int idx, prefetch_len, l, i;\n JSONValue el;\n int tab_block_num[PREFETCH_GROUP_LEN_MAX];\n \n if (array.type != JSON_ARRAY) {\n vm_error(\"expecting an array\\n\");\n goto config_error;\n }\n prefetch_len = array.u.array->len;\n idx = 0;\n while (idx < prefetch_len) {\n l = min_int(prefetch_len - idx, bf->prefetch_group_len);\n for(i = 0; i < l; i++) {\n el = json_array_get(array, idx + i);\n if (el.type != JSON_INT) {\n vm_error(\"expecting an integer\\n\");\n goto config_error;\n }\n tab_block_num[i] = el.u.int32;\n }\n if (l == 1) {\n block_num = tab_block_num[0];\n if (!bf_find_block(bf, block_num)) {\n bf_start_load_block(bs, block_num);\n }\n } else {\n bf_start_load_prefetch_group(bs, idx / bf->prefetch_group_len,\n tab_block_num, l);\n }\n idx += l;\n }\n }\n json_free(cfg);\n \n if (bf->start_cb) {\n bf->start_cb(bf->start_opaque);\n }\n}\n"], ["/linuxpdf/tinyemu/machine.c", "/*\n * VM utilities\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#include \"fs_utils.h\"\n#ifdef CONFIG_FS_NET\n#include \"fs_wget.h\"\n#endif\n\nvoid __attribute__((format(printf, 1, 2))) vm_error(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n#ifdef EMSCRIPTEN\n vprintf(fmt, ap);\n#else\n vfprintf(stderr, fmt, ap);\n#endif\n va_end(ap);\n}\n\nint vm_get_int(JSONValue obj, const char *name, int *pval)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n vm_error(\"expecting '%s' property\\n\", name);\n return -1;\n }\n if (val.type != JSON_INT) {\n vm_error(\"%s: integer expected\\n\", name);\n return -1;\n }\n *pval = val.u.int32;\n return 0;\n}\n\nint vm_get_int_opt(JSONValue obj, const char *name, int *pval, int def_val)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n *pval = def_val;\n return 0;\n }\n if (val.type != JSON_INT) {\n vm_error(\"%s: integer expected\\n\", name);\n return -1;\n }\n *pval = val.u.int32;\n return 0;\n}\n\nstatic int vm_get_str2(JSONValue obj, const char *name, const char **pstr,\n BOOL is_opt)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n if (is_opt) {\n *pstr = NULL;\n return 0;\n } else {\n vm_error(\"expecting '%s' property\\n\", name);\n return -1;\n }\n }\n if (val.type != JSON_STR) {\n vm_error(\"%s: string expected\\n\", name);\n return -1;\n }\n *pstr = val.u.str->data;\n return 0;\n}\n\nstatic int vm_get_str(JSONValue obj, const char *name, const char **pstr)\n{ \n return vm_get_str2(obj, name, pstr, FALSE);\n}\n\nstatic int vm_get_str_opt(JSONValue obj, const char *name, const char **pstr)\n{ \n return vm_get_str2(obj, name, pstr, TRUE);\n}\n\nstatic char *strdup_null(const char *str)\n{\n if (!str)\n return NULL;\n else\n return strdup(str);\n}\n\n/* currently only for \"TZ\" */\nstatic char *cmdline_subst(const char *cmdline)\n{\n DynBuf dbuf;\n const char *p;\n char var_name[32], *q, buf[32];\n \n dbuf_init(&dbuf);\n p = cmdline;\n while (*p != '\\0') {\n if (p[0] == '$' && p[1] == '{') {\n p += 2;\n q = var_name;\n while (*p != '\\0' && *p != '}') {\n if ((q - var_name) < sizeof(var_name) - 1)\n *q++ = *p;\n p++;\n }\n *q = '\\0';\n if (*p == '}')\n p++;\n if (!strcmp(var_name, \"TZ\")) {\n time_t ti;\n struct tm tm;\n int n, sg;\n /* get the offset to UTC */\n time(&ti);\n localtime_r(&ti, &tm);\n n = tm.tm_gmtoff / 60;\n sg = '-';\n if (n < 0) {\n sg = '+';\n n = -n;\n }\n snprintf(buf, sizeof(buf), \"UTC%c%02d:%02d\",\n sg, n / 60, n % 60);\n dbuf_putstr(&dbuf, buf);\n }\n } else {\n dbuf_putc(&dbuf, *p++);\n }\n }\n dbuf_putc(&dbuf, 0);\n return (char *)dbuf.buf;\n}\n\nstatic BOOL find_name(const char *name, const char *name_list)\n{\n size_t len;\n const char *p, *r;\n \n p = name_list;\n for(;;) {\n r = strchr(p, ',');\n if (!r) {\n if (!strcmp(name, p))\n return TRUE;\n break;\n } else {\n len = r - p;\n if (len == strlen(name) && !memcmp(name, p, len))\n return TRUE;\n p = r + 1;\n }\n }\n return FALSE;\n}\n\nstatic const VirtMachineClass *virt_machine_list[] = {\n#if defined(EMSCRIPTEN)\n /* only a single machine in the EMSCRIPTEN target */\n#ifndef CONFIG_X86EMU\n &riscv_machine_class,\n#endif \n#else\n &riscv_machine_class,\n#endif /* !EMSCRIPTEN */\n#ifdef CONFIG_X86EMU\n &pc_machine_class,\n#endif\n NULL,\n};\n\nstatic const VirtMachineClass *virt_machine_find_class(const char *machine_name)\n{\n const VirtMachineClass *vmc, **pvmc;\n \n for(pvmc = virt_machine_list; *pvmc != NULL; pvmc++) {\n vmc = *pvmc;\n if (find_name(machine_name, vmc->machine_names))\n return vmc;\n }\n return NULL;\n}\n\nstatic int virt_machine_parse_config(VirtMachineParams *p,\n char *config_file_str, int len)\n{\n int version, val;\n const char *tag_name, *str;\n char buf1[256];\n JSONValue cfg, obj, el;\n \n cfg = json_parse_value_len(config_file_str, len);\n if (json_is_error(cfg)) {\n vm_error(\"error: %s\\n\", json_get_error(cfg));\n json_free(cfg);\n return -1;\n }\n\n if (vm_get_int(cfg, \"version\", &version) < 0)\n goto tag_fail;\n if (version != VM_CONFIG_VERSION) {\n if (version > VM_CONFIG_VERSION) {\n vm_error(\"The emulator is too old to run this VM: please upgrade\\n\");\n return -1;\n } else {\n vm_error(\"The VM configuration file is too old for this emulator version: please upgrade the VM configuration file\\n\");\n return -1;\n }\n }\n \n if (vm_get_str(cfg, \"machine\", &str) < 0)\n goto tag_fail;\n p->machine_name = strdup(str);\n p->vmc = virt_machine_find_class(p->machine_name);\n if (!p->vmc) {\n vm_error(\"Unknown machine name: %s\\n\", p->machine_name);\n goto tag_fail;\n }\n p->vmc->virt_machine_set_defaults(p);\n\n tag_name = \"memory_size\";\n if (vm_get_int(cfg, tag_name, &val) < 0)\n goto tag_fail;\n p->ram_size = (uint64_t)val << 20;\n \n tag_name = \"bios\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_BIOS].filename = strdup(str);\n }\n\n tag_name = \"kernel\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_KERNEL].filename = strdup(str);\n }\n\n tag_name = \"initrd\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_INITRD].filename = strdup(str);\n }\n\n if (vm_get_str_opt(cfg, \"cmdline\", &str) < 0)\n goto tag_fail;\n if (str) {\n p->cmdline = cmdline_subst(str);\n }\n \n for(;;) {\n snprintf(buf1, sizeof(buf1), \"drive%d\", p->drive_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->drive_count >= MAX_DRIVE_DEVICE) {\n vm_error(\"Too many drives\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"file\", &str) < 0)\n goto tag_fail;\n p->tab_drive[p->drive_count].filename = strdup(str);\n if (vm_get_str_opt(obj, \"device\", &str) < 0)\n goto tag_fail;\n p->tab_drive[p->drive_count].device = strdup_null(str);\n p->drive_count++;\n }\n\n for(;;) {\n snprintf(buf1, sizeof(buf1), \"fs%d\", p->fs_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->fs_count >= MAX_DRIVE_DEVICE) {\n vm_error(\"Too many filesystems\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"file\", &str) < 0)\n goto tag_fail;\n p->tab_fs[p->fs_count].filename = strdup(str);\n if (vm_get_str_opt(obj, \"tag\", &str) < 0)\n goto tag_fail;\n if (!str) {\n if (p->fs_count == 0)\n strcpy(buf1, \"/dev/root\");\n else\n snprintf(buf1, sizeof(buf1), \"/dev/root%d\", p->fs_count);\n str = buf1;\n }\n p->tab_fs[p->fs_count].tag = strdup(str);\n p->fs_count++;\n }\n\n for(;;) {\n snprintf(buf1, sizeof(buf1), \"eth%d\", p->eth_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->eth_count >= MAX_ETH_DEVICE) {\n vm_error(\"Too many ethernet interfaces\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"driver\", &str) < 0)\n goto tag_fail;\n p->tab_eth[p->eth_count].driver = strdup(str);\n if (!strcmp(str, \"tap\")) {\n if (vm_get_str(obj, \"ifname\", &str) < 0)\n goto tag_fail;\n p->tab_eth[p->eth_count].ifname = strdup(str);\n }\n p->eth_count++;\n }\n\n p->display_device = NULL;\n obj = json_object_get(cfg, \"display0\");\n if (!json_is_undefined(obj)) {\n if (vm_get_str(obj, \"device\", &str) < 0)\n goto tag_fail;\n p->display_device = strdup(str);\n if (vm_get_int(obj, \"width\", &p->width) < 0)\n goto tag_fail;\n if (vm_get_int(obj, \"height\", &p->height) < 0)\n goto tag_fail;\n if (vm_get_str_opt(obj, \"vga_bios\", &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_VGA_BIOS].filename = strdup(str);\n }\n }\n\n if (vm_get_str_opt(cfg, \"input_device\", &str) < 0)\n goto tag_fail;\n p->input_device = strdup_null(str);\n\n if (vm_get_str_opt(cfg, \"accel\", &str) < 0)\n goto tag_fail;\n if (str) {\n if (!strcmp(str, \"none\")) {\n p->accel_enable = FALSE;\n } else if (!strcmp(str, \"auto\")) {\n p->accel_enable = TRUE;\n } else {\n vm_error(\"unsupported 'accel' config: %s\\n\", str);\n return -1;\n }\n }\n\n tag_name = \"rtc_local_time\";\n el = json_object_get(cfg, tag_name);\n if (!json_is_undefined(el)) {\n if (el.type != JSON_BOOL) {\n vm_error(\"%s: boolean expected\\n\", tag_name);\n goto tag_fail;\n }\n p->rtc_local_time = el.u.b;\n }\n \n json_free(cfg);\n return 0;\n tag_fail:\n json_free(cfg);\n return -1;\n}\n\ntypedef void FSLoadFileCB(void *opaque, uint8_t *buf, int buf_len);\n\ntypedef struct {\n VirtMachineParams *vm_params;\n void (*start_cb)(void *opaque);\n void *opaque;\n \n FSLoadFileCB *file_load_cb;\n void *file_load_opaque;\n int file_index;\n} VMConfigLoadState;\n\nstatic void config_file_loaded(void *opaque, uint8_t *buf, int buf_len);\nstatic void config_additional_file_load(VMConfigLoadState *s);\nstatic void config_additional_file_load_cb(void *opaque,\n uint8_t *buf, int buf_len);\n\n/* XXX: win32, URL */\nchar *get_file_path(const char *base_filename, const char *filename)\n{\n int len, len1;\n char *fname, *p;\n \n if (!base_filename)\n goto done;\n if (strchr(filename, ':'))\n goto done; /* full URL */\n if (filename[0] == '/')\n goto done;\n p = strrchr(base_filename, '/');\n if (!p) {\n done:\n return strdup(filename);\n }\n len = p + 1 - base_filename;\n len1 = strlen(filename);\n fname = malloc(len + len1 + 1);\n memcpy(fname, base_filename, len);\n memcpy(fname + len, filename, len1 + 1);\n return fname;\n}\n\n\n#ifdef EMSCRIPTEN\nstatic int load_file(uint8_t **pbuf, const char *filename)\n{\n abort();\n}\n#else\n/* return -1 if error. */\nstatic int load_file(uint8_t **pbuf, const char *filename)\n{\n FILE *f;\n int size;\n uint8_t *buf;\n \n f = fopen(filename, \"rb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n size = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = malloc(size);\n if (fread(buf, 1, size, f) != size) {\n fprintf(stderr, \"%s: read error\\n\", filename);\n exit(1);\n }\n fclose(f);\n *pbuf = buf;\n return size;\n}\n#endif\n\n#ifdef CONFIG_FS_NET\nstatic void config_load_file_cb(void *opaque, int err, void *data, size_t size)\n{\n VMConfigLoadState *s = opaque;\n \n // printf(\"err=%d data=%p size=%ld\\n\", err, data, size);\n if (err < 0) {\n vm_error(\"Error %d while loading file\\n\", -err);\n exit(1);\n }\n s->file_load_cb(s->file_load_opaque, data, size);\n}\n#endif\n\nstatic void config_load_file(VMConfigLoadState *s, const char *filename,\n FSLoadFileCB *cb, void *opaque)\n{\n // printf(\"loading %s\\n\", filename);\n#ifdef CONFIG_FS_NET\n if (is_url(filename)) {\n s->file_load_cb = cb;\n s->file_load_opaque = opaque;\n fs_wget(filename, NULL, NULL, s, config_load_file_cb, TRUE);\n } else\n#endif\n {\n uint8_t *buf;\n int size;\n size = load_file(&buf, filename);\n cb(opaque, buf, size);\n free(buf);\n }\n}\n\nvoid virt_machine_load_config_file(VirtMachineParams *p,\n const char *filename,\n void (*start_cb)(void *opaque),\n void *opaque)\n{\n VMConfigLoadState *s;\n \n s = mallocz(sizeof(*s));\n s->vm_params = p;\n s->start_cb = start_cb;\n s->opaque = opaque;\n p->cfg_filename = strdup(filename);\n\n config_load_file(s, filename, config_file_loaded, s);\n}\n\nstatic void config_file_loaded(void *opaque, uint8_t *buf, int buf_len)\n{\n VMConfigLoadState *s = opaque;\n VirtMachineParams *p = s->vm_params;\n\n if (virt_machine_parse_config(p, (char *)buf, buf_len) < 0)\n exit(1);\n \n /* load the additional files */\n s->file_index = 0;\n config_additional_file_load(s);\n}\n\nstatic void config_additional_file_load(VMConfigLoadState *s)\n{\n VirtMachineParams *p = s->vm_params;\n while (s->file_index < VM_FILE_COUNT &&\n p->files[s->file_index].filename == NULL) {\n s->file_index++;\n }\n if (s->file_index == VM_FILE_COUNT) {\n if (s->start_cb)\n s->start_cb(s->opaque);\n free(s);\n } else {\n char *fname;\n \n fname = get_file_path(p->cfg_filename,\n p->files[s->file_index].filename);\n config_load_file(s, fname,\n config_additional_file_load_cb, s);\n free(fname);\n }\n}\n\nstatic void config_additional_file_load_cb(void *opaque,\n uint8_t *buf, int buf_len)\n{\n VMConfigLoadState *s = opaque;\n VirtMachineParams *p = s->vm_params;\n\n p->files[s->file_index].buf = malloc(buf_len);\n memcpy(p->files[s->file_index].buf, buf, buf_len);\n p->files[s->file_index].len = buf_len;\n\n /* load the next files */\n s->file_index++;\n config_additional_file_load(s);\n}\n\nvoid vm_add_cmdline(VirtMachineParams *p, const char *cmdline)\n{\n char *new_cmdline, *old_cmdline;\n if (cmdline[0] == '!') {\n new_cmdline = strdup(cmdline + 1);\n } else {\n old_cmdline = p->cmdline;\n if (!old_cmdline)\n old_cmdline = \"\";\n new_cmdline = malloc(strlen(old_cmdline) + 1 + strlen(cmdline) + 1);\n strcpy(new_cmdline, old_cmdline);\n strcat(new_cmdline, \" \");\n strcat(new_cmdline, cmdline);\n }\n free(p->cmdline);\n p->cmdline = new_cmdline;\n}\n\nvoid virt_machine_free_config(VirtMachineParams *p)\n{\n int i;\n \n free(p->machine_name);\n free(p->cmdline);\n for(i = 0; i < VM_FILE_COUNT; i++) {\n free(p->files[i].filename);\n free(p->files[i].buf);\n }\n for(i = 0; i < p->drive_count; i++) {\n free(p->tab_drive[i].filename);\n free(p->tab_drive[i].device);\n }\n for(i = 0; i < p->fs_count; i++) {\n free(p->tab_fs[i].filename);\n free(p->tab_fs[i].tag);\n }\n for(i = 0; i < p->eth_count; i++) {\n free(p->tab_eth[i].driver);\n free(p->tab_eth[i].ifname);\n }\n free(p->input_device);\n free(p->display_device);\n free(p->cfg_filename);\n}\n\nVirtMachine *virt_machine_init(const VirtMachineParams *p)\n{\n const VirtMachineClass *vmc = p->vmc;\n return vmc->virt_machine_init(p);\n}\n\nvoid virt_machine_set_defaults(VirtMachineParams *p)\n{\n memset(p, 0, sizeof(*p));\n}\n\nvoid virt_machine_end(VirtMachine *s)\n{\n s->vmc->virt_machine_end(s);\n}\n"], ["/linuxpdf/tinyemu/fs_wget.c", "/*\n * HTTP file download\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n\n#if defined(EMSCRIPTEN)\n#include \n#else\n#include \n#endif\n\n/***********************************************/\n/* HTTP get */\n\n#ifdef EMSCRIPTEN\n\nstruct XHRState {\n void *opaque;\n WGetWriteCallback *cb;\n};\n\nstatic int downloading_count;\n\nvoid fs_wget_init(void)\n{\n}\n\nextern void fs_wget_update_downloading(int flag);\n\nstatic void fs_wget_update_downloading_count(int incr)\n{\n int prev_state, state;\n prev_state = (downloading_count > 0);\n downloading_count += incr;\n state = (downloading_count > 0);\n if (prev_state != state)\n fs_wget_update_downloading(state);\n}\n\nstatic void fs_wget_onerror(unsigned int handle, void *opaque, int status,\n const char *status_text)\n{\n XHRState *s = opaque;\n if (status <= 0)\n status = -404; /* HTTP not found error */\n else\n status = -status;\n fs_wget_update_downloading_count(-1);\n if (s->cb)\n s->cb(s->opaque, status, NULL, 0);\n}\n\nstatic void fs_wget_onload(unsigned int handle,\n void *opaque, void *data, unsigned int size)\n{\n XHRState *s = opaque;\n fs_wget_update_downloading_count(-1);\n if (s->cb)\n s->cb(s->opaque, 0, data, size);\n}\n\nextern int emscripten_async_wget3_data(const char* url, const char* requesttype, const char *user, const char *password, const uint8_t *post_data, int post_data_len, void *arg, int free, em_async_wget2_data_onload_func onload, em_async_wget2_data_onerror_func onerror, em_async_wget2_data_onprogress_func onprogress);\n\nXHRState *fs_wget2(const char *url, const char *user, const char *password,\n WGetReadCallback *read_cb, uint64_t post_data_len,\n void *opaque, WGetWriteCallback *cb, BOOL single_write)\n{\n XHRState *s;\n const char *request;\n uint8_t *post_data;\n \n s = mallocz(sizeof(*s));\n s->opaque = opaque;\n s->cb = cb;\n\n if (post_data_len != 0) {\n request = \"POST\";\n post_data = malloc(post_data_len);\n read_cb(opaque, post_data, post_data_len);\n } else {\n request = \"GET\";\n post_data = NULL;\n }\n fs_wget_update_downloading_count(1);\n\n emscripten_async_wget3_data(url, request, user, password,\n post_data, post_data_len, s, 1, fs_wget_onload,\n fs_wget_onerror, NULL);\n if (post_data_len != 0)\n free(post_data);\n return s;\n}\n\nvoid fs_wget_free(XHRState *s)\n{\n s->cb = NULL;\n s->opaque = NULL;\n}\n\n#else\n\nstruct XHRState {\n struct list_head link;\n CURL *eh;\n void *opaque;\n WGetWriteCallback *write_cb;\n WGetReadCallback *read_cb;\n\n BOOL single_write;\n DynBuf dbuf; /* used if single_write */\n};\n\ntypedef struct {\n struct list_head link;\n int64_t timeout;\n void (*cb)(void *opaque);\n void *opaque;\n} AsyncCallState;\n\nstatic CURLM *curl_multi_ctx;\nstatic struct list_head xhr_list; /* list of XHRState.link */\n\nvoid fs_wget_init(void)\n{\n if (curl_multi_ctx)\n return;\n curl_global_init(CURL_GLOBAL_ALL);\n curl_multi_ctx = curl_multi_init();\n init_list_head(&xhr_list);\n}\n\nvoid fs_wget_end(void)\n{\n curl_multi_cleanup(curl_multi_ctx);\n curl_global_cleanup();\n}\n\nstatic size_t fs_wget_write_cb(char *ptr, size_t size, size_t nmemb,\n void *userdata)\n{\n XHRState *s = userdata;\n size *= nmemb;\n\n if (s->single_write) {\n dbuf_write(&s->dbuf, s->dbuf.size, (void *)ptr, size);\n } else {\n s->write_cb(s->opaque, 1, ptr, size);\n }\n return size;\n}\n\nstatic size_t fs_wget_read_cb(char *ptr, size_t size, size_t nmemb,\n void *userdata)\n{\n XHRState *s = userdata;\n size *= nmemb;\n return s->read_cb(s->opaque, ptr, size);\n}\n\nXHRState *fs_wget2(const char *url, const char *user, const char *password,\n WGetReadCallback *read_cb, uint64_t post_data_len,\n void *opaque, WGetWriteCallback *write_cb, BOOL single_write)\n{\n XHRState *s;\n s = mallocz(sizeof(*s));\n s->eh = curl_easy_init();\n s->opaque = opaque;\n s->write_cb = write_cb;\n s->read_cb = read_cb;\n s->single_write = single_write;\n dbuf_init(&s->dbuf);\n \n curl_easy_setopt(s->eh, CURLOPT_PRIVATE, s);\n curl_easy_setopt(s->eh, CURLOPT_WRITEDATA, s);\n curl_easy_setopt(s->eh, CURLOPT_WRITEFUNCTION, fs_wget_write_cb);\n curl_easy_setopt(s->eh, CURLOPT_HEADER, 0);\n curl_easy_setopt(s->eh, CURLOPT_URL, url);\n curl_easy_setopt(s->eh, CURLOPT_VERBOSE, 0L);\n curl_easy_setopt(s->eh, CURLOPT_ACCEPT_ENCODING, \"\");\n if (user) {\n curl_easy_setopt(s->eh, CURLOPT_USERNAME, user);\n curl_easy_setopt(s->eh, CURLOPT_PASSWORD, password);\n }\n if (post_data_len != 0) {\n struct curl_slist *headers = NULL;\n headers = curl_slist_append(headers,\n \"Content-Type: application/octet-stream\");\n curl_easy_setopt(s->eh, CURLOPT_HTTPHEADER, headers);\n curl_easy_setopt(s->eh, CURLOPT_POST, 1L);\n curl_easy_setopt(s->eh, CURLOPT_POSTFIELDSIZE_LARGE,\n (curl_off_t)post_data_len);\n curl_easy_setopt(s->eh, CURLOPT_READDATA, s);\n curl_easy_setopt(s->eh, CURLOPT_READFUNCTION, fs_wget_read_cb);\n }\n curl_multi_add_handle(curl_multi_ctx, s->eh);\n list_add_tail(&s->link, &xhr_list);\n return s;\n}\n\nvoid fs_wget_free(XHRState *s)\n{\n dbuf_free(&s->dbuf);\n curl_easy_cleanup(s->eh);\n list_del(&s->link);\n free(s);\n}\n\n/* timeout is in ms */\nvoid fs_net_set_fdset(int *pfd_max, fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *ptimeout)\n{\n long timeout;\n int n, fd_max;\n CURLMsg *msg;\n \n if (!curl_multi_ctx)\n return;\n \n curl_multi_perform(curl_multi_ctx, &n);\n\n for(;;) {\n msg = curl_multi_info_read(curl_multi_ctx, &n);\n if (!msg)\n break;\n if (msg->msg == CURLMSG_DONE) {\n XHRState *s;\n long http_code;\n\n curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char **)&s);\n curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE,\n &http_code);\n /* signal the end of the transfer or error */\n if (http_code == 200) {\n if (s->single_write) {\n s->write_cb(s->opaque, 0, s->dbuf.buf, s->dbuf.size);\n } else {\n s->write_cb(s->opaque, 0, NULL, 0);\n }\n } else {\n s->write_cb(s->opaque, -http_code, NULL, 0);\n }\n curl_multi_remove_handle(curl_multi_ctx, s->eh);\n curl_easy_cleanup(s->eh);\n dbuf_free(&s->dbuf);\n list_del(&s->link);\n free(s);\n }\n }\n\n curl_multi_fdset(curl_multi_ctx, rfds, wfds, efds, &fd_max);\n *pfd_max = max_int(*pfd_max, fd_max);\n curl_multi_timeout(curl_multi_ctx, &timeout);\n if (timeout >= 0)\n *ptimeout = min_int(*ptimeout, timeout);\n}\n\nvoid fs_net_event_loop(FSNetEventLoopCompletionFunc *cb, void *opaque)\n{\n fd_set rfds, wfds, efds;\n int timeout, fd_max;\n struct timeval tv;\n \n if (!curl_multi_ctx)\n return;\n\n for(;;) {\n fd_max = -1;\n FD_ZERO(&rfds);\n FD_ZERO(&wfds);\n FD_ZERO(&efds);\n timeout = 10000;\n fs_net_set_fdset(&fd_max, &rfds, &wfds, &efds, &timeout);\n if (cb) {\n if (cb(opaque))\n break;\n } else {\n if (list_empty(&xhr_list))\n break;\n }\n tv.tv_sec = timeout / 1000;\n tv.tv_usec = (timeout % 1000) * 1000;\n select(fd_max + 1, &rfds, &wfds, &efds, &tv);\n }\n}\n\n#endif /* !EMSCRIPTEN */\n\nXHRState *fs_wget(const char *url, const char *user, const char *password,\n void *opaque, WGetWriteCallback *cb, BOOL single_write)\n{\n return fs_wget2(url, user, password, NULL, 0, opaque, cb, single_write);\n}\n\n/***********************************************/\n/* file decryption */\n\n#define ENCRYPTED_FILE_HEADER_SIZE (4 + AES_BLOCK_SIZE)\n\n#define DEC_BUF_SIZE (256 * AES_BLOCK_SIZE)\n\nstruct DecryptFileState {\n DecryptFileCB *write_cb;\n void *opaque;\n int dec_state;\n int dec_buf_pos;\n AES_KEY *aes_state;\n uint8_t iv[AES_BLOCK_SIZE];\n uint8_t dec_buf[DEC_BUF_SIZE];\n};\n\nDecryptFileState *decrypt_file_init(AES_KEY *aes_state,\n DecryptFileCB *write_cb,\n void *opaque)\n{\n DecryptFileState *s;\n s = mallocz(sizeof(*s));\n s->write_cb = write_cb;\n s->opaque = opaque;\n s->aes_state = aes_state;\n return s;\n}\n \nint decrypt_file(DecryptFileState *s, const uint8_t *data,\n size_t size)\n{\n int l, len, ret;\n\n while (size != 0) {\n switch(s->dec_state) {\n case 0:\n l = min_int(size, ENCRYPTED_FILE_HEADER_SIZE - s->dec_buf_pos);\n memcpy(s->dec_buf + s->dec_buf_pos, data, l);\n s->dec_buf_pos += l;\n if (s->dec_buf_pos >= ENCRYPTED_FILE_HEADER_SIZE) {\n if (memcmp(s->dec_buf, encrypted_file_magic, 4) != 0)\n return -1;\n memcpy(s->iv, s->dec_buf + 4, AES_BLOCK_SIZE);\n s->dec_state = 1;\n s->dec_buf_pos = 0;\n }\n break;\n case 1:\n l = min_int(size, DEC_BUF_SIZE - s->dec_buf_pos);\n memcpy(s->dec_buf + s->dec_buf_pos, data, l);\n s->dec_buf_pos += l;\n if (s->dec_buf_pos >= DEC_BUF_SIZE) {\n /* keep one block in case it is the padding */\n len = s->dec_buf_pos - AES_BLOCK_SIZE;\n AES_cbc_encrypt(s->dec_buf, s->dec_buf, len,\n s->aes_state, s->iv, FALSE);\n ret = s->write_cb(s->opaque, s->dec_buf, len);\n if (ret < 0)\n return ret;\n memcpy(s->dec_buf, s->dec_buf + s->dec_buf_pos - AES_BLOCK_SIZE,\n AES_BLOCK_SIZE);\n s->dec_buf_pos = AES_BLOCK_SIZE;\n }\n break;\n default:\n abort();\n }\n data += l;\n size -= l;\n }\n return 0;\n}\n\n/* write last blocks */\nint decrypt_file_flush(DecryptFileState *s)\n{\n int len, pad_len, ret;\n\n if (s->dec_state != 1)\n return -1;\n len = s->dec_buf_pos;\n if (len == 0 || \n (len % AES_BLOCK_SIZE) != 0)\n return -1;\n AES_cbc_encrypt(s->dec_buf, s->dec_buf, len,\n s->aes_state, s->iv, FALSE);\n pad_len = s->dec_buf[s->dec_buf_pos - 1];\n if (pad_len < 1 || pad_len > AES_BLOCK_SIZE)\n return -1;\n len -= pad_len;\n if (len != 0) {\n ret = s->write_cb(s->opaque, s->dec_buf, len);\n if (ret < 0)\n return ret;\n }\n return 0;\n}\n\nvoid decrypt_file_end(DecryptFileState *s)\n{\n free(s);\n}\n\n/* XHR file */\n\ntypedef struct {\n FSDevice *fs;\n FSFile *f;\n int64_t pos;\n FSWGetFileCB *cb;\n void *opaque;\n FSFile *posted_file;\n int64_t read_pos;\n DecryptFileState *dec_state;\n} FSWGetFileState;\n\nstatic int fs_wget_file_write_cb(void *opaque, const uint8_t *data,\n size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n\n ret = fs->fs_write(fs, s->f, s->pos, data, size);\n if (ret < 0)\n return ret;\n s->pos += ret;\n return ret;\n}\n\nstatic void fs_wget_file_on_load(void *opaque, int err, void *data, size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n int64_t ret_size;\n \n // printf(\"err=%d size=%ld\\n\", err, size);\n if (err < 0) {\n ret_size = err;\n goto done;\n } else {\n if (s->dec_state) {\n ret = decrypt_file(s->dec_state, data, size);\n if (ret >= 0 && err == 0) {\n /* handle the end of file */\n decrypt_file_flush(s->dec_state);\n }\n } else {\n ret = fs_wget_file_write_cb(s, data, size);\n }\n if (ret < 0) {\n ret_size = ret;\n goto done;\n } else if (err == 0) {\n /* end of transfer */\n ret_size = s->pos;\n done:\n s->cb(fs, s->f, ret_size, s->opaque);\n if (s->dec_state)\n decrypt_file_end(s->dec_state);\n free(s);\n }\n }\n}\n\nstatic size_t fs_wget_file_read_cb(void *opaque, void *data, size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n \n if (!s->posted_file)\n return 0;\n ret = fs->fs_read(fs, s->posted_file, s->read_pos, data, size);\n if (ret < 0)\n return 0;\n s->read_pos += ret;\n return ret;\n}\n\nvoid fs_wget_file2(FSDevice *fs, FSFile *f, const char *url,\n const char *user, const char *password,\n FSFile *posted_file, uint64_t post_data_len,\n FSWGetFileCB *cb, void *opaque,\n AES_KEY *aes_state)\n{\n FSWGetFileState *s;\n s = mallocz(sizeof(*s));\n s->fs = fs;\n s->f = f;\n s->pos = 0;\n s->cb = cb;\n s->opaque = opaque;\n s->posted_file = posted_file;\n s->read_pos = 0;\n if (aes_state) {\n s->dec_state = decrypt_file_init(aes_state, fs_wget_file_write_cb, s);\n }\n \n fs_wget2(url, user, password, fs_wget_file_read_cb, post_data_len,\n s, fs_wget_file_on_load, FALSE);\n}\n\n/***********************************************/\n/* PBKDF2 */\n\n#ifdef USE_BUILTIN_CRYPTO\n\n#define HMAC_BLOCK_SIZE 64\n\ntypedef struct {\n SHA256_CTX ctx;\n uint8_t K[HMAC_BLOCK_SIZE + SHA256_DIGEST_LENGTH];\n} HMAC_SHA256_CTX;\n\nvoid hmac_sha256_init(HMAC_SHA256_CTX *s, const uint8_t *key, int key_len)\n{\n int i, l;\n \n if (key_len > HMAC_BLOCK_SIZE) {\n SHA256(key, key_len, s->K);\n l = SHA256_DIGEST_LENGTH;\n } else {\n memcpy(s->K, key, key_len);\n l = key_len;\n }\n memset(s->K + l, 0, HMAC_BLOCK_SIZE - l);\n for(i = 0; i < HMAC_BLOCK_SIZE; i++)\n s->K[i] ^= 0x36;\n SHA256_Init(&s->ctx);\n SHA256_Update(&s->ctx, s->K, HMAC_BLOCK_SIZE);\n}\n\nvoid hmac_sha256_update(HMAC_SHA256_CTX *s, const uint8_t *buf, int len)\n{\n SHA256_Update(&s->ctx, buf, len);\n}\n\n/* out has a length of SHA256_DIGEST_LENGTH */\nvoid hmac_sha256_final(HMAC_SHA256_CTX *s, uint8_t *out)\n{\n int i;\n \n SHA256_Final(s->K + HMAC_BLOCK_SIZE, &s->ctx);\n for(i = 0; i < HMAC_BLOCK_SIZE; i++)\n s->K[i] ^= (0x36 ^ 0x5c);\n SHA256(s->K, HMAC_BLOCK_SIZE + SHA256_DIGEST_LENGTH, out);\n}\n\n#define SALT_LEN_MAX 32\n\nvoid pbkdf2_hmac_sha256(const uint8_t *pwd, int pwd_len,\n const uint8_t *salt, int salt_len,\n int iter, int key_len, uint8_t *out)\n{\n uint8_t F[SHA256_DIGEST_LENGTH], U[SALT_LEN_MAX + 4];\n HMAC_SHA256_CTX ctx;\n int it, U_len, j, l;\n uint32_t i;\n \n assert(salt_len <= SALT_LEN_MAX);\n i = 1;\n while (key_len > 0) {\n memset(F, 0, SHA256_DIGEST_LENGTH);\n memcpy(U, salt, salt_len);\n U[salt_len] = i >> 24;\n U[salt_len + 1] = i >> 16;\n U[salt_len + 2] = i >> 8;\n U[salt_len + 3] = i;\n U_len = salt_len + 4;\n for(it = 0; it < iter; it++) {\n hmac_sha256_init(&ctx, pwd, pwd_len);\n hmac_sha256_update(&ctx, U, U_len);\n hmac_sha256_final(&ctx, U);\n for(j = 0; j < SHA256_DIGEST_LENGTH; j++)\n F[j] ^= U[j];\n U_len = SHA256_DIGEST_LENGTH;\n }\n l = min_int(key_len, SHA256_DIGEST_LENGTH);\n memcpy(out, F, l);\n out += l;\n key_len -= l;\n i++;\n }\n}\n\n#else\n\nvoid pbkdf2_hmac_sha256(const uint8_t *pwd, int pwd_len,\n const uint8_t *salt, int salt_len,\n int iter, int key_len, uint8_t *out)\n{\n PKCS5_PBKDF2_HMAC((const char *)pwd, pwd_len, salt, salt_len,\n iter, EVP_sha256(), key_len, out);\n}\n\n#endif /* !USE_BUILTIN_CRYPTO */\n"], ["/linuxpdf/tinyemu/jsemu.c", "/*\n * JS emulator main\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#include \"list.h\"\n#include \"fbuf.h\"\n\nint virt_machine_run(void *opaque);\n\n/* provided in lib.js */\nextern void console_write(void *opaque, const uint8_t *buf, int len);\nextern void console_get_size(int *pw, int *ph);\nextern void fb_refresh(void *opaque, void *data,\n int x, int y, int w, int h, int stride);\nextern void net_recv_packet(EthernetDevice *bs,\n const uint8_t *buf, int len);\n\nstatic uint8_t console_fifo[1024];\nstatic int console_fifo_windex;\nstatic int console_fifo_rindex;\nstatic int console_fifo_count;\nstatic BOOL console_resize_pending;\n\nstatic int global_width;\nstatic int global_height;\nstatic VirtMachine *global_vm;\nstatic BOOL global_carrier_state;\n\nstatic int console_read(void *opaque, uint8_t *buf, int len)\n{\n int out_len, l;\n len = min_int(len, console_fifo_count);\n console_fifo_count -= len;\n out_len = 0;\n while (len != 0) {\n l = min_int(len, sizeof(console_fifo) - console_fifo_rindex);\n memcpy(buf + out_len, console_fifo + console_fifo_rindex, l);\n len -= l;\n out_len += l;\n console_fifo_rindex += l;\n if (console_fifo_rindex == sizeof(console_fifo))\n console_fifo_rindex = 0;\n }\n return out_len;\n}\n\n/* called from JS */\nvoid console_queue_char(int c)\n{\n if (console_fifo_count < sizeof(console_fifo)) {\n console_fifo[console_fifo_windex] = c;\n if (++console_fifo_windex == sizeof(console_fifo))\n console_fifo_windex = 0;\n console_fifo_count++;\n }\n}\n\n/* called from JS */\nvoid display_key_event(int is_down, int key_code)\n{\n if (global_vm) {\n vm_send_key_event(global_vm, is_down, key_code);\n }\n}\n\n/* called from JS */\nstatic int mouse_last_x, mouse_last_y, mouse_last_buttons;\n\nvoid display_mouse_event(int dx, int dy, int buttons)\n{\n if (global_vm) {\n if (vm_mouse_is_absolute(global_vm) || 1) {\n dx = min_int(dx, global_width - 1);\n dy = min_int(dy, global_height - 1);\n dx = (dx * VIRTIO_INPUT_ABS_SCALE) / global_width;\n dy = (dy * VIRTIO_INPUT_ABS_SCALE) / global_height;\n } else {\n /* relative mouse is not supported */\n dx = 0;\n dy = 0;\n }\n mouse_last_x = dx;\n mouse_last_y = dy;\n mouse_last_buttons = buttons;\n vm_send_mouse_event(global_vm, dx, dy, 0, buttons);\n }\n}\n\n/* called from JS */\nvoid display_wheel_event(int dz)\n{\n if (global_vm) {\n vm_send_mouse_event(global_vm, mouse_last_x, mouse_last_y, dz,\n mouse_last_buttons);\n }\n}\n\n/* called from JS */\nvoid net_write_packet(const uint8_t *buf, int buf_len)\n{\n EthernetDevice *net = global_vm->net;\n if (net) {\n net->device_write_packet(net, buf, buf_len);\n }\n}\n\n/* called from JS */\nvoid net_set_carrier(BOOL carrier_state)\n{\n EthernetDevice *net;\n global_carrier_state = carrier_state;\n if (global_vm && global_vm->net) {\n net = global_vm->net;\n net->device_set_carrier(net, carrier_state);\n }\n}\n\nstatic void fb_refresh1(FBDevice *fb_dev, void *opaque,\n int x, int y, int w, int h)\n{\n int stride = fb_dev->stride;\n fb_refresh(opaque, fb_dev->fb_data + y * stride + x * 4, x, y, w, h,\n stride);\n}\n\nstatic CharacterDevice *console_init(void)\n{\n CharacterDevice *dev;\n console_resize_pending = TRUE;\n dev = mallocz(sizeof(*dev));\n dev->write_data = console_write;\n dev->read_data = console_read;\n return dev;\n}\n\ntypedef struct {\n VirtMachineParams *p;\n int ram_size;\n char *cmdline;\n BOOL has_network;\n char *pwd;\n} VMStartState;\n\nstatic void init_vm(void *arg);\nstatic void init_vm_fs(void *arg);\nstatic void init_vm_drive(void *arg);\n\nvoid vm_start(const char *url, int ram_size, const char *cmdline,\n const char *pwd, int width, int height, BOOL has_network)\n{\n VMStartState *s;\n\n s = mallocz(sizeof(*s));\n s->ram_size = ram_size;\n s->cmdline = strdup(cmdline);\n if (pwd)\n s->pwd = strdup(pwd);\n global_width = width;\n global_height = height;\n s->has_network = has_network;\n s->p = mallocz(sizeof(VirtMachineParams));\n virt_machine_set_defaults(s->p);\n virt_machine_load_config_file(s->p, url, init_vm_fs, s);\n}\n\nstatic void init_vm_fs(void *arg)\n{\n VMStartState *s = arg;\n VirtMachineParams *p = s->p;\n\n if (p->fs_count > 0) {\n assert(p->fs_count == 1);\n p->tab_fs[0].fs_dev = fs_net_init(p->tab_fs[0].filename,\n init_vm_drive, s);\n if (s->pwd) {\n fs_net_set_pwd(p->tab_fs[0].fs_dev, s->pwd);\n }\n } else {\n init_vm_drive(s);\n }\n}\n\nstatic void init_vm_drive(void *arg)\n{\n VMStartState *s = arg;\n VirtMachineParams *p = s->p;\n\n if (p->drive_count > 0) {\n assert(p->drive_count == 1);\n p->tab_drive[0].block_dev =\n block_device_init_http(p->tab_drive[0].filename,\n 131072,\n init_vm, s);\n } else {\n init_vm(s);\n }\n}\n\nstatic void init_vm(void *arg)\n{\n VMStartState *s = arg;\n VirtMachine *m;\n VirtMachineParams *p = s->p;\n int i;\n \n p->rtc_real_time = TRUE;\n p->ram_size = s->ram_size << 20;\n if (s->cmdline && s->cmdline[0] != '\\0') {\n vm_add_cmdline(s->p, s->cmdline);\n }\n\n if (global_width > 0 && global_height > 0) {\n /* enable graphic output if needed */\n if (!p->display_device)\n p->display_device = strdup(\"simplefb\");\n p->width = global_width;\n p->height = global_height;\n } else {\n p->console = console_init();\n }\n \n if (p->eth_count > 0 && !s->has_network) {\n /* remove the interfaces */\n for(i = 0; i < p->eth_count; i++) {\n free(p->tab_eth[i].ifname);\n free(p->tab_eth[i].driver);\n }\n p->eth_count = 0;\n }\n\n if (p->eth_count > 0) {\n EthernetDevice *net;\n int i;\n assert(p->eth_count == 1);\n net = mallocz(sizeof(EthernetDevice));\n net->mac_addr[0] = 0x02;\n for(i = 1; i < 6; i++)\n net->mac_addr[i] = (int)(emscripten_random() * 256);\n net->write_packet = net_recv_packet;\n net->opaque = NULL;\n p->tab_eth[0].net = net;\n }\n\n m = virt_machine_init(p);\n global_vm = m;\n\n virt_machine_free_config(s->p);\n\n if (m->net) {\n m->net->device_set_carrier(m->net, global_carrier_state);\n }\n \n free(s->p);\n free(s->cmdline);\n if (s->pwd) {\n memset(s->pwd, 0, strlen(s->pwd));\n free(s->pwd);\n }\n free(s);\n \n EM_ASM({\n start_machine_interval($0);\n }, m);\n}\n\n/* need to be long enough to hide the non zero delay of setTimeout(_, 0) */\n#define MAX_EXEC_TOTAL_CYCLE 100000\n#define MAX_EXEC_CYCLE 1000\n\n#define MAX_SLEEP_TIME 10 /* in ms */\n\nint virt_machine_run(void *opaque)\n{\n VirtMachine *m = opaque;\n int delay, i;\n FBDevice *fb_dev;\n \n if (m->console_dev && virtio_console_can_write_data(m->console_dev)) {\n uint8_t buf[128];\n int ret, len;\n len = virtio_console_get_write_len(m->console_dev);\n len = min_int(len, sizeof(buf));\n ret = m->console->read_data(m->console->opaque, buf, len);\n if (ret > 0)\n virtio_console_write_data(m->console_dev, buf, ret);\n if (console_resize_pending) {\n int w, h;\n console_get_size(&w, &h);\n virtio_console_resize_event(m->console_dev, w, h);\n console_resize_pending = FALSE;\n }\n }\n\n fb_dev = m->fb_dev;\n if (fb_dev) {\n /* refresh the display */\n fb_dev->refresh(fb_dev, fb_refresh1, NULL);\n }\n \n i = 0;\n for(;;) {\n /* wait for an event: the only asynchronous event is the RTC timer */\n delay = virt_machine_get_sleep_duration(m, MAX_SLEEP_TIME);\n if (delay != 0 || i >= MAX_EXEC_TOTAL_CYCLE / MAX_EXEC_CYCLE)\n break;\n virt_machine_interp(m, MAX_EXEC_CYCLE);\n i++;\n }\n return i * MAX_EXEC_CYCLE;\n \n /*\n if (delay == 0) {\n emscripten_async_call(virt_machine_run, m, 0);\n } else {\n emscripten_async_call(virt_machine_run, m, MAX_SLEEP_TIME);\n }\n */\n}\n\n"], ["/linuxpdf/tinyemu/slirp/slirp.c", "/*\n * libslirp glue\n *\n * Copyright (c) 2004-2008 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"slirp.h\"\n\n/* host loopback address */\nstruct in_addr loopback_addr;\n\n/* emulated hosts use the MAC addr 52:55:IP:IP:IP:IP */\nstatic const uint8_t special_ethaddr[6] = {\n 0x52, 0x55, 0x00, 0x00, 0x00, 0x00\n};\n\nstatic const uint8_t zero_ethaddr[6] = { 0, 0, 0, 0, 0, 0 };\n\n/* XXX: suppress those select globals */\nfd_set *global_readfds, *global_writefds, *global_xfds;\n\nu_int curtime;\nstatic u_int time_fasttimo, last_slowtimo;\nstatic int do_slowtimo;\n\nstatic struct in_addr dns_addr;\nstatic u_int dns_addr_time;\n\n#ifdef _WIN32\n\nint get_dns_addr(struct in_addr *pdns_addr)\n{\n FIXED_INFO *FixedInfo=NULL;\n ULONG BufLen;\n DWORD ret;\n IP_ADDR_STRING *pIPAddr;\n struct in_addr tmp_addr;\n\n if (dns_addr.s_addr != 0 && (curtime - dns_addr_time) < 1000) {\n *pdns_addr = dns_addr;\n return 0;\n }\n\n FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));\n BufLen = sizeof(FIXED_INFO);\n\n if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen)) {\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n FixedInfo = GlobalAlloc(GPTR, BufLen);\n }\n\n if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS) {\n printf(\"GetNetworkParams failed. ret = %08x\\n\", (u_int)ret );\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n return -1;\n }\n\n pIPAddr = &(FixedInfo->DnsServerList);\n inet_aton(pIPAddr->IpAddress.String, &tmp_addr);\n *pdns_addr = tmp_addr;\n dns_addr = tmp_addr;\n dns_addr_time = curtime;\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n return 0;\n}\n\nstatic void winsock_cleanup(void)\n{\n WSACleanup();\n}\n\n#else\n\nstatic struct stat dns_addr_stat;\n\nint get_dns_addr(struct in_addr *pdns_addr)\n{\n char buff[512];\n char buff2[257];\n FILE *f;\n int found = 0;\n struct in_addr tmp_addr;\n\n if (dns_addr.s_addr != 0) {\n struct stat old_stat;\n if ((curtime - dns_addr_time) < 1000) {\n *pdns_addr = dns_addr;\n return 0;\n }\n old_stat = dns_addr_stat;\n if (stat(\"/etc/resolv.conf\", &dns_addr_stat) != 0)\n return -1;\n if ((dns_addr_stat.st_dev == old_stat.st_dev)\n && (dns_addr_stat.st_ino == old_stat.st_ino)\n && (dns_addr_stat.st_size == old_stat.st_size)\n && (dns_addr_stat.st_mtime == old_stat.st_mtime)) {\n *pdns_addr = dns_addr;\n return 0;\n }\n }\n\n f = fopen(\"/etc/resolv.conf\", \"r\");\n if (!f)\n return -1;\n\n#ifdef DEBUG\n lprint(\"IP address of your DNS(s): \");\n#endif\n while (fgets(buff, 512, f) != NULL) {\n if (sscanf(buff, \"nameserver%*[ \\t]%256s\", buff2) == 1) {\n if (!inet_aton(buff2, &tmp_addr))\n continue;\n /* If it's the first one, set it to dns_addr */\n if (!found) {\n *pdns_addr = tmp_addr;\n dns_addr = tmp_addr;\n dns_addr_time = curtime;\n }\n#ifdef DEBUG\n else\n lprint(\", \");\n#endif\n if (++found > 3) {\n#ifdef DEBUG\n lprint(\"(more)\");\n#endif\n break;\n }\n#ifdef DEBUG\n else\n lprint(\"%s\", inet_ntoa(tmp_addr));\n#endif\n }\n }\n fclose(f);\n if (!found)\n return -1;\n return 0;\n}\n\n#endif\n\nstatic void slirp_init_once(void)\n{\n static int initialized;\n#ifdef _WIN32\n WSADATA Data;\n#endif\n\n if (initialized) {\n return;\n }\n initialized = 1;\n\n#ifdef _WIN32\n WSAStartup(MAKEWORD(2,0), &Data);\n atexit(winsock_cleanup);\n#endif\n\n loopback_addr.s_addr = htonl(INADDR_LOOPBACK);\n}\n\nSlirp *slirp_init(int restricted, struct in_addr vnetwork,\n struct in_addr vnetmask, struct in_addr vhost,\n const char *vhostname, const char *tftp_path,\n const char *bootfile, struct in_addr vdhcp_start,\n struct in_addr vnameserver, void *opaque)\n{\n Slirp *slirp = mallocz(sizeof(Slirp));\n\n slirp_init_once();\n\n slirp->restricted = restricted;\n\n if_init(slirp);\n ip_init(slirp);\n\n /* Initialise mbufs *after* setting the MTU */\n m_init(slirp);\n\n slirp->vnetwork_addr = vnetwork;\n slirp->vnetwork_mask = vnetmask;\n slirp->vhost_addr = vhost;\n if (vhostname) {\n pstrcpy(slirp->client_hostname, sizeof(slirp->client_hostname),\n vhostname);\n }\n if (tftp_path) {\n slirp->tftp_prefix = strdup(tftp_path);\n }\n if (bootfile) {\n slirp->bootp_filename = strdup(bootfile);\n }\n slirp->vdhcp_startaddr = vdhcp_start;\n slirp->vnameserver_addr = vnameserver;\n\n slirp->opaque = opaque;\n\n return slirp;\n}\n\nvoid slirp_cleanup(Slirp *slirp)\n{\n free(slirp->tftp_prefix);\n free(slirp->bootp_filename);\n free(slirp);\n}\n\n#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)\n#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)\n#define UPD_NFDS(x) if (nfds < (x)) nfds = (x)\n\nvoid slirp_select_fill(Slirp *slirp, int *pnfds,\n fd_set *readfds, fd_set *writefds, fd_set *xfds)\n{\n struct socket *so, *so_next;\n int nfds;\n\n /* fail safe */\n global_readfds = NULL;\n global_writefds = NULL;\n global_xfds = NULL;\n\n nfds = *pnfds;\n\t/*\n\t * First, TCP sockets\n\t */\n\tdo_slowtimo = 0;\n\n\t{\n\t\t/*\n\t\t * *_slowtimo needs calling if there are IP fragments\n\t\t * in the fragment queue, or there are TCP connections active\n\t\t */\n\t\tdo_slowtimo |= ((slirp->tcb.so_next != &slirp->tcb) ||\n\t\t (&slirp->ipq.ip_link != slirp->ipq.ip_link.next));\n\n\t\tfor (so = slirp->tcb.so_next; so != &slirp->tcb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * See if we need a tcp_fasttimo\n\t\t\t */\n\t\t\tif (time_fasttimo == 0 && so->so_tcpcb->t_flags & TF_DELACK)\n\t\t\t time_fasttimo = curtime; /* Flag when we want a fasttimo */\n\n\t\t\t/*\n\t\t\t * NOFDREF can include still connecting to local-host,\n\t\t\t * newly socreated() sockets etc. Don't want to select these.\n\t \t\t */\n\t\t\tif (so->so_state & SS_NOFDREF || so->s == -1)\n\t\t\t continue;\n\n\t\t\t/*\n\t\t\t * Set for reading sockets which are accepting\n\t\t\t */\n\t\t\tif (so->so_state & SS_FACCEPTCONN) {\n FD_SET(so->s, readfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for writing sockets which are connecting\n\t\t\t */\n\t\t\tif (so->so_state & SS_ISFCONNECTING) {\n\t\t\t\tFD_SET(so->s, writefds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for writing if we are connected, can send more, and\n\t\t\t * we have something to send\n\t\t\t */\n\t\t\tif (CONN_CANFSEND(so) && so->so_rcv.sb_cc) {\n\t\t\t\tFD_SET(so->s, writefds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for reading (and urgent data) if we are connected, can\n\t\t\t * receive more, and we have room for it XXX /2 ?\n\t\t\t */\n\t\t\tif (CONN_CANFRCV(so) && (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2))) {\n\t\t\t\tFD_SET(so->s, readfds);\n\t\t\t\tFD_SET(so->s, xfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * UDP sockets\n\t\t */\n\t\tfor (so = slirp->udb.so_next; so != &slirp->udb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * See if it's timed out\n\t\t\t */\n\t\t\tif (so->so_expire) {\n\t\t\t\tif (so->so_expire <= curtime) {\n\t\t\t\t\tudp_detach(so);\n\t\t\t\t\tcontinue;\n\t\t\t\t} else\n\t\t\t\t\tdo_slowtimo = 1; /* Let socket expire */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * When UDP packets are received from over the\n\t\t\t * link, they're sendto()'d straight away, so\n\t\t\t * no need for setting for writing\n\t\t\t * Limit the number of packets queued by this session\n\t\t\t * to 4. Note that even though we try and limit this\n\t\t\t * to 4 packets, the session could have more queued\n\t\t\t * if the packets needed to be fragmented\n\t\t\t * (XXX <= 4 ?)\n\t\t\t */\n\t\t\tif ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4) {\n\t\t\t\tFD_SET(so->s, readfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\t\t}\n\t}\n\n *pnfds = nfds;\n}\n\nvoid slirp_select_poll(Slirp *slirp,\n fd_set *readfds, fd_set *writefds, fd_set *xfds,\n int select_error)\n{\n struct socket *so, *so_next;\n int ret;\n\n global_readfds = readfds;\n global_writefds = writefds;\n global_xfds = xfds;\n\n curtime = os_get_time_ms();\n\n {\n\t/*\n\t * See if anything has timed out\n\t */\n\t\tif (time_fasttimo && ((curtime - time_fasttimo) >= 2)) {\n\t\t\ttcp_fasttimo(slirp);\n\t\t\ttime_fasttimo = 0;\n\t\t}\n\t\tif (do_slowtimo && ((curtime - last_slowtimo) >= 499)) {\n\t\t\tip_slowtimo(slirp);\n\t\t\ttcp_slowtimo(slirp);\n\t\t\tlast_slowtimo = curtime;\n\t\t}\n\n\t/*\n\t * Check sockets\n\t */\n\tif (!select_error) {\n\t\t/*\n\t\t * Check TCP sockets\n\t\t */\n\t\tfor (so = slirp->tcb.so_next; so != &slirp->tcb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * FD_ISSET is meaningless on these sockets\n\t\t\t * (and they can crash the program)\n\t\t\t */\n\t\t\tif (so->so_state & SS_NOFDREF || so->s == -1)\n\t\t\t continue;\n\n\t\t\t/*\n\t\t\t * Check for URG data\n\t\t\t * This will soread as well, so no need to\n\t\t\t * test for readfds below if this succeeds\n\t\t\t */\n\t\t\tif (FD_ISSET(so->s, xfds))\n\t\t\t sorecvoob(so);\n\t\t\t/*\n\t\t\t * Check sockets for reading\n\t\t\t */\n\t\t\telse if (FD_ISSET(so->s, readfds)) {\n\t\t\t\t/*\n\t\t\t\t * Check for incoming connections\n\t\t\t\t */\n\t\t\t\tif (so->so_state & SS_FACCEPTCONN) {\n\t\t\t\t\ttcp_connect(so);\n\t\t\t\t\tcontinue;\n\t\t\t\t} /* else */\n\t\t\t\tret = soread(so);\n\n\t\t\t\t/* Output it if we read something */\n\t\t\t\tif (ret > 0)\n\t\t\t\t tcp_output(sototcpcb(so));\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Check sockets for writing\n\t\t\t */\n\t\t\tif (FD_ISSET(so->s, writefds)) {\n\t\t\t /*\n\t\t\t * Check for non-blocking, still-connecting sockets\n\t\t\t */\n\t\t\t if (so->so_state & SS_ISFCONNECTING) {\n\t\t\t /* Connected */\n\t\t\t so->so_state &= ~SS_ISFCONNECTING;\n\n\t\t\t ret = send(so->s, (const void *) &ret, 0, 0);\n\t\t\t if (ret < 0) {\n\t\t\t /* XXXXX Must fix, zero bytes is a NOP */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\t errno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t\tcontinue;\n\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\t\t\t }\n\t\t\t /* else so->so_state &= ~SS_ISFCONNECTING; */\n\n\t\t\t /*\n\t\t\t * Continue tcp_input\n\t\t\t */\n\t\t\t tcp_input((struct mbuf *)NULL, sizeof(struct ip), so);\n\t\t\t /* continue; */\n\t\t\t } else\n\t\t\t ret = sowrite(so);\n\t\t\t /*\n\t\t\t * XXXXX If we wrote something (a lot), there\n\t\t\t * could be a need for a window update.\n\t\t\t * In the worst case, the remote will send\n\t\t\t * a window probe to get things going again\n\t\t\t */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Probe a still-connecting, non-blocking socket\n\t\t\t * to check if it's still alive\n\t \t \t */\n#ifdef PROBE_CONN\n\t\t\tif (so->so_state & SS_ISFCONNECTING) {\n\t\t\t ret = recv(so->s, (char *)&ret, 0,0);\n\n\t\t\t if (ret < 0) {\n\t\t\t /* XXX */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\terrno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t continue; /* Still connecting, continue */\n\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\n\t\t\t /* tcp_input will take care of it */\n\t\t\t } else {\n\t\t\t ret = send(so->s, &ret, 0,0);\n\t\t\t if (ret < 0) {\n\t\t\t /* XXX */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\t errno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t\tcontinue;\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\t\t\t } else\n\t\t\t so->so_state &= ~SS_ISFCONNECTING;\n\n\t\t\t }\n\t\t\t tcp_input((struct mbuf *)NULL, sizeof(struct ip),so);\n\t\t\t} /* SS_ISFCONNECTING */\n#endif\n\t\t}\n\n\t\t/*\n\t\t * Now UDP sockets.\n\t\t * Incoming packets are sent straight away, they're not buffered.\n\t\t * Incoming UDP data isn't buffered either.\n\t\t */\n\t\tfor (so = slirp->udb.so_next; so != &slirp->udb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\tif (so->s != -1 && FD_ISSET(so->s, readfds)) {\n sorecvfrom(so);\n }\n\t\t}\n\t}\n\n\t/*\n\t * See if we can start outputting\n\t */\n\tif (slirp->if_queued) {\n\t if_start(slirp);\n\t}\n }\n\n\t/* clear global file descriptor sets.\n\t * these reside on the stack in vl.c\n\t * so they're unusable if we're not in\n\t * slirp_select_fill or slirp_select_poll.\n\t */\n\t global_readfds = NULL;\n\t global_writefds = NULL;\n\t global_xfds = NULL;\n}\n\n#define ETH_ALEN 6\n#define ETH_HLEN 14\n\n#define ETH_P_IP\t0x0800\t\t/* Internet Protocol packet\t*/\n#define ETH_P_ARP\t0x0806\t\t/* Address Resolution packet\t*/\n\n#define\tARPOP_REQUEST\t1\t\t/* ARP request\t\t\t*/\n#define\tARPOP_REPLY\t2\t\t/* ARP reply\t\t\t*/\n\nstruct ethhdr\n{\n\tunsigned char\th_dest[ETH_ALEN];\t/* destination eth addr\t*/\n\tunsigned char\th_source[ETH_ALEN];\t/* source ether addr\t*/\n\tunsigned short\th_proto;\t\t/* packet type ID field\t*/\n};\n\nstruct arphdr\n{\n\tunsigned short\tar_hrd;\t\t/* format of hardware address\t*/\n\tunsigned short\tar_pro;\t\t/* format of protocol address\t*/\n\tunsigned char\tar_hln;\t\t/* length of hardware address\t*/\n\tunsigned char\tar_pln;\t\t/* length of protocol address\t*/\n\tunsigned short\tar_op;\t\t/* ARP opcode (command)\t\t*/\n\n\t /*\n\t *\t Ethernet looks like this : This bit is variable sized however...\n\t */\n\tunsigned char\t\tar_sha[ETH_ALEN];\t/* sender hardware address\t*/\n\tuint32_t\t\tar_sip;\t\t\t/* sender IP address\t\t*/\n\tunsigned char\t\tar_tha[ETH_ALEN];\t/* target hardware address\t*/\n\tuint32_t\t\tar_tip\t;\t\t/* target IP address\t\t*/\n} __attribute__((packed));\n\nstatic void arp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)\n{\n struct ethhdr *eh = (struct ethhdr *)pkt;\n struct arphdr *ah = (struct arphdr *)(pkt + ETH_HLEN);\n uint8_t arp_reply[max(ETH_HLEN + sizeof(struct arphdr), 64)];\n struct ethhdr *reh = (struct ethhdr *)arp_reply;\n struct arphdr *rah = (struct arphdr *)(arp_reply + ETH_HLEN);\n int ar_op;\n struct ex_list *ex_ptr;\n\n ar_op = ntohs(ah->ar_op);\n switch(ar_op) {\n case ARPOP_REQUEST:\n if ((ah->ar_tip & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n if (ah->ar_tip == slirp->vnameserver_addr.s_addr ||\n ah->ar_tip == slirp->vhost_addr.s_addr)\n goto arp_ok;\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_addr.s_addr == ah->ar_tip)\n goto arp_ok;\n }\n return;\n arp_ok:\n memset(arp_reply, 0, sizeof(arp_reply));\n /* XXX: make an ARP request to have the client address */\n memcpy(slirp->client_ethaddr, eh->h_source, ETH_ALEN);\n\n /* ARP request for alias/dns mac address */\n memcpy(reh->h_dest, pkt + ETH_ALEN, ETH_ALEN);\n memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);\n memcpy(&reh->h_source[2], &ah->ar_tip, 4);\n reh->h_proto = htons(ETH_P_ARP);\n\n rah->ar_hrd = htons(1);\n rah->ar_pro = htons(ETH_P_IP);\n rah->ar_hln = ETH_ALEN;\n rah->ar_pln = 4;\n rah->ar_op = htons(ARPOP_REPLY);\n memcpy(rah->ar_sha, reh->h_source, ETH_ALEN);\n rah->ar_sip = ah->ar_tip;\n memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);\n rah->ar_tip = ah->ar_sip;\n slirp_output(slirp->opaque, arp_reply, sizeof(arp_reply));\n }\n break;\n case ARPOP_REPLY:\n /* reply to request of client mac address ? */\n if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN) &&\n ah->ar_sip == slirp->client_ipaddr.s_addr) {\n memcpy(slirp->client_ethaddr, ah->ar_sha, ETH_ALEN);\n }\n break;\n default:\n break;\n }\n}\n\nvoid slirp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)\n{\n struct mbuf *m;\n int proto;\n\n if (pkt_len < ETH_HLEN)\n return;\n\n proto = ntohs(*(uint16_t *)(pkt + 12));\n switch(proto) {\n case ETH_P_ARP:\n arp_input(slirp, pkt, pkt_len);\n break;\n case ETH_P_IP:\n m = m_get(slirp);\n if (!m)\n return;\n /* Note: we add to align the IP header */\n if (M_FREEROOM(m) < pkt_len + 2) {\n m_inc(m, pkt_len + 2);\n }\n m->m_len = pkt_len + 2;\n memcpy(m->m_data + 2, pkt, pkt_len);\n\n m->m_data += 2 + ETH_HLEN;\n m->m_len -= 2 + ETH_HLEN;\n\n ip_input(m);\n break;\n default:\n break;\n }\n}\n\n/* output the IP packet to the ethernet device */\nvoid if_encap(Slirp *slirp, const uint8_t *ip_data, int ip_data_len)\n{\n uint8_t buf[1600];\n struct ethhdr *eh = (struct ethhdr *)buf;\n\n if (ip_data_len + ETH_HLEN > sizeof(buf))\n return;\n \n if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN)) {\n uint8_t arp_req[ETH_HLEN + sizeof(struct arphdr)];\n struct ethhdr *reh = (struct ethhdr *)arp_req;\n struct arphdr *rah = (struct arphdr *)(arp_req + ETH_HLEN);\n const struct ip *iph = (const struct ip *)ip_data;\n\n /* If the client addr is not known, there is no point in\n sending the packet to it. Normally the sender should have\n done an ARP request to get its MAC address. Here we do it\n in place of sending the packet and we hope that the sender\n will retry sending its packet. */\n memset(reh->h_dest, 0xff, ETH_ALEN);\n memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);\n memcpy(&reh->h_source[2], &slirp->vhost_addr, 4);\n reh->h_proto = htons(ETH_P_ARP);\n rah->ar_hrd = htons(1);\n rah->ar_pro = htons(ETH_P_IP);\n rah->ar_hln = ETH_ALEN;\n rah->ar_pln = 4;\n rah->ar_op = htons(ARPOP_REQUEST);\n /* source hw addr */\n memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN - 4);\n memcpy(&rah->ar_sha[2], &slirp->vhost_addr, 4);\n /* source IP */\n rah->ar_sip = slirp->vhost_addr.s_addr;\n /* target hw addr (none) */\n memset(rah->ar_tha, 0, ETH_ALEN);\n /* target IP */\n rah->ar_tip = iph->ip_dst.s_addr;\n slirp->client_ipaddr = iph->ip_dst;\n slirp_output(slirp->opaque, arp_req, sizeof(arp_req));\n } else {\n memcpy(eh->h_dest, slirp->client_ethaddr, ETH_ALEN);\n memcpy(eh->h_source, special_ethaddr, ETH_ALEN - 4);\n /* XXX: not correct */\n memcpy(&eh->h_source[2], &slirp->vhost_addr, 4);\n eh->h_proto = htons(ETH_P_IP);\n memcpy(buf + sizeof(struct ethhdr), ip_data, ip_data_len);\n slirp_output(slirp->opaque, buf, ip_data_len + ETH_HLEN);\n }\n}\n\n/* Drop host forwarding rule, return 0 if found. */\nint slirp_remove_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,\n int host_port)\n{\n struct socket *so;\n struct socket *head = (is_udp ? &slirp->udb : &slirp->tcb);\n struct sockaddr_in addr;\n int port = htons(host_port);\n socklen_t addr_len;\n\n for (so = head->so_next; so != head; so = so->so_next) {\n addr_len = sizeof(addr);\n if ((so->so_state & SS_HOSTFWD) &&\n getsockname(so->s, (struct sockaddr *)&addr, &addr_len) == 0 &&\n addr.sin_addr.s_addr == host_addr.s_addr &&\n addr.sin_port == port) {\n close(so->s);\n sofree(so);\n return 0;\n }\n }\n\n return -1;\n}\n\nint slirp_add_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,\n int host_port, struct in_addr guest_addr, int guest_port)\n{\n if (!guest_addr.s_addr) {\n guest_addr = slirp->vdhcp_startaddr;\n }\n if (is_udp) {\n if (!udp_listen(slirp, host_addr.s_addr, htons(host_port),\n guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))\n return -1;\n } else {\n if (!tcp_listen(slirp, host_addr.s_addr, htons(host_port),\n guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))\n return -1;\n }\n return 0;\n}\n\nint slirp_add_exec(Slirp *slirp, int do_pty, const void *args,\n struct in_addr *guest_addr, int guest_port)\n{\n if (!guest_addr->s_addr) {\n guest_addr->s_addr = slirp->vnetwork_addr.s_addr |\n (htonl(0x0204) & ~slirp->vnetwork_mask.s_addr);\n }\n if ((guest_addr->s_addr & slirp->vnetwork_mask.s_addr) !=\n slirp->vnetwork_addr.s_addr ||\n guest_addr->s_addr == slirp->vhost_addr.s_addr ||\n guest_addr->s_addr == slirp->vnameserver_addr.s_addr) {\n return -1;\n }\n return add_exec(&slirp->exec_list, do_pty, (char *)args, *guest_addr,\n htons(guest_port));\n}\n\nssize_t slirp_send(struct socket *so, const void *buf, size_t len, int flags)\n{\n#if 0\n if (so->s == -1 && so->extra) {\n\t\tqemu_chr_write(so->extra, buf, len);\n\t\treturn len;\n\t}\n#endif\n\treturn send(so->s, buf, len, flags);\n}\n\nstatic struct socket *\nslirp_find_ctl_socket(Slirp *slirp, struct in_addr guest_addr, int guest_port)\n{\n struct socket *so;\n\n for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {\n if (so->so_faddr.s_addr == guest_addr.s_addr &&\n htons(so->so_fport) == guest_port) {\n return so;\n }\n }\n return NULL;\n}\n\nsize_t slirp_socket_can_recv(Slirp *slirp, struct in_addr guest_addr,\n int guest_port)\n{\n\tstruct iovec iov[2];\n\tstruct socket *so;\n\n\tso = slirp_find_ctl_socket(slirp, guest_addr, guest_port);\n\n\tif (!so || so->so_state & SS_NOFDREF)\n\t\treturn 0;\n\n\tif (!CONN_CANFRCV(so) || so->so_snd.sb_cc >= (so->so_snd.sb_datalen/2))\n\t\treturn 0;\n\n\treturn sopreprbuf(so, iov, NULL);\n}\n\nvoid slirp_socket_recv(Slirp *slirp, struct in_addr guest_addr, int guest_port,\n const uint8_t *buf, int size)\n{\n int ret;\n struct socket *so = slirp_find_ctl_socket(slirp, guest_addr, guest_port);\n\n if (!so)\n return;\n\n ret = soreadbuf(so, (const char *)buf, size);\n\n if (ret > 0)\n tcp_output(sototcpcb(so));\n}\n"], ["/linuxpdf/tinyemu/fs_disk.c", "/*\n * Filesystem on disk\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n\ntypedef struct {\n FSDevice common;\n char *root_path;\n} FSDeviceDisk;\n\nstatic void fs_close(FSDevice *fs, FSFile *f);\n\nstruct FSFile {\n uint32_t uid;\n char *path; /* complete path */\n BOOL is_opened;\n BOOL is_dir;\n union {\n int fd;\n DIR *dirp;\n } u;\n};\n\nstatic void fs_delete(FSDevice *fs, FSFile *f)\n{\n if (f->is_opened)\n fs_close(fs, f);\n free(f->path);\n free(f);\n}\n\n/* warning: path belong to fid_create() */\nstatic FSFile *fid_create(FSDevice *s1, char *path, uint32_t uid)\n{\n FSFile *f;\n f = mallocz(sizeof(*f));\n f->path = path;\n f->uid = uid;\n return f;\n}\n\n\nstatic int errno_table[][2] = {\n { P9_EPERM, EPERM },\n { P9_ENOENT, ENOENT },\n { P9_EIO, EIO },\n { P9_EEXIST, EEXIST },\n { P9_EINVAL, EINVAL },\n { P9_ENOSPC, ENOSPC },\n { P9_ENOTEMPTY, ENOTEMPTY },\n { P9_EPROTO, EPROTO },\n { P9_ENOTSUP, ENOTSUP },\n};\n\nstatic int errno_to_p9(int err)\n{\n int i;\n if (err == 0)\n return 0;\n for(i = 0; i < countof(errno_table); i++) {\n if (err == errno_table[i][1])\n return errno_table[i][0];\n }\n return P9_EINVAL;\n}\n\nstatic int open_flags[][2] = {\n { P9_O_CREAT, O_CREAT },\n { P9_O_EXCL, O_EXCL },\n // { P9_O_NOCTTY, O_NOCTTY },\n { P9_O_TRUNC, O_TRUNC },\n { P9_O_APPEND, O_APPEND },\n { P9_O_NONBLOCK, O_NONBLOCK },\n { P9_O_DSYNC, O_DSYNC },\n // { P9_O_FASYNC, O_FASYNC },\n // { P9_O_DIRECT, O_DIRECT },\n // { P9_O_LARGEFILE, O_LARGEFILE },\n // { P9_O_DIRECTORY, O_DIRECTORY },\n { P9_O_NOFOLLOW, O_NOFOLLOW },\n // { P9_O_NOATIME, O_NOATIME },\n // { P9_O_CLOEXEC, O_CLOEXEC },\n { P9_O_SYNC, O_SYNC },\n};\n\nstatic int p9_flags_to_host(int flags)\n{\n int ret, i;\n\n ret = (flags & P9_O_NOACCESS);\n for(i = 0; i < countof(open_flags); i++) {\n if (flags & open_flags[i][0])\n ret |= open_flags[i][1];\n }\n return ret;\n}\n\nstatic void stat_to_qid(FSQID *qid, const struct stat *st)\n{\n if (S_ISDIR(st->st_mode))\n qid->type = P9_QTDIR;\n else if (S_ISLNK(st->st_mode))\n qid->type = P9_QTSYMLINK;\n else\n qid->type = P9_QTFILE;\n qid->version = 0; /* no caching on client */\n qid->path = st->st_ino;\n}\n\nstatic void fs_statfs(FSDevice *fs1, FSStatFS *st)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n struct statfs st1;\n statfs(fs->root_path, &st1);\n st->f_bsize = st1.f_bsize;\n st->f_blocks = st1.f_blocks;\n st->f_bfree = st1.f_bfree;\n st->f_bavail = st1.f_bavail;\n st->f_files = st1.f_files;\n st->f_ffree = st1.f_ffree;\n}\n\nstatic char *compose_path(const char *path, const char *name)\n{\n int path_len, name_len;\n char *d;\n\n path_len = strlen(path);\n name_len = strlen(name);\n d = malloc(path_len + 1 + name_len + 1);\n memcpy(d, path, path_len);\n d[path_len] = '/';\n memcpy(d + path_len + 1, name, name_len + 1);\n return d;\n}\n\nstatic int fs_attach(FSDevice *fs1, FSFile **pf,\n FSQID *qid, uint32_t uid,\n const char *uname, const char *aname)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n struct stat st;\n FSFile *f;\n \n if (lstat(fs->root_path, &st) != 0) {\n *pf = NULL;\n return -errno_to_p9(errno);\n }\n f = fid_create(fs1, strdup(fs->root_path), uid);\n stat_to_qid(qid, &st);\n *pf = f;\n return 0;\n}\n\nstatic int fs_walk(FSDevice *fs, FSFile **pf, FSQID *qids,\n FSFile *f, int n, char **names)\n{\n char *path, *path1;\n struct stat st;\n int i;\n\n path = strdup(f->path);\n for(i = 0; i < n; i++) {\n path1 = compose_path(path, names[i]);\n if (lstat(path1, &st) != 0) {\n free(path1);\n break;\n }\n free(path);\n path = path1;\n stat_to_qid(&qids[i], &st);\n }\n *pf = fid_create(fs, path, f->uid);\n return i;\n}\n\n\nstatic int fs_mkdir(FSDevice *fs, FSQID *qid, FSFile *f,\n const char *name, uint32_t mode, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (mkdir(path, mode) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_open(FSDevice *fs, FSQID *qid, FSFile *f, uint32_t flags,\n FSOpenCompletionFunc *cb, void *opaque)\n{\n struct stat st;\n fs_close(fs, f);\n\n if (stat(f->path, &st) != 0) \n return -errno_to_p9(errno);\n stat_to_qid(qid, &st);\n \n if (flags & P9_O_DIRECTORY) {\n DIR *dirp;\n dirp = opendir(f->path);\n if (!dirp)\n return -errno_to_p9(errno);\n f->is_opened = TRUE;\n f->is_dir = TRUE;\n f->u.dirp = dirp;\n } else {\n int fd;\n fd = open(f->path, p9_flags_to_host(flags) & ~O_CREAT);\n if (fd < 0)\n return -errno_to_p9(errno);\n f->is_opened = TRUE;\n f->is_dir = FALSE;\n f->u.fd = fd;\n }\n return 0;\n}\n\nstatic int fs_create(FSDevice *fs, FSQID *qid, FSFile *f, const char *name, \n uint32_t flags, uint32_t mode, uint32_t gid)\n{\n struct stat st;\n char *path;\n int ret, fd;\n\n fs_close(fs, f);\n \n path = compose_path(f->path, name);\n fd = open(path, p9_flags_to_host(flags) | O_CREAT, mode);\n if (fd < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n ret = lstat(path, &st);\n if (ret != 0) {\n free(path);\n close(fd);\n return -errno_to_p9(errno);\n }\n free(f->path);\n f->path = path;\n f->is_opened = TRUE;\n f->is_dir = FALSE;\n f->u.fd = fd;\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_readdir(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n struct dirent *de;\n int len, pos, name_len, type, d_type;\n\n if (!f->is_opened || !f->is_dir)\n return -P9_EPROTO;\n if (offset == 0)\n rewinddir(f->u.dirp);\n else\n seekdir(f->u.dirp, offset);\n pos = 0;\n for(;;) {\n de = readdir(f->u.dirp);\n if (de == NULL)\n break;\n name_len = strlen(de->d_name);\n len = 13 + 8 + 1 + 2 + name_len;\n if ((pos + len) > count)\n break;\n offset = telldir(f->u.dirp);\n d_type = de->d_type;\n if (d_type == DT_UNKNOWN) {\n char *path;\n struct stat st;\n path = compose_path(f->path, de->d_name);\n if (lstat(path, &st) == 0) {\n d_type = st.st_mode >> 12;\n } else {\n d_type = DT_REG; /* default */\n }\n free(path);\n }\n if (d_type == DT_DIR)\n type = P9_QTDIR;\n else if (d_type == DT_LNK)\n type = P9_QTSYMLINK;\n else\n type = P9_QTFILE;\n buf[pos++] = type;\n put_le32(buf + pos, 0); /* version */\n pos += 4;\n put_le64(buf + pos, de->d_ino);\n pos += 8;\n put_le64(buf + pos, offset);\n pos += 8;\n buf[pos++] = d_type;\n put_le16(buf + pos, name_len);\n pos += 2;\n memcpy(buf + pos, de->d_name, name_len);\n pos += name_len;\n }\n return pos;\n}\n\nstatic int fs_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n int ret;\n\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n ret = pread(f->u.fd, buf, count, offset);\n if (ret < 0) \n return -errno_to_p9(errno);\n else\n return ret;\n}\n\nstatic int fs_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int count)\n{\n int ret;\n\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n ret = pwrite(f->u.fd, buf, count, offset);\n if (ret < 0) \n return -errno_to_p9(errno);\n else\n return ret;\n}\n\nstatic void fs_close(FSDevice *fs, FSFile *f)\n{\n if (!f->is_opened)\n return;\n if (f->is_dir)\n closedir(f->u.dirp);\n else\n close(f->u.fd);\n f->is_opened = FALSE;\n}\n\nstatic int fs_stat(FSDevice *fs, FSFile *f, FSStat *st)\n{\n struct stat st1;\n\n if (lstat(f->path, &st1) != 0)\n return -P9_ENOENT;\n stat_to_qid(&st->qid, &st1);\n st->st_mode = st1.st_mode;\n st->st_uid = st1.st_uid;\n st->st_gid = st1.st_gid;\n st->st_nlink = st1.st_nlink;\n st->st_rdev = st1.st_rdev;\n st->st_size = st1.st_size;\n st->st_blksize = st1.st_blksize;\n st->st_blocks = st1.st_blocks;\n st->st_atime_sec = st1.st_atim.tv_sec;\n st->st_atime_nsec = st1.st_atim.tv_nsec;\n st->st_mtime_sec = st1.st_mtim.tv_sec;\n st->st_mtime_nsec = st1.st_mtim.tv_nsec;\n st->st_ctime_sec = st1.st_ctim.tv_sec;\n st->st_ctime_nsec = st1.st_ctim.tv_nsec;\n return 0;\n}\n\nstatic int fs_setattr(FSDevice *fs, FSFile *f, uint32_t mask,\n uint32_t mode, uint32_t uid, uint32_t gid,\n uint64_t size, uint64_t atime_sec, uint64_t atime_nsec,\n uint64_t mtime_sec, uint64_t mtime_nsec)\n{\n BOOL ctime_updated = FALSE;\n\n if (mask & (P9_SETATTR_UID | P9_SETATTR_GID)) {\n if (lchown(f->path, (mask & P9_SETATTR_UID) ? uid : -1,\n (mask & P9_SETATTR_GID) ? gid : -1) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n /* must be done after uid change for suid */\n if (mask & P9_SETATTR_MODE) {\n if (chmod(f->path, mode) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if (mask & P9_SETATTR_SIZE) {\n if (truncate(f->path, size) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if (mask & (P9_SETATTR_ATIME | P9_SETATTR_MTIME)) {\n struct timespec ts[2];\n if (mask & P9_SETATTR_ATIME) {\n if (mask & P9_SETATTR_ATIME_SET) {\n ts[0].tv_sec = atime_sec;\n ts[0].tv_nsec = atime_nsec;\n } else {\n ts[0].tv_sec = 0;\n ts[0].tv_nsec = UTIME_NOW;\n }\n } else {\n ts[0].tv_sec = 0;\n ts[0].tv_nsec = UTIME_OMIT;\n }\n if (mask & P9_SETATTR_MTIME) {\n if (mask & P9_SETATTR_MTIME_SET) {\n ts[1].tv_sec = mtime_sec;\n ts[1].tv_nsec = mtime_nsec;\n } else {\n ts[1].tv_sec = 0;\n ts[1].tv_nsec = UTIME_NOW;\n }\n } else {\n ts[1].tv_sec = 0;\n ts[1].tv_nsec = UTIME_OMIT;\n }\n if (utimensat(AT_FDCWD, f->path, ts, AT_SYMLINK_NOFOLLOW) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if ((mask & P9_SETATTR_CTIME) && !ctime_updated) {\n if (lchown(f->path, -1, -1) < 0)\n return -errno_to_p9(errno);\n }\n return 0;\n}\n\nstatic int fs_link(FSDevice *fs, FSFile *df, FSFile *f, const char *name)\n{\n char *path;\n \n path = compose_path(df->path, name);\n if (link(f->path, path) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n return 0;\n}\n\nstatic int fs_symlink(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, const char *symgt, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (symlink(symgt, path) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_mknod(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, uint32_t mode, uint32_t major,\n uint32_t minor, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (mknod(path, mode, makedev(major, minor)) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_readlink(FSDevice *fs, char *buf, int buf_size, FSFile *f)\n{\n int ret;\n ret = readlink(f->path, buf, buf_size - 1);\n if (ret < 0)\n return -errno_to_p9(errno);\n buf[ret] = '\\0';\n return 0;\n}\n\nstatic int fs_renameat(FSDevice *fs, FSFile *f, const char *name, \n FSFile *new_f, const char *new_name)\n{\n char *path, *new_path;\n int ret;\n\n path = compose_path(f->path, name);\n new_path = compose_path(new_f->path, new_name);\n ret = rename(path, new_path);\n free(path);\n free(new_path);\n if (ret < 0)\n return -errno_to_p9(errno);\n return 0;\n}\n\nstatic int fs_unlinkat(FSDevice *fs, FSFile *f, const char *name)\n{\n char *path;\n int ret;\n\n path = compose_path(f->path, name);\n ret = remove(path);\n free(path);\n if (ret < 0)\n return -errno_to_p9(errno);\n return 0;\n \n}\n\nstatic int fs_lock(FSDevice *fs, FSFile *f, const FSLock *lock)\n{\n int ret;\n struct flock fl;\n \n /* XXX: lock directories too */\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n\n fl.l_type = lock->type;\n fl.l_whence = SEEK_SET;\n fl.l_start = lock->start;\n fl.l_len = lock->length;\n \n ret = fcntl(f->u.fd, F_SETLK, &fl);\n if (ret == 0) {\n ret = P9_LOCK_SUCCESS;\n } else if (errno == EAGAIN || errno == EACCES) {\n ret = P9_LOCK_BLOCKED;\n } else {\n ret = -errno_to_p9(errno);\n }\n return ret;\n}\n\nstatic int fs_getlock(FSDevice *fs, FSFile *f, FSLock *lock)\n{\n int ret;\n struct flock fl;\n \n /* XXX: lock directories too */\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n\n fl.l_type = lock->type;\n fl.l_whence = SEEK_SET;\n fl.l_start = lock->start;\n fl.l_len = lock->length;\n\n ret = fcntl(f->u.fd, F_GETLK, &fl);\n if (ret < 0) {\n ret = -errno_to_p9(errno);\n } else {\n lock->type = fl.l_type;\n lock->start = fl.l_start;\n lock->length = fl.l_len;\n }\n return ret;\n}\n\nstatic void fs_disk_end(FSDevice *fs1)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n free(fs->root_path);\n}\n\nFSDevice *fs_disk_init(const char *root_path)\n{\n FSDeviceDisk *fs;\n struct stat st;\n\n lstat(root_path, &st);\n if (!S_ISDIR(st.st_mode))\n return NULL;\n\n fs = mallocz(sizeof(*fs));\n\n fs->common.fs_end = fs_disk_end;\n fs->common.fs_delete = fs_delete;\n fs->common.fs_statfs = fs_statfs;\n fs->common.fs_attach = fs_attach;\n fs->common.fs_walk = fs_walk;\n fs->common.fs_mkdir = fs_mkdir;\n fs->common.fs_open = fs_open;\n fs->common.fs_create = fs_create;\n fs->common.fs_stat = fs_stat;\n fs->common.fs_setattr = fs_setattr;\n fs->common.fs_close = fs_close;\n fs->common.fs_readdir = fs_readdir;\n fs->common.fs_read = fs_read;\n fs->common.fs_write = fs_write;\n fs->common.fs_link = fs_link;\n fs->common.fs_symlink = fs_symlink;\n fs->common.fs_mknod = fs_mknod;\n fs->common.fs_readlink = fs_readlink;\n fs->common.fs_renameat = fs_renameat;\n fs->common.fs_unlinkat = fs_unlinkat;\n fs->common.fs_lock = fs_lock;\n fs->common.fs_getlock = fs_getlock;\n \n fs->root_path = strdup(root_path);\n return (FSDevice *)fs;\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_subr.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_subr.c\t8.1 (Berkeley) 6/10/93\n * tcp_subr.c,v 1.5 1994/10/08 22:39:58 phk Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n/* patchable/settable parameters for tcp */\n/* Don't do rfc1323 performance enhancements */\n#define TCP_DO_RFC1323 0\n\n/*\n * Tcp initialization\n */\nvoid\ntcp_init(Slirp *slirp)\n{\n slirp->tcp_iss = 1;\t\t/* wrong */\n slirp->tcb.so_next = slirp->tcb.so_prev = &slirp->tcb;\n slirp->tcp_last_so = &slirp->tcb;\n}\n\n/*\n * Create template to be used to send tcp packets on a connection.\n * Call after host entry created, fills\n * in a skeletal tcp/ip header, minimizing the amount of work\n * necessary when the connection is used.\n */\nvoid\ntcp_template(struct tcpcb *tp)\n{\n\tstruct socket *so = tp->t_socket;\n\tregister struct tcpiphdr *n = &tp->t_template;\n\n\tn->ti_mbuf = NULL;\n\tn->ti_x1 = 0;\n\tn->ti_pr = IPPROTO_TCP;\n\tn->ti_len = htons(sizeof (struct tcpiphdr) - sizeof (struct ip));\n\tn->ti_src = so->so_faddr;\n\tn->ti_dst = so->so_laddr;\n\tn->ti_sport = so->so_fport;\n\tn->ti_dport = so->so_lport;\n\n\tn->ti_seq = 0;\n\tn->ti_ack = 0;\n\tn->ti_x2 = 0;\n\tn->ti_off = 5;\n\tn->ti_flags = 0;\n\tn->ti_win = 0;\n\tn->ti_sum = 0;\n\tn->ti_urp = 0;\n}\n\n/*\n * Send a single message to the TCP at address specified by\n * the given TCP/IP header. If m == 0, then we make a copy\n * of the tcpiphdr at ti and send directly to the addressed host.\n * This is used to force keep alive messages out using the TCP\n * template for a connection tp->t_template. If flags are given\n * then we send a message back to the TCP which originated the\n * segment ti, and discard the mbuf containing it and any other\n * attached mbufs.\n *\n * In any case the ack and sequence number of the transmitted\n * segment are as specified by the parameters.\n */\nvoid\ntcp_respond(struct tcpcb *tp, struct tcpiphdr *ti, struct mbuf *m,\n tcp_seq ack, tcp_seq seq, int flags)\n{\n\tregister int tlen;\n\tint win = 0;\n\n\tDEBUG_CALL(\"tcp_respond\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"ti = %lx\", (long)ti);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"ack = %u\", ack);\n\tDEBUG_ARG(\"seq = %u\", seq);\n\tDEBUG_ARG(\"flags = %x\", flags);\n\n\tif (tp)\n\t\twin = sbspace(&tp->t_socket->so_rcv);\n if (m == NULL) {\n\t\tif ((m = m_get(tp->t_socket->slirp)) == NULL)\n\t\t\treturn;\n\t\ttlen = 0;\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\t*mtod(m, struct tcpiphdr *) = *ti;\n\t\tti = mtod(m, struct tcpiphdr *);\n\t\tflags = TH_ACK;\n\t} else {\n\t\t/*\n\t\t * ti points into m so the next line is just making\n\t\t * the mbuf point to ti\n\t\t */\n\t\tm->m_data = (caddr_t)ti;\n\n\t\tm->m_len = sizeof (struct tcpiphdr);\n\t\ttlen = 0;\n#define xchg(a,b,type) { type t; t=a; a=b; b=t; }\n\t\txchg(ti->ti_dst.s_addr, ti->ti_src.s_addr, uint32_t);\n\t\txchg(ti->ti_dport, ti->ti_sport, uint16_t);\n#undef xchg\n\t}\n\tti->ti_len = htons((u_short)(sizeof (struct tcphdr) + tlen));\n\ttlen += sizeof (struct tcpiphdr);\n\tm->m_len = tlen;\n\n ti->ti_mbuf = NULL;\n\tti->ti_x1 = 0;\n\tti->ti_seq = htonl(seq);\n\tti->ti_ack = htonl(ack);\n\tti->ti_x2 = 0;\n\tti->ti_off = sizeof (struct tcphdr) >> 2;\n\tti->ti_flags = flags;\n\tif (tp)\n\t\tti->ti_win = htons((uint16_t) (win >> tp->rcv_scale));\n\telse\n\t\tti->ti_win = htons((uint16_t)win);\n\tti->ti_urp = 0;\n\tti->ti_sum = 0;\n\tti->ti_sum = cksum(m, tlen);\n\t((struct ip *)ti)->ip_len = tlen;\n\n\tif(flags & TH_RST)\n\t ((struct ip *)ti)->ip_ttl = MAXTTL;\n\telse\n\t ((struct ip *)ti)->ip_ttl = IPDEFTTL;\n\n\t(void) ip_output((struct socket *)0, m);\n}\n\n/*\n * Create a new TCP control block, making an\n * empty reassembly queue and hooking it to the argument\n * protocol control block.\n */\nstruct tcpcb *\ntcp_newtcpcb(struct socket *so)\n{\n\tregister struct tcpcb *tp;\n\n\ttp = (struct tcpcb *)malloc(sizeof(*tp));\n\tif (tp == NULL)\n\t\treturn ((struct tcpcb *)0);\n\n\tmemset((char *) tp, 0, sizeof(struct tcpcb));\n\ttp->seg_next = tp->seg_prev = (struct tcpiphdr*)tp;\n\ttp->t_maxseg = TCP_MSS;\n\n\ttp->t_flags = TCP_DO_RFC1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;\n\ttp->t_socket = so;\n\n\t/*\n\t * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no\n\t * rtt estimate. Set rttvar so that srtt + 2 * rttvar gives\n\t * reasonable initial retransmit time.\n\t */\n\ttp->t_srtt = TCPTV_SRTTBASE;\n\ttp->t_rttvar = TCPTV_SRTTDFLT << 2;\n\ttp->t_rttmin = TCPTV_MIN;\n\n\tTCPT_RANGESET(tp->t_rxtcur,\n\t ((TCPTV_SRTTBASE >> 2) + (TCPTV_SRTTDFLT << 2)) >> 1,\n\t TCPTV_MIN, TCPTV_REXMTMAX);\n\n\ttp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;\n\ttp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;\n\ttp->t_state = TCPS_CLOSED;\n\n\tso->so_tcpcb = tp;\n\n\treturn (tp);\n}\n\n/*\n * Drop a TCP connection, reporting\n * the specified error. If connection is synchronized,\n * then send a RST to peer.\n */\nstruct tcpcb *tcp_drop(struct tcpcb *tp, int err)\n{\n\tDEBUG_CALL(\"tcp_drop\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"errno = %d\", errno);\n\n\tif (TCPS_HAVERCVDSYN(tp->t_state)) {\n\t\ttp->t_state = TCPS_CLOSED;\n\t\t(void) tcp_output(tp);\n\t}\n\treturn (tcp_close(tp));\n}\n\n/*\n * Close a TCP control block:\n *\tdiscard all space held by the tcp\n *\tdiscard internet protocol block\n *\twake up any sleepers\n */\nstruct tcpcb *\ntcp_close(struct tcpcb *tp)\n{\n\tregister struct tcpiphdr *t;\n\tstruct socket *so = tp->t_socket;\n\tSlirp *slirp = so->slirp;\n\tregister struct mbuf *m;\n\n\tDEBUG_CALL(\"tcp_close\");\n\tDEBUG_ARG(\"tp = %lx\", (long )tp);\n\n\t/* free the reassembly queue, if any */\n\tt = tcpfrag_list_first(tp);\n\twhile (!tcpfrag_list_end(t, tp)) {\n\t\tt = tcpiphdr_next(t);\n\t\tm = tcpiphdr_prev(t)->ti_mbuf;\n\t\tremque(tcpiphdr2qlink(tcpiphdr_prev(t)));\n\t\tm_freem(m);\n\t}\n\tfree(tp);\n so->so_tcpcb = NULL;\n\t/* clobber input socket cache if we're closing the cached connection */\n\tif (so == slirp->tcp_last_so)\n\t\tslirp->tcp_last_so = &slirp->tcb;\n\tclosesocket(so->s);\n\tsbfree(&so->so_rcv);\n\tsbfree(&so->so_snd);\n\tsofree(so);\n\treturn ((struct tcpcb *)0);\n}\n\n/*\n * TCP protocol interface to socket abstraction.\n */\n\n/*\n * User issued close, and wish to trail through shutdown states:\n * if never received SYN, just forget it. If got a SYN from peer,\n * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.\n * If already got a FIN from peer, then almost done; go to LAST_ACK\n * state. In all other cases, have already sent FIN to peer (e.g.\n * after PRU_SHUTDOWN), and just have to play tedious game waiting\n * for peer to send FIN or not respond to keep-alives, etc.\n * We can let the user exit from the close as soon as the FIN is acked.\n */\nvoid\ntcp_sockclosed(struct tcpcb *tp)\n{\n\n\tDEBUG_CALL(\"tcp_sockclosed\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\n\tswitch (tp->t_state) {\n\n\tcase TCPS_CLOSED:\n\tcase TCPS_LISTEN:\n\tcase TCPS_SYN_SENT:\n\t\ttp->t_state = TCPS_CLOSED;\n\t\ttp = tcp_close(tp);\n\t\tbreak;\n\n\tcase TCPS_SYN_RECEIVED:\n\tcase TCPS_ESTABLISHED:\n\t\ttp->t_state = TCPS_FIN_WAIT_1;\n\t\tbreak;\n\n\tcase TCPS_CLOSE_WAIT:\n\t\ttp->t_state = TCPS_LAST_ACK;\n\t\tbreak;\n\t}\n\tif (tp)\n\t\ttcp_output(tp);\n}\n\n/*\n * Connect to a host on the Internet\n * Called by tcp_input\n * Only do a connect, the tcp fields will be set in tcp_input\n * return 0 if there's a result of the connect,\n * else return -1 means we're still connecting\n * The return value is almost always -1 since the socket is\n * nonblocking. Connect returns after the SYN is sent, and does\n * not wait for ACK+SYN.\n */\nint tcp_fconnect(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n int ret=0;\n\n DEBUG_CALL(\"tcp_fconnect\");\n DEBUG_ARG(\"so = %lx\", (long )so);\n\n if( (ret = so->s = os_socket(AF_INET,SOCK_STREAM,0)) >= 0) {\n int opt, s=so->s;\n struct sockaddr_in addr;\n\n fd_nonblock(s);\n opt = 1;\n setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(opt ));\n opt = 1;\n setsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(opt ));\n\n addr.sin_family = AF_INET;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n /* It's an alias */\n if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\tif (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n } else {\n\taddr.sin_addr = loopback_addr;\n }\n } else\n addr.sin_addr = so->so_faddr;\n addr.sin_port = so->so_fport;\n\n DEBUG_MISC((dfd, \" connect()ing, addr.sin_port=%d, \"\n\t\t\"addr.sin_addr.s_addr=%.16s\\n\",\n\t\tntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));\n /* We don't care what port we get */\n ret = connect(s,(struct sockaddr *)&addr,sizeof (addr));\n\n /*\n * If it's not in progress, it failed, so we just return 0,\n * without clearing SS_NOFDREF\n */\n soisfconnecting(so);\n }\n\n return(ret);\n}\n\n/*\n * Accept the socket and connect to the local-host\n *\n * We have a problem. The correct thing to do would be\n * to first connect to the local-host, and only if the\n * connection is accepted, then do an accept() here.\n * But, a) we need to know who's trying to connect\n * to the socket to be able to SYN the local-host, and\n * b) we are already connected to the foreign host by\n * the time it gets to accept(), so... We simply accept\n * here and SYN the local-host.\n */\nvoid\ntcp_connect(struct socket *inso)\n{\n\tSlirp *slirp = inso->slirp;\n\tstruct socket *so;\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\tstruct tcpcb *tp;\n\tint s, opt;\n\n\tDEBUG_CALL(\"tcp_connect\");\n\tDEBUG_ARG(\"inso = %lx\", (long)inso);\n\n\t/*\n\t * If it's an SS_ACCEPTONCE socket, no need to socreate()\n\t * another socket, just use the accept() socket.\n\t */\n\tif (inso->so_state & SS_FACCEPTONCE) {\n\t\t/* FACCEPTONCE already have a tcpcb */\n\t\tso = inso;\n\t} else {\n\t\tif ((so = socreate(slirp)) == NULL) {\n\t\t\t/* If it failed, get rid of the pending connection */\n\t\t\tclosesocket(accept(inso->s,(struct sockaddr *)&addr,&addrlen));\n\t\t\treturn;\n\t\t}\n\t\tif (tcp_attach(so) < 0) {\n\t\t\tfree(so); /* NOT sofree */\n\t\t\treturn;\n\t\t}\n\t\tso->so_laddr = inso->so_laddr;\n\t\tso->so_lport = inso->so_lport;\n\t}\n\n\t(void) tcp_mss(sototcpcb(so), 0);\n\n\tif ((s = accept(inso->s,(struct sockaddr *)&addr,&addrlen)) < 0) {\n\t\ttcp_close(sototcpcb(so)); /* This will sofree() as well */\n\t\treturn;\n\t}\n\tfd_nonblock(s);\n\topt = 1;\n\tsetsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\topt = 1;\n\tsetsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\topt = 1;\n\tsetsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&opt,sizeof(int));\n\n\tso->so_fport = addr.sin_port;\n\tso->so_faddr = addr.sin_addr;\n\t/* Translate connections from localhost to the real hostname */\n\tif (so->so_faddr.s_addr == 0 || so->so_faddr.s_addr == loopback_addr.s_addr)\n\t so->so_faddr = slirp->vhost_addr;\n\n\t/* Close the accept() socket, set right state */\n\tif (inso->so_state & SS_FACCEPTONCE) {\n\t\tclosesocket(so->s); /* If we only accept once, close the accept() socket */\n\t\tso->so_state = SS_NOFDREF; /* Don't select it yet, even though we have an FD */\n\t\t\t\t\t /* if it's not FACCEPTONCE, it's already NOFDREF */\n\t}\n\tso->s = s;\n\tso->so_state |= SS_INCOMING;\n\n\tso->so_iptos = tcp_tos(so);\n\ttp = sototcpcb(so);\n\n\ttcp_template(tp);\n\n\ttp->t_state = TCPS_SYN_SENT;\n\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\ttp->iss = slirp->tcp_iss;\n\tslirp->tcp_iss += TCP_ISSINCR/2;\n\ttcp_sendseqinit(tp);\n\ttcp_output(tp);\n}\n\n/*\n * Attach a TCPCB to a socket.\n */\nint\ntcp_attach(struct socket *so)\n{\n\tif ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL)\n\t return -1;\n\n\tinsque(so, &so->slirp->tcb);\n\n\treturn 0;\n}\n\n/*\n * Set the socket's type of service field\n */\nstatic const struct tos_t tcptos[] = {\n\t {0, 20, IPTOS_THROUGHPUT, 0},\t/* ftp data */\n\t {21, 21, IPTOS_LOWDELAY, EMU_FTP},\t/* ftp control */\n\t {0, 23, IPTOS_LOWDELAY, 0},\t/* telnet */\n\t {0, 80, IPTOS_THROUGHPUT, 0},\t/* WWW */\n\t {0, 513, IPTOS_LOWDELAY, EMU_RLOGIN|EMU_NOCONNECT},\t/* rlogin */\n\t {0, 514, IPTOS_LOWDELAY, EMU_RSH|EMU_NOCONNECT},\t/* shell */\n\t {0, 544, IPTOS_LOWDELAY, EMU_KSH},\t\t/* kshell */\n\t {0, 543, IPTOS_LOWDELAY, 0},\t/* klogin */\n\t {0, 6667, IPTOS_THROUGHPUT, EMU_IRC},\t/* IRC */\n\t {0, 6668, IPTOS_THROUGHPUT, EMU_IRC},\t/* IRC undernet */\n\t {0, 7070, IPTOS_LOWDELAY, EMU_REALAUDIO }, /* RealAudio control */\n\t {0, 113, IPTOS_LOWDELAY, EMU_IDENT }, /* identd protocol */\n\t {0, 0, 0, 0}\n};\n\nstatic struct emu_t *tcpemu = NULL;\n\n/*\n * Return TOS according to the above table\n */\nuint8_t\ntcp_tos(struct socket *so)\n{\n\tint i = 0;\n\tstruct emu_t *emup;\n\n\twhile(tcptos[i].tos) {\n\t\tif ((tcptos[i].fport && (ntohs(so->so_fport) == tcptos[i].fport)) ||\n\t\t (tcptos[i].lport && (ntohs(so->so_lport) == tcptos[i].lport))) {\n\t\t\tso->so_emu = tcptos[i].emu;\n\t\t\treturn tcptos[i].tos;\n\t\t}\n\t\ti++;\n\t}\n\n\t/* Nope, lets see if there's a user-added one */\n\tfor (emup = tcpemu; emup; emup = emup->next) {\n\t\tif ((emup->fport && (ntohs(so->so_fport) == emup->fport)) ||\n\t\t (emup->lport && (ntohs(so->so_lport) == emup->lport))) {\n\t\t\tso->so_emu = emup->emu;\n\t\t\treturn emup->tos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/*\n * Emulate programs that try and connect to us\n * This includes ftp (the data connection is\n * initiated by the server) and IRC (DCC CHAT and\n * DCC SEND) for now\n *\n * NOTE: It's possible to crash SLiRP by sending it\n * unstandard strings to emulate... if this is a problem,\n * more checks are needed here\n *\n * XXX Assumes the whole command came in one packet\n *\n * XXX Some ftp clients will have their TOS set to\n * LOWDELAY and so Nagel will kick in. Because of this,\n * we'll get the first letter, followed by the rest, so\n * we simply scan for ORT instead of PORT...\n * DCC doesn't have this problem because there's other stuff\n * in the packet before the DCC command.\n *\n * Return 1 if the mbuf m is still valid and should be\n * sbappend()ed\n *\n * NOTE: if you return 0 you MUST m_free() the mbuf!\n */\nint\ntcp_emu(struct socket *so, struct mbuf *m)\n{\n\tSlirp *slirp = so->slirp;\n\tu_int n1, n2, n3, n4, n5, n6;\n char buff[257];\n\tuint32_t laddr;\n\tu_int lport;\n\tchar *bptr;\n\n\tDEBUG_CALL(\"tcp_emu\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n\tswitch(so->so_emu) {\n\t\tint x, i;\n\n\t case EMU_IDENT:\n\t\t/*\n\t\t * Identification protocol as per rfc-1413\n\t\t */\n\n\t\t{\n\t\t\tstruct socket *tmpso;\n\t\t\tstruct sockaddr_in addr;\n\t\t\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\t\t\tstruct sbuf *so_rcv = &so->so_rcv;\n\n\t\t\tmemcpy(so_rcv->sb_wptr, m->m_data, m->m_len);\n\t\t\tso_rcv->sb_wptr += m->m_len;\n\t\t\tso_rcv->sb_rptr += m->m_len;\n\t\t\tm->m_data[m->m_len] = 0; /* NULL terminate */\n\t\t\tif (strchr(m->m_data, '\\r') || strchr(m->m_data, '\\n')) {\n\t\t\t\tif (sscanf(so_rcv->sb_data, \"%u%*[ ,]%u\", &n1, &n2) == 2) {\n\t\t\t\t\tHTONS(n1);\n\t\t\t\t\tHTONS(n2);\n\t\t\t\t\t/* n2 is the one on our host */\n\t\t\t\t\tfor (tmpso = slirp->tcb.so_next;\n\t\t\t\t\t tmpso != &slirp->tcb;\n\t\t\t\t\t tmpso = tmpso->so_next) {\n\t\t\t\t\t\tif (tmpso->so_laddr.s_addr == so->so_laddr.s_addr &&\n\t\t\t\t\t\t tmpso->so_lport == n2 &&\n\t\t\t\t\t\t tmpso->so_faddr.s_addr == so->so_faddr.s_addr &&\n\t\t\t\t\t\t tmpso->so_fport == n1) {\n\t\t\t\t\t\t\tif (getsockname(tmpso->s,\n\t\t\t\t\t\t\t\t(struct sockaddr *)&addr, &addrlen) == 0)\n\t\t\t\t\t\t\t n2 = ntohs(addr.sin_port);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n so_rcv->sb_cc = snprintf(so_rcv->sb_data,\n so_rcv->sb_datalen,\n \"%d,%d\\r\\n\", n1, n2);\n\t\t\t\tso_rcv->sb_rptr = so_rcv->sb_data;\n\t\t\t\tso_rcv->sb_wptr = so_rcv->sb_data + so_rcv->sb_cc;\n\t\t\t}\n\t\t\tm_free(m);\n\t\t\treturn 0;\n\t\t}\n\n case EMU_FTP: /* ftp */\n *(m->m_data+m->m_len) = 0; /* NUL terminate for strstr */\n\t\tif ((bptr = (char *)strstr(m->m_data, \"ORT\")) != NULL) {\n\t\t\t/*\n\t\t\t * Need to emulate the PORT command\n\t\t\t */\n\t\t\tx = sscanf(bptr, \"ORT %u,%u,%u,%u,%u,%u\\r\\n%256[^\\177]\",\n\t\t\t\t &n1, &n2, &n3, &n4, &n5, &n6, buff);\n\t\t\tif (x < 6)\n\t\t\t return 1;\n\n\t\t\tladdr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));\n\t\t\tlport = htons((n5 << 8) | (n6));\n\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr,\n\t\t\t lport, SS_FACCEPTONCE)) == NULL) {\n\t\t\t return 1;\n\t\t\t}\n\t\t\tn6 = ntohs(so->so_fport);\n\n\t\t\tn5 = (n6 >> 8) & 0xff;\n\t\t\tn6 &= 0xff;\n\n\t\t\tladdr = ntohl(so->so_faddr.s_addr);\n\n\t\t\tn1 = ((laddr >> 24) & 0xff);\n\t\t\tn2 = ((laddr >> 16) & 0xff);\n\t\t\tn3 = ((laddr >> 8) & 0xff);\n\t\t\tn4 = (laddr & 0xff);\n\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size - m->m_len,\n \"ORT %d,%d,%d,%d,%d,%d\\r\\n%s\",\n n1, n2, n3, n4, n5, n6, x==7?buff:\"\");\n\t\t\treturn 1;\n\t\t} else if ((bptr = (char *)strstr(m->m_data, \"27 Entering\")) != NULL) {\n\t\t\t/*\n\t\t\t * Need to emulate the PASV response\n\t\t\t */\n\t\t\tx = sscanf(bptr, \"27 Entering Passive Mode (%u,%u,%u,%u,%u,%u)\\r\\n%256[^\\177]\",\n\t\t\t\t &n1, &n2, &n3, &n4, &n5, &n6, buff);\n\t\t\tif (x < 6)\n\t\t\t return 1;\n\n\t\t\tladdr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));\n\t\t\tlport = htons((n5 << 8) | (n6));\n\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr,\n\t\t\t lport, SS_FACCEPTONCE)) == NULL) {\n\t\t\t return 1;\n\t\t\t}\n\t\t\tn6 = ntohs(so->so_fport);\n\n\t\t\tn5 = (n6 >> 8) & 0xff;\n\t\t\tn6 &= 0xff;\n\n\t\t\tladdr = ntohl(so->so_faddr.s_addr);\n\n\t\t\tn1 = ((laddr >> 24) & 0xff);\n\t\t\tn2 = ((laddr >> 16) & 0xff);\n\t\t\tn3 = ((laddr >> 8) & 0xff);\n\t\t\tn4 = (laddr & 0xff);\n\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n\t\t\tm->m_len += snprintf(bptr, m->m_hdr.mh_size - m->m_len,\n \"27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\\r\\n%s\",\n n1, n2, n3, n4, n5, n6, x==7?buff:\"\");\n\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn 1;\n\n\t case EMU_KSH:\n\t\t/*\n\t\t * The kshell (Kerberos rsh) and shell services both pass\n\t\t * a local port port number to carry signals to the server\n\t\t * and stderr to the client. It is passed at the beginning\n\t\t * of the connection as a NUL-terminated decimal ASCII string.\n\t\t */\n\t\tso->so_emu = 0;\n\t\tfor (lport = 0, i = 0; i < m->m_len-1; ++i) {\n\t\t\tif (m->m_data[i] < '0' || m->m_data[i] > '9')\n\t\t\t\treturn 1; /* invalid number */\n\t\t\tlport *= 10;\n\t\t\tlport += m->m_data[i] - '0';\n\t\t}\n\t\tif (m->m_data[m->m_len-1] == '\\0' && lport != 0 &&\n\t\t (so = tcp_listen(slirp, INADDR_ANY, 0, so->so_laddr.s_addr,\n\t\t htons(lport), SS_FACCEPTONCE)) != NULL)\n m->m_len = snprintf(m->m_data, m->m_hdr.mh_size, \"%d\",\n ntohs(so->so_fport)) + 1;\n\t\treturn 1;\n\n\t case EMU_IRC:\n\t\t/*\n\t\t * Need to emulate DCC CHAT, DCC SEND and DCC MOVE\n\t\t */\n\t\t*(m->m_data+m->m_len) = 0; /* NULL terminate the string for strstr */\n\t\tif ((bptr = (char *)strstr(m->m_data, \"DCC\")) == NULL)\n\t\t\t return 1;\n\n\t\t/* The %256s is for the broken mIRC */\n\t\tif (sscanf(bptr, \"DCC CHAT %256s %u %u\", buff, &laddr, &lport) == 3) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC CHAT chat %lu %u%c\\n\",\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), 1);\n\t\t} else if (sscanf(bptr, \"DCC SEND %256s %u %u %u\", buff, &laddr, &lport, &n1) == 4) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC SEND %s %lu %u %u%c\\n\", buff,\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), n1, 1);\n\t\t} else if (sscanf(bptr, \"DCC MOVE %256s %u %u %u\", buff, &laddr, &lport, &n1) == 4) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC MOVE %s %lu %u %u%c\\n\", buff,\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), n1, 1);\n\t\t}\n\t\treturn 1;\n\n\t case EMU_REALAUDIO:\n /*\n\t\t * RealAudio emulation - JP. We must try to parse the incoming\n\t\t * data and try to find the two characters that contain the\n\t\t * port number. Then we redirect an udp port and replace the\n\t\t * number with the real port we got.\n\t\t *\n\t\t * The 1.0 beta versions of the player are not supported\n\t\t * any more.\n\t\t *\n\t\t * A typical packet for player version 1.0 (release version):\n\t\t *\n\t\t * 0000:50 4E 41 00 05\n\t\t * 0000:00 01 00 02 1B D7 00 00 67 E6 6C DC 63 00 12 50 ........g.l.c..P\n\t\t * 0010:4E 43 4C 49 45 4E 54 20 31 30 31 20 41 4C 50 48 NCLIENT 101 ALPH\n\t\t * 0020:41 6C 00 00 52 00 17 72 61 66 69 6C 65 73 2F 76 Al..R..rafiles/v\n\t\t * 0030:6F 61 2F 65 6E 67 6C 69 73 68 5F 2E 72 61 79 42 oa/english_.rayB\n\t\t *\n\t\t * Now the port number 0x1BD7 is found at offset 0x04 of the\n\t\t * Now the port number 0x1BD7 is found at offset 0x04 of the\n\t\t * second packet. This time we received five bytes first and\n\t\t * then the rest. You never know how many bytes you get.\n\t\t *\n\t\t * A typical packet for player version 2.0 (beta):\n\t\t *\n\t\t * 0000:50 4E 41 00 06 00 02 00 00 00 01 00 02 1B C1 00 PNA.............\n\t\t * 0010:00 67 75 78 F5 63 00 0A 57 69 6E 32 2E 30 2E 30 .gux.c..Win2.0.0\n\t\t * 0020:2E 35 6C 00 00 52 00 1C 72 61 66 69 6C 65 73 2F .5l..R..rafiles/\n\t\t * 0030:77 65 62 73 69 74 65 2F 32 30 72 65 6C 65 61 73 website/20releas\n\t\t * 0040:65 2E 72 61 79 53 00 00 06 36 42 e.rayS...6B\n\t\t *\n\t\t * Port number 0x1BC1 is found at offset 0x0d.\n\t\t *\n\t\t * This is just a horrible switch statement. Variable ra tells\n\t\t * us where we're going.\n\t\t */\n\n\t\tbptr = m->m_data;\n\t\twhile (bptr < m->m_data + m->m_len) {\n\t\t\tu_short p;\n\t\t\tstatic int ra = 0;\n\t\t\tchar ra_tbl[4];\n\n\t\t\tra_tbl[0] = 0x50;\n\t\t\tra_tbl[1] = 0x4e;\n\t\t\tra_tbl[2] = 0x41;\n\t\t\tra_tbl[3] = 0;\n\n\t\t\tswitch (ra) {\n\t\t\t case 0:\n\t\t\t case 2:\n\t\t\t case 3:\n\t\t\t\tif (*bptr++ != ra_tbl[ra]) {\n\t\t\t\t\tra = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t case 1:\n\t\t\t\t/*\n\t\t\t\t * We may get 0x50 several times, ignore them\n\t\t\t\t */\n\t\t\t\tif (*bptr == 0x50) {\n\t\t\t\t\tra = 1;\n\t\t\t\t\tbptr++;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (*bptr++ != ra_tbl[ra]) {\n\t\t\t\t\tra = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t case 4:\n\t\t\t\t/*\n\t\t\t\t * skip version number\n\t\t\t\t */\n\t\t\t\tbptr++;\n\t\t\t\tbreak;\n\n\t\t\t case 5:\n\t\t\t\t/*\n\t\t\t\t * The difference between versions 1.0 and\n\t\t\t\t * 2.0 is here. For future versions of\n\t\t\t\t * the player this may need to be modified.\n\t\t\t\t */\n\t\t\t\tif (*(bptr + 1) == 0x02)\n\t\t\t\t bptr += 8;\n\t\t\t\telse\n\t\t\t\t bptr += 4;\n\t\t\t\tbreak;\n\n\t\t\t case 6:\n\t\t\t\t/* This is the field containing the port\n\t\t\t\t * number that RA-player is listening to.\n\t\t\t\t */\n\t\t\t\tlport = (((u_char*)bptr)[0] << 8)\n\t\t\t\t+ ((u_char *)bptr)[1];\n\t\t\t\tif (lport < 6970)\n\t\t\t\t lport += 256; /* don't know why */\n\t\t\t\tif (lport < 6970 || lport > 7170)\n\t\t\t\t return 1; /* failed */\n\n\t\t\t\t/* try to get udp port between 6970 - 7170 */\n\t\t\t\tfor (p = 6970; p < 7071; p++) {\n\t\t\t\t\tif (udp_listen(slirp, INADDR_ANY,\n\t\t\t\t\t\t htons(p),\n\t\t\t\t\t\t so->so_laddr.s_addr,\n\t\t\t\t\t\t htons(lport),\n\t\t\t\t\t\t SS_FACCEPTONCE)) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (p == 7071)\n\t\t\t\t p = 0;\n\t\t\t\t*(u_char *)bptr++ = (p >> 8) & 0xff;\n *(u_char *)bptr = p & 0xff;\n\t\t\t\tra = 0;\n\t\t\t\treturn 1; /* port redirected, we're done */\n\t\t\t\tbreak;\n\n\t\t\t default:\n\t\t\t\tra = 0;\n\t\t\t}\n\t\t\tra++;\n\t\t}\n\t\treturn 1;\n\n\t default:\n\t\t/* Ooops, not emulated, won't call tcp_emu again */\n\t\tso->so_emu = 0;\n\t\treturn 1;\n\t}\n}\n\n/*\n * Do misc. config of SLiRP while its running.\n * Return 0 if this connections is to be closed, 1 otherwise,\n * return 2 if this is a command-line connection\n */\nint tcp_ctl(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n struct sbuf *sb = &so->so_snd;\n struct ex_list *ex_ptr;\n int do_pty;\n\n DEBUG_CALL(\"tcp_ctl\");\n DEBUG_ARG(\"so = %lx\", (long )so);\n\n if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {\n /* Check if it's pty_exec */\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_fport == so->so_fport &&\n so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {\n if (ex_ptr->ex_pty == 3) {\n so->s = -1;\n so->extra = (void *)ex_ptr->ex_exec;\n return 1;\n }\n do_pty = ex_ptr->ex_pty;\n DEBUG_MISC((dfd, \" executing %s \\n\",ex_ptr->ex_exec));\n return fork_exec(so, ex_ptr->ex_exec, do_pty);\n }\n }\n }\n sb->sb_cc =\n snprintf(sb->sb_wptr, sb->sb_datalen - (sb->sb_wptr - sb->sb_data),\n \"Error: No application configured.\\r\\n\");\n sb->sb_wptr += sb->sb_cc;\n return 0;\n}\n"], ["/linuxpdf/tinyemu/slirp/bootp.c", "/*\n * QEMU BOOTP/DHCP server\n *\n * Copyright (c) 2004 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"slirp.h\"\n\n/* XXX: only DHCP is supported */\n\n#define LEASE_TIME (24 * 3600)\n\nstatic const uint8_t rfc1533_cookie[] = { RFC1533_COOKIE };\n\n#ifdef DEBUG\n#define DPRINTF(fmt, ...) \\\ndo if (slirp_debug & DBG_CALL) { fprintf(dfd, fmt, ## __VA_ARGS__); fflush(dfd); } while (0)\n#else\n#define DPRINTF(fmt, ...) do{}while(0)\n#endif\n\nstatic BOOTPClient *get_new_addr(Slirp *slirp, struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n BOOTPClient *bc;\n int i;\n\n for(i = 0; i < NB_BOOTP_CLIENTS; i++) {\n bc = &slirp->bootp_clients[i];\n if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6))\n goto found;\n }\n return NULL;\n found:\n bc = &slirp->bootp_clients[i];\n bc->allocated = 1;\n paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i);\n return bc;\n}\n\nstatic BOOTPClient *request_addr(Slirp *slirp, const struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n uint32_t req_addr = ntohl(paddr->s_addr);\n uint32_t dhcp_addr = ntohl(slirp->vdhcp_startaddr.s_addr);\n BOOTPClient *bc;\n\n if (req_addr >= dhcp_addr &&\n req_addr < (dhcp_addr + NB_BOOTP_CLIENTS)) {\n bc = &slirp->bootp_clients[req_addr - dhcp_addr];\n if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6)) {\n bc->allocated = 1;\n return bc;\n }\n }\n return NULL;\n}\n\nstatic BOOTPClient *find_addr(Slirp *slirp, struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n BOOTPClient *bc;\n int i;\n\n for(i = 0; i < NB_BOOTP_CLIENTS; i++) {\n if (!memcmp(macaddr, slirp->bootp_clients[i].macaddr, 6))\n goto found;\n }\n return NULL;\n found:\n bc = &slirp->bootp_clients[i];\n bc->allocated = 1;\n paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i);\n return bc;\n}\n\nstatic void dhcp_decode(const struct bootp_t *bp, int *pmsg_type,\n struct in_addr *preq_addr)\n{\n const uint8_t *p, *p_end;\n int len, tag;\n\n *pmsg_type = 0;\n preq_addr->s_addr = htonl(0L);\n\n p = bp->bp_vend;\n p_end = p + DHCP_OPT_LEN;\n if (memcmp(p, rfc1533_cookie, 4) != 0)\n return;\n p += 4;\n while (p < p_end) {\n tag = p[0];\n if (tag == RFC1533_PAD) {\n p++;\n } else if (tag == RFC1533_END) {\n break;\n } else {\n p++;\n if (p >= p_end)\n break;\n len = *p++;\n DPRINTF(\"dhcp: tag=%d len=%d\\n\", tag, len);\n\n switch(tag) {\n case RFC2132_MSG_TYPE:\n if (len >= 1)\n *pmsg_type = p[0];\n break;\n case RFC2132_REQ_ADDR:\n if (len >= 4) {\n memcpy(&(preq_addr->s_addr), p, 4);\n }\n break;\n default:\n break;\n }\n p += len;\n }\n }\n if (*pmsg_type == DHCPREQUEST && preq_addr->s_addr == htonl(0L) &&\n bp->bp_ciaddr.s_addr) {\n memcpy(&(preq_addr->s_addr), &bp->bp_ciaddr, 4);\n }\n}\n\nstatic void bootp_reply(Slirp *slirp, const struct bootp_t *bp)\n{\n BOOTPClient *bc = NULL;\n struct mbuf *m;\n struct bootp_t *rbp;\n struct sockaddr_in saddr, daddr;\n struct in_addr preq_addr;\n int dhcp_msg_type, val;\n uint8_t *q;\n\n /* extract exact DHCP msg type */\n dhcp_decode(bp, &dhcp_msg_type, &preq_addr);\n DPRINTF(\"bootp packet op=%d msgtype=%d\", bp->bp_op, dhcp_msg_type);\n if (preq_addr.s_addr != htonl(0L))\n DPRINTF(\" req_addr=%08x\\n\", ntohl(preq_addr.s_addr));\n else\n DPRINTF(\"\\n\");\n\n if (dhcp_msg_type == 0)\n dhcp_msg_type = DHCPREQUEST; /* Force reply for old BOOTP clients */\n\n if (dhcp_msg_type != DHCPDISCOVER &&\n dhcp_msg_type != DHCPREQUEST)\n return;\n /* XXX: this is a hack to get the client mac address */\n memcpy(slirp->client_ethaddr, bp->bp_hwaddr, 6);\n\n m = m_get(slirp);\n if (!m) {\n return;\n }\n m->m_data += IF_MAXLINKHDR;\n rbp = (struct bootp_t *)m->m_data;\n m->m_data += sizeof(struct udpiphdr);\n memset(rbp, 0, sizeof(struct bootp_t));\n\n if (dhcp_msg_type == DHCPDISCOVER) {\n if (preq_addr.s_addr != htonl(0L)) {\n bc = request_addr(slirp, &preq_addr, slirp->client_ethaddr);\n if (bc) {\n daddr.sin_addr = preq_addr;\n }\n }\n if (!bc) {\n new_addr:\n bc = get_new_addr(slirp, &daddr.sin_addr, slirp->client_ethaddr);\n if (!bc) {\n DPRINTF(\"no address left\\n\");\n return;\n }\n }\n memcpy(bc->macaddr, slirp->client_ethaddr, 6);\n } else if (preq_addr.s_addr != htonl(0L)) {\n bc = request_addr(slirp, &preq_addr, slirp->client_ethaddr);\n if (bc) {\n daddr.sin_addr = preq_addr;\n memcpy(bc->macaddr, slirp->client_ethaddr, 6);\n } else {\n daddr.sin_addr.s_addr = 0;\n }\n } else {\n bc = find_addr(slirp, &daddr.sin_addr, bp->bp_hwaddr);\n if (!bc) {\n /* if never assigned, behaves as if it was already\n assigned (windows fix because it remembers its address) */\n goto new_addr;\n }\n }\n\n saddr.sin_addr = slirp->vhost_addr;\n saddr.sin_port = htons(BOOTP_SERVER);\n\n daddr.sin_port = htons(BOOTP_CLIENT);\n\n rbp->bp_op = BOOTP_REPLY;\n rbp->bp_xid = bp->bp_xid;\n rbp->bp_htype = 1;\n rbp->bp_hlen = 6;\n memcpy(rbp->bp_hwaddr, bp->bp_hwaddr, 6);\n\n rbp->bp_yiaddr = daddr.sin_addr; /* Client IP address */\n rbp->bp_siaddr = saddr.sin_addr; /* Server IP address */\n\n q = rbp->bp_vend;\n memcpy(q, rfc1533_cookie, 4);\n q += 4;\n\n if (bc) {\n DPRINTF(\"%s addr=%08x\\n\",\n (dhcp_msg_type == DHCPDISCOVER) ? \"offered\" : \"ack'ed\",\n ntohl(daddr.sin_addr.s_addr));\n\n if (dhcp_msg_type == DHCPDISCOVER) {\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPOFFER;\n } else /* DHCPREQUEST */ {\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPACK;\n }\n\n if (slirp->bootp_filename)\n snprintf((char *)rbp->bp_file, sizeof(rbp->bp_file), \"%s\",\n slirp->bootp_filename);\n\n *q++ = RFC2132_SRV_ID;\n *q++ = 4;\n memcpy(q, &saddr.sin_addr, 4);\n q += 4;\n\n *q++ = RFC1533_NETMASK;\n *q++ = 4;\n memcpy(q, &slirp->vnetwork_mask, 4);\n q += 4;\n\n if (!slirp->restricted) {\n *q++ = RFC1533_GATEWAY;\n *q++ = 4;\n memcpy(q, &saddr.sin_addr, 4);\n q += 4;\n\n *q++ = RFC1533_DNS;\n *q++ = 4;\n memcpy(q, &slirp->vnameserver_addr, 4);\n q += 4;\n }\n\n *q++ = RFC2132_LEASE_TIME;\n *q++ = 4;\n val = htonl(LEASE_TIME);\n memcpy(q, &val, 4);\n q += 4;\n\n if (*slirp->client_hostname) {\n val = strlen(slirp->client_hostname);\n *q++ = RFC1533_HOSTNAME;\n *q++ = val;\n memcpy(q, slirp->client_hostname, val);\n q += val;\n }\n } else {\n static const char nak_msg[] = \"requested address not available\";\n\n DPRINTF(\"nak'ed addr=%08x\\n\", ntohl(preq_addr->s_addr));\n\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPNAK;\n\n *q++ = RFC2132_MESSAGE;\n *q++ = sizeof(nak_msg) - 1;\n memcpy(q, nak_msg, sizeof(nak_msg) - 1);\n q += sizeof(nak_msg) - 1;\n }\n *q = RFC1533_END;\n\n daddr.sin_addr.s_addr = 0xffffffffu;\n\n m->m_len = sizeof(struct bootp_t) -\n sizeof(struct ip) - sizeof(struct udphdr);\n udp_output2(NULL, m, &saddr, &daddr, IPTOS_LOWDELAY);\n}\n\nvoid bootp_input(struct mbuf *m)\n{\n struct bootp_t *bp = mtod(m, struct bootp_t *);\n\n if (bp->bp_op == BOOTP_REQUEST) {\n bootp_reply(m->slirp, bp);\n }\n}\n"], ["/linuxpdf/tinyemu/sdl.c", "/*\n * SDL display driver\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"cutils.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n#define KEYCODE_MAX 127\n\nstatic SDL_Surface *screen;\nstatic SDL_Surface *fb_surface;\nstatic int screen_width, screen_height, fb_width, fb_height, fb_stride;\nstatic SDL_Cursor *sdl_cursor_hidden;\nstatic uint8_t key_pressed[KEYCODE_MAX + 1];\n\nstatic void sdl_update_fb_surface(FBDevice *fb_dev)\n{\n if (!fb_surface)\n goto force_alloc;\n if (fb_width != fb_dev->width ||\n fb_height != fb_dev->height ||\n fb_stride != fb_dev->stride) {\n force_alloc:\n if (fb_surface != NULL)\n SDL_FreeSurface(fb_surface);\n fb_width = fb_dev->width;\n fb_height = fb_dev->height;\n fb_stride = fb_dev->stride;\n fb_surface = SDL_CreateRGBSurfaceFrom(fb_dev->fb_data,\n fb_dev->width, fb_dev->height,\n 32, fb_dev->stride,\n 0x00ff0000,\n 0x0000ff00,\n 0x000000ff,\n 0x00000000);\n if (!fb_surface) {\n fprintf(stderr, \"Could not create SDL framebuffer surface\\n\");\n exit(1);\n }\n }\n}\n\nstatic void sdl_update(FBDevice *fb_dev, void *opaque,\n int x, int y, int w, int h)\n{\n SDL_Rect r;\n // printf(\"sdl_update: %d %d %d %d\\n\", x, y, w, h);\n r.x = x;\n r.y = y;\n r.w = w;\n r.h = h;\n SDL_BlitSurface(fb_surface, &r, screen, &r);\n SDL_UpdateRect(screen, r.x, r.y, r.w, r.h);\n}\n\n#if defined(_WIN32)\n\nstatic int sdl_get_keycode(const SDL_KeyboardEvent *ev)\n{\n return ev->keysym.scancode;\n}\n\n#else\n\n/* we assume Xorg is used with a PC keyboard. Return 0 if no keycode found. */\nstatic int sdl_get_keycode(const SDL_KeyboardEvent *ev)\n{\n int keycode;\n keycode = ev->keysym.scancode;\n if (keycode < 9) {\n keycode = 0;\n } else if (keycode < 127 + 8) {\n keycode -= 8;\n } else {\n keycode = 0;\n }\n return keycode;\n}\n\n#endif\n\n/* release all pressed keys */\nstatic void sdl_reset_keys(VirtMachine *m)\n{\n int i;\n \n for(i = 1; i <= KEYCODE_MAX; i++) {\n if (key_pressed[i]) {\n vm_send_key_event(m, FALSE, i);\n key_pressed[i] = FALSE;\n }\n }\n}\n\nstatic void sdl_handle_key_event(const SDL_KeyboardEvent *ev, VirtMachine *m)\n{\n int keycode, keypress;\n\n keycode = sdl_get_keycode(ev);\n if (keycode) {\n if (keycode == 0x3a || keycode ==0x45) {\n /* SDL does not generate key up for numlock & caps lock */\n vm_send_key_event(m, TRUE, keycode);\n vm_send_key_event(m, FALSE, keycode);\n } else {\n keypress = (ev->type == SDL_KEYDOWN);\n if (keycode <= KEYCODE_MAX)\n key_pressed[keycode] = keypress;\n vm_send_key_event(m, keypress, keycode);\n }\n } else if (ev->type == SDL_KEYUP) {\n /* workaround to reset the keyboard state (used when changing\n desktop with ctrl-alt-x on Linux) */\n sdl_reset_keys(m);\n }\n}\n\nstatic void sdl_send_mouse_event(VirtMachine *m, int x1, int y1,\n int dz, int state, BOOL is_absolute)\n{\n int buttons, x, y;\n\n buttons = 0;\n if (state & SDL_BUTTON(SDL_BUTTON_LEFT))\n buttons |= (1 << 0);\n if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))\n buttons |= (1 << 1);\n if (state & SDL_BUTTON(SDL_BUTTON_MIDDLE))\n buttons |= (1 << 2);\n if (is_absolute) {\n x = (x1 * 32768) / screen_width;\n y = (y1 * 32768) / screen_height;\n } else {\n x = x1;\n y = y1;\n }\n vm_send_mouse_event(m, x, y, dz, buttons);\n}\n\nstatic void sdl_handle_mouse_motion_event(const SDL_Event *ev, VirtMachine *m)\n{\n BOOL is_absolute = vm_mouse_is_absolute(m);\n int x, y;\n if (is_absolute) {\n x = ev->motion.x;\n y = ev->motion.y;\n } else {\n x = ev->motion.xrel;\n y = ev->motion.yrel;\n }\n sdl_send_mouse_event(m, x, y, 0, ev->motion.state, is_absolute);\n}\n\nstatic void sdl_handle_mouse_button_event(const SDL_Event *ev, VirtMachine *m)\n{\n BOOL is_absolute = vm_mouse_is_absolute(m);\n int state, dz;\n\n dz = 0;\n if (ev->type == SDL_MOUSEBUTTONDOWN) {\n if (ev->button.button == SDL_BUTTON_WHEELUP) {\n dz = 1;\n } else if (ev->button.button == SDL_BUTTON_WHEELDOWN) {\n dz = -1;\n }\n }\n \n state = SDL_GetMouseState(NULL, NULL);\n /* just in case */\n if (ev->type == SDL_MOUSEBUTTONDOWN)\n state |= SDL_BUTTON(ev->button.button);\n else\n state &= ~SDL_BUTTON(ev->button.button);\n\n if (is_absolute) {\n sdl_send_mouse_event(m, ev->button.x, ev->button.y,\n dz, state, is_absolute);\n } else {\n sdl_send_mouse_event(m, 0, 0, dz, state, is_absolute);\n }\n}\n\nvoid sdl_refresh(VirtMachine *m)\n{\n SDL_Event ev_s, *ev = &ev_s;\n\n if (!m->fb_dev)\n return;\n \n sdl_update_fb_surface(m->fb_dev);\n\n m->fb_dev->refresh(m->fb_dev, sdl_update, NULL);\n \n while (SDL_PollEvent(ev)) {\n switch (ev->type) {\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n sdl_handle_key_event(&ev->key, m);\n break;\n case SDL_MOUSEMOTION:\n sdl_handle_mouse_motion_event(ev, m);\n break;\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n sdl_handle_mouse_button_event(ev, m);\n break;\n case SDL_QUIT:\n exit(0);\n }\n }\n}\n\nstatic void sdl_hide_cursor(void)\n{\n uint8_t data = 0;\n sdl_cursor_hidden = SDL_CreateCursor(&data, &data, 8, 1, 0, 0);\n SDL_ShowCursor(1);\n SDL_SetCursor(sdl_cursor_hidden);\n}\n\nvoid sdl_init(int width, int height)\n{\n int flags;\n \n screen_width = width;\n screen_height = height;\n\n if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE)) {\n fprintf(stderr, \"Could not initialize SDL - exiting\\n\");\n exit(1);\n }\n\n flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;\n screen = SDL_SetVideoMode(width, height, 0, flags);\n if (!screen || !screen->pixels) {\n fprintf(stderr, \"Could not open SDL display\\n\");\n exit(1);\n }\n\n SDL_WM_SetCaption(\"TinyEMU\", \"TinyEMU\");\n\n sdl_hide_cursor();\n}\n\n"], ["/linuxpdf/tinyemu/json.c", "/*\n * Pseudo JSON parser\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"json.h\"\n#include \"fs_utils.h\"\n\nstatic JSONValue parse_string(const char **pp)\n{\n char buf[4096], *q;\n const char *p;\n int c, h;\n \n q = buf;\n p = *pp;\n p++;\n for(;;) {\n c = *p++;\n if (c == '\\0' || c == '\\n') {\n return json_error_new(\"unterminated string\");\n } else if (c == '\\\"') {\n break;\n } else if (c == '\\\\') {\n c = *p++;\n switch(c) {\n case '\\'':\n case '\\\"':\n case '\\\\':\n goto add_char;\n case 'n':\n c = '\\n';\n goto add_char;\n case 'r':\n c = '\\r';\n goto add_char;\n case 't':\n c = '\\t';\n goto add_char;\n case 'x':\n h = from_hex(*p++);\n if (h < 0)\n return json_error_new(\"invalig hex digit\");\n c = h << 4;\n h = from_hex(*p++);\n if (h < 0)\n return json_error_new(\"invalig hex digit\");\n c |= h;\n goto add_char;\n default:\n return json_error_new(\"unknown escape code\");\n }\n } else {\n add_char:\n if (q >= buf + sizeof(buf) - 1)\n return json_error_new(\"string too long\");\n *q++ = c;\n }\n }\n *q = '\\0';\n *pp = p;\n return json_string_new(buf);\n}\n\nstatic JSONProperty *json_object_get2(JSONObject *obj, const char *name)\n{\n JSONProperty *f;\n int i;\n for(i = 0; i < obj->len; i++) {\n f = &obj->props[i];\n if (!strcmp(f->name.u.str->data, name))\n return f;\n }\n return NULL;\n}\n\nJSONValue json_object_get(JSONValue val, const char *name)\n{\n JSONProperty *f;\n JSONObject *obj;\n \n if (val.type != JSON_OBJ)\n return json_undefined_new();\n obj = val.u.obj;\n f = json_object_get2(obj, name);\n if (!f)\n return json_undefined_new();\n return f->value;\n}\n\nint json_object_set(JSONValue val, const char *name, JSONValue prop_val)\n{\n JSONObject *obj;\n JSONProperty *f;\n int new_size;\n \n if (val.type != JSON_OBJ)\n return -1;\n obj = val.u.obj;\n f = json_object_get2(obj, name);\n if (f) {\n json_free(f->value);\n f->value = prop_val;\n } else {\n if (obj->len >= obj->size) {\n new_size = max_int(obj->len + 1, obj->size * 3 / 2);\n obj->props = realloc(obj->props, new_size * sizeof(JSONProperty));\n obj->size = new_size;\n }\n f = &obj->props[obj->len++];\n f->name = json_string_new(name);\n f->value = prop_val;\n }\n return 0;\n}\n\nJSONValue json_array_get(JSONValue val, unsigned int idx)\n{\n JSONArray *array;\n \n if (val.type != JSON_ARRAY)\n return json_undefined_new();\n array = val.u.array;\n if (idx < array->len) {\n return array->tab[idx];\n } else {\n return json_undefined_new();\n }\n}\n\nint json_array_set(JSONValue val, unsigned int idx, JSONValue prop_val)\n{\n JSONArray *array;\n int new_size;\n \n if (val.type != JSON_ARRAY)\n return -1;\n array = val.u.array;\n if (idx < array->len) {\n json_free(array->tab[idx]);\n array->tab[idx] = prop_val;\n } else if (idx == array->len) {\n if (array->len >= array->size) {\n new_size = max_int(array->len + 1, array->size * 3 / 2);\n array->tab = realloc(array->tab, new_size * sizeof(JSONValue));\n array->size = new_size;\n }\n array->tab[array->len++] = prop_val;\n } else {\n return -1;\n }\n return 0;\n}\n\nconst char *json_get_str(JSONValue val)\n{\n if (val.type != JSON_STR)\n return NULL;\n return val.u.str->data;\n}\n\nconst char *json_get_error(JSONValue val)\n{\n if (val.type != JSON_EXCEPTION)\n return NULL;\n return val.u.str->data;\n}\n\nJSONValue json_string_new2(const char *str, int len)\n{\n JSONValue val;\n JSONString *str1;\n\n str1 = malloc(sizeof(JSONString) + len + 1);\n str1->len = len;\n memcpy(str1->data, str, len + 1);\n val.type = JSON_STR;\n val.u.str = str1;\n return val;\n}\n\nJSONValue json_string_new(const char *str)\n{\n return json_string_new2(str, strlen(str));\n}\n\nJSONValue __attribute__((format(printf, 1, 2))) json_error_new(const char *fmt, ...)\n{\n JSONValue val;\n va_list ap;\n char buf[256];\n \n va_start(ap, fmt);\n vsnprintf(buf, sizeof(buf), fmt, ap);\n va_end(ap);\n val = json_string_new(buf);\n val.type = JSON_EXCEPTION;\n return val;\n}\n\nJSONValue json_object_new(void)\n{\n JSONValue val;\n JSONObject *obj;\n obj = mallocz(sizeof(JSONObject));\n val.type = JSON_OBJ;\n val.u.obj = obj;\n return val;\n}\n\nJSONValue json_array_new(void)\n{\n JSONValue val;\n JSONArray *array;\n array = mallocz(sizeof(JSONArray));\n val.type = JSON_ARRAY;\n val.u.array = array;\n return val;\n}\n\nvoid json_free(JSONValue val)\n{\n switch(val.type) {\n case JSON_STR:\n case JSON_EXCEPTION:\n free(val.u.str);\n break;\n case JSON_INT:\n case JSON_BOOL:\n case JSON_NULL:\n case JSON_UNDEFINED:\n break;\n case JSON_ARRAY:\n {\n JSONArray *array = val.u.array;\n int i;\n \n for(i = 0; i < array->len; i++) {\n json_free(array->tab[i]);\n }\n free(array);\n }\n break;\n case JSON_OBJ:\n {\n JSONObject *obj = val.u.obj;\n JSONProperty *f;\n int i;\n \n for(i = 0; i < obj->len; i++) {\n f = &obj->props[i];\n json_free(f->name);\n json_free(f->value);\n }\n free(obj);\n }\n break;\n default:\n abort();\n }\n}\n\nstatic void skip_spaces(const char **pp)\n{\n const char *p;\n p = *pp;\n for(;;) {\n if (isspace(*p)) {\n p++;\n } else if (p[0] == '/' && p[1] == '/') {\n p += 2;\n while (*p != '\\0' && *p != '\\n')\n p++;\n } else if (p[0] == '/' && p[1] == '*') {\n p += 2;\n while (*p != '\\0' && (p[0] != '*' || p[1] != '/'))\n p++;\n if (*p != '\\0')\n p += 2;\n } else {\n break;\n }\n }\n *pp = p;\n}\n\nstatic inline BOOL is_ident_first(int c)\n{\n return (c >= 'a' && c <= 'z') ||\n (c >= 'A' && c <= 'Z') ||\n c == '_' || c == '$';\n}\n\nstatic int parse_ident(char *buf, int buf_size, const char **pp)\n{\n char *q;\n const char *p;\n p = *pp;\n q = buf;\n *q++ = *p++; /* first char is already tested */\n while (is_ident_first(*p) || isdigit(*p)) {\n if ((q - buf) >= buf_size - 1)\n return -1;\n *q++ = *p++;\n }\n *pp = p;\n *q = '\\0';\n return 0;\n}\n\nJSONValue json_parse_value2(const char **pp)\n{\n char buf[128];\n const char *p;\n JSONValue val, val1, tag;\n \n p = *pp;\n skip_spaces(&p);\n if (*p == '\\0') {\n return json_error_new(\"unexpected end of file\");\n }\n if (isdigit(*p)) {\n val = json_int32_new(strtol(p, (char **)&p, 0));\n } else if (*p == '\"') {\n val = parse_string(&p);\n } else if (*p == '{') {\n p++;\n val = json_object_new();\n for(;;) {\n skip_spaces(&p);\n if (*p == '}') {\n p++;\n break;\n }\n if (*p == '\"') {\n tag = parse_string(&p);\n if (json_is_error(tag))\n return tag;\n } else if (is_ident_first(*p)) {\n if (parse_ident(buf, sizeof(buf), &p) < 0)\n goto invalid_prop;\n tag = json_string_new(buf);\n } else {\n goto invalid_prop;\n }\n // printf(\"property: %s\\n\", json_get_str(tag));\n if (tag.u.str->len == 0) {\n invalid_prop:\n return json_error_new(\"Invalid property name\");\n }\n skip_spaces(&p);\n if (*p != ':') {\n return json_error_new(\"':' expected\");\n }\n p++;\n \n val1 = json_parse_value2(&p);\n json_object_set(val, tag.u.str->data, val1);\n\n skip_spaces(&p);\n if (*p == ',') {\n p++;\n } else if (*p != '}') {\n return json_error_new(\"expecting ',' or '}'\");\n }\n }\n } else if (*p == '[') {\n int idx;\n \n p++;\n val = json_array_new();\n idx = 0;\n for(;;) {\n skip_spaces(&p);\n if (*p == ']') {\n p++;\n break;\n }\n val1 = json_parse_value2(&p);\n json_array_set(val, idx++, val1);\n\n skip_spaces(&p);\n if (*p == ',') {\n p++;\n } else if (*p != ']') {\n return json_error_new(\"expecting ',' or ']'\");\n }\n }\n } else if (is_ident_first(*p)) {\n if (parse_ident(buf, sizeof(buf), &p) < 0)\n goto unknown_id;\n if (!strcmp(buf, \"null\")) {\n val = json_null_new();\n } else if (!strcmp(buf, \"true\")) {\n val = json_bool_new(TRUE);\n } else if (!strcmp(buf, \"false\")) {\n val = json_bool_new(FALSE);\n } else {\n unknown_id:\n return json_error_new(\"unknown identifier: '%s'\", buf);\n }\n } else {\n return json_error_new(\"unexpected character\");\n }\n *pp = p;\n return val;\n}\n\nJSONValue json_parse_value(const char *p)\n{\n JSONValue val;\n val = json_parse_value2(&p); \n if (json_is_error(val))\n return val;\n skip_spaces(&p);\n if (*p != '\\0') {\n json_free(val);\n return json_error_new(\"unexpected characters at the end\");\n }\n return val;\n}\n\nJSONValue json_parse_value_len(const char *p, int len)\n{\n char *str;\n JSONValue val;\n str = malloc(len + 1);\n memcpy(str, p, len);\n str[len] = '\\0';\n val = json_parse_value(str);\n free(str);\n return val;\n}\n"], ["/linuxpdf/tinyemu/slirp/socket.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\nstatic void sofcantrcvmore(struct socket *so);\nstatic void sofcantsendmore(struct socket *so);\n\nstruct socket *\nsolookup(struct socket *head, struct in_addr laddr, u_int lport,\n struct in_addr faddr, u_int fport)\n{\n\tstruct socket *so;\n\n\tfor (so = head->so_next; so != head; so = so->so_next) {\n\t\tif (so->so_lport == lport &&\n\t\t so->so_laddr.s_addr == laddr.s_addr &&\n\t\t so->so_faddr.s_addr == faddr.s_addr &&\n\t\t so->so_fport == fport)\n\t\t break;\n\t}\n\n\tif (so == head)\n\t return (struct socket *)NULL;\n\treturn so;\n\n}\n\n/*\n * Create a new socket, initialise the fields\n * It is the responsibility of the caller to\n * insque() it into the correct linked-list\n */\nstruct socket *\nsocreate(Slirp *slirp)\n{\n struct socket *so;\n\n so = (struct socket *)malloc(sizeof(struct socket));\n if(so) {\n memset(so, 0, sizeof(struct socket));\n so->so_state = SS_NOFDREF;\n so->s = -1;\n so->slirp = slirp;\n }\n return(so);\n}\n\n/*\n * remque and free a socket, clobber cache\n */\nvoid\nsofree(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n\n if (so->so_emu==EMU_RSH && so->extra) {\n\tsofree(so->extra);\n\tso->extra=NULL;\n }\n if (so == slirp->tcp_last_so) {\n slirp->tcp_last_so = &slirp->tcb;\n } else if (so == slirp->udp_last_so) {\n slirp->udp_last_so = &slirp->udb;\n }\n m_free(so->so_m);\n\n if(so->so_next && so->so_prev)\n remque(so); /* crashes if so is not in a queue */\n\n free(so);\n}\n\nsize_t sopreprbuf(struct socket *so, struct iovec *iov, int *np)\n{\n\tint n, lss, total;\n\tstruct sbuf *sb = &so->so_snd;\n\tint len = sb->sb_datalen - sb->sb_cc;\n\tint mss = so->so_tcpcb->t_maxseg;\n\n\tDEBUG_CALL(\"sopreprbuf\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\tif (len <= 0)\n\t\treturn 0;\n\n\tiov[0].iov_base = sb->sb_wptr;\n iov[1].iov_base = NULL;\n iov[1].iov_len = 0;\n\tif (sb->sb_wptr < sb->sb_rptr) {\n\t\tiov[0].iov_len = sb->sb_rptr - sb->sb_wptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len)\n\t\t iov[0].iov_len = len;\n\t\tif (iov[0].iov_len > mss)\n\t\t iov[0].iov_len -= iov[0].iov_len%mss;\n\t\tn = 1;\n\t} else {\n\t\tiov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_wptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tlen -= iov[0].iov_len;\n\t\tif (len) {\n\t\t\tiov[1].iov_base = sb->sb_data;\n\t\t\tiov[1].iov_len = sb->sb_rptr - sb->sb_data;\n\t\t\tif(iov[1].iov_len > len)\n\t\t\t iov[1].iov_len = len;\n\t\t\ttotal = iov[0].iov_len + iov[1].iov_len;\n\t\t\tif (total > mss) {\n\t\t\t\tlss = total%mss;\n\t\t\t\tif (iov[1].iov_len > lss) {\n\t\t\t\t\tiov[1].iov_len -= lss;\n\t\t\t\t\tn = 2;\n\t\t\t\t} else {\n\t\t\t\t\tlss -= iov[1].iov_len;\n\t\t\t\t\tiov[0].iov_len -= lss;\n\t\t\t\t\tn = 1;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tn = 2;\n\t\t} else {\n\t\t\tif (iov[0].iov_len > mss)\n\t\t\t iov[0].iov_len -= iov[0].iov_len%mss;\n\t\t\tn = 1;\n\t\t}\n\t}\n\tif (np)\n\t\t*np = n;\n\n\treturn iov[0].iov_len + (n - 1) * iov[1].iov_len;\n}\n\n/*\n * Read from so's socket into sb_snd, updating all relevant sbuf fields\n * NOTE: This will only be called if it is select()ed for reading, so\n * a read() of 0 (or less) means it's disconnected\n */\nint\nsoread(struct socket *so)\n{\n\tint n, nn;\n\tstruct sbuf *sb = &so->so_snd;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"soread\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\t/*\n\t * No need to check if there's enough room to read.\n\t * soread wouldn't have been called if there weren't\n\t */\n\tsopreprbuf(so, iov, &n);\n\n#ifdef HAVE_READV\n\tnn = readv(so->s, (struct iovec *)iov, n);\n\tDEBUG_MISC((dfd, \" ... read nn = %d bytes\\n\", nn));\n#else\n\tnn = recv(so->s, iov[0].iov_base, iov[0].iov_len,0);\n#endif\n\tif (nn <= 0) {\n\t\tif (nn < 0 && (errno == EINTR || errno == EAGAIN))\n\t\t\treturn 0;\n\t\telse {\n\t\t\tDEBUG_MISC((dfd, \" --- soread() disconnected, nn = %d, errno = %d-%s\\n\", nn, errno,strerror(errno)));\n\t\t\tsofcantrcvmore(so);\n\t\t\ttcp_sockclosed(sototcpcb(so));\n\t\t\treturn -1;\n\t\t}\n\t}\n\n#ifndef HAVE_READV\n\t/*\n\t * If there was no error, try and read the second time round\n\t * We read again if n = 2 (ie, there's another part of the buffer)\n\t * and we read as much as we could in the first read\n\t * We don't test for <= 0 this time, because there legitimately\n\t * might not be any more data (since the socket is non-blocking),\n\t * a close will be detected on next iteration.\n\t * A return of -1 wont (shouldn't) happen, since it didn't happen above\n\t */\n\tif (n == 2 && nn == iov[0].iov_len) {\n int ret;\n ret = recv(so->s, iov[1].iov_base, iov[1].iov_len,0);\n if (ret > 0)\n nn += ret;\n }\n\n\tDEBUG_MISC((dfd, \" ... read nn = %d bytes\\n\", nn));\n#endif\n\n\t/* Update fields */\n\tsb->sb_cc += nn;\n\tsb->sb_wptr += nn;\n\tif (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_wptr -= sb->sb_datalen;\n\treturn nn;\n}\n\nint soreadbuf(struct socket *so, const char *buf, int size)\n{\n int n, nn, copy = size;\n\tstruct sbuf *sb = &so->so_snd;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"soreadbuf\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\t/*\n\t * No need to check if there's enough room to read.\n\t * soread wouldn't have been called if there weren't\n\t */\n\tif (sopreprbuf(so, iov, &n) < size)\n goto err;\n\n nn = min(iov[0].iov_len, copy);\n memcpy(iov[0].iov_base, buf, nn);\n\n copy -= nn;\n buf += nn;\n\n if (copy == 0)\n goto done;\n\n memcpy(iov[1].iov_base, buf, copy);\n\ndone:\n /* Update fields */\n\tsb->sb_cc += size;\n\tsb->sb_wptr += size;\n\tif (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_wptr -= sb->sb_datalen;\n return size;\nerr:\n\n sofcantrcvmore(so);\n tcp_sockclosed(sototcpcb(so));\n fprintf(stderr, \"soreadbuf buffer to small\");\n return -1;\n}\n\n/*\n * Get urgent data\n *\n * When the socket is created, we set it SO_OOBINLINE,\n * so when OOB data arrives, we soread() it and everything\n * in the send buffer is sent as urgent data\n */\nvoid\nsorecvoob(struct socket *so)\n{\n\tstruct tcpcb *tp = sototcpcb(so);\n\n\tDEBUG_CALL(\"sorecvoob\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\t/*\n\t * We take a guess at how much urgent data has arrived.\n\t * In most situations, when urgent data arrives, the next\n\t * read() should get all the urgent data. This guess will\n\t * be wrong however if more data arrives just after the\n\t * urgent data, or the read() doesn't return all the\n\t * urgent data.\n\t */\n\tsoread(so);\n\ttp->snd_up = tp->snd_una + so->so_snd.sb_cc;\n\ttp->t_force = 1;\n\ttcp_output(tp);\n\ttp->t_force = 0;\n}\n\n/*\n * Send urgent data\n * There's a lot duplicated code here, but...\n */\nint\nsosendoob(struct socket *so)\n{\n\tstruct sbuf *sb = &so->so_rcv;\n\tchar buff[2048]; /* XXX Shouldn't be sending more oob data than this */\n\n\tint n, len;\n\n\tDEBUG_CALL(\"sosendoob\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"sb->sb_cc = %d\", sb->sb_cc);\n\n\tif (so->so_urgc > 2048)\n\t so->so_urgc = 2048; /* XXXX */\n\n\tif (sb->sb_rptr < sb->sb_wptr) {\n\t\t/* We can send it directly */\n\t\tn = slirp_send(so, sb->sb_rptr, so->so_urgc, (MSG_OOB)); /* |MSG_DONTWAIT)); */\n\t\tso->so_urgc -= n;\n\n\t\tDEBUG_MISC((dfd, \" --- sent %d bytes urgent data, %d urgent bytes left\\n\", n, so->so_urgc));\n\t} else {\n\t\t/*\n\t\t * Since there's no sendv or sendtov like writev,\n\t\t * we must copy all data to a linear buffer then\n\t\t * send it all\n\t\t */\n\t\tlen = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;\n\t\tif (len > so->so_urgc) len = so->so_urgc;\n\t\tmemcpy(buff, sb->sb_rptr, len);\n\t\tso->so_urgc -= len;\n\t\tif (so->so_urgc) {\n\t\t\tn = sb->sb_wptr - sb->sb_data;\n\t\t\tif (n > so->so_urgc) n = so->so_urgc;\n\t\t\tmemcpy((buff + len), sb->sb_data, n);\n\t\t\tso->so_urgc -= n;\n\t\t\tlen += n;\n\t\t}\n\t\tn = slirp_send(so, buff, len, (MSG_OOB)); /* |MSG_DONTWAIT)); */\n#ifdef DEBUG\n\t\tif (n != len)\n\t\t DEBUG_ERROR((dfd, \"Didn't send all data urgently XXXXX\\n\"));\n#endif\n\t\tDEBUG_MISC((dfd, \" ---2 sent %d bytes urgent data, %d urgent bytes left\\n\", n, so->so_urgc));\n\t}\n\n\tsb->sb_cc -= n;\n\tsb->sb_rptr += n;\n\tif (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n\treturn n;\n}\n\n/*\n * Write data from so_rcv to so's socket,\n * updating all sbuf field as necessary\n */\nint\nsowrite(struct socket *so)\n{\n\tint n,nn;\n\tstruct sbuf *sb = &so->so_rcv;\n\tint len = sb->sb_cc;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"sowrite\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\tif (so->so_urgc) {\n\t\tsosendoob(so);\n\t\tif (sb->sb_cc == 0)\n\t\t\treturn 0;\n\t}\n\n\t/*\n\t * No need to check if there's something to write,\n\t * sowrite wouldn't have been called otherwise\n\t */\n\n\tiov[0].iov_base = sb->sb_rptr;\n iov[1].iov_base = NULL;\n iov[1].iov_len = 0;\n\tif (sb->sb_rptr < sb->sb_wptr) {\n\t\tiov[0].iov_len = sb->sb_wptr - sb->sb_rptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tn = 1;\n\t} else {\n\t\tiov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tlen -= iov[0].iov_len;\n\t\tif (len) {\n\t\t\tiov[1].iov_base = sb->sb_data;\n\t\t\tiov[1].iov_len = sb->sb_wptr - sb->sb_data;\n\t\t\tif (iov[1].iov_len > len) iov[1].iov_len = len;\n\t\t\tn = 2;\n\t\t} else\n\t\t\tn = 1;\n\t}\n\t/* Check if there's urgent data to send, and if so, send it */\n\n#ifdef HAVE_READV\n\tnn = writev(so->s, (const struct iovec *)iov, n);\n\n\tDEBUG_MISC((dfd, \" ... wrote nn = %d bytes\\n\", nn));\n#else\n\tnn = slirp_send(so, iov[0].iov_base, iov[0].iov_len,0);\n#endif\n\t/* This should never happen, but people tell me it does *shrug* */\n\tif (nn < 0 && (errno == EAGAIN || errno == EINTR))\n\t\treturn 0;\n\n\tif (nn <= 0) {\n\t\tDEBUG_MISC((dfd, \" --- sowrite disconnected, so->so_state = %x, errno = %d\\n\",\n\t\t\tso->so_state, errno));\n\t\tsofcantsendmore(so);\n\t\ttcp_sockclosed(sototcpcb(so));\n\t\treturn -1;\n\t}\n\n#ifndef HAVE_READV\n\tif (n == 2 && nn == iov[0].iov_len) {\n int ret;\n ret = slirp_send(so, iov[1].iov_base, iov[1].iov_len,0);\n if (ret > 0)\n nn += ret;\n }\n DEBUG_MISC((dfd, \" ... wrote nn = %d bytes\\n\", nn));\n#endif\n\n\t/* Update sbuf */\n\tsb->sb_cc -= nn;\n\tsb->sb_rptr += nn;\n\tif (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n\t/*\n\t * If in DRAIN mode, and there's no more data, set\n\t * it CANTSENDMORE\n\t */\n\tif ((so->so_state & SS_FWDRAIN) && sb->sb_cc == 0)\n\t\tsofcantsendmore(so);\n\n\treturn nn;\n}\n\n/*\n * recvfrom() a UDP socket\n */\nvoid\nsorecvfrom(struct socket *so)\n{\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\n\tDEBUG_CALL(\"sorecvfrom\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\tif (so->so_type == IPPROTO_ICMP) { /* This is a \"ping\" reply */\n\t char buff[256];\n\t int len;\n\n\t len = recvfrom(so->s, buff, 256, 0,\n\t\t\t (struct sockaddr *)&addr, &addrlen);\n\t /* XXX Check if reply is \"correct\"? */\n\n\t if(len == -1 || len == 0) {\n\t u_char code=ICMP_UNREACH_PORT;\n\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;\n\n\t DEBUG_MISC((dfd,\" udp icmp rx errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));\n\t } else {\n\t icmp_reflect(so->so_m);\n so->so_m = NULL; /* Don't m_free() it again! */\n\t }\n\t /* No need for this socket anymore, udp_detach it */\n\t udp_detach(so);\n\t} else { \t/* A \"normal\" UDP packet */\n\t struct mbuf *m;\n int len;\n#ifdef _WIN32\n unsigned long n;\n#else\n int n;\n#endif\n\n\t m = m_get(so->slirp);\n\t if (!m) {\n\t return;\n\t }\n\t m->m_data += IF_MAXLINKHDR;\n\n\t /*\n\t * XXX Shouldn't FIONREAD packets destined for port 53,\n\t * but I don't know the max packet size for DNS lookups\n\t */\n\t len = M_FREEROOM(m);\n\t /* if (so->so_fport != htons(53)) { */\n\t ioctlsocket(so->s, FIONREAD, &n);\n\n\t if (n > len) {\n\t n = (m->m_data - m->m_dat) + m->m_len + n + 1;\n\t m_inc(m, n);\n\t len = M_FREEROOM(m);\n\t }\n\t /* } */\n\n\t m->m_len = recvfrom(so->s, m->m_data, len, 0,\n\t\t\t (struct sockaddr *)&addr, &addrlen);\n\t DEBUG_MISC((dfd, \" did recvfrom %d, errno = %d-%s\\n\",\n\t\t m->m_len, errno,strerror(errno)));\n\t if(m->m_len<0) {\n\t u_char code=ICMP_UNREACH_PORT;\n\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;\n\n\t DEBUG_MISC((dfd,\" rx error, tx icmp ICMP_UNREACH:%i\\n\", code));\n\t icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));\n\t m_free(m);\n\t } else {\n\t /*\n\t * Hack: domain name lookup will be used the most for UDP,\n\t * and since they'll only be used once there's no need\n\t * for the 4 minute (or whatever) timeout... So we time them\n\t * out much quicker (10 seconds for now...)\n\t */\n\t if (so->so_expire) {\n\t if (so->so_fport == htons(53))\n\t\tso->so_expire = curtime + SO_EXPIREFAST;\n\t else\n\t\tso->so_expire = curtime + SO_EXPIRE;\n\t }\n\n\t /*\n\t * If this packet was destined for CTL_ADDR,\n\t * make it look like that's where it came from, done by udp_output\n\t */\n\t udp_output(so, m, &addr);\n\t } /* rx error */\n\t} /* if ping packet */\n}\n\n/*\n * sendto() a socket\n */\nint\nsosendto(struct socket *so, struct mbuf *m)\n{\n\tSlirp *slirp = so->slirp;\n\tint ret;\n\tstruct sockaddr_in addr;\n\n\tDEBUG_CALL(\"sosendto\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n addr.sin_family = AF_INET;\n\tif ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n\t slirp->vnetwork_addr.s_addr) {\n\t /* It's an alias */\n\t if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\t if (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n\t } else {\n\t addr.sin_addr = loopback_addr;\n\t }\n\t} else\n\t addr.sin_addr = so->so_faddr;\n\taddr.sin_port = so->so_fport;\n\n\tDEBUG_MISC((dfd, \" sendto()ing, addr.sin_port=%d, addr.sin_addr.s_addr=%.16s\\n\", ntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));\n\n\t/* Don't care what port we get */\n\tret = sendto(so->s, m->m_data, m->m_len, 0,\n\t\t (struct sockaddr *)&addr, sizeof (struct sockaddr));\n\tif (ret < 0)\n\t\treturn -1;\n\n\t/*\n\t * Kill the socket if there's no reply in 4 minutes,\n\t * but only if it's an expirable socket\n\t */\n\tif (so->so_expire)\n\t\tso->so_expire = curtime + SO_EXPIRE;\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= SS_ISFCONNECTED; /* So that it gets select()ed */\n\treturn 0;\n}\n\n/*\n * Listen for incoming TCP connections\n */\nstruct socket *\ntcp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,\n u_int lport, int flags)\n{\n\tstruct sockaddr_in addr;\n\tstruct socket *so;\n\tint s, opt = 1;\n\tsocklen_t addrlen = sizeof(addr);\n\tmemset(&addr, 0, addrlen);\n\n\tDEBUG_CALL(\"tcp_listen\");\n\tDEBUG_ARG(\"haddr = %x\", haddr);\n\tDEBUG_ARG(\"hport = %d\", hport);\n\tDEBUG_ARG(\"laddr = %x\", laddr);\n\tDEBUG_ARG(\"lport = %d\", lport);\n\tDEBUG_ARG(\"flags = %x\", flags);\n\n\tso = socreate(slirp);\n\tif (!so) {\n\t return NULL;\n\t}\n\n\t/* Don't tcp_attach... we don't need so_snd nor so_rcv */\n\tif ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL) {\n\t\tfree(so);\n\t\treturn NULL;\n\t}\n\tinsque(so, &slirp->tcb);\n\n\t/*\n\t * SS_FACCEPTONCE sockets must time out.\n\t */\n\tif (flags & SS_FACCEPTONCE)\n\t so->so_tcpcb->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT*2;\n\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= (SS_FACCEPTCONN | flags);\n\tso->so_lport = lport; /* Kept in network format */\n\tso->so_laddr.s_addr = laddr; /* Ditto */\n\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = haddr;\n\taddr.sin_port = hport;\n\n\tif (((s = os_socket(AF_INET,SOCK_STREAM,0)) < 0) ||\n\t (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int)) < 0) ||\n\t (bind(s,(struct sockaddr *)&addr, sizeof(addr)) < 0) ||\n\t (listen(s,1) < 0)) {\n\t\tint tmperrno = errno; /* Don't clobber the real reason we failed */\n\n\t\tclose(s);\n\t\tsofree(so);\n\t\t/* Restore the real errno */\n#ifdef _WIN32\n\t\tWSASetLastError(tmperrno);\n#else\n\t\terrno = tmperrno;\n#endif\n\t\treturn NULL;\n\t}\n\tsetsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\n\tgetsockname(s,(struct sockaddr *)&addr,&addrlen);\n\tso->so_fport = addr.sin_port;\n\tif (addr.sin_addr.s_addr == 0 || addr.sin_addr.s_addr == loopback_addr.s_addr)\n\t so->so_faddr = slirp->vhost_addr;\n\telse\n\t so->so_faddr = addr.sin_addr;\n\n\tso->s = s;\n\treturn so;\n}\n\n/*\n * Various session state calls\n * XXX Should be #define's\n * The socket state stuff needs work, these often get call 2 or 3\n * times each when only 1 was needed\n */\nvoid\nsoisfconnecting(struct socket *so)\n{\n\tso->so_state &= ~(SS_NOFDREF|SS_ISFCONNECTED|SS_FCANTRCVMORE|\n\t\t\t SS_FCANTSENDMORE|SS_FWDRAIN);\n\tso->so_state |= SS_ISFCONNECTING; /* Clobber other states */\n}\n\nvoid\nsoisfconnected(struct socket *so)\n{\n\tso->so_state &= ~(SS_ISFCONNECTING|SS_FWDRAIN|SS_NOFDREF);\n\tso->so_state |= SS_ISFCONNECTED; /* Clobber other states */\n}\n\nstatic void\nsofcantrcvmore(struct socket *so)\n{\n\tif ((so->so_state & SS_NOFDREF) == 0) {\n\t\tshutdown(so->s,0);\n\t\tif(global_writefds) {\n\t\t FD_CLR(so->s,global_writefds);\n\t\t}\n\t}\n\tso->so_state &= ~(SS_ISFCONNECTING);\n\tif (so->so_state & SS_FCANTSENDMORE) {\n\t so->so_state &= SS_PERSISTENT_MASK;\n\t so->so_state |= SS_NOFDREF; /* Don't select it */\n\t} else {\n\t so->so_state |= SS_FCANTRCVMORE;\n\t}\n}\n\nstatic void\nsofcantsendmore(struct socket *so)\n{\n\tif ((so->so_state & SS_NOFDREF) == 0) {\n shutdown(so->s,1); /* send FIN to fhost */\n if (global_readfds) {\n FD_CLR(so->s,global_readfds);\n }\n if (global_xfds) {\n FD_CLR(so->s,global_xfds);\n }\n\t}\n\tso->so_state &= ~(SS_ISFCONNECTING);\n\tif (so->so_state & SS_FCANTRCVMORE) {\n\t so->so_state &= SS_PERSISTENT_MASK;\n\t so->so_state |= SS_NOFDREF; /* as above */\n\t} else {\n\t so->so_state |= SS_FCANTSENDMORE;\n\t}\n}\n\n/*\n * Set write drain mode\n * Set CANTSENDMORE once all data has been write()n\n */\nvoid\nsofwdrain(struct socket *so)\n{\n\tif (so->so_rcv.sb_cc)\n\t\tso->so_state |= SS_FWDRAIN;\n\telse\n\t\tsofcantsendmore(so);\n}\n"], ["/linuxpdf/tinyemu/ps2.c", "/*\n * QEMU PS/2 keyboard/mouse emulation\n *\n * Copyright (c) 2003 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n\n/* debug PC keyboard */\n//#define DEBUG_KBD\n\n/* debug PC keyboard : only mouse */\n//#define DEBUG_MOUSE\n\n/* Keyboard Commands */\n#define KBD_CMD_SET_LEDS\t0xED\t/* Set keyboard leds */\n#define KBD_CMD_ECHO \t0xEE\n#define KBD_CMD_GET_ID \t 0xF2\t/* get keyboard ID */\n#define KBD_CMD_SET_RATE\t0xF3\t/* Set typematic rate */\n#define KBD_CMD_ENABLE\t\t0xF4\t/* Enable scanning */\n#define KBD_CMD_RESET_DISABLE\t0xF5\t/* reset and disable scanning */\n#define KBD_CMD_RESET_ENABLE \t0xF6 /* reset and enable scanning */\n#define KBD_CMD_RESET\t\t0xFF\t/* Reset */\n\n/* Keyboard Replies */\n#define KBD_REPLY_POR\t\t0xAA\t/* Power on reset */\n#define KBD_REPLY_ACK\t\t0xFA\t/* Command ACK */\n#define KBD_REPLY_RESEND\t0xFE\t/* Command NACK, send the cmd again */\n\n/* Mouse Commands */\n#define AUX_SET_SCALE11\t\t0xE6\t/* Set 1:1 scaling */\n#define AUX_SET_SCALE21\t\t0xE7\t/* Set 2:1 scaling */\n#define AUX_SET_RES\t\t0xE8\t/* Set resolution */\n#define AUX_GET_SCALE\t\t0xE9\t/* Get scaling factor */\n#define AUX_SET_STREAM\t\t0xEA\t/* Set stream mode */\n#define AUX_POLL\t\t0xEB\t/* Poll */\n#define AUX_RESET_WRAP\t\t0xEC\t/* Reset wrap mode */\n#define AUX_SET_WRAP\t\t0xEE\t/* Set wrap mode */\n#define AUX_SET_REMOTE\t\t0xF0\t/* Set remote mode */\n#define AUX_GET_TYPE\t\t0xF2\t/* Get type */\n#define AUX_SET_SAMPLE\t\t0xF3\t/* Set sample rate */\n#define AUX_ENABLE_DEV\t\t0xF4\t/* Enable aux device */\n#define AUX_DISABLE_DEV\t\t0xF5\t/* Disable aux device */\n#define AUX_SET_DEFAULT\t\t0xF6\n#define AUX_RESET\t\t0xFF\t/* Reset aux device */\n#define AUX_ACK\t\t\t0xFA\t/* Command byte ACK. */\n\n#define MOUSE_STATUS_REMOTE 0x40\n#define MOUSE_STATUS_ENABLED 0x20\n#define MOUSE_STATUS_SCALE21 0x10\n\n#define PS2_QUEUE_SIZE 256\n\ntypedef struct {\n uint8_t data[PS2_QUEUE_SIZE];\n int rptr, wptr, count;\n} PS2Queue;\n\ntypedef struct {\n PS2Queue queue;\n int32_t write_cmd;\n void (*update_irq)(void *, int);\n void *update_arg;\n} PS2State;\n\nstruct PS2KbdState {\n PS2State common;\n int scan_enabled;\n /* Qemu uses translated PC scancodes internally. To avoid multiple\n conversions we do the translation (if any) in the PS/2 emulation\n not the keyboard controller. */\n int translate;\n};\n\nstruct PS2MouseState {\n PS2State common;\n uint8_t mouse_status;\n uint8_t mouse_resolution;\n uint8_t mouse_sample_rate;\n uint8_t mouse_wrap;\n uint8_t mouse_type; /* 0 = PS2, 3 = IMPS/2, 4 = IMEX */\n uint8_t mouse_detect_state;\n int mouse_dx; /* current values, needed for 'poll' mode */\n int mouse_dy;\n int mouse_dz;\n uint8_t mouse_buttons;\n};\n\nvoid ps2_queue(void *opaque, int b)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q = &s->queue;\n\n if (q->count >= PS2_QUEUE_SIZE)\n return;\n q->data[q->wptr] = b;\n if (++q->wptr == PS2_QUEUE_SIZE)\n q->wptr = 0;\n q->count++;\n s->update_irq(s->update_arg, 1);\n}\n\n#define INPUT_MAKE_KEY_MIN 96\n#define INPUT_MAKE_KEY_MAX 127\n\nstatic const uint8_t linux_input_to_keycode_set1[INPUT_MAKE_KEY_MAX - INPUT_MAKE_KEY_MIN + 1] = {\n 0x1c, 0x1d, 0x35, 0x00, 0x38, 0x00, 0x47, 0x48, \n 0x49, 0x4b, 0x4d, 0x4f, 0x50, 0x51, 0x52, 0x53, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x5b, 0x5c, 0x5d, \n};\n\n/* keycode is a Linux input layer keycode. We only support the PS/2\n keycode set 1 */\nvoid ps2_put_keycode(PS2KbdState *s, BOOL is_down, int keycode)\n{\n if (keycode >= INPUT_MAKE_KEY_MIN) {\n if (keycode > INPUT_MAKE_KEY_MAX)\n return;\n keycode = linux_input_to_keycode_set1[keycode - INPUT_MAKE_KEY_MIN];\n if (keycode == 0)\n return;\n ps2_queue(&s->common, 0xe0);\n }\n ps2_queue(&s->common, keycode | ((!is_down) << 7));\n}\n\nuint32_t ps2_read_data(void *opaque)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q;\n int val, index;\n\n q = &s->queue;\n if (q->count == 0) {\n /* NOTE: if no data left, we return the last keyboard one\n (needed for EMM386) */\n /* XXX: need a timer to do things correctly */\n index = q->rptr - 1;\n if (index < 0)\n index = PS2_QUEUE_SIZE - 1;\n val = q->data[index];\n } else {\n val = q->data[q->rptr];\n if (++q->rptr == PS2_QUEUE_SIZE)\n q->rptr = 0;\n q->count--;\n /* reading deasserts IRQ */\n s->update_irq(s->update_arg, 0);\n /* reassert IRQs if data left */\n s->update_irq(s->update_arg, q->count != 0);\n }\n return val;\n}\n\nstatic void ps2_reset_keyboard(PS2KbdState *s)\n{\n s->scan_enabled = 1;\n}\n\nvoid ps2_write_keyboard(void *opaque, int val)\n{\n PS2KbdState *s = (PS2KbdState *)opaque;\n\n switch(s->common.write_cmd) {\n default:\n case -1:\n switch(val) {\n case 0x00:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case 0x05:\n ps2_queue(&s->common, KBD_REPLY_RESEND);\n break;\n case KBD_CMD_GET_ID:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n ps2_queue(&s->common, 0xab);\n ps2_queue(&s->common, 0x83);\n break;\n case KBD_CMD_ECHO:\n ps2_queue(&s->common, KBD_CMD_ECHO);\n break;\n case KBD_CMD_ENABLE:\n s->scan_enabled = 1;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_SET_LEDS:\n case KBD_CMD_SET_RATE:\n s->common.write_cmd = val;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET_DISABLE:\n ps2_reset_keyboard(s);\n s->scan_enabled = 0;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET_ENABLE:\n ps2_reset_keyboard(s);\n s->scan_enabled = 1;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET:\n ps2_reset_keyboard(s);\n ps2_queue(&s->common, KBD_REPLY_ACK);\n ps2_queue(&s->common, KBD_REPLY_POR);\n break;\n default:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n }\n break;\n case KBD_CMD_SET_LEDS:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n s->common.write_cmd = -1;\n break;\n case KBD_CMD_SET_RATE:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n s->common.write_cmd = -1;\n break;\n }\n}\n\n/* Set the scancode translation mode.\n 0 = raw scancodes.\n 1 = translated scancodes (used by qemu internally). */\n\nvoid ps2_keyboard_set_translation(void *opaque, int mode)\n{\n PS2KbdState *s = (PS2KbdState *)opaque;\n s->translate = mode;\n}\n\nstatic void ps2_mouse_send_packet(PS2MouseState *s)\n{\n unsigned int b;\n int dx1, dy1, dz1;\n\n dx1 = s->mouse_dx;\n dy1 = s->mouse_dy;\n dz1 = s->mouse_dz;\n /* XXX: increase range to 8 bits ? */\n if (dx1 > 127)\n dx1 = 127;\n else if (dx1 < -127)\n dx1 = -127;\n if (dy1 > 127)\n dy1 = 127;\n else if (dy1 < -127)\n dy1 = -127;\n b = 0x08 | ((dx1 < 0) << 4) | ((dy1 < 0) << 5) | (s->mouse_buttons & 0x07);\n ps2_queue(&s->common, b);\n ps2_queue(&s->common, dx1 & 0xff);\n ps2_queue(&s->common, dy1 & 0xff);\n /* extra byte for IMPS/2 or IMEX */\n switch(s->mouse_type) {\n default:\n break;\n case 3:\n if (dz1 > 127)\n dz1 = 127;\n else if (dz1 < -127)\n dz1 = -127;\n ps2_queue(&s->common, dz1 & 0xff);\n break;\n case 4:\n if (dz1 > 7)\n dz1 = 7;\n else if (dz1 < -7)\n dz1 = -7;\n b = (dz1 & 0x0f) | ((s->mouse_buttons & 0x18) << 1);\n ps2_queue(&s->common, b);\n break;\n }\n\n /* update deltas */\n s->mouse_dx -= dx1;\n s->mouse_dy -= dy1;\n s->mouse_dz -= dz1;\n}\n\nvoid ps2_mouse_event(PS2MouseState *s,\n int dx, int dy, int dz, int buttons_state)\n{\n /* check if deltas are recorded when disabled */\n if (!(s->mouse_status & MOUSE_STATUS_ENABLED))\n return;\n\n s->mouse_dx += dx;\n s->mouse_dy -= dy;\n s->mouse_dz += dz;\n /* XXX: SDL sometimes generates nul events: we delete them */\n if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0 &&\n s->mouse_buttons == buttons_state)\n\treturn;\n s->mouse_buttons = buttons_state;\n\n if (!(s->mouse_status & MOUSE_STATUS_REMOTE) &&\n (s->common.queue.count < (PS2_QUEUE_SIZE - 16))) {\n for(;;) {\n /* if not remote, send event. Multiple events are sent if\n too big deltas */\n ps2_mouse_send_packet(s);\n if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0)\n break;\n }\n }\n}\n\nvoid ps2_write_mouse(void *opaque, int val)\n{\n PS2MouseState *s = (PS2MouseState *)opaque;\n#ifdef DEBUG_MOUSE\n printf(\"kbd: write mouse 0x%02x\\n\", val);\n#endif\n switch(s->common.write_cmd) {\n default:\n case -1:\n /* mouse command */\n if (s->mouse_wrap) {\n if (val == AUX_RESET_WRAP) {\n s->mouse_wrap = 0;\n ps2_queue(&s->common, AUX_ACK);\n return;\n } else if (val != AUX_RESET) {\n ps2_queue(&s->common, val);\n return;\n }\n }\n switch(val) {\n case AUX_SET_SCALE11:\n s->mouse_status &= ~MOUSE_STATUS_SCALE21;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_SCALE21:\n s->mouse_status |= MOUSE_STATUS_SCALE21;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_STREAM:\n s->mouse_status &= ~MOUSE_STATUS_REMOTE;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_WRAP:\n s->mouse_wrap = 1;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_REMOTE:\n s->mouse_status |= MOUSE_STATUS_REMOTE;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_GET_TYPE:\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, s->mouse_type);\n break;\n case AUX_SET_RES:\n case AUX_SET_SAMPLE:\n s->common.write_cmd = val;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_GET_SCALE:\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, s->mouse_status);\n ps2_queue(&s->common, s->mouse_resolution);\n ps2_queue(&s->common, s->mouse_sample_rate);\n break;\n case AUX_POLL:\n ps2_queue(&s->common, AUX_ACK);\n ps2_mouse_send_packet(s);\n break;\n case AUX_ENABLE_DEV:\n s->mouse_status |= MOUSE_STATUS_ENABLED;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_DISABLE_DEV:\n s->mouse_status &= ~MOUSE_STATUS_ENABLED;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_DEFAULT:\n s->mouse_sample_rate = 100;\n s->mouse_resolution = 2;\n s->mouse_status = 0;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_RESET:\n s->mouse_sample_rate = 100;\n s->mouse_resolution = 2;\n s->mouse_status = 0;\n s->mouse_type = 0;\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, 0xaa);\n ps2_queue(&s->common, s->mouse_type);\n break;\n default:\n break;\n }\n break;\n case AUX_SET_SAMPLE:\n s->mouse_sample_rate = val;\n /* detect IMPS/2 or IMEX */\n switch(s->mouse_detect_state) {\n default:\n case 0:\n if (val == 200)\n s->mouse_detect_state = 1;\n break;\n case 1:\n if (val == 100)\n s->mouse_detect_state = 2;\n else if (val == 200)\n s->mouse_detect_state = 3;\n else\n s->mouse_detect_state = 0;\n break;\n case 2:\n if (val == 80)\n s->mouse_type = 3; /* IMPS/2 */\n s->mouse_detect_state = 0;\n break;\n case 3:\n if (val == 80)\n s->mouse_type = 4; /* IMEX */\n s->mouse_detect_state = 0;\n break;\n }\n ps2_queue(&s->common, AUX_ACK);\n s->common.write_cmd = -1;\n break;\n case AUX_SET_RES:\n s->mouse_resolution = val;\n ps2_queue(&s->common, AUX_ACK);\n s->common.write_cmd = -1;\n break;\n }\n}\n\nstatic void ps2_reset(void *opaque)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q;\n s->write_cmd = -1;\n q = &s->queue;\n q->rptr = 0;\n q->wptr = 0;\n q->count = 0;\n}\n\nPS2KbdState *ps2_kbd_init(void (*update_irq)(void *, int), void *update_arg)\n{\n PS2KbdState *s = (PS2KbdState *)mallocz(sizeof(PS2KbdState));\n\n s->common.update_irq = update_irq;\n s->common.update_arg = update_arg;\n ps2_reset(&s->common);\n return s;\n}\n\nPS2MouseState *ps2_mouse_init(void (*update_irq)(void *, int), void *update_arg)\n{\n PS2MouseState *s = (PS2MouseState *)mallocz(sizeof(PS2MouseState));\n\n s->common.update_irq = update_irq;\n s->common.update_arg = update_arg;\n ps2_reset(&s->common);\n return s;\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_input.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_input.c\t8.5 (Berkeley) 4/10/94\n * tcp_input.c,v 1.10 1994/10/13 18:36:32 wollman Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n#define\tTCPREXMTTHRESH 3\n\n#define TCP_PAWS_IDLE\t(24 * 24 * 60 * 60 * PR_SLOWHZ)\n\n/* for modulo comparisons of timestamps */\n#define TSTMP_LT(a,b)\t((int)((a)-(b)) < 0)\n#define TSTMP_GEQ(a,b)\t((int)((a)-(b)) >= 0)\n\n/*\n * Insert segment ti into reassembly queue of tcp with\n * control block tp. Return TH_FIN if reassembly now includes\n * a segment with FIN. The macro form does the common case inline\n * (segment is the next to be received on an established connection,\n * and the queue is empty), avoiding linkage into and removal\n * from the queue and repetition of various conversions.\n * Set DELACK for segments received in order, but ack immediately\n * when segments are out of order (so fast retransmit can work).\n */\n#ifdef TCP_ACK_HACK\n#define TCP_REASS(tp, ti, m, so, flags) {\\\n if ((ti)->ti_seq == (tp)->rcv_nxt && \\\n tcpfrag_list_empty(tp) && \\\n (tp)->t_state == TCPS_ESTABLISHED) {\\\n if (ti->ti_flags & TH_PUSH) \\\n tp->t_flags |= TF_ACKNOW; \\\n else \\\n tp->t_flags |= TF_DELACK; \\\n (tp)->rcv_nxt += (ti)->ti_len; \\\n flags = (ti)->ti_flags & TH_FIN; \\\n if (so->so_emu) { \\\n\t\t if (tcp_emu((so),(m))) sbappend((so), (m)); \\\n\t } else \\\n\t \t sbappend((so), (m)); \\\n\t} else {\\\n (flags) = tcp_reass((tp), (ti), (m)); \\\n tp->t_flags |= TF_ACKNOW; \\\n } \\\n}\n#else\n#define\tTCP_REASS(tp, ti, m, so, flags) { \\\n\tif ((ti)->ti_seq == (tp)->rcv_nxt && \\\n tcpfrag_list_empty(tp) && \\\n\t (tp)->t_state == TCPS_ESTABLISHED) { \\\n\t\ttp->t_flags |= TF_DELACK; \\\n\t\t(tp)->rcv_nxt += (ti)->ti_len; \\\n\t\tflags = (ti)->ti_flags & TH_FIN; \\\n\t\tif (so->so_emu) { \\\n\t\t\tif (tcp_emu((so),(m))) sbappend(so, (m)); \\\n\t\t} else \\\n\t\t\tsbappend((so), (m)); \\\n\t} else { \\\n\t\t(flags) = tcp_reass((tp), (ti), (m)); \\\n\t\ttp->t_flags |= TF_ACKNOW; \\\n\t} \\\n}\n#endif\nstatic void tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt,\n struct tcpiphdr *ti);\nstatic void tcp_xmit_timer(register struct tcpcb *tp, int rtt);\n\nstatic int\ntcp_reass(register struct tcpcb *tp, register struct tcpiphdr *ti,\n struct mbuf *m)\n{\n\tregister struct tcpiphdr *q;\n\tstruct socket *so = tp->t_socket;\n\tint flags;\n\n\t/*\n\t * Call with ti==NULL after become established to\n\t * force pre-ESTABLISHED data up to user socket.\n\t */\n if (ti == NULL)\n\t\tgoto present;\n\n\t/*\n\t * Find a segment which begins after this one does.\n\t */\n\tfor (q = tcpfrag_list_first(tp); !tcpfrag_list_end(q, tp);\n q = tcpiphdr_next(q))\n\t\tif (SEQ_GT(q->ti_seq, ti->ti_seq))\n\t\t\tbreak;\n\n\t/*\n\t * If there is a preceding segment, it may provide some of\n\t * our data already. If so, drop the data from the incoming\n\t * segment. If it provides all of our data, drop us.\n\t */\n\tif (!tcpfrag_list_end(tcpiphdr_prev(q), tp)) {\n\t\tregister int i;\n\t\tq = tcpiphdr_prev(q);\n\t\t/* conversion to int (in i) handles seq wraparound */\n\t\ti = q->ti_seq + q->ti_len - ti->ti_seq;\n\t\tif (i > 0) {\n\t\t\tif (i >= ti->ti_len) {\n\t\t\t\tm_freem(m);\n\t\t\t\t/*\n\t\t\t\t * Try to present any queued data\n\t\t\t\t * at the left window edge to the user.\n\t\t\t\t * This is needed after the 3-WHS\n\t\t\t\t * completes.\n\t\t\t\t */\n\t\t\t\tgoto present; /* ??? */\n\t\t\t}\n\t\t\tm_adj(m, i);\n\t\t\tti->ti_len -= i;\n\t\t\tti->ti_seq += i;\n\t\t}\n\t\tq = tcpiphdr_next(q);\n\t}\n\tti->ti_mbuf = m;\n\n\t/*\n\t * While we overlap succeeding segments trim them or,\n\t * if they are completely covered, dequeue them.\n\t */\n\twhile (!tcpfrag_list_end(q, tp)) {\n\t\tregister int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;\n\t\tif (i <= 0)\n\t\t\tbreak;\n\t\tif (i < q->ti_len) {\n\t\t\tq->ti_seq += i;\n\t\t\tq->ti_len -= i;\n\t\t\tm_adj(q->ti_mbuf, i);\n\t\t\tbreak;\n\t\t}\n\t\tq = tcpiphdr_next(q);\n\t\tm = tcpiphdr_prev(q)->ti_mbuf;\n\t\tremque(tcpiphdr2qlink(tcpiphdr_prev(q)));\n\t\tm_freem(m);\n\t}\n\n\t/*\n\t * Stick new segment in its place.\n\t */\n\tinsque(tcpiphdr2qlink(ti), tcpiphdr2qlink(tcpiphdr_prev(q)));\n\npresent:\n\t/*\n\t * Present data to user, advancing rcv_nxt through\n\t * completed sequence space.\n\t */\n\tif (!TCPS_HAVEESTABLISHED(tp->t_state))\n\t\treturn (0);\n\tti = tcpfrag_list_first(tp);\n\tif (tcpfrag_list_end(ti, tp) || ti->ti_seq != tp->rcv_nxt)\n\t\treturn (0);\n\tif (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)\n\t\treturn (0);\n\tdo {\n\t\ttp->rcv_nxt += ti->ti_len;\n\t\tflags = ti->ti_flags & TH_FIN;\n\t\tremque(tcpiphdr2qlink(ti));\n\t\tm = ti->ti_mbuf;\n\t\tti = tcpiphdr_next(ti);\n\t\tif (so->so_state & SS_FCANTSENDMORE)\n\t\t\tm_freem(m);\n\t\telse {\n\t\t\tif (so->so_emu) {\n\t\t\t\tif (tcp_emu(so,m)) sbappend(so, m);\n\t\t\t} else\n\t\t\t\tsbappend(so, m);\n\t\t}\n\t} while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);\n\treturn (flags);\n}\n\n/*\n * TCP input routine, follows pages 65-76 of the\n * protocol specification dated September, 1981 very closely.\n */\nvoid\ntcp_input(struct mbuf *m, int iphlen, struct socket *inso)\n{\n \tstruct ip save_ip, *ip;\n\tregister struct tcpiphdr *ti;\n\tcaddr_t optp = NULL;\n\tint optlen = 0;\n\tint len, tlen, off;\n register struct tcpcb *tp = NULL;\n\tregister int tiflags;\n struct socket *so = NULL;\n\tint todrop, acked, ourfinisacked, needoutput = 0;\n\tint iss = 0;\n\tu_long tiwin;\n\tint ret;\n struct ex_list *ex_ptr;\n Slirp *slirp;\n\n\tDEBUG_CALL(\"tcp_input\");\n\tDEBUG_ARGS((dfd,\" m = %8lx iphlen = %2d inso = %lx\\n\",\n\t\t (long )m, iphlen, (long )inso ));\n\n\t/*\n\t * If called with m == 0, then we're continuing the connect\n\t */\n\tif (m == NULL) {\n\t\tso = inso;\n\t\tslirp = so->slirp;\n\n\t\t/* Re-set a few variables */\n\t\ttp = sototcpcb(so);\n\t\tm = so->so_m;\n so->so_m = NULL;\n\t\tti = so->so_ti;\n\t\ttiwin = ti->ti_win;\n\t\ttiflags = ti->ti_flags;\n\n\t\tgoto cont_conn;\n\t}\n\tslirp = m->slirp;\n\n\t/*\n\t * Get IP and TCP header together in first mbuf.\n\t * Note: IP leaves IP header in first mbuf.\n\t */\n\tti = mtod(m, struct tcpiphdr *);\n\tif (iphlen > sizeof(struct ip )) {\n\t ip_stripoptions(m, (struct mbuf *)0);\n\t iphlen=sizeof(struct ip );\n\t}\n\t/* XXX Check if too short */\n\n\n\t/*\n\t * Save a copy of the IP header in case we want restore it\n\t * for sending an ICMP error message in response.\n\t */\n\tip=mtod(m, struct ip *);\n\tsave_ip = *ip;\n\tsave_ip.ip_len+= iphlen;\n\n\t/*\n\t * Checksum extended TCP header and data.\n\t */\n\ttlen = ((struct ip *)ti)->ip_len;\n tcpiphdr2qlink(ti)->next = tcpiphdr2qlink(ti)->prev = NULL;\n memset(&ti->ti_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));\n\tti->ti_x1 = 0;\n\tti->ti_len = htons((uint16_t)tlen);\n\tlen = sizeof(struct ip ) + tlen;\n\tif(cksum(m, len)) {\n\t goto drop;\n\t}\n\n\t/*\n\t * Check that TCP offset makes sense,\n\t * pull out TCP options and adjust length.\t\tXXX\n\t */\n\toff = ti->ti_off << 2;\n\tif (off < sizeof (struct tcphdr) || off > tlen) {\n\t goto drop;\n\t}\n\ttlen -= off;\n\tti->ti_len = tlen;\n\tif (off > sizeof (struct tcphdr)) {\n\t optlen = off - sizeof (struct tcphdr);\n\t optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);\n\t}\n\ttiflags = ti->ti_flags;\n\n\t/*\n\t * Convert TCP protocol specific fields to host format.\n\t */\n\tNTOHL(ti->ti_seq);\n\tNTOHL(ti->ti_ack);\n\tNTOHS(ti->ti_win);\n\tNTOHS(ti->ti_urp);\n\n\t/*\n\t * Drop TCP, IP headers and TCP options.\n\t */\n\tm->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\tm->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\n if (slirp->restricted) {\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_fport == ti->ti_dport &&\n ti->ti_dst.s_addr == ex_ptr->ex_addr.s_addr) {\n break;\n }\n }\n if (!ex_ptr)\n goto drop;\n }\n\t/*\n\t * Locate pcb for segment.\n\t */\nfindso:\n\tso = slirp->tcp_last_so;\n\tif (so->so_fport != ti->ti_dport ||\n\t so->so_lport != ti->ti_sport ||\n\t so->so_laddr.s_addr != ti->ti_src.s_addr ||\n\t so->so_faddr.s_addr != ti->ti_dst.s_addr) {\n\t\tso = solookup(&slirp->tcb, ti->ti_src, ti->ti_sport,\n\t\t\t ti->ti_dst, ti->ti_dport);\n\t\tif (so)\n\t\t\tslirp->tcp_last_so = so;\n\t}\n\n\t/*\n\t * If the state is CLOSED (i.e., TCB does not exist) then\n\t * all data in the incoming segment is discarded.\n\t * If the TCB exists but is in CLOSED state, it is embryonic,\n\t * but should either do a listen or a connect soon.\n\t *\n\t * state == CLOSED means we've done socreate() but haven't\n\t * attached it to a protocol yet...\n\t *\n\t * XXX If a TCB does not exist, and the TH_SYN flag is\n\t * the only flag set, then create a session, mark it\n\t * as if it was LISTENING, and continue...\n\t */\n if (so == NULL) {\n\t if ((tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) != TH_SYN)\n\t goto dropwithreset;\n\n\t if ((so = socreate(slirp)) == NULL)\n\t goto dropwithreset;\n\t if (tcp_attach(so) < 0) {\n\t free(so); /* Not sofree (if it failed, it's not insqued) */\n\t goto dropwithreset;\n\t }\n\n\t sbreserve(&so->so_snd, TCP_SNDSPACE);\n\t sbreserve(&so->so_rcv, TCP_RCVSPACE);\n\n\t so->so_laddr = ti->ti_src;\n\t so->so_lport = ti->ti_sport;\n\t so->so_faddr = ti->ti_dst;\n\t so->so_fport = ti->ti_dport;\n\n\t if ((so->so_iptos = tcp_tos(so)) == 0)\n\t so->so_iptos = ((struct ip *)ti)->ip_tos;\n\n\t tp = sototcpcb(so);\n\t tp->t_state = TCPS_LISTEN;\n\t}\n\n /*\n * If this is a still-connecting socket, this probably\n * a retransmit of the SYN. Whether it's a retransmit SYN\n\t * or something else, we nuke it.\n */\n if (so->so_state & SS_ISFCONNECTING)\n goto drop;\n\n\ttp = sototcpcb(so);\n\n\t/* XXX Should never fail */\n if (tp == NULL)\n\t\tgoto dropwithreset;\n\tif (tp->t_state == TCPS_CLOSED)\n\t\tgoto drop;\n\n\ttiwin = ti->ti_win;\n\n\t/*\n\t * Segment received on connection.\n\t * Reset idle time and keep-alive timer.\n\t */\n\ttp->t_idle = 0;\n\tif (SO_OPTIONS)\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;\n\telse\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;\n\n\t/*\n\t * Process options if not in LISTEN state,\n\t * else do it below (after getting remote address).\n\t */\n\tif (optp && tp->t_state != TCPS_LISTEN)\n\t\ttcp_dooptions(tp, (u_char *)optp, optlen, ti);\n\n\t/*\n\t * Header prediction: check for the two common cases\n\t * of a uni-directional data xfer. If the packet has\n\t * no control flags, is in-sequence, the window didn't\n\t * change and we're not retransmitting, it's a\n\t * candidate. If the length is zero and the ack moved\n\t * forward, we're the sender side of the xfer. Just\n\t * free the data acked & wake any higher level process\n\t * that was blocked waiting for space. If the length\n\t * is non-zero and the ack didn't move, we're the\n\t * receiver side. If we're getting packets in-order\n\t * (the reassembly queue is empty), add the data to\n\t * the socket buffer and note that we need a delayed ack.\n\t *\n\t * XXX Some of these tests are not needed\n\t * eg: the tiwin == tp->snd_wnd prevents many more\n\t * predictions.. with no *real* advantage..\n\t */\n\tif (tp->t_state == TCPS_ESTABLISHED &&\n\t (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&\n\t ti->ti_seq == tp->rcv_nxt &&\n\t tiwin && tiwin == tp->snd_wnd &&\n\t tp->snd_nxt == tp->snd_max) {\n\t\tif (ti->ti_len == 0) {\n\t\t\tif (SEQ_GT(ti->ti_ack, tp->snd_una) &&\n\t\t\t SEQ_LEQ(ti->ti_ack, tp->snd_max) &&\n\t\t\t tp->snd_cwnd >= tp->snd_wnd) {\n\t\t\t\t/*\n\t\t\t\t * this is a pure ack for outstanding data.\n\t\t\t\t */\n\t\t\t\tif (tp->t_rtt &&\n\t\t\t\t SEQ_GT(ti->ti_ack, tp->t_rtseq))\n\t\t\t\t\ttcp_xmit_timer(tp, tp->t_rtt);\n\t\t\t\tacked = ti->ti_ack - tp->snd_una;\n\t\t\t\tsbdrop(&so->so_snd, acked);\n\t\t\t\ttp->snd_una = ti->ti_ack;\n\t\t\t\tm_freem(m);\n\n\t\t\t\t/*\n\t\t\t\t * If all outstanding data are acked, stop\n\t\t\t\t * retransmit timer, otherwise restart timer\n\t\t\t\t * using current (possibly backed-off) value.\n\t\t\t\t * If process is waiting for space,\n\t\t\t\t * wakeup/selwakeup/signal. If data\n\t\t\t\t * are ready to send, let tcp_output\n\t\t\t\t * decide between more output or persist.\n\t\t\t\t */\n\t\t\t\tif (tp->snd_una == tp->snd_max)\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\t\telse if (tp->t_timer[TCPT_PERSIST] == 0)\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\n\t\t\t\t/*\n\t\t\t\t * This is called because sowwakeup might have\n\t\t\t\t * put data into so_snd. Since we don't so sowwakeup,\n\t\t\t\t * we don't need this.. XXX???\n\t\t\t\t */\n\t\t\t\tif (so->so_snd.sb_cc)\n\t\t\t\t\t(void) tcp_output(tp);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (ti->ti_ack == tp->snd_una &&\n\t\t tcpfrag_list_empty(tp) &&\n\t\t ti->ti_len <= sbspace(&so->so_rcv)) {\n\t\t\t/*\n\t\t\t * this is a pure, in-sequence data packet\n\t\t\t * with nothing on the reassembly queue and\n\t\t\t * we have enough buffer space to take it.\n\t\t\t */\n\t\t\ttp->rcv_nxt += ti->ti_len;\n\t\t\t/*\n\t\t\t * Add data to socket buffer.\n\t\t\t */\n\t\t\tif (so->so_emu) {\n\t\t\t\tif (tcp_emu(so,m)) sbappend(so, m);\n\t\t\t} else\n\t\t\t\tsbappend(so, m);\n\n\t\t\t/*\n\t\t\t * If this is a short packet, then ACK now - with Nagel\n\t\t\t *\tcongestion avoidance sender won't send more until\n\t\t\t *\the gets an ACK.\n\t\t\t *\n\t\t\t * It is better to not delay acks at all to maximize\n\t\t\t * TCP throughput. See RFC 2581.\n\t\t\t */\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttcp_output(tp);\n\t\t\treturn;\n\t\t}\n\t} /* header prediction */\n\t/*\n\t * Calculate amount of space in receive window,\n\t * and then do TCP input processing.\n\t * Receive window is amount of space in rcv queue,\n\t * but not less than advertised window.\n\t */\n\t{ int win;\n win = sbspace(&so->so_rcv);\n\t if (win < 0)\n\t win = 0;\n\t tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));\n\t}\n\n\tswitch (tp->t_state) {\n\n\t/*\n\t * If the state is LISTEN then ignore segment if it contains an RST.\n\t * If the segment contains an ACK then it is bad and send a RST.\n\t * If it does not contain a SYN then it is not interesting; drop it.\n\t * Don't bother responding if the destination was a broadcast.\n\t * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial\n\t * tp->iss, and send a segment:\n\t * \n\t * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.\n\t * Fill in remote peer address fields if not previously specified.\n\t * Enter SYN_RECEIVED state, and process any other fields of this\n\t * segment in this state.\n\t */\n\tcase TCPS_LISTEN: {\n\n\t if (tiflags & TH_RST)\n\t goto drop;\n\t if (tiflags & TH_ACK)\n\t goto dropwithreset;\n\t if ((tiflags & TH_SYN) == 0)\n\t goto drop;\n\n\t /*\n\t * This has way too many gotos...\n\t * But a bit of spaghetti code never hurt anybody :)\n\t */\n\n\t /*\n\t * If this is destined for the control address, then flag to\n\t * tcp_ctl once connected, otherwise connect\n\t */\n\t if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n\t slirp->vnetwork_addr.s_addr) {\n\t if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr &&\n\t\tso->so_faddr.s_addr != slirp->vnameserver_addr.s_addr) {\n\t\t/* May be an add exec */\n\t\tfor (ex_ptr = slirp->exec_list; ex_ptr;\n\t\t ex_ptr = ex_ptr->ex_next) {\n\t\t if(ex_ptr->ex_fport == so->so_fport &&\n\t\t so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {\n\t\t so->so_state |= SS_CTL;\n\t\t break;\n\t\t }\n\t\t}\n\t\tif (so->so_state & SS_CTL) {\n\t\t goto cont_input;\n\t\t}\n\t }\n\t /* CTL_ALIAS: Do nothing, tcp_fconnect will be called on it */\n\t }\n\n\t if (so->so_emu & EMU_NOCONNECT) {\n\t so->so_emu &= ~EMU_NOCONNECT;\n\t goto cont_input;\n\t }\n\n\t if((tcp_fconnect(so) == -1) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK)) {\n\t u_char code=ICMP_UNREACH_NET;\n\t DEBUG_MISC((dfd,\" tcp fconnect errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t if(errno == ECONNREFUSED) {\n\t /* ACK the SYN, send RST to refuse the connection */\n\t tcp_respond(tp, ti, m, ti->ti_seq+1, (tcp_seq)0,\n\t\t\t TH_RST|TH_ACK);\n\t } else {\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t HTONL(ti->ti_seq); /* restore tcp header */\n\t HTONL(ti->ti_ack);\n\t HTONS(ti->ti_win);\n\t HTONS(ti->ti_urp);\n\t m->m_data -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\t m->m_len += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\t *ip=save_ip;\n\t icmp_error(m, ICMP_UNREACH,code, 0,strerror(errno));\n\t }\n tcp_close(tp);\n\t m_free(m);\n\t } else {\n\t /*\n\t * Haven't connected yet, save the current mbuf\n\t * and ti, and return\n\t * XXX Some OS's don't tell us whether the connect()\n\t * succeeded or not. So we must time it out.\n\t */\n\t so->so_m = m;\n\t so->so_ti = ti;\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\t tp->t_state = TCPS_SYN_RECEIVED;\n\t }\n\t return;\n\n\tcont_conn:\n\t /* m==NULL\n\t * Check if the connect succeeded\n\t */\n\t if (so->so_state & SS_NOFDREF) {\n\t tp = tcp_close(tp);\n\t goto dropwithreset;\n\t }\n\tcont_input:\n\t tcp_template(tp);\n\n\t if (optp)\n\t tcp_dooptions(tp, (u_char *)optp, optlen, ti);\n\n\t if (iss)\n\t tp->iss = iss;\n\t else\n\t tp->iss = slirp->tcp_iss;\n\t slirp->tcp_iss += TCP_ISSINCR/2;\n\t tp->irs = ti->ti_seq;\n\t tcp_sendseqinit(tp);\n\t tcp_rcvseqinit(tp);\n\t tp->t_flags |= TF_ACKNOW;\n\t tp->t_state = TCPS_SYN_RECEIVED;\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\t goto trimthenstep6;\n\t} /* case TCPS_LISTEN */\n\n\t/*\n\t * If the state is SYN_SENT:\n\t *\tif seg contains an ACK, but not for our SYN, drop the input.\n\t *\tif seg contains a RST, then drop the connection.\n\t *\tif seg does not contain SYN, then drop it.\n\t * Otherwise this is an acceptable SYN segment\n\t *\tinitialize tp->rcv_nxt and tp->irs\n\t *\tif seg contains ack then advance tp->snd_una\n\t *\tif SYN has been acked change to ESTABLISHED else SYN_RCVD state\n\t *\tarrange for segment to be acked (eventually)\n\t *\tcontinue processing rest of data/controls, beginning with URG\n\t */\n\tcase TCPS_SYN_SENT:\n\t\tif ((tiflags & TH_ACK) &&\n\t\t (SEQ_LEQ(ti->ti_ack, tp->iss) ||\n\t\t SEQ_GT(ti->ti_ack, tp->snd_max)))\n\t\t\tgoto dropwithreset;\n\n\t\tif (tiflags & TH_RST) {\n if (tiflags & TH_ACK) {\n tcp_drop(tp, 0); /* XXX Check t_softerror! */\n }\n\t\t\tgoto drop;\n\t\t}\n\n\t\tif ((tiflags & TH_SYN) == 0)\n\t\t\tgoto drop;\n\t\tif (tiflags & TH_ACK) {\n\t\t\ttp->snd_una = ti->ti_ack;\n\t\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_una))\n\t\t\t\ttp->snd_nxt = tp->snd_una;\n\t\t}\n\n\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\ttp->irs = ti->ti_seq;\n\t\ttcp_rcvseqinit(tp);\n\t\ttp->t_flags |= TF_ACKNOW;\n\t\tif (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {\n\t\t\tsoisfconnected(so);\n\t\t\ttp->t_state = TCPS_ESTABLISHED;\n\n\t\t\t(void) tcp_reass(tp, (struct tcpiphdr *)0,\n\t\t\t\t(struct mbuf *)0);\n\t\t\t/*\n\t\t\t * if we didn't have to retransmit the SYN,\n\t\t\t * use its rtt as our initial srtt & rtt var.\n\t\t\t */\n\t\t\tif (tp->t_rtt)\n\t\t\t\ttcp_xmit_timer(tp, tp->t_rtt);\n\t\t} else\n\t\t\ttp->t_state = TCPS_SYN_RECEIVED;\n\ntrimthenstep6:\n\t\t/*\n\t\t * Advance ti->ti_seq to correspond to first data byte.\n\t\t * If data, trim to stay within window,\n\t\t * dropping FIN if necessary.\n\t\t */\n\t\tti->ti_seq++;\n\t\tif (ti->ti_len > tp->rcv_wnd) {\n\t\t\ttodrop = ti->ti_len - tp->rcv_wnd;\n\t\t\tm_adj(m, -todrop);\n\t\t\tti->ti_len = tp->rcv_wnd;\n\t\t\ttiflags &= ~TH_FIN;\n\t\t}\n\t\ttp->snd_wl1 = ti->ti_seq - 1;\n\t\ttp->rcv_up = ti->ti_seq;\n\t\tgoto step6;\n\t} /* switch tp->t_state */\n\t/*\n\t * States other than LISTEN or SYN_SENT.\n\t * Check that at least some bytes of segment are within\n\t * receive window. If segment begins before rcv_nxt,\n\t * drop leading data (and SYN); if nothing left, just ack.\n\t */\n\ttodrop = tp->rcv_nxt - ti->ti_seq;\n\tif (todrop > 0) {\n\t\tif (tiflags & TH_SYN) {\n\t\t\ttiflags &= ~TH_SYN;\n\t\t\tti->ti_seq++;\n\t\t\tif (ti->ti_urp > 1)\n\t\t\t\tti->ti_urp--;\n\t\t\telse\n\t\t\t\ttiflags &= ~TH_URG;\n\t\t\ttodrop--;\n\t\t}\n\t\t/*\n\t\t * Following if statement from Stevens, vol. 2, p. 960.\n\t\t */\n\t\tif (todrop > ti->ti_len\n\t\t || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {\n\t\t\t/*\n\t\t\t * Any valid FIN must be to the left of the window.\n\t\t\t * At this point the FIN must be a duplicate or out\n\t\t\t * of sequence; drop it.\n\t\t\t */\n\t\t\ttiflags &= ~TH_FIN;\n\n\t\t\t/*\n\t\t\t * Send an ACK to resynchronize and drop any data.\n\t\t\t * But keep on processing for RST or ACK.\n\t\t\t */\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttodrop = ti->ti_len;\n\t\t}\n\t\tm_adj(m, todrop);\n\t\tti->ti_seq += todrop;\n\t\tti->ti_len -= todrop;\n\t\tif (ti->ti_urp > todrop)\n\t\t\tti->ti_urp -= todrop;\n\t\telse {\n\t\t\ttiflags &= ~TH_URG;\n\t\t\tti->ti_urp = 0;\n\t\t}\n\t}\n\t/*\n\t * If new data are received on a connection after the\n\t * user processes are gone, then RST the other end.\n\t */\n\tif ((so->so_state & SS_NOFDREF) &&\n\t tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {\n\t\ttp = tcp_close(tp);\n\t\tgoto dropwithreset;\n\t}\n\n\t/*\n\t * If segment ends after window, drop trailing data\n\t * (and PUSH and FIN); if nothing left, just ACK.\n\t */\n\ttodrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);\n\tif (todrop > 0) {\n\t\tif (todrop >= ti->ti_len) {\n\t\t\t/*\n\t\t\t * If a new connection request is received\n\t\t\t * while in TIME_WAIT, drop the old connection\n\t\t\t * and start over if the sequence numbers\n\t\t\t * are above the previous ones.\n\t\t\t */\n\t\t\tif (tiflags & TH_SYN &&\n\t\t\t tp->t_state == TCPS_TIME_WAIT &&\n\t\t\t SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {\n\t\t\t\tiss = tp->rcv_nxt + TCP_ISSINCR;\n\t\t\t\ttp = tcp_close(tp);\n\t\t\t\tgoto findso;\n\t\t\t}\n\t\t\t/*\n\t\t\t * If window is closed can only take segments at\n\t\t\t * window edge, and have to drop data and PUSH from\n\t\t\t * incoming segments. Continue processing, but\n\t\t\t * remember to ack. Otherwise, drop segment\n\t\t\t * and ack.\n\t\t\t */\n\t\t\tif (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {\n\t\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\t} else {\n\t\t\t\tgoto dropafterack;\n\t\t\t}\n\t\t}\n\t\tm_adj(m, -todrop);\n\t\tti->ti_len -= todrop;\n\t\ttiflags &= ~(TH_PUSH|TH_FIN);\n\t}\n\n\t/*\n\t * If the RST bit is set examine the state:\n\t * SYN_RECEIVED STATE:\n\t *\tIf passive open, return to LISTEN state.\n\t *\tIf active open, inform user that connection was refused.\n\t * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:\n\t *\tInform user that connection was reset, and close tcb.\n\t * CLOSING, LAST_ACK, TIME_WAIT STATES\n\t *\tClose the tcb.\n\t */\n\tif (tiflags&TH_RST) switch (tp->t_state) {\n\n\tcase TCPS_SYN_RECEIVED:\n\tcase TCPS_ESTABLISHED:\n\tcase TCPS_FIN_WAIT_1:\n\tcase TCPS_FIN_WAIT_2:\n\tcase TCPS_CLOSE_WAIT:\n\t\ttp->t_state = TCPS_CLOSED;\n tcp_close(tp);\n\t\tgoto drop;\n\n\tcase TCPS_CLOSING:\n\tcase TCPS_LAST_ACK:\n\tcase TCPS_TIME_WAIT:\n tcp_close(tp);\n\t\tgoto drop;\n\t}\n\n\t/*\n\t * If a SYN is in the window, then this is an\n\t * error and we send an RST and drop the connection.\n\t */\n\tif (tiflags & TH_SYN) {\n\t\ttp = tcp_drop(tp,0);\n\t\tgoto dropwithreset;\n\t}\n\n\t/*\n\t * If the ACK bit is off we drop the segment and return.\n\t */\n\tif ((tiflags & TH_ACK) == 0) goto drop;\n\n\t/*\n\t * Ack processing.\n\t */\n\tswitch (tp->t_state) {\n\t/*\n\t * In SYN_RECEIVED state if the ack ACKs our SYN then enter\n\t * ESTABLISHED state and continue processing, otherwise\n\t * send an RST. una<=ack<=max\n\t */\n\tcase TCPS_SYN_RECEIVED:\n\n\t\tif (SEQ_GT(tp->snd_una, ti->ti_ack) ||\n\t\t SEQ_GT(ti->ti_ack, tp->snd_max))\n\t\t\tgoto dropwithreset;\n\t\ttp->t_state = TCPS_ESTABLISHED;\n\t\t/*\n\t\t * The sent SYN is ack'ed with our sequence number +1\n\t\t * The first data byte already in the buffer will get\n\t\t * lost if no correction is made. This is only needed for\n\t\t * SS_CTL since the buffer is empty otherwise.\n\t\t * tp->snd_una++; or:\n\t\t */\n\t\ttp->snd_una=ti->ti_ack;\n\t\tif (so->so_state & SS_CTL) {\n\t\t /* So tcp_ctl reports the right state */\n\t\t ret = tcp_ctl(so);\n\t\t if (ret == 1) {\n\t\t soisfconnected(so);\n\t\t so->so_state &= ~SS_CTL; /* success XXX */\n\t\t } else if (ret == 2) {\n\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t so->so_state |= SS_NOFDREF; /* CTL_CMD */\n\t\t } else {\n\t\t needoutput = 1;\n\t\t tp->t_state = TCPS_FIN_WAIT_1;\n\t\t }\n\t\t} else {\n\t\t soisfconnected(so);\n\t\t}\n\n\t\t(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);\n\t\ttp->snd_wl1 = ti->ti_seq - 1;\n\t\t/* Avoid ack processing; snd_una==ti_ack => dup ack */\n\t\tgoto synrx_to_est;\n\t\t/* fall into ... */\n\n\t/*\n\t * In ESTABLISHED state: drop duplicate ACKs; ACK out of range\n\t * ACKs. If the ack is in the range\n\t *\ttp->snd_una < ti->ti_ack <= tp->snd_max\n\t * then advance tp->snd_una to ti->ti_ack and drop\n\t * data from the retransmission queue. If this ACK reflects\n\t * more up to date window information we update our window information.\n\t */\n\tcase TCPS_ESTABLISHED:\n\tcase TCPS_FIN_WAIT_1:\n\tcase TCPS_FIN_WAIT_2:\n\tcase TCPS_CLOSE_WAIT:\n\tcase TCPS_CLOSING:\n\tcase TCPS_LAST_ACK:\n\tcase TCPS_TIME_WAIT:\n\n\t\tif (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {\n\t\t\tif (ti->ti_len == 0 && tiwin == tp->snd_wnd) {\n\t\t\t DEBUG_MISC((dfd,\" dup ack m = %lx so = %lx \\n\",\n\t\t\t\t (long )m, (long )so));\n\t\t\t\t/*\n\t\t\t\t * If we have outstanding data (other than\n\t\t\t\t * a window probe), this is a completely\n\t\t\t\t * duplicate ack (ie, window info didn't\n\t\t\t\t * change), the ack is the biggest we've\n\t\t\t\t * seen and we've seen exactly our rexmt\n\t\t\t\t * threshold of them, assume a packet\n\t\t\t\t * has been dropped and retransmit it.\n\t\t\t\t * Kludge snd_nxt & the congestion\n\t\t\t\t * window so we send only this one\n\t\t\t\t * packet.\n\t\t\t\t *\n\t\t\t\t * We know we're losing at the current\n\t\t\t\t * window size so do congestion avoidance\n\t\t\t\t * (set ssthresh to half the current window\n\t\t\t\t * and pull our congestion window back to\n\t\t\t\t * the new ssthresh).\n\t\t\t\t *\n\t\t\t\t * Dup acks mean that packets have left the\n\t\t\t\t * network (they're now cached at the receiver)\n\t\t\t\t * so bump cwnd by the amount in the receiver\n\t\t\t\t * to keep a constant cwnd packets in the\n\t\t\t\t * network.\n\t\t\t\t */\n\t\t\t\tif (tp->t_timer[TCPT_REXMT] == 0 ||\n\t\t\t\t ti->ti_ack != tp->snd_una)\n\t\t\t\t\ttp->t_dupacks = 0;\n\t\t\t\telse if (++tp->t_dupacks == TCPREXMTTHRESH) {\n\t\t\t\t\ttcp_seq onxt = tp->snd_nxt;\n\t\t\t\t\tu_int win =\n\t\t\t\t\t min(tp->snd_wnd, tp->snd_cwnd) / 2 /\n\t\t\t\t\t\ttp->t_maxseg;\n\n\t\t\t\t\tif (win < 2)\n\t\t\t\t\t\twin = 2;\n\t\t\t\t\ttp->snd_ssthresh = win * tp->t_maxseg;\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\t\t\ttp->t_rtt = 0;\n\t\t\t\t\ttp->snd_nxt = ti->ti_ack;\n\t\t\t\t\ttp->snd_cwnd = tp->t_maxseg;\n\t\t\t\t\t(void) tcp_output(tp);\n\t\t\t\t\ttp->snd_cwnd = tp->snd_ssthresh +\n\t\t\t\t\t tp->t_maxseg * tp->t_dupacks;\n\t\t\t\t\tif (SEQ_GT(onxt, tp->snd_nxt))\n\t\t\t\t\t\ttp->snd_nxt = onxt;\n\t\t\t\t\tgoto drop;\n\t\t\t\t} else if (tp->t_dupacks > TCPREXMTTHRESH) {\n\t\t\t\t\ttp->snd_cwnd += tp->t_maxseg;\n\t\t\t\t\t(void) tcp_output(tp);\n\t\t\t\t\tgoto drop;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\ttp->t_dupacks = 0;\n\t\t\tbreak;\n\t\t}\n\tsynrx_to_est:\n\t\t/*\n\t\t * If the congestion window was inflated to account\n\t\t * for the other side's cached packets, retract it.\n\t\t */\n\t\tif (tp->t_dupacks > TCPREXMTTHRESH &&\n\t\t tp->snd_cwnd > tp->snd_ssthresh)\n\t\t\ttp->snd_cwnd = tp->snd_ssthresh;\n\t\ttp->t_dupacks = 0;\n\t\tif (SEQ_GT(ti->ti_ack, tp->snd_max)) {\n\t\t\tgoto dropafterack;\n\t\t}\n\t\tacked = ti->ti_ack - tp->snd_una;\n\n\t\t/*\n\t\t * If transmit timer is running and timed sequence\n\t\t * number was acked, update smoothed round trip time.\n\t\t * Since we now have an rtt measurement, cancel the\n\t\t * timer backoff (cf., Phil Karn's retransmit alg.).\n\t\t * Recompute the initial retransmit timer.\n\t\t */\n\t\tif (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))\n\t\t\ttcp_xmit_timer(tp,tp->t_rtt);\n\n\t\t/*\n\t\t * If all outstanding data is acked, stop retransmit\n\t\t * timer and remember to restart (more output or persist).\n\t\t * If there is more data to be acked, restart retransmit\n\t\t * timer, using current (possibly backed-off) value.\n\t\t */\n\t\tif (ti->ti_ack == tp->snd_max) {\n\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\tneedoutput = 1;\n\t\t} else if (tp->t_timer[TCPT_PERSIST] == 0)\n\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t/*\n\t\t * When new data is acked, open the congestion window.\n\t\t * If the window gives us less than ssthresh packets\n\t\t * in flight, open exponentially (maxseg per packet).\n\t\t * Otherwise open linearly: maxseg per window\n\t\t * (maxseg^2 / cwnd per packet).\n\t\t */\n\t\t{\n\t\t register u_int cw = tp->snd_cwnd;\n\t\t register u_int incr = tp->t_maxseg;\n\n\t\t if (cw > tp->snd_ssthresh)\n\t\t incr = incr * incr / cw;\n\t\t tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<snd_scale);\n\t\t}\n\t\tif (acked > so->so_snd.sb_cc) {\n\t\t\ttp->snd_wnd -= so->so_snd.sb_cc;\n\t\t\tsbdrop(&so->so_snd, (int )so->so_snd.sb_cc);\n\t\t\tourfinisacked = 1;\n\t\t} else {\n\t\t\tsbdrop(&so->so_snd, acked);\n\t\t\ttp->snd_wnd -= acked;\n\t\t\tourfinisacked = 0;\n\t\t}\n\t\ttp->snd_una = ti->ti_ack;\n\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_una))\n\t\t\ttp->snd_nxt = tp->snd_una;\n\n\t\tswitch (tp->t_state) {\n\n\t\t/*\n\t\t * In FIN_WAIT_1 STATE in addition to the processing\n\t\t * for the ESTABLISHED state if our FIN is now acknowledged\n\t\t * then enter FIN_WAIT_2.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_1:\n\t\t\tif (ourfinisacked) {\n\t\t\t\t/*\n\t\t\t\t * If we can't receive any more\n\t\t\t\t * data, then closing user can proceed.\n\t\t\t\t * Starting the timer is contrary to the\n\t\t\t\t * specification, but if we don't get a FIN\n\t\t\t\t * we'll hang forever.\n\t\t\t\t */\n\t\t\t\tif (so->so_state & SS_FCANTRCVMORE) {\n\t\t\t\t\ttp->t_timer[TCPT_2MSL] = TCP_MAXIDLE;\n\t\t\t\t}\n\t\t\t\ttp->t_state = TCPS_FIN_WAIT_2;\n\t\t\t}\n\t\t\tbreak;\n\n\t \t/*\n\t\t * In CLOSING STATE in addition to the processing for\n\t\t * the ESTABLISHED state if the ACK acknowledges our FIN\n\t\t * then enter the TIME-WAIT state, otherwise ignore\n\t\t * the segment.\n\t\t */\n\t\tcase TCPS_CLOSING:\n\t\t\tif (ourfinisacked) {\n\t\t\t\ttp->t_state = TCPS_TIME_WAIT;\n\t\t\t\ttcp_canceltimers(tp);\n\t\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In LAST_ACK, we may still be waiting for data to drain\n\t\t * and/or to be acked, as well as for the ack of our FIN.\n\t\t * If our FIN is now acknowledged, delete the TCB,\n\t\t * enter the closed state and return.\n\t\t */\n\t\tcase TCPS_LAST_ACK:\n\t\t\tif (ourfinisacked) {\n tcp_close(tp);\n\t\t\t\tgoto drop;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In TIME_WAIT state the only thing that should arrive\n\t\t * is a retransmission of the remote FIN. Acknowledge\n\t\t * it and restart the finack timer.\n\t\t */\n\t\tcase TCPS_TIME_WAIT:\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tgoto dropafterack;\n\t\t}\n\t} /* switch(tp->t_state) */\n\nstep6:\n\t/*\n\t * Update window information.\n\t * Don't look at window if no ACK: TAC's send garbage on first SYN.\n\t */\n\tif ((tiflags & TH_ACK) &&\n\t (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||\n\t (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||\n\t (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {\n\t\ttp->snd_wnd = tiwin;\n\t\ttp->snd_wl1 = ti->ti_seq;\n\t\ttp->snd_wl2 = ti->ti_ack;\n\t\tif (tp->snd_wnd > tp->max_sndwnd)\n\t\t\ttp->max_sndwnd = tp->snd_wnd;\n\t\tneedoutput = 1;\n\t}\n\n\t/*\n\t * Process segments with URG.\n\t */\n\tif ((tiflags & TH_URG) && ti->ti_urp &&\n\t TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\t/*\n\t\t * This is a kludge, but if we receive and accept\n\t\t * random urgent pointers, we'll crash in\n\t\t * soreceive. It's hard to imagine someone\n\t\t * actually wanting to send this much urgent data.\n\t\t */\n\t\tif (ti->ti_urp + so->so_rcv.sb_cc > so->so_rcv.sb_datalen) {\n\t\t\tti->ti_urp = 0;\n\t\t\ttiflags &= ~TH_URG;\n\t\t\tgoto dodata;\n\t\t}\n\t\t/*\n\t\t * If this segment advances the known urgent pointer,\n\t\t * then mark the data stream. This should not happen\n\t\t * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since\n\t\t * a FIN has been received from the remote side.\n\t\t * In these states we ignore the URG.\n\t\t *\n\t\t * According to RFC961 (Assigned Protocols),\n\t\t * the urgent pointer points to the last octet\n\t\t * of urgent data. We continue, however,\n\t\t * to consider it to indicate the first octet\n\t\t * of data past the urgent section as the original\n\t\t * spec states (in one of two places).\n\t\t */\n\t\tif (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {\n\t\t\ttp->rcv_up = ti->ti_seq + ti->ti_urp;\n\t\t\tso->so_urgc = so->so_rcv.sb_cc +\n\t\t\t\t(tp->rcv_up - tp->rcv_nxt); /* -1; */\n\t\t\ttp->rcv_up = ti->ti_seq + ti->ti_urp;\n\n\t\t}\n\t} else\n\t\t/*\n\t\t * If no out of band data is expected,\n\t\t * pull receive urgent pointer along\n\t\t * with the receive window.\n\t\t */\n\t\tif (SEQ_GT(tp->rcv_nxt, tp->rcv_up))\n\t\t\ttp->rcv_up = tp->rcv_nxt;\ndodata:\n\n\t/*\n\t * Process the segment text, merging it into the TCP sequencing queue,\n\t * and arranging for acknowledgment of receipt if necessary.\n\t * This process logically involves adjusting tp->rcv_wnd as data\n\t * is presented to the user (this happens in tcp_usrreq.c,\n\t * case PRU_RCVD). If a FIN has already been received on this\n\t * connection then we just ignore the text.\n\t */\n\tif ((ti->ti_len || (tiflags&TH_FIN)) &&\n\t TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\tTCP_REASS(tp, ti, m, so, tiflags);\n\t} else {\n\t\tm_free(m);\n\t\ttiflags &= ~TH_FIN;\n\t}\n\n\t/*\n\t * If FIN is received ACK the FIN and let the user know\n\t * that the connection is closing.\n\t */\n\tif (tiflags & TH_FIN) {\n\t\tif (TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\t\t/*\n\t\t\t * If we receive a FIN we can't send more data,\n\t\t\t * set it SS_FDRAIN\n * Shutdown the socket if there is no rx data in the\n\t\t\t * buffer.\n\t\t\t * soread() is called on completion of shutdown() and\n\t\t\t * will got to TCPS_LAST_ACK, and use tcp_output()\n\t\t\t * to send the FIN.\n\t\t\t */\n\t\t\tsofwdrain(so);\n\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttp->rcv_nxt++;\n\t\t}\n\t\tswitch (tp->t_state) {\n\n\t \t/*\n\t\t * In SYN_RECEIVED and ESTABLISHED STATES\n\t\t * enter the CLOSE_WAIT state.\n\t\t */\n\t\tcase TCPS_SYN_RECEIVED:\n\t\tcase TCPS_ESTABLISHED:\n\t\t if(so->so_emu == EMU_CTL) /* no shutdown on socket */\n\t\t tp->t_state = TCPS_LAST_ACK;\n\t\t else\n\t\t tp->t_state = TCPS_CLOSE_WAIT;\n\t\t break;\n\n\t \t/*\n\t\t * If still in FIN_WAIT_1 STATE FIN has not been acked so\n\t\t * enter the CLOSING state.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_1:\n\t\t\ttp->t_state = TCPS_CLOSING;\n\t\t\tbreak;\n\n\t \t/*\n\t\t * In FIN_WAIT_2 state enter the TIME_WAIT state,\n\t\t * starting the time-wait timer, turning off the other\n\t\t * standard timers.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_2:\n\t\t\ttp->t_state = TCPS_TIME_WAIT;\n\t\t\ttcp_canceltimers(tp);\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In TIME_WAIT state restart the 2 MSL time_wait timer.\n\t\t */\n\t\tcase TCPS_TIME_WAIT:\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/*\n\t * If this is a small packet, then ACK now - with Nagel\n\t * congestion avoidance sender won't send more until\n\t * he gets an ACK.\n\t *\n\t * See above.\n\t */\n\tif (ti->ti_len && (unsigned)ti->ti_len <= 5 &&\n\t ((struct tcpiphdr_2 *)ti)->first_char == (char)27) {\n\t\ttp->t_flags |= TF_ACKNOW;\n\t}\n\n\t/*\n\t * Return any desired output.\n\t */\n\tif (needoutput || (tp->t_flags & TF_ACKNOW)) {\n\t\t(void) tcp_output(tp);\n\t}\n\treturn;\n\ndropafterack:\n\t/*\n\t * Generate an ACK dropping incoming segment if it occupies\n\t * sequence space, where the ACK reflects our state.\n\t */\n\tif (tiflags & TH_RST)\n\t\tgoto drop;\n\tm_freem(m);\n\ttp->t_flags |= TF_ACKNOW;\n\t(void) tcp_output(tp);\n\treturn;\n\ndropwithreset:\n\t/* reuses m if m!=NULL, m_free() unnecessary */\n\tif (tiflags & TH_ACK)\n\t\ttcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);\n\telse {\n\t\tif (tiflags & TH_SYN) ti->ti_len++;\n\t\ttcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,\n\t\t TH_RST|TH_ACK);\n\t}\n\n\treturn;\n\ndrop:\n\t/*\n\t * Drop space held by incoming segment and return.\n\t */\n\tm_free(m);\n\n\treturn;\n}\n\nstatic void\ntcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcpiphdr *ti)\n{\n\tuint16_t mss;\n\tint opt, optlen;\n\n\tDEBUG_CALL(\"tcp_dooptions\");\n\tDEBUG_ARGS((dfd,\" tp = %lx cnt=%i \\n\", (long )tp, cnt));\n\n\tfor (; cnt > 0; cnt -= optlen, cp += optlen) {\n\t\topt = cp[0];\n\t\tif (opt == TCPOPT_EOL)\n\t\t\tbreak;\n\t\tif (opt == TCPOPT_NOP)\n\t\t\toptlen = 1;\n\t\telse {\n\t\t\toptlen = cp[1];\n\t\t\tif (optlen <= 0)\n\t\t\t\tbreak;\n\t\t}\n\t\tswitch (opt) {\n\n\t\tdefault:\n\t\t\tcontinue;\n\n\t\tcase TCPOPT_MAXSEG:\n\t\t\tif (optlen != TCPOLEN_MAXSEG)\n\t\t\t\tcontinue;\n\t\t\tif (!(ti->ti_flags & TH_SYN))\n\t\t\t\tcontinue;\n\t\t\tmemcpy((char *) &mss, (char *) cp + 2, sizeof(mss));\n\t\t\tNTOHS(mss);\n\t\t\t(void) tcp_mss(tp, mss);\t/* sets t_maxseg */\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n/*\n * Pull out of band byte out of a segment so\n * it doesn't appear in the user's data queue.\n * It is still reflected in the segment length for\n * sequencing purposes.\n */\n\n#ifdef notdef\n\nvoid\ntcp_pulloutofband(so, ti, m)\n\tstruct socket *so;\n\tstruct tcpiphdr *ti;\n\tregister struct mbuf *m;\n{\n\tint cnt = ti->ti_urp - 1;\n\n\twhile (cnt >= 0) {\n\t\tif (m->m_len > cnt) {\n\t\t\tchar *cp = mtod(m, caddr_t) + cnt;\n\t\t\tstruct tcpcb *tp = sototcpcb(so);\n\n\t\t\ttp->t_iobc = *cp;\n\t\t\ttp->t_oobflags |= TCPOOB_HAVEDATA;\n\t\t\tmemcpy(sp, cp+1, (unsigned)(m->m_len - cnt - 1));\n\t\t\tm->m_len--;\n\t\t\treturn;\n\t\t}\n\t\tcnt -= m->m_len;\n\t\tm = m->m_next; /* XXX WRONG! Fix it! */\n\t\tif (m == 0)\n\t\t\tbreak;\n\t}\n\tpanic(\"tcp_pulloutofband\");\n}\n\n#endif /* notdef */\n\n/*\n * Collect new round-trip time estimate\n * and update averages and current timeout.\n */\n\nstatic void\ntcp_xmit_timer(register struct tcpcb *tp, int rtt)\n{\n\tregister short delta;\n\n\tDEBUG_CALL(\"tcp_xmit_timer\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"rtt = %d\", rtt);\n\n\tif (tp->t_srtt != 0) {\n\t\t/*\n\t\t * srtt is stored as fixed point with 3 bits after the\n\t\t * binary point (i.e., scaled by 8). The following magic\n\t\t * is equivalent to the smoothing algorithm in rfc793 with\n\t\t * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed\n\t\t * point). Adjust rtt to origin 0.\n\t\t */\n\t\tdelta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);\n\t\tif ((tp->t_srtt += delta) <= 0)\n\t\t\ttp->t_srtt = 1;\n\t\t/*\n\t\t * We accumulate a smoothed rtt variance (actually, a\n\t\t * smoothed mean difference), then set the retransmit\n\t\t * timer to smoothed rtt + 4 times the smoothed variance.\n\t\t * rttvar is stored as fixed point with 2 bits after the\n\t\t * binary point (scaled by 4). The following is\n\t\t * equivalent to rfc793 smoothing with an alpha of .75\n\t\t * (rttvar = rttvar*3/4 + |delta| / 4). This replaces\n\t\t * rfc793's wired-in beta.\n\t\t */\n\t\tif (delta < 0)\n\t\t\tdelta = -delta;\n\t\tdelta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);\n\t\tif ((tp->t_rttvar += delta) <= 0)\n\t\t\ttp->t_rttvar = 1;\n\t} else {\n\t\t/*\n\t\t * No rtt measurement yet - use the unsmoothed rtt.\n\t\t * Set the variance to half the rtt (so our first\n\t\t * retransmit happens at 3*rtt).\n\t\t */\n\t\ttp->t_srtt = rtt << TCP_RTT_SHIFT;\n\t\ttp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);\n\t}\n\ttp->t_rtt = 0;\n\ttp->t_rxtshift = 0;\n\n\t/*\n\t * the retransmit should happen at rtt + 4 * rttvar.\n\t * Because of the way we do the smoothing, srtt and rttvar\n\t * will each average +1/2 tick of bias. When we compute\n\t * the retransmit timer, we want 1/2 tick of rounding and\n\t * 1 extra tick because of +-1/2 tick uncertainty in the\n\t * firing of the timer. The bias will give us exactly the\n\t * 1.5 tick we need. But, because the bias is\n\t * statistical, we have to test that we don't drop below\n\t * the minimum feasible timer (which is 2 ticks).\n\t */\n\tTCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),\n\t (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */\n\n\t/*\n\t * We received an ack for a packet that wasn't retransmitted;\n\t * it is probably safe to discard any error indications we've\n\t * received recently. This isn't quite right, but close enough\n\t * for now (a route might have failed after we sent a segment,\n\t * and the return path might not be symmetrical).\n\t */\n\ttp->t_softerror = 0;\n}\n\n/*\n * Determine a reasonable value for maxseg size.\n * If the route is known, check route for mtu.\n * If none, use an mss that can be handled on the outgoing\n * interface without forcing IP to fragment; if bigger than\n * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES\n * to utilize large mbufs. If no route is found, route has no mtu,\n * or the destination isn't local, use a default, hopefully conservative\n * size (usually 512 or the default IP max size, but no more than the mtu\n * of the interface), as we can't discover anything about intervening\n * gateways or networks. We also initialize the congestion/slow start\n * window to be a single segment if the destination isn't local.\n * While looking at the routing entry, we also initialize other path-dependent\n * parameters from pre-set or cached values in the routing entry.\n */\n\nint\ntcp_mss(struct tcpcb *tp, u_int offer)\n{\n\tstruct socket *so = tp->t_socket;\n\tint mss;\n\n\tDEBUG_CALL(\"tcp_mss\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"offer = %d\", offer);\n\n\tmss = min(IF_MTU, IF_MRU) - sizeof(struct tcpiphdr);\n\tif (offer)\n\t\tmss = min(mss, offer);\n\tmss = max(mss, 32);\n\tif (mss < tp->t_maxseg || offer != 0)\n\t tp->t_maxseg = mss;\n\n\ttp->snd_cwnd = mss;\n\n\tsbreserve(&so->so_snd, TCP_SNDSPACE + ((TCP_SNDSPACE % mss) ?\n (mss - (TCP_SNDSPACE % mss)) :\n 0));\n\tsbreserve(&so->so_rcv, TCP_RCVSPACE + ((TCP_RCVSPACE % mss) ?\n (mss - (TCP_RCVSPACE % mss)) :\n 0));\n\n\tDEBUG_MISC((dfd, \" returning mss = %d\\n\", mss));\n\n\treturn mss;\n}\n"], ["/linuxpdf/tinyemu/vmmouse.c", "/*\n * VM mouse emulation\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n\n#define VMPORT_MAGIC 0x564D5868\n\n#define REG_EAX 0\n#define REG_EBX 1\n#define REG_ECX 2\n#define REG_EDX 3\n#define REG_ESI 4\n#define REG_EDI 5\n\n#define FIFO_SIZE (4 * 16)\n\nstruct VMMouseState {\n PS2MouseState *ps2_mouse;\n int fifo_count, fifo_rindex, fifo_windex;\n BOOL enabled;\n BOOL absolute;\n uint32_t fifo_buf[FIFO_SIZE];\n};\n\nstatic void put_queue(VMMouseState *s, uint32_t val)\n{\n if (s->fifo_count >= FIFO_SIZE)\n return;\n s->fifo_buf[s->fifo_windex] = val;\n if (++s->fifo_windex == FIFO_SIZE)\n s->fifo_windex = 0;\n s->fifo_count++;\n}\n\nstatic void read_data(VMMouseState *s, uint32_t *regs, int size)\n{\n int i;\n if (size > 6 || size > s->fifo_count) {\n // printf(\"vmmouse: read error req=%d count=%d\\n\", size, s->fifo_count);\n s->enabled = FALSE;\n return;\n }\n for(i = 0; i < size; i++) {\n regs[i] = s->fifo_buf[s->fifo_rindex];\n if (++s->fifo_rindex == FIFO_SIZE)\n s->fifo_rindex = 0;\n }\n s->fifo_count -= size;\n}\n\nvoid vmmouse_send_mouse_event(VMMouseState *s, int x, int y, int dz,\n int buttons)\n{\n int state;\n\n if (!s->enabled) {\n ps2_mouse_event(s->ps2_mouse, x, y, dz, buttons);\n return;\n }\n\n if ((s->fifo_count + 4) > FIFO_SIZE)\n return;\n\n state = 0;\n if (buttons & 1)\n state |= 0x20;\n if (buttons & 2)\n state |= 0x10;\n if (buttons & 4)\n state |= 0x08;\n if (s->absolute) {\n /* range = 0 ... 65535 */\n x *= 2; \n y *= 2;\n }\n\n put_queue(s, state);\n put_queue(s, x);\n put_queue(s, y);\n put_queue(s, -dz);\n\n /* send PS/2 mouse event */\n ps2_mouse_event(s->ps2_mouse, 1, 0, 0, 0);\n}\n\nvoid vmmouse_handler(VMMouseState *s, uint32_t *regs)\n{\n uint32_t cmd;\n \n cmd = regs[REG_ECX] & 0xff;\n switch(cmd) {\n case 10: /* get version */\n regs[REG_EBX] = VMPORT_MAGIC;\n break;\n case 39: /* VMMOUSE_DATA */\n read_data(s, regs, regs[REG_EBX]);\n break;\n case 40: /* VMMOUSE_STATUS */\n regs[REG_EAX] = ((s->enabled ? 0 : 0xffff) << 16) | s->fifo_count;\n break;\n case 41: /* VMMOUSE_COMMAND */\n switch(regs[REG_EBX]) {\n case 0x45414552: /* read id */\n if (s->fifo_count < FIFO_SIZE) {\n put_queue(s, 0x3442554a);\n s->enabled = TRUE;\n }\n break;\n case 0x000000f5: /* disable */\n s->enabled = FALSE;\n break;\n case 0x4c455252: /* set relative */\n s->absolute = 0;\n break;\n case 0x53424152: /* set absolute */\n s->absolute = 1;\n break;\n }\n break;\n }\n}\n\nBOOL vmmouse_is_absolute(VMMouseState *s)\n{\n return s->absolute;\n}\n\nVMMouseState *vmmouse_init(PS2MouseState *ps2_mouse)\n{\n VMMouseState *s;\n s = mallocz(sizeof(*s));\n s->ps2_mouse = ps2_mouse;\n return s;\n}\n"], ["/linuxpdf/tinyemu/build_filelist.c", "/*\n * File list builder for RISCVEMU network filesystem\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"fs_utils.h\"\n\nvoid print_str(FILE *f, const char *str)\n{\n const char *s;\n int c;\n s = str;\n while (*s != '\\0') {\n if (*s <= ' ' || *s > '~')\n goto use_quote;\n s++;\n }\n fputs(str, f);\n return;\n use_quote:\n s = str;\n fputc('\"', f);\n while (*s != '\\0') {\n c = *(uint8_t *)s;\n if (c < ' ' || c == 127) {\n fprintf(f, \"\\\\x%02x\", c);\n } else if (c == '\\\\' || c == '\\\"') {\n fprintf(f, \"\\\\%c\", c);\n } else {\n fputc(c, f);\n }\n s++;\n }\n fputc('\"', f);\n}\n\n#define COPY_BUF_LEN (1024 * 1024)\n\nstatic void copy_file(const char *src_filename, const char *dst_filename)\n{\n uint8_t *buf;\n FILE *fi, *fo;\n int len;\n \n buf = malloc(COPY_BUF_LEN);\n fi = fopen(src_filename, \"rb\");\n if (!fi) {\n perror(src_filename);\n exit(1);\n }\n fo = fopen(dst_filename, \"wb\");\n if (!fo) {\n perror(dst_filename);\n exit(1);\n }\n for(;;) {\n len = fread(buf, 1, COPY_BUF_LEN, fi);\n if (len == 0)\n break;\n fwrite(buf, 1, len, fo);\n }\n fclose(fo);\n fclose(fi);\n}\n\ntypedef struct {\n char *files_path;\n uint64_t next_inode_num;\n uint64_t fs_size;\n uint64_t fs_max_size;\n FILE *f;\n} ScanState;\n\nstatic void add_file_size(ScanState *s, uint64_t size)\n{\n s->fs_size += block_align(size, FS_BLOCK_SIZE);\n if (s->fs_size > s->fs_max_size) {\n fprintf(stderr, \"Filesystem Quota exceeded (%\" PRId64 \" bytes)\\n\", s->fs_max_size);\n exit(1);\n }\n}\n\nvoid scan_dir(ScanState *s, const char *path)\n{\n FILE *f = s->f;\n DIR *dirp;\n struct dirent *de;\n const char *name;\n struct stat st;\n char *path1;\n uint32_t mode, v;\n\n dirp = opendir(path);\n if (!dirp) {\n perror(path);\n exit(1);\n }\n for(;;) {\n de = readdir(dirp);\n if (!de)\n break;\n name = de->d_name;\n if (!strcmp(name, \".\") || !strcmp(name, \"..\"))\n continue;\n path1 = compose_path(path, name);\n if (lstat(path1, &st) < 0) {\n perror(path1);\n exit(1);\n }\n\n mode = st.st_mode & 0xffff;\n fprintf(f, \"%06o %u %u\", \n mode, \n (int)st.st_uid,\n (int)st.st_gid);\n if (S_ISCHR(mode) || S_ISBLK(mode)) {\n fprintf(f, \" %u %u\",\n (int)major(st.st_rdev),\n (int)minor(st.st_rdev));\n }\n if (S_ISREG(mode)) {\n fprintf(f, \" %\" PRIu64, st.st_size);\n }\n /* modification time (at most ms resolution) */\n fprintf(f, \" %u\", (int)st.st_mtim.tv_sec);\n v = st.st_mtim.tv_nsec;\n if (v != 0) {\n fprintf(f, \".\");\n while (v != 0) {\n fprintf(f, \"%u\", v / 100000000);\n v = (v % 100000000) * 10;\n }\n }\n \n fprintf(f, \" \");\n print_str(f, name);\n if (S_ISLNK(mode)) {\n char buf[1024];\n int len;\n len = readlink(path1, buf, sizeof(buf) - 1);\n if (len < 0) {\n perror(\"readlink\");\n exit(1);\n }\n buf[len] = '\\0';\n fprintf(f, \" \");\n print_str(f, buf);\n } else if (S_ISREG(mode) && st.st_size > 0) {\n char buf1[FILEID_SIZE_MAX], *fname;\n FSFileID file_id;\n file_id = s->next_inode_num++;\n fprintf(f, \" %\" PRIx64, file_id);\n file_id_to_filename(buf1, file_id);\n fname = compose_path(s->files_path, buf1);\n copy_file(path1, fname);\n add_file_size(s, st.st_size);\n }\n\n fprintf(f, \"\\n\");\n if (S_ISDIR(mode)) {\n scan_dir(s, path1);\n }\n free(path1);\n }\n\n closedir(dirp);\n fprintf(f, \".\\n\"); /* end of directory */\n}\n\nvoid help(void)\n{\n printf(\"usage: build_filelist [options] source_path dest_path\\n\"\n \"\\n\"\n \"Options:\\n\"\n \"-m size_mb set the max filesystem size in MiB\\n\");\n exit(1);\n}\n\n#define LOCK_FILENAME \"lock\"\n\nint main(int argc, char **argv)\n{\n const char *dst_path, *src_path;\n ScanState s_s, *s = &s_s;\n FILE *f;\n char *filename;\n FSFileID root_id;\n char fname[FILEID_SIZE_MAX];\n struct stat st;\n uint64_t first_inode, fs_max_size;\n int c;\n \n first_inode = 1;\n fs_max_size = (uint64_t)1 << 30;\n for(;;) {\n c = getopt(argc, argv, \"hi:m:\");\n if (c == -1)\n break;\n switch(c) {\n case 'h':\n help();\n case 'i':\n first_inode = strtoul(optarg, NULL, 0);\n break;\n case 'm':\n fs_max_size = (uint64_t)strtoul(optarg, NULL, 0) << 20;\n break;\n default:\n exit(1);\n }\n }\n\n if (optind + 1 >= argc)\n help();\n src_path = argv[optind];\n dst_path = argv[optind + 1];\n \n mkdir(dst_path, 0755);\n\n s->files_path = compose_path(dst_path, ROOT_FILENAME);\n s->next_inode_num = first_inode;\n s->fs_size = 0;\n s->fs_max_size = fs_max_size;\n \n mkdir(s->files_path, 0755);\n\n root_id = s->next_inode_num++;\n file_id_to_filename(fname, root_id);\n filename = compose_path(s->files_path, fname);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fprintf(f, \"Version: 1\\n\");\n fprintf(f, \"Revision: 1\\n\");\n fprintf(f, \"\\n\");\n s->f = f;\n scan_dir(s, src_path);\n fclose(f);\n\n /* take into account the filelist size */\n if (stat(filename, &st) < 0) {\n perror(filename);\n exit(1);\n }\n add_file_size(s, st.st_size);\n \n free(filename);\n \n filename = compose_path(dst_path, HEAD_FILENAME);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fprintf(f, \"Version: 1\\n\");\n fprintf(f, \"Revision: 1\\n\");\n fprintf(f, \"NextFileID: %\" PRIx64 \"\\n\", s->next_inode_num);\n fprintf(f, \"FSFileCount: %\" PRIu64 \"\\n\", s->next_inode_num - 1);\n fprintf(f, \"FSSize: %\" PRIu64 \"\\n\", s->fs_size);\n fprintf(f, \"FSMaxSize: %\" PRIu64 \"\\n\", s->fs_max_size);\n fprintf(f, \"Key:\\n\"); /* not encrypted */\n fprintf(f, \"RootID: %\" PRIx64 \"\\n\", root_id);\n fclose(f);\n free(filename);\n \n filename = compose_path(dst_path, LOCK_FILENAME);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fclose(f);\n free(filename);\n\n return 0;\n}\n"], ["/linuxpdf/tinyemu/slirp/misc.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n#ifdef DEBUG\nint slirp_debug = DBG_CALL|DBG_MISC|DBG_ERROR;\n#endif\n\nstruct quehead {\n\tstruct quehead *qh_link;\n\tstruct quehead *qh_rlink;\n};\n\ninline void\ninsque(void *a, void *b)\n{\n\tregister struct quehead *element = (struct quehead *) a;\n\tregister struct quehead *head = (struct quehead *) b;\n\telement->qh_link = head->qh_link;\n\thead->qh_link = (struct quehead *)element;\n\telement->qh_rlink = (struct quehead *)head;\n\t((struct quehead *)(element->qh_link))->qh_rlink\n\t= (struct quehead *)element;\n}\n\ninline void\nremque(void *a)\n{\n register struct quehead *element = (struct quehead *) a;\n ((struct quehead *)(element->qh_link))->qh_rlink = element->qh_rlink;\n ((struct quehead *)(element->qh_rlink))->qh_link = element->qh_link;\n element->qh_rlink = NULL;\n}\n\nint add_exec(struct ex_list **ex_ptr, int do_pty, char *exec,\n struct in_addr addr, int port)\n{\n\tstruct ex_list *tmp_ptr;\n\n\t/* First, check if the port is \"bound\" */\n\tfor (tmp_ptr = *ex_ptr; tmp_ptr; tmp_ptr = tmp_ptr->ex_next) {\n\t\tif (port == tmp_ptr->ex_fport &&\n\t\t addr.s_addr == tmp_ptr->ex_addr.s_addr)\n\t\t\treturn -1;\n\t}\n\n\ttmp_ptr = *ex_ptr;\n\t*ex_ptr = (struct ex_list *)malloc(sizeof(struct ex_list));\n\t(*ex_ptr)->ex_fport = port;\n\t(*ex_ptr)->ex_addr = addr;\n\t(*ex_ptr)->ex_pty = do_pty;\n\t(*ex_ptr)->ex_exec = (do_pty == 3) ? exec : strdup(exec);\n\t(*ex_ptr)->ex_next = tmp_ptr;\n\treturn 0;\n}\n\n#ifndef HAVE_STRERROR\n\n/*\n * For systems with no strerror\n */\n\nextern int sys_nerr;\nextern char *sys_errlist[];\n\nchar *\nstrerror(error)\n\tint error;\n{\n\tif (error < sys_nerr)\n\t return sys_errlist[error];\n\telse\n\t return \"Unknown error.\";\n}\n\n#endif\n\nint os_socket(int domain, int type, int protocol)\n{\n return socket(domain, type, protocol);\n}\n\nuint32_t os_get_time_ms(void)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return ts.tv_sec * 1000 +\n (ts.tv_nsec / 1000000);\n}\n\n\n#if 1\n\nint\nfork_exec(struct socket *so, const char *ex, int do_pty)\n{\n /* not implemented */\n return 0;\n}\n\n#else\n\n/*\n * XXX This is ugly\n * We create and bind a socket, then fork off to another\n * process, which connects to this socket, after which we\n * exec the wanted program. If something (strange) happens,\n * the accept() call could block us forever.\n *\n * do_pty = 0 Fork/exec inetd style\n * do_pty = 1 Fork/exec using slirp.telnetd\n * do_ptr = 2 Fork/exec using pty\n */\nint\nfork_exec(struct socket *so, const char *ex, int do_pty)\n{\n\tint s;\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(addr);\n\tint opt;\n int master = -1;\n\tconst char *argv[256];\n\t/* don't want to clobber the original */\n\tchar *bptr;\n\tconst char *curarg;\n\tint c, i, ret;\n\n\tDEBUG_CALL(\"fork_exec\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"ex = %lx\", (long)ex);\n\tDEBUG_ARG(\"do_pty = %lx\", (long)do_pty);\n\n\tif (do_pty == 2) {\n return 0;\n\t} else {\n\t\taddr.sin_family = AF_INET;\n\t\taddr.sin_port = 0;\n\t\taddr.sin_addr.s_addr = INADDR_ANY;\n\n\t\tif ((s = os_socket(AF_INET, SOCK_STREAM, 0)) < 0 ||\n\t\t bind(s, (struct sockaddr *)&addr, addrlen) < 0 ||\n\t\t listen(s, 1) < 0) {\n\t\t\tlprint(\"Error: inet socket: %s\\n\", strerror(errno));\n\t\t\tclosesocket(s);\n\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tswitch(fork()) {\n\t case -1:\n\t\tlprint(\"Error: fork failed: %s\\n\", strerror(errno));\n\t\tclose(s);\n\t\tif (do_pty == 2)\n\t\t close(master);\n\t\treturn 0;\n\n\t case 0:\n\t\t/* Set the DISPLAY */\n\t\tif (do_pty == 2) {\n\t\t\t(void) close(master);\n#ifdef TIOCSCTTY /* XXXXX */\n\t\t\t(void) setsid();\n\t\t\tioctl(s, TIOCSCTTY, (char *)NULL);\n#endif\n\t\t} else {\n\t\t\tgetsockname(s, (struct sockaddr *)&addr, &addrlen);\n\t\t\tclose(s);\n\t\t\t/*\n\t\t\t * Connect to the socket\n\t\t\t * XXX If any of these fail, we're in trouble!\n\t \t\t */\n\t\t\ts = os_socket(AF_INET, SOCK_STREAM, 0);\n\t\t\taddr.sin_addr = loopback_addr;\n do {\n ret = connect(s, (struct sockaddr *)&addr, addrlen);\n } while (ret < 0 && errno == EINTR);\n\t\t}\n\n\t\tdup2(s, 0);\n\t\tdup2(s, 1);\n\t\tdup2(s, 2);\n\t\tfor (s = getdtablesize() - 1; s >= 3; s--)\n\t\t close(s);\n\n\t\ti = 0;\n\t\tbptr = qemu_strdup(ex); /* No need to free() this */\n\t\tif (do_pty == 1) {\n\t\t\t/* Setup \"slirp.telnetd -x\" */\n\t\t\targv[i++] = \"slirp.telnetd\";\n\t\t\targv[i++] = \"-x\";\n\t\t\targv[i++] = bptr;\n\t\t} else\n\t\t do {\n\t\t\t/* Change the string into argv[] */\n\t\t\tcurarg = bptr;\n\t\t\twhile (*bptr != ' ' && *bptr != (char)0)\n\t\t\t bptr++;\n\t\t\tc = *bptr;\n\t\t\t*bptr++ = (char)0;\n\t\t\targv[i++] = strdup(curarg);\n\t\t } while (c);\n\n argv[i] = NULL;\n\t\texecvp(argv[0], (char **)argv);\n\n\t\t/* Ooops, failed, let's tell the user why */\n fprintf(stderr, \"Error: execvp of %s failed: %s\\n\",\n argv[0], strerror(errno));\n\t\tclose(0); close(1); close(2); /* XXX */\n\t\texit(1);\n\n\t default:\n\t\tif (do_pty == 2) {\n\t\t\tclose(s);\n\t\t\tso->s = master;\n\t\t} else {\n\t\t\t/*\n\t\t\t * XXX this could block us...\n\t\t\t * XXX Should set a timer here, and if accept() doesn't\n\t\t \t * return after X seconds, declare it a failure\n\t\t \t * The only reason this will block forever is if socket()\n\t\t \t * of connect() fail in the child process\n\t\t \t */\n do {\n so->s = accept(s, (struct sockaddr *)&addr, &addrlen);\n } while (so->s < 0 && errno == EINTR);\n closesocket(s);\n\t\t\topt = 1;\n\t\t\tsetsockopt(so->s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\t\t\topt = 1;\n\t\t\tsetsockopt(so->s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\t\t}\n\t\tfd_nonblock(so->s);\n\n\t\t/* Append the telnet options now */\n if (so->so_m != NULL && do_pty == 1) {\n\t\t\tsbappend(so, so->so_m);\n so->so_m = NULL;\n\t\t}\n\n\t\treturn 1;\n\t}\n}\n#endif\n\n#ifndef HAVE_STRDUP\nchar *\nstrdup(str)\n\tconst char *str;\n{\n\tchar *bptr;\n\n\tbptr = (char *)malloc(strlen(str)+1);\n\tstrcpy(bptr, str);\n\n\treturn bptr;\n}\n#endif\n\nvoid lprint(const char *format, ...)\n{\n va_list args;\n\n va_start(args, format);\n vprintf(format, args);\n va_end(args);\n}\n\n/*\n * Set fd blocking and non-blocking\n */\n\nvoid\nfd_nonblock(int fd)\n{\n#ifdef FIONBIO\n#ifdef _WIN32\n unsigned long opt = 1;\n#else\n int opt = 1;\n#endif\n\n\tioctlsocket(fd, FIONBIO, &opt);\n#else\n\tint opt;\n\n\topt = fcntl(fd, F_GETFL, 0);\n\topt |= O_NONBLOCK;\n\tfcntl(fd, F_SETFL, opt);\n#endif\n}\n\nvoid\nfd_block(int fd)\n{\n#ifdef FIONBIO\n#ifdef _WIN32\n unsigned long opt = 0;\n#else\n\tint opt = 0;\n#endif\n\n\tioctlsocket(fd, FIONBIO, &opt);\n#else\n\tint opt;\n\n\topt = fcntl(fd, F_GETFL, 0);\n\topt &= ~O_NONBLOCK;\n\tfcntl(fd, F_SETFL, opt);\n#endif\n}\n\n#if 0\nvoid slirp_connection_info(Slirp *slirp, Monitor *mon)\n{\n const char * const tcpstates[] = {\n [TCPS_CLOSED] = \"CLOSED\",\n [TCPS_LISTEN] = \"LISTEN\",\n [TCPS_SYN_SENT] = \"SYN_SENT\",\n [TCPS_SYN_RECEIVED] = \"SYN_RCVD\",\n [TCPS_ESTABLISHED] = \"ESTABLISHED\",\n [TCPS_CLOSE_WAIT] = \"CLOSE_WAIT\",\n [TCPS_FIN_WAIT_1] = \"FIN_WAIT_1\",\n [TCPS_CLOSING] = \"CLOSING\",\n [TCPS_LAST_ACK] = \"LAST_ACK\",\n [TCPS_FIN_WAIT_2] = \"FIN_WAIT_2\",\n [TCPS_TIME_WAIT] = \"TIME_WAIT\",\n };\n struct in_addr dst_addr;\n struct sockaddr_in src;\n socklen_t src_len;\n uint16_t dst_port;\n struct socket *so;\n const char *state;\n char buf[20];\n int n;\n\n monitor_printf(mon, \" Protocol[State] FD Source Address Port \"\n \"Dest. Address Port RecvQ SendQ\\n\");\n\n for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {\n if (so->so_state & SS_HOSTFWD) {\n state = \"HOST_FORWARD\";\n } else if (so->so_tcpcb) {\n state = tcpstates[so->so_tcpcb->t_state];\n } else {\n state = \"NONE\";\n }\n if (so->so_state & (SS_HOSTFWD | SS_INCOMING)) {\n src_len = sizeof(src);\n getsockname(so->s, (struct sockaddr *)&src, &src_len);\n dst_addr = so->so_laddr;\n dst_port = so->so_lport;\n } else {\n src.sin_addr = so->so_laddr;\n src.sin_port = so->so_lport;\n dst_addr = so->so_faddr;\n dst_port = so->so_fport;\n }\n n = snprintf(buf, sizeof(buf), \" TCP[%s]\", state);\n memset(&buf[n], ' ', 19 - n);\n buf[19] = 0;\n monitor_printf(mon, \"%s %3d %15s %5d \", buf, so->s,\n src.sin_addr.s_addr ? inet_ntoa(src.sin_addr) : \"*\",\n ntohs(src.sin_port));\n monitor_printf(mon, \"%15s %5d %5d %5d\\n\",\n inet_ntoa(dst_addr), ntohs(dst_port),\n so->so_rcv.sb_cc, so->so_snd.sb_cc);\n }\n\n for (so = slirp->udb.so_next; so != &slirp->udb; so = so->so_next) {\n if (so->so_state & SS_HOSTFWD) {\n n = snprintf(buf, sizeof(buf), \" UDP[HOST_FORWARD]\");\n src_len = sizeof(src);\n getsockname(so->s, (struct sockaddr *)&src, &src_len);\n dst_addr = so->so_laddr;\n dst_port = so->so_lport;\n } else {\n n = snprintf(buf, sizeof(buf), \" UDP[%d sec]\",\n (so->so_expire - curtime) / 1000);\n src.sin_addr = so->so_laddr;\n src.sin_port = so->so_lport;\n dst_addr = so->so_faddr;\n dst_port = so->so_fport;\n }\n memset(&buf[n], ' ', 19 - n);\n buf[19] = 0;\n monitor_printf(mon, \"%s %3d %15s %5d \", buf, so->s,\n src.sin_addr.s_addr ? inet_ntoa(src.sin_addr) : \"*\",\n ntohs(src.sin_port));\n monitor_printf(mon, \"%15s %5d %5d %5d\\n\",\n inet_ntoa(dst_addr), ntohs(dst_port),\n so->so_rcv.sb_cc, so->so_snd.sb_cc);\n }\n}\n#endif\n"], ["/linuxpdf/tinyemu/slirp/ip_icmp.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_icmp.c\t8.2 (Berkeley) 1/4/94\n * ip_icmp.c,v 1.7 1995/05/30 08:09:42 rgrimes Exp\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n/* The message sent when emulating PING */\n/* Be nice and tell them it's just a pseudo-ping packet */\nstatic const char icmp_ping_msg[] = \"This is a pseudo-PING packet used by Slirp to emulate ICMP ECHO-REQUEST packets.\\n\";\n\n/* list of actions for icmp_error() on RX of an icmp message */\nstatic const int icmp_flush[19] = {\n/* ECHO REPLY (0) */ 0,\n\t\t 1,\n\t\t 1,\n/* DEST UNREACH (3) */ 1,\n/* SOURCE QUENCH (4)*/ 1,\n/* REDIRECT (5) */ 1,\n\t\t 1,\n\t\t 1,\n/* ECHO (8) */ 0,\n/* ROUTERADVERT (9) */ 1,\n/* ROUTERSOLICIT (10) */ 1,\n/* TIME EXCEEDED (11) */ 1,\n/* PARAMETER PROBLEM (12) */ 1,\n/* TIMESTAMP (13) */ 0,\n/* TIMESTAMP REPLY (14) */ 0,\n/* INFO (15) */ 0,\n/* INFO REPLY (16) */ 0,\n/* ADDR MASK (17) */ 0,\n/* ADDR MASK REPLY (18) */ 0\n};\n\n/*\n * Process a received ICMP message.\n */\nvoid\nicmp_input(struct mbuf *m, int hlen)\n{\n register struct icmp *icp;\n register struct ip *ip=mtod(m, struct ip *);\n int icmplen=ip->ip_len;\n Slirp *slirp = m->slirp;\n\n DEBUG_CALL(\"icmp_input\");\n DEBUG_ARG(\"m = %lx\", (long )m);\n DEBUG_ARG(\"m_len = %d\", m->m_len);\n\n /*\n * Locate icmp structure in mbuf, and check\n * that its not corrupted and of at least minimum length.\n */\n if (icmplen < ICMP_MINLEN) { /* min 8 bytes payload */\n freeit:\n m_freem(m);\n goto end_error;\n }\n\n m->m_len -= hlen;\n m->m_data += hlen;\n icp = mtod(m, struct icmp *);\n if (cksum(m, icmplen)) {\n goto freeit;\n }\n m->m_len += hlen;\n m->m_data -= hlen;\n\n DEBUG_ARG(\"icmp_type = %d\", icp->icmp_type);\n switch (icp->icmp_type) {\n case ICMP_ECHO:\n icp->icmp_type = ICMP_ECHOREPLY;\n ip->ip_len += hlen;\t /* since ip_input subtracts this */\n if (ip->ip_dst.s_addr == slirp->vhost_addr.s_addr) {\n icmp_reflect(m);\n } else {\n struct socket *so;\n struct sockaddr_in addr;\n if ((so = socreate(slirp)) == NULL) goto freeit;\n if(udp_attach(so) == -1) {\n\tDEBUG_MISC((dfd,\"icmp_input udp_attach errno = %d-%s\\n\",\n\t\t errno,strerror(errno)));\n\tsofree(so);\n\tm_free(m);\n\tgoto end_error;\n }\n so->so_m = m;\n so->so_faddr = ip->ip_dst;\n so->so_fport = htons(7);\n so->so_laddr = ip->ip_src;\n so->so_lport = htons(9);\n so->so_iptos = ip->ip_tos;\n so->so_type = IPPROTO_ICMP;\n so->so_state = SS_ISFCONNECTED;\n\n /* Send the packet */\n addr.sin_family = AF_INET;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n\t/* It's an alias */\n\tif (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\t if (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n\t} else {\n\t addr.sin_addr = loopback_addr;\n\t}\n } else {\n\taddr.sin_addr = so->so_faddr;\n }\n addr.sin_port = so->so_fport;\n if(sendto(so->s, icmp_ping_msg, strlen(icmp_ping_msg), 0,\n\t\t(struct sockaddr *)&addr, sizeof(addr)) == -1) {\n\tDEBUG_MISC((dfd,\"icmp_input udp sendto tx errno = %d-%s\\n\",\n\t\t errno,strerror(errno)));\n\ticmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));\n\tudp_detach(so);\n }\n } /* if ip->ip_dst.s_addr == alias_addr.s_addr */\n break;\n case ICMP_UNREACH:\n /* XXX? report error? close socket? */\n case ICMP_TIMXCEED:\n case ICMP_PARAMPROB:\n case ICMP_SOURCEQUENCH:\n case ICMP_TSTAMP:\n case ICMP_MASKREQ:\n case ICMP_REDIRECT:\n m_freem(m);\n break;\n\n default:\n m_freem(m);\n } /* swith */\n\nend_error:\n /* m is m_free()'d xor put in a socket xor or given to ip_send */\n return;\n}\n\n\n/*\n *\tSend an ICMP message in response to a situation\n *\n *\tRFC 1122: 3.2.2\tMUST send at least the IP header and 8 bytes of header. MAY send more (we do).\n *\t\t\tMUST NOT change this header information.\n *\t\t\tMUST NOT reply to a multicast/broadcast IP address.\n *\t\t\tMUST NOT reply to a multicast/broadcast MAC address.\n *\t\t\tMUST reply to only the first fragment.\n */\n/*\n * Send ICMP_UNREACH back to the source regarding msrc.\n * mbuf *msrc is used as a template, but is NOT m_free()'d.\n * It is reported as the bad ip packet. The header should\n * be fully correct and in host byte order.\n * ICMP fragmentation is illegal. All machines must accept 576 bytes in one\n * packet. The maximum payload is 576-20(ip hdr)-8(icmp hdr)=548\n */\n\n#define ICMP_MAXDATALEN (IP_MSS-28)\nvoid\nicmp_error(struct mbuf *msrc, u_char type, u_char code, int minsize,\n const char *message)\n{\n unsigned hlen, shlen, s_ip_len;\n register struct ip *ip;\n register struct icmp *icp;\n register struct mbuf *m;\n\n DEBUG_CALL(\"icmp_error\");\n DEBUG_ARG(\"msrc = %lx\", (long )msrc);\n DEBUG_ARG(\"msrc_len = %d\", msrc->m_len);\n\n if(type!=ICMP_UNREACH && type!=ICMP_TIMXCEED) goto end_error;\n\n /* check msrc */\n if(!msrc) goto end_error;\n ip = mtod(msrc, struct ip *);\n#ifdef DEBUG\n { char bufa[20], bufb[20];\n strcpy(bufa, inet_ntoa(ip->ip_src));\n strcpy(bufb, inet_ntoa(ip->ip_dst));\n DEBUG_MISC((dfd, \" %.16s to %.16s\\n\", bufa, bufb));\n }\n#endif\n if(ip->ip_off & IP_OFFMASK) goto end_error; /* Only reply to fragment 0 */\n\n shlen=ip->ip_hl << 2;\n s_ip_len=ip->ip_len;\n if(ip->ip_p == IPPROTO_ICMP) {\n icp = (struct icmp *)((char *)ip + shlen);\n /*\n *\tAssume any unknown ICMP type is an error. This isn't\n *\tspecified by the RFC, but think about it..\n */\n if(icp->icmp_type>18 || icmp_flush[icp->icmp_type]) goto end_error;\n }\n\n /* make a copy */\n m = m_get(msrc->slirp);\n if (!m) {\n goto end_error;\n }\n\n { int new_m_size;\n new_m_size=sizeof(struct ip )+ICMP_MINLEN+msrc->m_len+ICMP_MAXDATALEN;\n if(new_m_size>m->m_size) m_inc(m, new_m_size);\n }\n memcpy(m->m_data, msrc->m_data, msrc->m_len);\n m->m_len = msrc->m_len; /* copy msrc to m */\n\n /* make the header of the reply packet */\n ip = mtod(m, struct ip *);\n hlen= sizeof(struct ip ); /* no options in reply */\n\n /* fill in icmp */\n m->m_data += hlen;\n m->m_len -= hlen;\n\n icp = mtod(m, struct icmp *);\n\n if(minsize) s_ip_len=shlen+ICMP_MINLEN; /* return header+8b only */\n else if(s_ip_len>ICMP_MAXDATALEN) /* maximum size */\n s_ip_len=ICMP_MAXDATALEN;\n\n m->m_len=ICMP_MINLEN+s_ip_len; /* 8 bytes ICMP header */\n\n /* min. size = 8+sizeof(struct ip)+8 */\n\n icp->icmp_type = type;\n icp->icmp_code = code;\n icp->icmp_id = 0;\n icp->icmp_seq = 0;\n\n memcpy(&icp->icmp_ip, msrc->m_data, s_ip_len); /* report the ip packet */\n HTONS(icp->icmp_ip.ip_len);\n HTONS(icp->icmp_ip.ip_id);\n HTONS(icp->icmp_ip.ip_off);\n\n#ifdef DEBUG\n if(message) { /* DEBUG : append message to ICMP packet */\n int message_len;\n char *cpnt;\n message_len=strlen(message);\n if(message_len>ICMP_MAXDATALEN) message_len=ICMP_MAXDATALEN;\n cpnt=(char *)m->m_data+m->m_len;\n memcpy(cpnt, message, message_len);\n m->m_len+=message_len;\n }\n#endif\n\n icp->icmp_cksum = 0;\n icp->icmp_cksum = cksum(m, m->m_len);\n\n m->m_data -= hlen;\n m->m_len += hlen;\n\n /* fill in ip */\n ip->ip_hl = hlen >> 2;\n ip->ip_len = m->m_len;\n\n ip->ip_tos=((ip->ip_tos & 0x1E) | 0xC0); /* high priority for errors */\n\n ip->ip_ttl = MAXTTL;\n ip->ip_p = IPPROTO_ICMP;\n ip->ip_dst = ip->ip_src; /* ip adresses */\n ip->ip_src = m->slirp->vhost_addr;\n\n (void ) ip_output((struct socket *)NULL, m);\n\nend_error:\n return;\n}\n#undef ICMP_MAXDATALEN\n\n/*\n * Reflect the ip packet back to the source\n */\nvoid\nicmp_reflect(struct mbuf *m)\n{\n register struct ip *ip = mtod(m, struct ip *);\n int hlen = ip->ip_hl << 2;\n int optlen = hlen - sizeof(struct ip );\n register struct icmp *icp;\n\n /*\n * Send an icmp packet back to the ip level,\n * after supplying a checksum.\n */\n m->m_data += hlen;\n m->m_len -= hlen;\n icp = mtod(m, struct icmp *);\n\n icp->icmp_cksum = 0;\n icp->icmp_cksum = cksum(m, ip->ip_len - hlen);\n\n m->m_data -= hlen;\n m->m_len += hlen;\n\n /* fill in ip */\n if (optlen > 0) {\n /*\n * Strip out original options by copying rest of first\n * mbuf's data back, and adjust the IP length.\n */\n memmove((caddr_t)(ip + 1), (caddr_t)ip + hlen,\n\t (unsigned )(m->m_len - hlen));\n hlen -= optlen;\n ip->ip_hl = hlen >> 2;\n ip->ip_len -= optlen;\n m->m_len -= optlen;\n }\n\n ip->ip_ttl = MAXTTL;\n { /* swap */\n struct in_addr icmp_dst;\n icmp_dst = ip->ip_dst;\n ip->ip_dst = ip->ip_src;\n ip->ip_src = icmp_dst;\n }\n\n (void ) ip_output((struct socket *)NULL, m);\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_input.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_input.c\t8.2 (Berkeley) 1/4/94\n * ip_input.c,v 1.11 1994/11/16 10:17:08 jkh Exp\n */\n\n/*\n * Changes and additions relating to SLiRP are\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n#define container_of(ptr, type, member) ({ \\\n const typeof( ((type *)0)->member ) *__mptr = (ptr); \\\n (type *)( (char *)__mptr - offsetof(type,member) );})\n\nstatic struct ip *ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp);\nstatic void ip_freef(Slirp *slirp, struct ipq *fp);\nstatic void ip_enq(register struct ipasfrag *p,\n register struct ipasfrag *prev);\nstatic void ip_deq(register struct ipasfrag *p);\n\n/*\n * IP initialization: fill in IP protocol switch table.\n * All protocols not implemented in kernel go to raw IP protocol handler.\n */\nvoid\nip_init(Slirp *slirp)\n{\n slirp->ipq.ip_link.next = slirp->ipq.ip_link.prev = &slirp->ipq.ip_link;\n udp_init(slirp);\n tcp_init(slirp);\n}\n\n/*\n * Ip input routine. Checksum and byte swap header. If fragmented\n * try to reassemble. Process options. Pass to next level.\n */\nvoid\nip_input(struct mbuf *m)\n{\n\tSlirp *slirp = m->slirp;\n\tregister struct ip *ip;\n\tint hlen;\n\n\tDEBUG_CALL(\"ip_input\");\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"m_len = %d\", m->m_len);\n\n\tif (m->m_len < sizeof (struct ip)) {\n\t\treturn;\n\t}\n\n\tip = mtod(m, struct ip *);\n\n\tif (ip->ip_v != IPVERSION) {\n\t\tgoto bad;\n\t}\n\n\thlen = ip->ip_hl << 2;\n\tif (hlenm->m_len) {/* min header length */\n\t goto bad; /* or packet too short */\n\t}\n\n /* keep ip header intact for ICMP reply\n\t * ip->ip_sum = cksum(m, hlen);\n\t * if (ip->ip_sum) {\n\t */\n\tif(cksum(m,hlen)) {\n\t goto bad;\n\t}\n\n\t/*\n\t * Convert fields to host representation.\n\t */\n\tNTOHS(ip->ip_len);\n\tif (ip->ip_len < hlen) {\n\t\tgoto bad;\n\t}\n\tNTOHS(ip->ip_id);\n\tNTOHS(ip->ip_off);\n\n\t/*\n\t * Check that the amount of data in the buffers\n\t * is as at least much as the IP header would have us expect.\n\t * Trim mbufs if longer than we expect.\n\t * Drop packet if shorter than we expect.\n\t */\n\tif (m->m_len < ip->ip_len) {\n\t\tgoto bad;\n\t}\n\n if (slirp->restricted) {\n if ((ip->ip_dst.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n if (ip->ip_dst.s_addr == 0xffffffff && ip->ip_p != IPPROTO_UDP)\n goto bad;\n } else {\n uint32_t inv_mask = ~slirp->vnetwork_mask.s_addr;\n struct ex_list *ex_ptr;\n\n if ((ip->ip_dst.s_addr & inv_mask) == inv_mask) {\n goto bad;\n }\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)\n if (ex_ptr->ex_addr.s_addr == ip->ip_dst.s_addr)\n break;\n\n if (!ex_ptr)\n goto bad;\n }\n }\n\n\t/* Should drop packet if mbuf too long? hmmm... */\n\tif (m->m_len > ip->ip_len)\n\t m_adj(m, ip->ip_len - m->m_len);\n\n\t/* check ip_ttl for a correct ICMP reply */\n\tif(ip->ip_ttl==0) {\n\t icmp_error(m, ICMP_TIMXCEED,ICMP_TIMXCEED_INTRANS, 0,\"ttl\");\n\t goto bad;\n\t}\n\n\t/*\n\t * If offset or IP_MF are set, must reassemble.\n\t * Otherwise, nothing need be done.\n\t * (We could look in the reassembly queue to see\n\t * if the packet was previously fragmented,\n\t * but it's not worth the time; just let them time out.)\n\t *\n\t * XXX This should fail, don't fragment yet\n\t */\n\tif (ip->ip_off &~ IP_DF) {\n\t register struct ipq *fp;\n struct qlink *l;\n\t\t/*\n\t\t * Look for queue of fragments\n\t\t * of this datagram.\n\t\t */\n\t\tfor (l = slirp->ipq.ip_link.next; l != &slirp->ipq.ip_link;\n\t\t l = l->next) {\n fp = container_of(l, struct ipq, ip_link);\n if (ip->ip_id == fp->ipq_id &&\n ip->ip_src.s_addr == fp->ipq_src.s_addr &&\n ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&\n ip->ip_p == fp->ipq_p)\n\t\t goto found;\n }\n fp = NULL;\n\tfound:\n\n\t\t/*\n\t\t * Adjust ip_len to not reflect header,\n\t\t * set ip_mff if more fragments are expected,\n\t\t * convert offset of this to bytes.\n\t\t */\n\t\tip->ip_len -= hlen;\n\t\tif (ip->ip_off & IP_MF)\n\t\t ip->ip_tos |= 1;\n\t\telse\n\t\t ip->ip_tos &= ~1;\n\n\t\tip->ip_off <<= 3;\n\n\t\t/*\n\t\t * If datagram marked as having more fragments\n\t\t * or if this is not the first fragment,\n\t\t * attempt reassembly; if it succeeds, proceed.\n\t\t */\n\t\tif (ip->ip_tos & 1 || ip->ip_off) {\n\t\t\tip = ip_reass(slirp, ip, fp);\n if (ip == NULL)\n\t\t\t\treturn;\n\t\t\tm = dtom(slirp, ip);\n\t\t} else\n\t\t\tif (fp)\n\t\t \t ip_freef(slirp, fp);\n\n\t} else\n\t\tip->ip_len -= hlen;\n\n\t/*\n\t * Switch out to protocol's input routine.\n\t */\n\tswitch (ip->ip_p) {\n\t case IPPROTO_TCP:\n\t\ttcp_input(m, hlen, (struct socket *)NULL);\n\t\tbreak;\n\t case IPPROTO_UDP:\n\t\tudp_input(m, hlen);\n\t\tbreak;\n\t case IPPROTO_ICMP:\n\t\ticmp_input(m, hlen);\n\t\tbreak;\n\t default:\n\t\tm_free(m);\n\t}\n\treturn;\nbad:\n\tm_freem(m);\n\treturn;\n}\n\n#define iptofrag(P) ((struct ipasfrag *)(((char*)(P)) - sizeof(struct qlink)))\n#define fragtoip(P) ((struct ip*)(((char*)(P)) + sizeof(struct qlink)))\n/*\n * Take incoming datagram fragment and try to\n * reassemble it into whole datagram. If a chain for\n * reassembly of this datagram already exists, then it\n * is given as fp; otherwise have to make a chain.\n */\nstatic struct ip *\nip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)\n{\n\tregister struct mbuf *m = dtom(slirp, ip);\n\tregister struct ipasfrag *q;\n\tint hlen = ip->ip_hl << 2;\n\tint i, next;\n\n\tDEBUG_CALL(\"ip_reass\");\n\tDEBUG_ARG(\"ip = %lx\", (long)ip);\n\tDEBUG_ARG(\"fp = %lx\", (long)fp);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n\t/*\n\t * Presence of header sizes in mbufs\n\t * would confuse code below.\n * Fragment m_data is concatenated.\n\t */\n\tm->m_data += hlen;\n\tm->m_len -= hlen;\n\n\t/*\n\t * If first fragment to arrive, create a reassembly queue.\n\t */\n if (fp == NULL) {\n\t struct mbuf *t = m_get(slirp);\n\n\t if (t == NULL) {\n\t goto dropfrag;\n\t }\n\t fp = mtod(t, struct ipq *);\n\t insque(&fp->ip_link, &slirp->ipq.ip_link);\n\t fp->ipq_ttl = IPFRAGTTL;\n\t fp->ipq_p = ip->ip_p;\n\t fp->ipq_id = ip->ip_id;\n\t fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;\n\t fp->ipq_src = ip->ip_src;\n\t fp->ipq_dst = ip->ip_dst;\n\t q = (struct ipasfrag *)fp;\n\t goto insert;\n\t}\n\n\t/*\n\t * Find a segment which begins after this one does.\n\t */\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next)\n\t\tif (q->ipf_off > ip->ip_off)\n\t\t\tbreak;\n\n\t/*\n\t * If there is a preceding segment, it may provide some of\n\t * our data already. If so, drop the data from the incoming\n\t * segment. If it provides all of our data, drop us.\n\t */\n\tif (q->ipf_prev != &fp->frag_link) {\n struct ipasfrag *pq = q->ipf_prev;\n\t\ti = pq->ipf_off + pq->ipf_len - ip->ip_off;\n\t\tif (i > 0) {\n\t\t\tif (i >= ip->ip_len)\n\t\t\t\tgoto dropfrag;\n\t\t\tm_adj(dtom(slirp, ip), i);\n\t\t\tip->ip_off += i;\n\t\t\tip->ip_len -= i;\n\t\t}\n\t}\n\n\t/*\n\t * While we overlap succeeding segments trim them or,\n\t * if they are completely covered, dequeue them.\n\t */\n\twhile (q != (struct ipasfrag*)&fp->frag_link &&\n ip->ip_off + ip->ip_len > q->ipf_off) {\n\t\ti = (ip->ip_off + ip->ip_len) - q->ipf_off;\n\t\tif (i < q->ipf_len) {\n\t\t\tq->ipf_len -= i;\n\t\t\tq->ipf_off += i;\n\t\t\tm_adj(dtom(slirp, q), i);\n\t\t\tbreak;\n\t\t}\n\t\tq = q->ipf_next;\n\t\tm_freem(dtom(slirp, q->ipf_prev));\n\t\tip_deq(q->ipf_prev);\n\t}\n\ninsert:\n\t/*\n\t * Stick new segment in its place;\n\t * check for complete reassembly.\n\t */\n\tip_enq(iptofrag(ip), q->ipf_prev);\n\tnext = 0;\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link;\n q = q->ipf_next) {\n\t\tif (q->ipf_off != next)\n return NULL;\n\t\tnext += q->ipf_len;\n\t}\n\tif (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)\n return NULL;\n\n\t/*\n\t * Reassembly is complete; concatenate fragments.\n\t */\n q = fp->frag_link.next;\n\tm = dtom(slirp, q);\n\n\tq = (struct ipasfrag *) q->ipf_next;\n\twhile (q != (struct ipasfrag*)&fp->frag_link) {\n\t struct mbuf *t = dtom(slirp, q);\n\t q = (struct ipasfrag *) q->ipf_next;\n\t m_cat(m, t);\n\t}\n\n\t/*\n\t * Create header for new ip packet by\n\t * modifying header of first packet;\n\t * dequeue and discard fragment reassembly header.\n\t * Make header visible.\n\t */\n\tq = fp->frag_link.next;\n\n\t/*\n\t * If the fragments concatenated to an mbuf that's\n\t * bigger than the total size of the fragment, then and\n\t * m_ext buffer was alloced. But fp->ipq_next points to\n\t * the old buffer (in the mbuf), so we must point ip\n\t * into the new buffer.\n\t */\n\tif (m->m_flags & M_EXT) {\n\t int delta = (char *)q - m->m_dat;\n\t q = (struct ipasfrag *)(m->m_ext + delta);\n\t}\n\n ip = fragtoip(q);\n\tip->ip_len = next;\n\tip->ip_tos &= ~1;\n\tip->ip_src = fp->ipq_src;\n\tip->ip_dst = fp->ipq_dst;\n\tremque(&fp->ip_link);\n\t(void) m_free(dtom(slirp, fp));\n\tm->m_len += (ip->ip_hl << 2);\n\tm->m_data -= (ip->ip_hl << 2);\n\n\treturn ip;\n\ndropfrag:\n\tm_freem(m);\n return NULL;\n}\n\n/*\n * Free a fragment reassembly header and all\n * associated datagrams.\n */\nstatic void\nip_freef(Slirp *slirp, struct ipq *fp)\n{\n\tregister struct ipasfrag *q, *p;\n\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link; q = p) {\n\t\tp = q->ipf_next;\n\t\tip_deq(q);\n\t\tm_freem(dtom(slirp, q));\n\t}\n\tremque(&fp->ip_link);\n\t(void) m_free(dtom(slirp, fp));\n}\n\n/*\n * Put an ip fragment on a reassembly chain.\n * Like insque, but pointers in middle of structure.\n */\nstatic void\nip_enq(register struct ipasfrag *p, register struct ipasfrag *prev)\n{\n\tDEBUG_CALL(\"ip_enq\");\n\tDEBUG_ARG(\"prev = %lx\", (long)prev);\n\tp->ipf_prev = prev;\n\tp->ipf_next = prev->ipf_next;\n\t((struct ipasfrag *)(prev->ipf_next))->ipf_prev = p;\n\tprev->ipf_next = p;\n}\n\n/*\n * To ip_enq as remque is to insque.\n */\nstatic void\nip_deq(register struct ipasfrag *p)\n{\n\t((struct ipasfrag *)(p->ipf_prev))->ipf_next = p->ipf_next;\n\t((struct ipasfrag *)(p->ipf_next))->ipf_prev = p->ipf_prev;\n}\n\n/*\n * IP timer processing;\n * if a timer expires on a reassembly\n * queue, discard it.\n */\nvoid\nip_slowtimo(Slirp *slirp)\n{\n struct qlink *l;\n\n\tDEBUG_CALL(\"ip_slowtimo\");\n\n l = slirp->ipq.ip_link.next;\n\n if (l == NULL)\n\t return;\n\n while (l != &slirp->ipq.ip_link) {\n struct ipq *fp = container_of(l, struct ipq, ip_link);\n l = l->next;\n\t\tif (--fp->ipq_ttl == 0) {\n\t\t\tip_freef(slirp, fp);\n\t\t}\n }\n}\n\n/*\n * Do option processing on a datagram,\n * possibly discarding it if bad options are encountered,\n * or forwarding it if source-routed.\n * Returns 1 if packet has been forwarded/freed,\n * 0 if the packet should be processed further.\n */\n\n#ifdef notdef\n\nint\nip_dooptions(m)\n\tstruct mbuf *m;\n{\n\tregister struct ip *ip = mtod(m, struct ip *);\n\tregister u_char *cp;\n\tregister struct ip_timestamp *ipt;\n\tregister struct in_ifaddr *ia;\n\tint opt, optlen, cnt, off, code, type, forward = 0;\n\tstruct in_addr *sin, dst;\ntypedef uint32_t n_time;\n\tn_time ntime;\n\n\tdst = ip->ip_dst;\n\tcp = (u_char *)(ip + 1);\n\tcnt = (ip->ip_hl << 2) - sizeof (struct ip);\n\tfor (; cnt > 0; cnt -= optlen, cp += optlen) {\n\t\topt = cp[IPOPT_OPTVAL];\n\t\tif (opt == IPOPT_EOL)\n\t\t\tbreak;\n\t\tif (opt == IPOPT_NOP)\n\t\t\toptlen = 1;\n\t\telse {\n\t\t\toptlen = cp[IPOPT_OLEN];\n\t\t\tif (optlen <= 0 || optlen > cnt) {\n\t\t\t\tcode = &cp[IPOPT_OLEN] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t}\n\t\tswitch (opt) {\n\n\t\tdefault:\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Source routing with record.\n\t\t * Find interface with current destination address.\n\t\t * If none on this machine then drop if strictly routed,\n\t\t * or do nothing if loosely routed.\n\t\t * Record interface address and bring up next address\n\t\t * component. If strictly routed make sure next\n\t\t * address is on directly accessible net.\n\t\t */\n\t\tcase IPOPT_LSRR:\n\t\tcase IPOPT_SSRR:\n\t\t\tif ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {\n\t\t\t\tcode = &cp[IPOPT_OFFSET] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tipaddr.sin_addr = ip->ip_dst;\n\t\t\tia = (struct in_ifaddr *)\n\t\t\t\tifa_ifwithaddr((struct sockaddr *)&ipaddr);\n\t\t\tif (ia == 0) {\n\t\t\t\tif (opt == IPOPT_SSRR) {\n\t\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\t\tcode = ICMP_UNREACH_SRCFAIL;\n\t\t\t\t\tgoto bad;\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Loose routing, and not at next destination\n\t\t\t\t * yet; nothing to do except forward.\n\t\t\t\t */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toff--;\t\t\t/ * 0 origin * /\n\t\t\tif (off > optlen - sizeof(struct in_addr)) {\n\t\t\t\t/*\n\t\t\t\t * End of source route. Should be for us.\n\t\t\t\t */\n\t\t\t\tsave_rte(cp, ip->ip_src);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/*\n\t\t\t * locate outgoing interface\n\t\t\t */\n\t\t\tbcopy((caddr_t)(cp + off), (caddr_t)&ipaddr.sin_addr,\n\t\t\t sizeof(ipaddr.sin_addr));\n\t\t\tif (opt == IPOPT_SSRR) {\n#define\tINA\tstruct in_ifaddr *\n#define\tSA\tstruct sockaddr *\n \t\t\t if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)\n\t\t\t\tia = (INA)ifa_ifwithnet((SA)&ipaddr);\n\t\t\t} else\n\t\t\t\tia = ip_rtaddr(ipaddr.sin_addr);\n\t\t\tif (ia == 0) {\n\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\tcode = ICMP_UNREACH_SRCFAIL;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tip->ip_dst = ipaddr.sin_addr;\n\t\t\tbcopy((caddr_t)&(IA_SIN(ia)->sin_addr),\n\t\t\t (caddr_t)(cp + off), sizeof(struct in_addr));\n\t\t\tcp[IPOPT_OFFSET] += sizeof(struct in_addr);\n\t\t\t/*\n\t\t\t * Let ip_intr's mcast routing check handle mcast pkts\n\t\t\t */\n\t\t\tforward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));\n\t\t\tbreak;\n\n\t\tcase IPOPT_RR:\n\t\t\tif ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {\n\t\t\t\tcode = &cp[IPOPT_OFFSET] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\t/*\n\t\t\t * If no space remains, ignore.\n\t\t\t */\n\t\t\toff--;\t\t\t * 0 origin *\n\t\t\tif (off > optlen - sizeof(struct in_addr))\n\t\t\t\tbreak;\n\t\t\tbcopy((caddr_t)(&ip->ip_dst), (caddr_t)&ipaddr.sin_addr,\n\t\t\t sizeof(ipaddr.sin_addr));\n\t\t\t/*\n\t\t\t * locate outgoing interface; if we're the destination,\n\t\t\t * use the incoming interface (should be same).\n\t\t\t */\n\t\t\tif ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&\n\t\t\t (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {\n\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\tcode = ICMP_UNREACH_HOST;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tbcopy((caddr_t)&(IA_SIN(ia)->sin_addr),\n\t\t\t (caddr_t)(cp + off), sizeof(struct in_addr));\n\t\t\tcp[IPOPT_OFFSET] += sizeof(struct in_addr);\n\t\t\tbreak;\n\n\t\tcase IPOPT_TS:\n\t\t\tcode = cp - (u_char *)ip;\n\t\t\tipt = (struct ip_timestamp *)cp;\n\t\t\tif (ipt->ipt_len < 5)\n\t\t\t\tgoto bad;\n\t\t\tif (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {\n\t\t\t\tif (++ipt->ipt_oflw == 0)\n\t\t\t\t\tgoto bad;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);\n\t\t\tswitch (ipt->ipt_flg) {\n\n\t\t\tcase IPOPT_TS_TSONLY:\n\t\t\t\tbreak;\n\n\t\t\tcase IPOPT_TS_TSANDADDR:\n\t\t\t\tif (ipt->ipt_ptr + sizeof(n_time) +\n\t\t\t\t sizeof(struct in_addr) > ipt->ipt_len)\n\t\t\t\t\tgoto bad;\n\t\t\t\tipaddr.sin_addr = dst;\n\t\t\t\tia = (INA)ifaof_ i f p foraddr((SA)&ipaddr,\n\t\t\t\t\t\t\t m->m_pkthdr.rcvif);\n\t\t\t\tif (ia == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tbcopy((caddr_t)&IA_SIN(ia)->sin_addr,\n\t\t\t\t (caddr_t)sin, sizeof(struct in_addr));\n\t\t\t\tipt->ipt_ptr += sizeof(struct in_addr);\n\t\t\t\tbreak;\n\n\t\t\tcase IPOPT_TS_PRESPEC:\n\t\t\t\tif (ipt->ipt_ptr + sizeof(n_time) +\n\t\t\t\t sizeof(struct in_addr) > ipt->ipt_len)\n\t\t\t\t\tgoto bad;\n\t\t\t\tbcopy((caddr_t)sin, (caddr_t)&ipaddr.sin_addr,\n\t\t\t\t sizeof(struct in_addr));\n\t\t\t\tif (ifa_ifwithaddr((SA)&ipaddr) == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tipt->ipt_ptr += sizeof(struct in_addr);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tntime = iptime();\n\t\t\tbcopy((caddr_t)&ntime, (caddr_t)cp + ipt->ipt_ptr - 1,\n\t\t\t sizeof(n_time));\n\t\t\tipt->ipt_ptr += sizeof(n_time);\n\t\t}\n\t}\n\tif (forward) {\n\t\tip_forward(m, 1);\n\t\treturn (1);\n\t}\n\treturn (0);\nbad:\n \ticmp_error(m, type, code, 0, 0);\n\n\treturn (1);\n}\n\n#endif /* notdef */\n\n/*\n * Strip out IP options, at higher\n * level protocol in the kernel.\n * Second argument is buffer to which options\n * will be moved, and return value is their length.\n * (XXX) should be deleted; last arg currently ignored.\n */\nvoid\nip_stripoptions(register struct mbuf *m, struct mbuf *mopt)\n{\n\tregister int i;\n\tstruct ip *ip = mtod(m, struct ip *);\n\tregister caddr_t opts;\n\tint olen;\n\n\tolen = (ip->ip_hl<<2) - sizeof (struct ip);\n\topts = (caddr_t)(ip + 1);\n\ti = m->m_len - (sizeof (struct ip) + olen);\n\tmemcpy(opts, opts + olen, (unsigned)i);\n\tm->m_len -= olen;\n\n\tip->ip_hl = sizeof(struct ip) >> 2;\n}\n"], ["/linuxpdf/tinyemu/cutils.c", "/*\n * Misc C utilities\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n\nvoid *mallocz(size_t size)\n{\n void *ptr;\n ptr = malloc(size);\n if (!ptr)\n return NULL;\n memset(ptr, 0, size);\n return ptr;\n}\n\nvoid pstrcpy(char *buf, int buf_size, const char *str)\n{\n int c;\n char *q = buf;\n\n if (buf_size <= 0)\n return;\n\n for(;;) {\n c = *str++;\n if (c == 0 || q >= buf + buf_size - 1)\n break;\n *q++ = c;\n }\n *q = '\\0';\n}\n\nchar *pstrcat(char *buf, int buf_size, const char *s)\n{\n int len;\n len = strlen(buf);\n if (len < buf_size)\n pstrcpy(buf + len, buf_size - len, s);\n return buf;\n}\n\nint strstart(const char *str, const char *val, const char **ptr)\n{\n const char *p, *q;\n p = str;\n q = val;\n while (*q != '\\0') {\n if (*p != *q)\n return 0;\n p++;\n q++;\n }\n if (ptr)\n *ptr = p;\n return 1;\n}\n\nvoid dbuf_init(DynBuf *s)\n{\n memset(s, 0, sizeof(*s));\n}\n\nvoid dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len)\n{\n size_t end, new_size;\n new_size = end = offset + len;\n if (new_size > s->allocated_size) {\n new_size = max_int(new_size, s->allocated_size * 3 / 2);\n s->buf = realloc(s->buf, new_size);\n s->allocated_size = new_size;\n }\n memcpy(s->buf + offset, data, len);\n if (end > s->size)\n s->size = end;\n}\n\nvoid dbuf_putc(DynBuf *s, uint8_t c)\n{\n dbuf_write(s, s->size, &c, 1);\n}\n\nvoid dbuf_putstr(DynBuf *s, const char *str)\n{\n dbuf_write(s, s->size, (const uint8_t *)str, strlen(str));\n}\n\nvoid dbuf_free(DynBuf *s)\n{\n free(s->buf);\n memset(s, 0, sizeof(*s));\n}\n"], ["/linuxpdf/tinyemu/slirp/udp.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)udp_usrreq.c\t8.4 (Berkeley) 1/21/94\n * udp_usrreq.c,v 1.4 1994/10/02 17:48:45 phk Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\nstatic uint8_t udp_tos(struct socket *so);\n\nvoid\nudp_init(Slirp *slirp)\n{\n slirp->udb.so_next = slirp->udb.so_prev = &slirp->udb;\n slirp->udp_last_so = &slirp->udb;\n}\n/* m->m_data points at ip packet header\n * m->m_len length ip packet\n * ip->ip_len length data (IPDU)\n */\nvoid\nudp_input(register struct mbuf *m, int iphlen)\n{\n\tSlirp *slirp = m->slirp;\n\tregister struct ip *ip;\n\tregister struct udphdr *uh;\n\tint len;\n\tstruct ip save_ip;\n\tstruct socket *so;\n\n\tDEBUG_CALL(\"udp_input\");\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"iphlen = %d\", iphlen);\n\n\t/*\n\t * Strip IP options, if any; should skip this,\n\t * make available to user, and use on returned packets,\n\t * but we don't yet have a way to check the checksum\n\t * with options still present.\n\t */\n\tif(iphlen > sizeof(struct ip)) {\n\t\tip_stripoptions(m, (struct mbuf *)0);\n\t\tiphlen = sizeof(struct ip);\n\t}\n\n\t/*\n\t * Get IP and UDP header together in first mbuf.\n\t */\n\tip = mtod(m, struct ip *);\n\tuh = (struct udphdr *)((caddr_t)ip + iphlen);\n\n\t/*\n\t * Make mbuf data length reflect UDP length.\n\t * If not enough data to reflect UDP length, drop.\n\t */\n\tlen = ntohs((uint16_t)uh->uh_ulen);\n\n\tif (ip->ip_len != len) {\n\t\tif (len > ip->ip_len) {\n\t\t\tgoto bad;\n\t\t}\n\t\tm_adj(m, len - ip->ip_len);\n\t\tip->ip_len = len;\n\t}\n\n\t/*\n\t * Save a copy of the IP header in case we want restore it\n\t * for sending an ICMP error message in response.\n\t */\n\tsave_ip = *ip;\n\tsave_ip.ip_len+= iphlen; /* tcp_input subtracts this */\n\n\t/*\n\t * Checksum extended UDP header and data.\n\t */\n\tif (uh->uh_sum) {\n memset(&((struct ipovly *)ip)->ih_mbuf, 0, sizeof(struct mbuf_ptr));\n\t ((struct ipovly *)ip)->ih_x1 = 0;\n\t ((struct ipovly *)ip)->ih_len = uh->uh_ulen;\n\t if(cksum(m, len + sizeof(struct ip))) {\n\t goto bad;\n\t }\n\t}\n\n /*\n * handle DHCP/BOOTP\n */\n if (ntohs(uh->uh_dport) == BOOTP_SERVER) {\n bootp_input(m);\n goto bad;\n }\n\n if (slirp->restricted) {\n goto bad;\n }\n\n#if 0\n /*\n * handle TFTP\n */\n if (ntohs(uh->uh_dport) == TFTP_SERVER) {\n tftp_input(m);\n goto bad;\n }\n#endif\n \n\t/*\n\t * Locate pcb for datagram.\n\t */\n\tso = slirp->udp_last_so;\n\tif (so->so_lport != uh->uh_sport ||\n\t so->so_laddr.s_addr != ip->ip_src.s_addr) {\n\t\tstruct socket *tmp;\n\n\t\tfor (tmp = slirp->udb.so_next; tmp != &slirp->udb;\n\t\t tmp = tmp->so_next) {\n\t\t\tif (tmp->so_lport == uh->uh_sport &&\n\t\t\t tmp->so_laddr.s_addr == ip->ip_src.s_addr) {\n\t\t\t\tso = tmp;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (tmp == &slirp->udb) {\n\t\t so = NULL;\n\t\t} else {\n\t\t slirp->udp_last_so = so;\n\t\t}\n\t}\n\n\tif (so == NULL) {\n\t /*\n\t * If there's no socket for this packet,\n\t * create one\n\t */\n\t so = socreate(slirp);\n\t if (!so) {\n\t goto bad;\n\t }\n\t if(udp_attach(so) == -1) {\n\t DEBUG_MISC((dfd,\" udp_attach errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t sofree(so);\n\t goto bad;\n\t }\n\n\t /*\n\t * Setup fields\n\t */\n\t so->so_laddr = ip->ip_src;\n\t so->so_lport = uh->uh_sport;\n\n\t if ((so->so_iptos = udp_tos(so)) == 0)\n\t so->so_iptos = ip->ip_tos;\n\n\t /*\n\t * XXXXX Here, check if it's in udpexec_list,\n\t * and if it is, do the fork_exec() etc.\n\t */\n\t}\n\n so->so_faddr = ip->ip_dst; /* XXX */\n so->so_fport = uh->uh_dport; /* XXX */\n\n\tiphlen += sizeof(struct udphdr);\n\tm->m_len -= iphlen;\n\tm->m_data += iphlen;\n\n\t/*\n\t * Now we sendto() the packet.\n\t */\n\tif(sosendto(so,m) == -1) {\n\t m->m_len += iphlen;\n\t m->m_data -= iphlen;\n\t *ip=save_ip;\n\t DEBUG_MISC((dfd,\"udp tx errno = %d-%s\\n\",errno,strerror(errno)));\n\t icmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));\n\t}\n\n\tm_free(so->so_m); /* used for ICMP if error on sorecvfrom */\n\n\t/* restore the orig mbuf packet */\n\tm->m_len += iphlen;\n\tm->m_data -= iphlen;\n\t*ip=save_ip;\n\tso->so_m=m; /* ICMP backup */\n\n\treturn;\nbad:\n\tm_freem(m);\n\treturn;\n}\n\nint udp_output2(struct socket *so, struct mbuf *m,\n struct sockaddr_in *saddr, struct sockaddr_in *daddr,\n int iptos)\n{\n\tregister struct udpiphdr *ui;\n\tint error = 0;\n\n\tDEBUG_CALL(\"udp_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"saddr = %lx\", (long)saddr->sin_addr.s_addr);\n\tDEBUG_ARG(\"daddr = %lx\", (long)daddr->sin_addr.s_addr);\n\n\t/*\n\t * Adjust for header\n\t */\n\tm->m_data -= sizeof(struct udpiphdr);\n\tm->m_len += sizeof(struct udpiphdr);\n\n\t/*\n\t * Fill in mbuf with extended UDP header\n\t * and addresses and length put into network format.\n\t */\n\tui = mtod(m, struct udpiphdr *);\n memset(&ui->ui_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));\n\tui->ui_x1 = 0;\n\tui->ui_pr = IPPROTO_UDP;\n\tui->ui_len = htons(m->m_len - sizeof(struct ip));\n\t/* XXXXX Check for from-one-location sockets, or from-any-location sockets */\n ui->ui_src = saddr->sin_addr;\n\tui->ui_dst = daddr->sin_addr;\n\tui->ui_sport = saddr->sin_port;\n\tui->ui_dport = daddr->sin_port;\n\tui->ui_ulen = ui->ui_len;\n\n\t/*\n\t * Stuff checksum and output datagram.\n\t */\n\tui->ui_sum = 0;\n\tif ((ui->ui_sum = cksum(m, m->m_len)) == 0)\n\t\tui->ui_sum = 0xffff;\n\t((struct ip *)ui)->ip_len = m->m_len;\n\n\t((struct ip *)ui)->ip_ttl = IPDEFTTL;\n\t((struct ip *)ui)->ip_tos = iptos;\n\n\terror = ip_output(so, m);\n\n\treturn (error);\n}\n\nint udp_output(struct socket *so, struct mbuf *m,\n struct sockaddr_in *addr)\n\n{\n Slirp *slirp = so->slirp;\n struct sockaddr_in saddr, daddr;\n\n saddr = *addr;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n uint32_t inv_mask = ~slirp->vnetwork_mask.s_addr;\n\n if ((so->so_faddr.s_addr & inv_mask) == inv_mask) {\n saddr.sin_addr = slirp->vhost_addr;\n } else if (addr->sin_addr.s_addr == loopback_addr.s_addr ||\n so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {\n saddr.sin_addr = so->so_faddr;\n }\n }\n daddr.sin_addr = so->so_laddr;\n daddr.sin_port = so->so_lport;\n\n return udp_output2(so, m, &saddr, &daddr, so->so_iptos);\n}\n\nint\nudp_attach(struct socket *so)\n{\n if((so->s = os_socket(AF_INET,SOCK_DGRAM,0)) != -1) {\n so->so_expire = curtime + SO_EXPIRE;\n insque(so, &so->slirp->udb);\n }\n return(so->s);\n}\n\nvoid\nudp_detach(struct socket *so)\n{\n\tclosesocket(so->s);\n\tsofree(so);\n}\n\nstatic const struct tos_t udptos[] = {\n\t{0, 53, IPTOS_LOWDELAY, 0},\t\t\t/* DNS */\n\t{0, 0, 0, 0}\n};\n\nstatic uint8_t\nudp_tos(struct socket *so)\n{\n\tint i = 0;\n\n\twhile(udptos[i].tos) {\n\t\tif ((udptos[i].fport && ntohs(so->so_fport) == udptos[i].fport) ||\n\t\t (udptos[i].lport && ntohs(so->so_lport) == udptos[i].lport)) {\n\t\t \tso->so_emu = udptos[i].emu;\n\t\t\treturn udptos[i].tos;\n\t\t}\n\t\ti++;\n\t}\n\n\treturn 0;\n}\n\nstruct socket *\nudp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,\n u_int lport, int flags)\n{\n\tstruct sockaddr_in addr;\n\tstruct socket *so;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in), opt = 1;\n\n\tso = socreate(slirp);\n\tif (!so) {\n\t return NULL;\n\t}\n\tso->s = os_socket(AF_INET,SOCK_DGRAM,0);\n\tso->so_expire = curtime + SO_EXPIRE;\n\tinsque(so, &slirp->udb);\n\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = haddr;\n\taddr.sin_port = hport;\n\n\tif (bind(so->s,(struct sockaddr *)&addr, addrlen) < 0) {\n\t\tudp_detach(so);\n\t\treturn NULL;\n\t}\n\tsetsockopt(so->s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\n\tgetsockname(so->s,(struct sockaddr *)&addr,&addrlen);\n\tso->so_fport = addr.sin_port;\n\tif (addr.sin_addr.s_addr == 0 ||\n\t addr.sin_addr.s_addr == loopback_addr.s_addr) {\n\t so->so_faddr = slirp->vhost_addr;\n\t} else {\n\t so->so_faddr = addr.sin_addr;\n\t}\n\tso->so_lport = lport;\n\tso->so_laddr.s_addr = laddr;\n\tif (flags != SS_FACCEPTONCE)\n\t so->so_expire = 0;\n\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= SS_ISFCONNECTED | flags;\n\n\treturn so;\n}\n"], ["/linuxpdf/tinyemu/fs_utils.c", "/*\n * Misc FS utilities\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs_utils.h\"\n\n/* last byte is the version */\nconst uint8_t encrypted_file_magic[4] = { 0xfb, 0xa2, 0xe9, 0x01 };\n\nchar *compose_path(const char *path, const char *name)\n{\n int path_len, name_len;\n char *d, *q;\n\n if (path[0] == '\\0') {\n d = strdup(name);\n } else {\n path_len = strlen(path);\n name_len = strlen(name);\n d = malloc(path_len + 1 + name_len + 1);\n q = d;\n memcpy(q, path, path_len);\n q += path_len;\n if (path[path_len - 1] != '/')\n *q++ = '/';\n memcpy(q, name, name_len + 1);\n }\n return d;\n}\n\nchar *compose_url(const char *base_url, const char *name)\n{\n if (strchr(name, ':')) {\n return strdup(name);\n } else {\n return compose_path(base_url, name);\n }\n}\n\nvoid skip_line(const char **pp)\n{\n const char *p;\n p = *pp;\n while (*p != '\\n' && *p != '\\0')\n p++;\n if (*p == '\\n')\n p++;\n *pp = p;\n}\n\nchar *quoted_str(const char *str)\n{\n const char *s;\n char *q;\n int c;\n char *buf;\n\n if (str[0] == '\\0')\n goto use_quote;\n s = str;\n while (*s != '\\0') {\n if (*s <= ' ' || *s > '~')\n goto use_quote;\n s++;\n }\n return strdup(str);\n use_quote:\n buf = malloc(strlen(str) * 4 + 2 + 1);\n q = buf;\n s = str;\n *q++ = '\"';\n while (*s != '\\0') {\n c = *(uint8_t *)s;\n if (c < ' ' || c == 127) {\n q += sprintf(q, \"\\\\x%02x\", c);\n } else if (c == '\\\\' || c == '\\\"') {\n q += sprintf(q, \"\\\\%c\", c);\n } else {\n *q++ = c;\n }\n s++;\n }\n *q++ = '\"';\n *q = '\\0';\n return buf;\n}\n\nint parse_fname(char *buf, int buf_size, const char **pp)\n{\n const char *p;\n char *q;\n int c, h;\n \n p = *pp;\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\0')\n return -1;\n q = buf;\n if (*p == '\"') {\n p++;\n for(;;) {\n c = *p++;\n if (c == '\\0' || c == '\\n') {\n return -1;\n } else if (c == '\\\"') {\n break;\n } else if (c == '\\\\') {\n c = *p++;\n switch(c) {\n case '\\'':\n case '\\\"':\n case '\\\\':\n goto add_char;\n case 'n':\n c = '\\n';\n goto add_char;\n case 'r':\n c = '\\r';\n goto add_char;\n case 't':\n c = '\\t';\n goto add_char;\n case 'x':\n h = from_hex(*p++);\n if (h < 0)\n return -1;\n c = h << 4;\n h = from_hex(*p++);\n if (h < 0)\n return -1;\n c |= h;\n goto add_char;\n default:\n return -1;\n }\n } else {\n add_char:\n if (q >= buf + buf_size - 1)\n return -1;\n *q++ = c;\n }\n }\n } else {\n while (!isspace_nolf(*p) && *p != '\\0' && *p != '\\n') {\n if (q >= buf + buf_size - 1)\n return -1;\n *q++ = *p++;\n }\n }\n *q = '\\0';\n *pp = p;\n return 0;\n}\n\nint parse_uint32_base(uint32_t *pval, const char **pp, int base)\n{\n const char *p, *p1;\n p = *pp;\n while (isspace_nolf(*p))\n p++;\n *pval = strtoul(p, (char **)&p1, base);\n if (p1 == p)\n return -1;\n *pp = p1;\n return 0;\n}\n\nint parse_uint64_base(uint64_t *pval, const char **pp, int base)\n{\n const char *p, *p1;\n p = *pp;\n while (isspace_nolf(*p))\n p++;\n *pval = strtoull(p, (char **)&p1, base);\n if (p1 == p)\n return -1;\n *pp = p1;\n return 0;\n}\n\nint parse_uint64(uint64_t *pval, const char **pp)\n{\n return parse_uint64_base(pval, pp, 0);\n}\n\nint parse_uint32(uint32_t *pval, const char **pp)\n{\n return parse_uint32_base(pval, pp, 0);\n}\n\nint parse_time(uint32_t *psec, uint32_t *pnsec, const char **pp)\n{\n const char *p;\n uint32_t v, m;\n p = *pp;\n if (parse_uint32(psec, &p) < 0)\n return -1;\n v = 0;\n if (*p == '.') {\n p++;\n /* XXX: inefficient */\n m = 1000000000;\n v = 0;\n while (*p >= '0' && *p <= '9') {\n m /= 10;\n v += (*p - '0') * m;\n p++;\n }\n }\n *pnsec = v;\n *pp = p;\n return 0;\n}\n\nint parse_file_id(FSFileID *pval, const char **pp)\n{\n return parse_uint64_base(pval, pp, 16);\n}\n\nchar *file_id_to_filename(char *buf, FSFileID file_id)\n{\n sprintf(buf, \"%016\" PRIx64, file_id);\n return buf;\n}\n\nvoid encode_hex(char *str, const uint8_t *buf, int len)\n{\n int i;\n for(i = 0; i < len; i++)\n sprintf(str + 2 * i, \"%02x\", buf[i]);\n}\n\nint decode_hex(uint8_t *buf, const char *str, int len)\n{\n int h0, h1, i;\n\n for(i = 0; i < len; i++) {\n h0 = from_hex(str[2 * i]);\n if (h0 < 0)\n return -1;\n h1 = from_hex(str[2 * i + 1]);\n if (h1 < 0)\n return -1;\n buf[i] = (h0 << 4) | h1;\n }\n return 0;\n}\n\n/* return NULL if no end of header found */\nconst char *skip_header(const char *p)\n{\n p = strstr(p, \"\\n\\n\");\n if (!p)\n return NULL;\n return p + 2;\n}\n\n/* return 0 if OK, < 0 if error */\nint parse_tag(char *buf, int buf_size, const char *str, const char *tag)\n{\n char tagname[128], *q;\n const char *p, *p1;\n int len;\n \n p = str;\n for(;;) {\n if (*p == '\\0' || *p == '\\n')\n break;\n q = tagname;\n while (*p != ':' && *p != '\\n' && *p != '\\0') {\n if ((q - tagname) < sizeof(tagname) - 1)\n *q++ = *p;\n p++;\n }\n *q = '\\0';\n if (*p != ':')\n return -1;\n p++;\n while (isspace_nolf(*p))\n p++;\n p1 = p;\n p = strchr(p, '\\n');\n if (!p)\n len = strlen(p1);\n else\n len = p - p1;\n if (!strcmp(tagname, tag)) {\n if (len > buf_size - 1)\n len = buf_size - 1;\n memcpy(buf, p1, len);\n buf[len] = '\\0';\n return 0;\n }\n if (!p)\n break;\n else\n p++;\n }\n return -1;\n}\n\nint parse_tag_uint64(uint64_t *pval, const char *str, const char *tag)\n{\n char buf[64];\n const char *p;\n if (parse_tag(buf, sizeof(buf), str, tag))\n return -1;\n p = buf;\n return parse_uint64(pval, &p);\n}\n\nint parse_tag_file_id(FSFileID *pval, const char *str, const char *tag)\n{\n char buf[64];\n const char *p;\n if (parse_tag(buf, sizeof(buf), str, tag))\n return -1;\n p = buf;\n return parse_uint64_base(pval, &p, 16);\n}\n\nint parse_tag_version(const char *str)\n{\n uint64_t version;\n if (parse_tag_uint64(&version, str, \"Version\"))\n return -1;\n return version;\n}\n\nBOOL is_url(const char *path)\n{\n return (strstart(path, \"http:\", NULL) ||\n strstart(path, \"https:\", NULL) ||\n strstart(path, \"file:\", NULL));\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_output.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_output.c\t8.3 (Berkeley) 12/30/93\n * tcp_output.c,v 1.3 1994/09/15 10:36:55 davidg Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\nstatic const u_char tcp_outflags[TCP_NSTATES] = {\n\tTH_RST|TH_ACK, 0, TH_SYN, TH_SYN|TH_ACK,\n\tTH_ACK, TH_ACK, TH_FIN|TH_ACK, TH_FIN|TH_ACK,\n\tTH_FIN|TH_ACK, TH_ACK, TH_ACK,\n};\n\n\n#define MAX_TCPOPTLEN\t32\t/* max # bytes that go in options */\n\n/*\n * Tcp output routine: figure out what should be sent and send it.\n */\nint\ntcp_output(struct tcpcb *tp)\n{\n\tregister struct socket *so = tp->t_socket;\n\tregister long len, win;\n\tint off, flags, error;\n\tregister struct mbuf *m;\n\tregister struct tcpiphdr *ti;\n\tu_char opt[MAX_TCPOPTLEN];\n\tunsigned optlen, hdrlen;\n\tint idle, sendalot;\n\n\tDEBUG_CALL(\"tcp_output\");\n\tDEBUG_ARG(\"tp = %lx\", (long )tp);\n\n\t/*\n\t * Determine length of data that should be transmitted,\n\t * and flags that will be used.\n\t * If there is some data or critical controls (SYN, RST)\n\t * to send, then transmit; otherwise, investigate further.\n\t */\n\tidle = (tp->snd_max == tp->snd_una);\n\tif (idle && tp->t_idle >= tp->t_rxtcur)\n\t\t/*\n\t\t * We have been idle for \"a while\" and no acks are\n\t\t * expected to clock out any data we send --\n\t\t * slow start to get ack \"clock\" running again.\n\t\t */\n\t\ttp->snd_cwnd = tp->t_maxseg;\nagain:\n\tsendalot = 0;\n\toff = tp->snd_nxt - tp->snd_una;\n\twin = min(tp->snd_wnd, tp->snd_cwnd);\n\n\tflags = tcp_outflags[tp->t_state];\n\n\tDEBUG_MISC((dfd, \" --- tcp_output flags = 0x%x\\n\",flags));\n\n\t/*\n\t * If in persist timeout with window of 0, send 1 byte.\n\t * Otherwise, if window is small but nonzero\n\t * and timer expired, we will send what we can\n\t * and go to transmit state.\n\t */\n\tif (tp->t_force) {\n\t\tif (win == 0) {\n\t\t\t/*\n\t\t\t * If we still have some data to send, then\n\t\t\t * clear the FIN bit. Usually this would\n\t\t\t * happen below when it realizes that we\n\t\t\t * aren't sending all the data. However,\n\t\t\t * if we have exactly 1 byte of unset data,\n\t\t\t * then it won't clear the FIN bit below,\n\t\t\t * and if we are in persist state, we wind\n\t\t\t * up sending the packet without recording\n\t\t\t * that we sent the FIN bit.\n\t\t\t *\n\t\t\t * We can't just blindly clear the FIN bit,\n\t\t\t * because if we don't have any more data\n\t\t\t * to send then the probe will be the FIN\n\t\t\t * itself.\n\t\t\t */\n\t\t\tif (off < so->so_snd.sb_cc)\n\t\t\t\tflags &= ~TH_FIN;\n\t\t\twin = 1;\n\t\t} else {\n\t\t\ttp->t_timer[TCPT_PERSIST] = 0;\n\t\t\ttp->t_rxtshift = 0;\n\t\t}\n\t}\n\n\tlen = min(so->so_snd.sb_cc, win) - off;\n\n\tif (len < 0) {\n\t\t/*\n\t\t * If FIN has been sent but not acked,\n\t\t * but we haven't been called to retransmit,\n\t\t * len will be -1. Otherwise, window shrank\n\t\t * after we sent into it. If window shrank to 0,\n\t\t * cancel pending retransmit and pull snd_nxt\n\t\t * back to (closed) window. We will enter persist\n\t\t * state below. If the window didn't close completely,\n\t\t * just wait for an ACK.\n\t\t */\n\t\tlen = 0;\n\t\tif (win == 0) {\n\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\ttp->snd_nxt = tp->snd_una;\n\t\t}\n\t}\n\n\tif (len > tp->t_maxseg) {\n\t\tlen = tp->t_maxseg;\n\t\tsendalot = 1;\n\t}\n\tif (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc))\n\t\tflags &= ~TH_FIN;\n\n\twin = sbspace(&so->so_rcv);\n\n\t/*\n\t * Sender silly window avoidance. If connection is idle\n\t * and can send all data, a maximum segment,\n\t * at least a maximum default-size segment do it,\n\t * or are forced, do it; otherwise don't bother.\n\t * If peer's buffer is tiny, then send\n\t * when window is at least half open.\n\t * If retransmitting (possibly after persist timer forced us\n\t * to send into a small window), then must resend.\n\t */\n\tif (len) {\n\t\tif (len == tp->t_maxseg)\n\t\t\tgoto send;\n\t\tif ((1 || idle || tp->t_flags & TF_NODELAY) &&\n\t\t len + off >= so->so_snd.sb_cc)\n\t\t\tgoto send;\n\t\tif (tp->t_force)\n\t\t\tgoto send;\n\t\tif (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)\n\t\t\tgoto send;\n\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_max))\n\t\t\tgoto send;\n\t}\n\n\t/*\n\t * Compare available window to amount of window\n\t * known to peer (as advertised window less\n\t * next expected input). If the difference is at least two\n\t * max size segments, or at least 50% of the maximum possible\n\t * window, then want to send a window update to peer.\n\t */\n\tif (win > 0) {\n\t\t/*\n\t\t * \"adv\" is the amount we can increase the window,\n\t\t * taking into account that we are limited by\n\t\t * TCP_MAXWIN << tp->rcv_scale.\n\t\t */\n\t\tlong adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -\n\t\t\t(tp->rcv_adv - tp->rcv_nxt);\n\n\t\tif (adv >= (long) (2 * tp->t_maxseg))\n\t\t\tgoto send;\n\t\tif (2 * adv >= (long) so->so_rcv.sb_datalen)\n\t\t\tgoto send;\n\t}\n\n\t/*\n\t * Send if we owe peer an ACK.\n\t */\n\tif (tp->t_flags & TF_ACKNOW)\n\t\tgoto send;\n\tif (flags & (TH_SYN|TH_RST))\n\t\tgoto send;\n\tif (SEQ_GT(tp->snd_up, tp->snd_una))\n\t\tgoto send;\n\t/*\n\t * If our state indicates that FIN should be sent\n\t * and we have not yet done so, or we're retransmitting the FIN,\n\t * then we need to send.\n\t */\n\tif (flags & TH_FIN &&\n\t ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))\n\t\tgoto send;\n\n\t/*\n\t * TCP window updates are not reliable, rather a polling protocol\n\t * using ``persist'' packets is used to insure receipt of window\n\t * updates. The three ``states'' for the output side are:\n\t *\tidle\t\t\tnot doing retransmits or persists\n\t *\tpersisting\t\tto move a small or zero window\n\t *\t(re)transmitting\tand thereby not persisting\n\t *\n\t * tp->t_timer[TCPT_PERSIST]\n\t *\tis set when we are in persist state.\n\t * tp->t_force\n\t *\tis set when we are called to send a persist packet.\n\t * tp->t_timer[TCPT_REXMT]\n\t *\tis set when we are retransmitting\n\t * The output side is idle when both timers are zero.\n\t *\n\t * If send window is too small, there is data to transmit, and no\n\t * retransmit or persist is pending, then go to persist state.\n\t * If nothing happens soon, send when timer expires:\n\t * if window is nonzero, transmit what we can,\n\t * otherwise force out a byte.\n\t */\n\tif (so->so_snd.sb_cc && tp->t_timer[TCPT_REXMT] == 0 &&\n\t tp->t_timer[TCPT_PERSIST] == 0) {\n\t\ttp->t_rxtshift = 0;\n\t\ttcp_setpersist(tp);\n\t}\n\n\t/*\n\t * No reason to send a segment, just return.\n\t */\n\treturn (0);\n\nsend:\n\t/*\n\t * Before ESTABLISHED, force sending of initial options\n\t * unless TCP set not to do any options.\n\t * NOTE: we assume that the IP/TCP header plus TCP options\n\t * always fit in a single mbuf, leaving room for a maximum\n\t * link header, i.e.\n\t *\tmax_linkhdr + sizeof (struct tcpiphdr) + optlen <= MHLEN\n\t */\n\toptlen = 0;\n\thdrlen = sizeof (struct tcpiphdr);\n\tif (flags & TH_SYN) {\n\t\ttp->snd_nxt = tp->iss;\n\t\tif ((tp->t_flags & TF_NOOPT) == 0) {\n\t\t\tuint16_t mss;\n\n\t\t\topt[0] = TCPOPT_MAXSEG;\n\t\t\topt[1] = 4;\n\t\t\tmss = htons((uint16_t) tcp_mss(tp, 0));\n\t\t\tmemcpy((caddr_t)(opt + 2), (caddr_t)&mss, sizeof(mss));\n\t\t\toptlen = 4;\n\t\t}\n \t}\n\n \thdrlen += optlen;\n\n\t/*\n\t * Adjust data length if insertion of options will\n\t * bump the packet length beyond the t_maxseg length.\n\t */\n\t if (len > tp->t_maxseg - optlen) {\n\t\tlen = tp->t_maxseg - optlen;\n\t\tsendalot = 1;\n\t }\n\n\t/*\n\t * Grab a header mbuf, attaching a copy of data to\n\t * be transmitted, and initialize the header from\n\t * the template for sends on this connection.\n\t */\n\tif (len) {\n\t\tm = m_get(so->slirp);\n\t\tif (m == NULL) {\n\t\t\terror = 1;\n\t\t\tgoto out;\n\t\t}\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\tm->m_len = hdrlen;\n\n\t\tsbcopy(&so->so_snd, off, (int) len, mtod(m, caddr_t) + hdrlen);\n\t\tm->m_len += len;\n\n\t\t/*\n\t\t * If we're sending everything we've got, set PUSH.\n\t\t * (This will keep happy those implementations which only\n\t\t * give data to the user when a buffer fills or\n\t\t * a PUSH comes in.)\n\t\t */\n\t\tif (off + len == so->so_snd.sb_cc)\n\t\t\tflags |= TH_PUSH;\n\t} else {\n\t\tm = m_get(so->slirp);\n\t\tif (m == NULL) {\n\t\t\terror = 1;\n\t\t\tgoto out;\n\t\t}\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\tm->m_len = hdrlen;\n\t}\n\n\tti = mtod(m, struct tcpiphdr *);\n\n\tmemcpy((caddr_t)ti, &tp->t_template, sizeof (struct tcpiphdr));\n\n\t/*\n\t * Fill in fields, remembering maximum advertised\n\t * window for use in delaying messages about window sizes.\n\t * If resending a FIN, be sure not to use a new sequence number.\n\t */\n\tif (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&\n\t tp->snd_nxt == tp->snd_max)\n\t\ttp->snd_nxt--;\n\t/*\n\t * If we are doing retransmissions, then snd_nxt will\n\t * not reflect the first unsent octet. For ACK only\n\t * packets, we do not want the sequence number of the\n\t * retransmitted packet, we want the sequence number\n\t * of the next unsent octet. So, if there is no data\n\t * (and no SYN or FIN), use snd_max instead of snd_nxt\n\t * when filling in ti_seq. But if we are in persist\n\t * state, snd_max might reflect one byte beyond the\n\t * right edge of the window, so use snd_nxt in that\n\t * case, since we know we aren't doing a retransmission.\n\t * (retransmit and persist are mutually exclusive...)\n\t */\n\tif (len || (flags & (TH_SYN|TH_FIN)) || tp->t_timer[TCPT_PERSIST])\n\t\tti->ti_seq = htonl(tp->snd_nxt);\n\telse\n\t\tti->ti_seq = htonl(tp->snd_max);\n\tti->ti_ack = htonl(tp->rcv_nxt);\n\tif (optlen) {\n\t\tmemcpy((caddr_t)(ti + 1), (caddr_t)opt, optlen);\n\t\tti->ti_off = (sizeof (struct tcphdr) + optlen) >> 2;\n\t}\n\tti->ti_flags = flags;\n\t/*\n\t * Calculate receive window. Don't shrink window,\n\t * but avoid silly window syndrome.\n\t */\n\tif (win < (long)(so->so_rcv.sb_datalen / 4) && win < (long)tp->t_maxseg)\n\t\twin = 0;\n\tif (win > (long)TCP_MAXWIN << tp->rcv_scale)\n\t\twin = (long)TCP_MAXWIN << tp->rcv_scale;\n\tif (win < (long)(tp->rcv_adv - tp->rcv_nxt))\n\t\twin = (long)(tp->rcv_adv - tp->rcv_nxt);\n\tti->ti_win = htons((uint16_t) (win>>tp->rcv_scale));\n\n\tif (SEQ_GT(tp->snd_up, tp->snd_una)) {\n\t\tti->ti_urp = htons((uint16_t)(tp->snd_up - ntohl(ti->ti_seq)));\n\t\tti->ti_flags |= TH_URG;\n\t} else\n\t\t/*\n\t\t * If no urgent pointer to send, then we pull\n\t\t * the urgent pointer to the left edge of the send window\n\t\t * so that it doesn't drift into the send window on sequence\n\t\t * number wraparound.\n\t\t */\n\t\ttp->snd_up = tp->snd_una;\t\t/* drag it along */\n\n\t/*\n\t * Put TCP length in extended header, and then\n\t * checksum extended header and data.\n\t */\n\tif (len + optlen)\n\t\tti->ti_len = htons((uint16_t)(sizeof (struct tcphdr) +\n\t\t optlen + len));\n\tti->ti_sum = cksum(m, (int)(hdrlen + len));\n\n\t/*\n\t * In transmit state, time the transmission and arrange for\n\t * the retransmit. In persist state, just set snd_max.\n\t */\n\tif (tp->t_force == 0 || tp->t_timer[TCPT_PERSIST] == 0) {\n\t\ttcp_seq startseq = tp->snd_nxt;\n\n\t\t/*\n\t\t * Advance snd_nxt over sequence space of this segment.\n\t\t */\n\t\tif (flags & (TH_SYN|TH_FIN)) {\n\t\t\tif (flags & TH_SYN)\n\t\t\t\ttp->snd_nxt++;\n\t\t\tif (flags & TH_FIN) {\n\t\t\t\ttp->snd_nxt++;\n\t\t\t\ttp->t_flags |= TF_SENTFIN;\n\t\t\t}\n\t\t}\n\t\ttp->snd_nxt += len;\n\t\tif (SEQ_GT(tp->snd_nxt, tp->snd_max)) {\n\t\t\ttp->snd_max = tp->snd_nxt;\n\t\t\t/*\n\t\t\t * Time this transmission if not a retransmission and\n\t\t\t * not currently timing anything.\n\t\t\t */\n\t\t\tif (tp->t_rtt == 0) {\n\t\t\t\ttp->t_rtt = 1;\n\t\t\t\ttp->t_rtseq = startseq;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Set retransmit timer if not currently set,\n\t\t * and not doing an ack or a keep-alive probe.\n\t\t * Initial value for retransmit timer is smoothed\n\t\t * round-trip time + 2 * round-trip time variance.\n\t\t * Initialize shift counter which is used for backoff\n\t\t * of retransmit time.\n\t\t */\n\t\tif (tp->t_timer[TCPT_REXMT] == 0 &&\n\t\t tp->snd_nxt != tp->snd_una) {\n\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t\tif (tp->t_timer[TCPT_PERSIST]) {\n\t\t\t\ttp->t_timer[TCPT_PERSIST] = 0;\n\t\t\t\ttp->t_rxtshift = 0;\n\t\t\t}\n\t\t}\n\t} else\n\t\tif (SEQ_GT(tp->snd_nxt + len, tp->snd_max))\n\t\t\ttp->snd_max = tp->snd_nxt + len;\n\n\t/*\n\t * Fill in IP length and desired time to live and\n\t * send to IP level. There should be a better way\n\t * to handle ttl and tos; we could keep them in\n\t * the template, but need a way to checksum without them.\n\t */\n\tm->m_len = hdrlen + len; /* XXX Needed? m_len should be correct */\n\n {\n\n\t((struct ip *)ti)->ip_len = m->m_len;\n\n\t((struct ip *)ti)->ip_ttl = IPDEFTTL;\n\t((struct ip *)ti)->ip_tos = so->so_iptos;\n\n\terror = ip_output(so, m);\n }\n\tif (error) {\nout:\n\t\treturn (error);\n\t}\n\n\t/*\n\t * Data sent (as far as we can tell).\n\t * If this advertises a larger window than any other segment,\n\t * then remember the size of the advertised window.\n\t * Any pending ACK has now been sent.\n\t */\n\tif (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))\n\t\ttp->rcv_adv = tp->rcv_nxt + win;\n\ttp->last_ack_sent = tp->rcv_nxt;\n\ttp->t_flags &= ~(TF_ACKNOW|TF_DELACK);\n\tif (sendalot)\n\t\tgoto again;\n\n\treturn (0);\n}\n\nvoid\ntcp_setpersist(struct tcpcb *tp)\n{\n int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;\n\n\t/*\n\t * Start/restart persistence timer.\n\t */\n\tTCPT_RANGESET(tp->t_timer[TCPT_PERSIST],\n\t t * tcp_backoff[tp->t_rxtshift],\n\t TCPTV_PERSMIN, TCPTV_PERSMAX);\n\tif (tp->t_rxtshift < TCP_MAXRXTSHIFT)\n\t\ttp->t_rxtshift++;\n}\n"], ["/linuxpdf/tinyemu/splitimg.c", "/*\n * Disk image splitter\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n int blocksize, ret, i;\n const char *infilename, *outpath;\n FILE *f, *fo;\n char buf1[1024];\n uint8_t *buf;\n\n if ((optind + 1) >= argc) {\n printf(\"splitimg version \" CONFIG_VERSION \", Copyright (c) 2011-2016 Fabrice Bellard\\n\"\n \"usage: splitimg infile outpath [blocksize]\\n\"\n \"Create a multi-file disk image for the RISCVEMU HTTP block device\\n\"\n \"\\n\"\n \"outpath must be a directory\\n\"\n \"blocksize is the block size in KB\\n\");\n exit(1);\n }\n\n infilename = argv[optind++];\n outpath = argv[optind++];\n blocksize = 256;\n if (optind < argc)\n blocksize = strtol(argv[optind++], NULL, 0);\n\n blocksize *= 1024;\n \n buf = malloc(blocksize);\n\n f = fopen(infilename, \"rb\");\n if (!f) {\n perror(infilename);\n exit(1);\n }\n i = 0;\n for(;;) {\n ret = fread(buf, 1, blocksize, f);\n if (ret < 0) {\n perror(\"fread\");\n exit(1);\n }\n if (ret == 0)\n break;\n if (ret < blocksize) {\n printf(\"warning: last block is not full\\n\");\n memset(buf + ret, 0, blocksize - ret);\n }\n snprintf(buf1, sizeof(buf1), \"%s/blk%09u.bin\", outpath, i);\n fo = fopen(buf1, \"wb\");\n if (!fo) {\n perror(buf1);\n exit(1);\n }\n fwrite(buf, 1, blocksize, fo);\n fclose(fo);\n i++;\n }\n fclose(f);\n printf(\"%d blocks\\n\", i);\n\n snprintf(buf1, sizeof(buf1), \"%s/blk.txt\", outpath);\n fo = fopen(buf1, \"wb\");\n if (!fo) {\n perror(buf1);\n exit(1);\n }\n fprintf(fo, \"{\\n\");\n fprintf(fo, \" block_size: %d,\\n\", blocksize / 1024);\n fprintf(fo, \" n_block: %d,\\n\", i);\n fprintf(fo, \"}\\n\");\n fclose(fo);\n return 0;\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_timer.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_timer.c\t8.1 (Berkeley) 6/10/93\n * tcp_timer.c,v 1.2 1994/08/02 07:49:10 davidg Exp\n */\n\n#include \"slirp.h\"\n\nstatic struct tcpcb *tcp_timers(register struct tcpcb *tp, int timer);\n\n/*\n * Fast timeout routine for processing delayed acks\n */\nvoid\ntcp_fasttimo(Slirp *slirp)\n{\n\tregister struct socket *so;\n\tregister struct tcpcb *tp;\n\n\tDEBUG_CALL(\"tcp_fasttimo\");\n\n\tso = slirp->tcb.so_next;\n\tif (so)\n\tfor (; so != &slirp->tcb; so = so->so_next)\n\t\tif ((tp = (struct tcpcb *)so->so_tcpcb) &&\n\t\t (tp->t_flags & TF_DELACK)) {\n\t\t\ttp->t_flags &= ~TF_DELACK;\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\t(void) tcp_output(tp);\n\t\t}\n}\n\n/*\n * Tcp protocol timeout routine called every 500 ms.\n * Updates the timers in all active tcb's and\n * causes finite state machine actions if timers expire.\n */\nvoid\ntcp_slowtimo(Slirp *slirp)\n{\n\tregister struct socket *ip, *ipnxt;\n\tregister struct tcpcb *tp;\n\tregister int i;\n\n\tDEBUG_CALL(\"tcp_slowtimo\");\n\n\t/*\n\t * Search through tcb's and update active timers.\n\t */\n\tip = slirp->tcb.so_next;\n if (ip == NULL) {\n return;\n }\n\tfor (; ip != &slirp->tcb; ip = ipnxt) {\n\t\tipnxt = ip->so_next;\n\t\ttp = sototcpcb(ip);\n if (tp == NULL) {\n continue;\n }\n\t\tfor (i = 0; i < TCPT_NTIMERS; i++) {\n\t\t\tif (tp->t_timer[i] && --tp->t_timer[i] == 0) {\n\t\t\t\ttcp_timers(tp,i);\n\t\t\t\tif (ipnxt->so_prev != ip)\n\t\t\t\t\tgoto tpgone;\n\t\t\t}\n\t\t}\n\t\ttp->t_idle++;\n\t\tif (tp->t_rtt)\n\t\t tp->t_rtt++;\ntpgone:\n\t\t;\n\t}\n\tslirp->tcp_iss += TCP_ISSINCR/PR_SLOWHZ;\t/* increment iss */\n\tslirp->tcp_now++;\t\t\t\t/* for timestamps */\n}\n\n/*\n * Cancel all timers for TCP tp.\n */\nvoid\ntcp_canceltimers(struct tcpcb *tp)\n{\n\tregister int i;\n\n\tfor (i = 0; i < TCPT_NTIMERS; i++)\n\t\ttp->t_timer[i] = 0;\n}\n\nconst int tcp_backoff[TCP_MAXRXTSHIFT + 1] =\n { 1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64 };\n\n/*\n * TCP timer processing.\n */\nstatic struct tcpcb *\ntcp_timers(register struct tcpcb *tp, int timer)\n{\n\tregister int rexmt;\n\n\tDEBUG_CALL(\"tcp_timers\");\n\n\tswitch (timer) {\n\n\t/*\n\t * 2 MSL timeout in shutdown went off. If we're closed but\n\t * still waiting for peer to close and connection has been idle\n\t * too long, or if 2MSL time is up from TIME_WAIT, delete connection\n\t * control block. Otherwise, check again in a bit.\n\t */\n\tcase TCPT_2MSL:\n\t\tif (tp->t_state != TCPS_TIME_WAIT &&\n\t\t tp->t_idle <= TCP_MAXIDLE)\n\t\t\ttp->t_timer[TCPT_2MSL] = TCPTV_KEEPINTVL;\n\t\telse\n\t\t\ttp = tcp_close(tp);\n\t\tbreak;\n\n\t/*\n\t * Retransmission timer went off. Message has not\n\t * been acked within retransmit interval. Back off\n\t * to a longer retransmit interval and retransmit one segment.\n\t */\n\tcase TCPT_REXMT:\n\n\t\t/*\n\t\t * XXXXX If a packet has timed out, then remove all the queued\n\t\t * packets for that session.\n\t\t */\n\n\t\tif (++tp->t_rxtshift > TCP_MAXRXTSHIFT) {\n\t\t\t/*\n\t\t\t * This is a hack to suit our terminal server here at the uni of canberra\n\t\t\t * since they have trouble with zeroes... It usually lets them through\n\t\t\t * unharmed, but under some conditions, it'll eat the zeros. If we\n\t\t\t * keep retransmitting it, it'll keep eating the zeroes, so we keep\n\t\t\t * retransmitting, and eventually the connection dies...\n\t\t\t * (this only happens on incoming data)\n\t\t\t *\n\t\t\t * So, if we were gonna drop the connection from too many retransmits,\n\t\t\t * don't... instead halve the t_maxseg, which might break up the NULLs and\n\t\t\t * let them through\n\t\t\t *\n\t\t\t * *sigh*\n\t\t\t */\n\n\t\t\ttp->t_maxseg >>= 1;\n\t\t\tif (tp->t_maxseg < 32) {\n\t\t\t\t/*\n\t\t\t\t * We tried our best, now the connection must die!\n\t\t\t\t */\n\t\t\t\ttp->t_rxtshift = TCP_MAXRXTSHIFT;\n\t\t\t\ttp = tcp_drop(tp, tp->t_softerror);\n\t\t\t\t/* tp->t_softerror : ETIMEDOUT); */ /* XXX */\n\t\t\t\treturn (tp); /* XXX */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set rxtshift to 6, which is still at the maximum\n\t\t\t * backoff time\n\t\t\t */\n\t\t\ttp->t_rxtshift = 6;\n\t\t}\n\t\trexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];\n\t\tTCPT_RANGESET(tp->t_rxtcur, rexmt,\n\t\t (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */\n\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t/*\n\t\t * If losing, let the lower level know and try for\n\t\t * a better route. Also, if we backed off this far,\n\t\t * our srtt estimate is probably bogus. Clobber it\n\t\t * so we'll take the next rtt measurement as our srtt;\n\t\t * move the current srtt into rttvar to keep the current\n\t\t * retransmit times until then.\n\t\t */\n\t\tif (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {\n\t\t\ttp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);\n\t\t\ttp->t_srtt = 0;\n\t\t}\n\t\ttp->snd_nxt = tp->snd_una;\n\t\t/*\n\t\t * If timing a segment in this window, stop the timer.\n\t\t */\n\t\ttp->t_rtt = 0;\n\t\t/*\n\t\t * Close the congestion window down to one segment\n\t\t * (we'll open it by one segment for each ack we get).\n\t\t * Since we probably have a window's worth of unacked\n\t\t * data accumulated, this \"slow start\" keeps us from\n\t\t * dumping all that data as back-to-back packets (which\n\t\t * might overwhelm an intermediate gateway).\n\t\t *\n\t\t * There are two phases to the opening: Initially we\n\t\t * open by one mss on each ack. This makes the window\n\t\t * size increase exponentially with time. If the\n\t\t * window is larger than the path can handle, this\n\t\t * exponential growth results in dropped packet(s)\n\t\t * almost immediately. To get more time between\n\t\t * drops but still \"push\" the network to take advantage\n\t\t * of improving conditions, we switch from exponential\n\t\t * to linear window opening at some threshold size.\n\t\t * For a threshold, we use half the current window\n\t\t * size, truncated to a multiple of the mss.\n\t\t *\n\t\t * (the minimum cwnd that will give us exponential\n\t\t * growth is 2 mss. We don't allow the threshold\n\t\t * to go below this.)\n\t\t */\n\t\t{\n\t\tu_int win = min(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg;\n\t\tif (win < 2)\n\t\t\twin = 2;\n\t\ttp->snd_cwnd = tp->t_maxseg;\n\t\ttp->snd_ssthresh = win * tp->t_maxseg;\n\t\ttp->t_dupacks = 0;\n\t\t}\n\t\t(void) tcp_output(tp);\n\t\tbreak;\n\n\t/*\n\t * Persistence timer into zero window.\n\t * Force a byte to be output, if possible.\n\t */\n\tcase TCPT_PERSIST:\n\t\ttcp_setpersist(tp);\n\t\ttp->t_force = 1;\n\t\t(void) tcp_output(tp);\n\t\ttp->t_force = 0;\n\t\tbreak;\n\n\t/*\n\t * Keep-alive timer went off; send something\n\t * or drop connection if idle for too long.\n\t */\n\tcase TCPT_KEEP:\n\t\tif (tp->t_state < TCPS_ESTABLISHED)\n\t\t\tgoto dropit;\n\n\t\tif ((SO_OPTIONS) && tp->t_state <= TCPS_CLOSE_WAIT) {\n\t\t \tif (tp->t_idle >= TCPTV_KEEP_IDLE + TCP_MAXIDLE)\n\t\t\t\tgoto dropit;\n\t\t\t/*\n\t\t\t * Send a packet designed to force a response\n\t\t\t * if the peer is up and reachable:\n\t\t\t * either an ACK if the connection is still alive,\n\t\t\t * or an RST if the peer has closed the connection\n\t\t\t * due to timeout or reboot.\n\t\t\t * Using sequence number tp->snd_una-1\n\t\t\t * causes the transmitted zero-length segment\n\t\t\t * to lie outside the receive window;\n\t\t\t * by the protocol spec, this requires the\n\t\t\t * correspondent TCP to respond.\n\t\t\t */\n\t\t\ttcp_respond(tp, &tp->t_template, (struct mbuf *)NULL,\n\t\t\t tp->rcv_nxt, tp->snd_una - 1, 0);\n\t\t\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;\n\t\t} else\n\t\t\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;\n\t\tbreak;\n\n\tdropit:\n\t\ttp = tcp_drop(tp, 0);\n\t\tbreak;\n\t}\n\n\treturn (tp);\n}\n"], ["/linuxpdf/tinyemu/slirp/mbuf.c", "/*\n * Copyright (c) 1995 Danny Gasparovski\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n/*\n * mbuf's in SLiRP are much simpler than the real mbufs in\n * FreeBSD. They are fixed size, determined by the MTU,\n * so that one whole packet can fit. Mbuf's cannot be\n * chained together. If there's more data than the mbuf\n * could hold, an external malloced buffer is pointed to\n * by m_ext (and the data pointers) and M_EXT is set in\n * the flags\n */\n\n#include \"slirp.h\"\n\n#define MBUF_THRESH 30\n\n/*\n * Find a nice value for msize\n * XXX if_maxlinkhdr already in mtu\n */\n#define SLIRP_MSIZE (IF_MTU + IF_MAXLINKHDR + offsetof(struct mbuf, m_dat) + 6)\n\nvoid\nm_init(Slirp *slirp)\n{\n slirp->m_freelist.m_next = slirp->m_freelist.m_prev = &slirp->m_freelist;\n slirp->m_usedlist.m_next = slirp->m_usedlist.m_prev = &slirp->m_usedlist;\n}\n\n/*\n * Get an mbuf from the free list, if there are none\n * malloc one\n *\n * Because fragmentation can occur if we alloc new mbufs and\n * free old mbufs, we mark all mbufs above mbuf_thresh as M_DOFREE,\n * which tells m_free to actually free() it\n */\nstruct mbuf *\nm_get(Slirp *slirp)\n{\n\tregister struct mbuf *m;\n\tint flags = 0;\n\n\tDEBUG_CALL(\"m_get\");\n\n\tif (slirp->m_freelist.m_next == &slirp->m_freelist) {\n\t\tm = (struct mbuf *)malloc(SLIRP_MSIZE);\n\t\tif (m == NULL) goto end_error;\n\t\tslirp->mbuf_alloced++;\n\t\tif (slirp->mbuf_alloced > MBUF_THRESH)\n\t\t\tflags = M_DOFREE;\n\t\tm->slirp = slirp;\n\t} else {\n\t\tm = slirp->m_freelist.m_next;\n\t\tremque(m);\n\t}\n\n\t/* Insert it in the used list */\n\tinsque(m,&slirp->m_usedlist);\n\tm->m_flags = (flags | M_USEDLIST);\n\n\t/* Initialise it */\n\tm->m_size = SLIRP_MSIZE - offsetof(struct mbuf, m_dat);\n\tm->m_data = m->m_dat;\n\tm->m_len = 0;\n m->m_nextpkt = NULL;\n m->m_prevpkt = NULL;\nend_error:\n\tDEBUG_ARG(\"m = %lx\", (long )m);\n\treturn m;\n}\n\nvoid\nm_free(struct mbuf *m)\n{\n\n DEBUG_CALL(\"m_free\");\n DEBUG_ARG(\"m = %lx\", (long )m);\n\n if(m) {\n\t/* Remove from m_usedlist */\n\tif (m->m_flags & M_USEDLIST)\n\t remque(m);\n\n\t/* If it's M_EXT, free() it */\n\tif (m->m_flags & M_EXT)\n\t free(m->m_ext);\n\n\t/*\n\t * Either free() it or put it on the free list\n\t */\n\tif (m->m_flags & M_DOFREE) {\n\t\tm->slirp->mbuf_alloced--;\n\t\tfree(m);\n\t} else if ((m->m_flags & M_FREELIST) == 0) {\n\t\tinsque(m,&m->slirp->m_freelist);\n\t\tm->m_flags = M_FREELIST; /* Clobber other flags */\n\t}\n } /* if(m) */\n}\n\n/*\n * Copy data from one mbuf to the end of\n * the other.. if result is too big for one mbuf, malloc()\n * an M_EXT data segment\n */\nvoid\nm_cat(struct mbuf *m, struct mbuf *n)\n{\n\t/*\n\t * If there's no room, realloc\n\t */\n\tif (M_FREEROOM(m) < n->m_len)\n\t\tm_inc(m,m->m_size+MINCSIZE);\n\n\tmemcpy(m->m_data+m->m_len, n->m_data, n->m_len);\n\tm->m_len += n->m_len;\n\n\tm_free(n);\n}\n\n\n/* make m size bytes large */\nvoid\nm_inc(struct mbuf *m, int size)\n{\n\tint datasize;\n\n\t/* some compiles throw up on gotos. This one we can fake. */\n if(m->m_size>size) return;\n\n if (m->m_flags & M_EXT) {\n\t datasize = m->m_data - m->m_ext;\n\t m->m_ext = (char *)realloc(m->m_ext,size);\n\t m->m_data = m->m_ext + datasize;\n } else {\n\t char *dat;\n\t datasize = m->m_data - m->m_dat;\n\t dat = (char *)malloc(size);\n\t memcpy(dat, m->m_dat, m->m_size);\n\n\t m->m_ext = dat;\n\t m->m_data = m->m_ext + datasize;\n\t m->m_flags |= M_EXT;\n }\n\n m->m_size = size;\n\n}\n\n\n\nvoid\nm_adj(struct mbuf *m, int len)\n{\n\tif (m == NULL)\n\t\treturn;\n\tif (len >= 0) {\n\t\t/* Trim from head */\n\t\tm->m_data += len;\n\t\tm->m_len -= len;\n\t} else {\n\t\t/* Trim from tail */\n\t\tlen = -len;\n\t\tm->m_len -= len;\n\t}\n}\n\n\n/*\n * Copy len bytes from m, starting off bytes into n\n */\nint\nm_copy(struct mbuf *n, struct mbuf *m, int off, int len)\n{\n\tif (len > M_FREEROOM(n))\n\t\treturn -1;\n\n\tmemcpy((n->m_data + n->m_len), (m->m_data + off), len);\n\tn->m_len += len;\n\treturn 0;\n}\n\n\n/*\n * Given a pointer into an mbuf, return the mbuf\n * XXX This is a kludge, I should eliminate the need for it\n * Fortunately, it's not used often\n */\nstruct mbuf *\ndtom(Slirp *slirp, void *dat)\n{\n\tstruct mbuf *m;\n\n\tDEBUG_CALL(\"dtom\");\n\tDEBUG_ARG(\"dat = %lx\", (long )dat);\n\n\t/* bug corrected for M_EXT buffers */\n\tfor (m = slirp->m_usedlist.m_next; m != &slirp->m_usedlist;\n\t m = m->m_next) {\n\t if (m->m_flags & M_EXT) {\n\t if( (char *)dat>=m->m_ext && (char *)dat<(m->m_ext + m->m_size) )\n\t return m;\n\t } else {\n\t if( (char *)dat >= m->m_dat && (char *)dat<(m->m_dat + m->m_size) )\n\t return m;\n\t }\n\t}\n\n\tDEBUG_ERROR((dfd, \"dtom failed\"));\n\n\treturn (struct mbuf *)0;\n}\n"], ["/linuxpdf/tinyemu/fs.c", "/*\n * Filesystem utilities\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"fs.h\"\n\nFSFile *fs_dup(FSDevice *fs, FSFile *f)\n{\n FSQID qid;\n fs->fs_walk(fs, &f, &qid, f, 0, NULL);\n return f;\n}\n\nFSFile *fs_walk_path1(FSDevice *fs, FSFile *f, const char *path,\n char **pname)\n{\n const char *p;\n char *name;\n FSFile *f1;\n FSQID qid;\n int len, ret;\n BOOL is_last, is_first;\n\n if (path[0] == '/')\n path++;\n \n is_first = TRUE;\n for(;;) {\n p = strchr(path, '/');\n if (!p) {\n name = (char *)path;\n if (pname) {\n *pname = name;\n if (is_first) {\n ret = fs->fs_walk(fs, &f, &qid, f, 0, NULL);\n if (ret < 0)\n f = NULL;\n }\n return f;\n }\n is_last = TRUE;\n } else {\n len = p - path;\n name = malloc(len + 1);\n memcpy(name, path, len);\n name[len] = '\\0';\n is_last = FALSE;\n }\n ret = fs->fs_walk(fs, &f1, &qid, f, 1, &name);\n if (!is_last)\n free(name);\n if (!is_first)\n fs->fs_delete(fs, f);\n f = f1;\n is_first = FALSE;\n if (ret <= 0) {\n fs->fs_delete(fs, f);\n f = NULL;\n break;\n } else if (is_last) {\n break;\n }\n path = p + 1;\n }\n return f;\n}\n\nFSFile *fs_walk_path(FSDevice *fs, FSFile *f, const char *path)\n{\n return fs_walk_path1(fs, f, path, NULL);\n}\n\nvoid fs_end(FSDevice *fs)\n{\n fs->fs_end(fs);\n free(fs);\n}\n"], ["/linuxpdf/tinyemu/sha256.c", "/* LibTomCrypt, modular cryptographic library -- Tom St Denis\n *\n * LibTomCrypt is a library that provides various cryptographic\n * algorithms in a highly modular and flexible manner.\n *\n * The library is free for all purposes without any express\n * guarantee it works.\n *\n * Tom St Denis, tomstdenis@gmail.com, http://libtom.org\n */\n#include \n#include \n#include \"cutils.h\"\n#include \"sha256.h\"\n\n#define LOAD32H(a, b) a = get_be32(b)\n#define STORE32H(a, b) put_be32(b, a)\n#define STORE64H(a, b) put_be64(b, a)\n#define RORc(x, y) ( ((((uint32_t)(x)&0xFFFFFFFFUL)>>(uint32_t)((y)&31)) | ((uint32_t)(x)<<(uint32_t)(32-((y)&31)))) & 0xFFFFFFFFUL)\n\n#if defined(CONFIG_EMBUE)\n#define LTC_SMALL_CODE\n#endif\n\n/**\n @file sha256.c\n LTC_SHA256 by Tom St Denis\n*/\n\n#ifdef LTC_SMALL_CODE\n/* the K array */\nstatic const uint32_t K[64] = {\n 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,\n 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,\n 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,\n 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,\n 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,\n 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,\n 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,\n 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,\n 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,\n 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,\n 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,\n 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,\n 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL\n};\n#endif\n\n/* Various logical functions */\n#define Ch(x,y,z) (z ^ (x & (y ^ z)))\n#define Maj(x,y,z) (((x | y) & z) | (x & y))\n#define S(x, n) RORc((x),(n))\n#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))\n#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))\n#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25))\n#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3))\n#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10))\n\n/* compress 512-bits */\nstatic void sha256_compress(SHA256_CTX *s, unsigned char *buf)\n{\n uint32_t S[8], W[64], t0, t1;\n#ifdef LTC_SMALL_CODE\n uint32_t t;\n#endif\n int i;\n\n /* copy state into S */\n for (i = 0; i < 8; i++) {\n S[i] = s->state[i];\n }\n\n /* copy the state into 512-bits into W[0..15] */\n for (i = 0; i < 16; i++) {\n LOAD32H(W[i], buf + (4*i));\n }\n\n /* fill W[16..63] */\n for (i = 16; i < 64; i++) {\n W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];\n }\n\n /* Compress */\n#ifdef LTC_SMALL_CODE\n#define RND(a,b,c,d,e,f,g,h,i) \\\n t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \\\n t1 = Sigma0(a) + Maj(a, b, c); \\\n d += t0; \\\n h = t0 + t1;\n\n for (i = 0; i < 64; ++i) {\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i);\n t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4];\n S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;\n }\n#else\n#define RND(a,b,c,d,e,f,g,h,i,ki) \\\n t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i]; \\\n t1 = Sigma0(a) + Maj(a, b, c); \\\n d += t0; \\\n h = t0 + t1;\n\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,0x428a2f98);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,0x71374491);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,0xb5c0fbcf);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,0xe9b5dba5);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,0x3956c25b);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],5,0x59f111f1);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],6,0x923f82a4);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],7,0xab1c5ed5);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],8,0xd807aa98);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],9,0x12835b01);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],10,0x243185be);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],11,0x550c7dc3);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],12,0x72be5d74);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],13,0x80deb1fe);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],14,0x9bdc06a7);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],15,0xc19bf174);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],16,0xe49b69c1);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],17,0xefbe4786);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],18,0x0fc19dc6);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],19,0x240ca1cc);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],20,0x2de92c6f);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],21,0x4a7484aa);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],22,0x5cb0a9dc);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],23,0x76f988da);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],24,0x983e5152);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],25,0xa831c66d);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],26,0xb00327c8);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],27,0xbf597fc7);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],28,0xc6e00bf3);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],29,0xd5a79147);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],30,0x06ca6351);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],31,0x14292967);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],32,0x27b70a85);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],33,0x2e1b2138);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],34,0x4d2c6dfc);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],35,0x53380d13);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],36,0x650a7354);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],37,0x766a0abb);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],38,0x81c2c92e);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],39,0x92722c85);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],40,0xa2bfe8a1);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],41,0xa81a664b);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],42,0xc24b8b70);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],43,0xc76c51a3);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],44,0xd192e819);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],45,0xd6990624);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],46,0xf40e3585);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],47,0x106aa070);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],48,0x19a4c116);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],49,0x1e376c08);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],50,0x2748774c);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],51,0x34b0bcb5);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],52,0x391c0cb3);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],53,0x4ed8aa4a);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],54,0x5b9cca4f);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],55,0x682e6ff3);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],56,0x748f82ee);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],57,0x78a5636f);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],58,0x84c87814);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],59,0x8cc70208);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],60,0x90befffa);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],61,0xa4506ceb);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);\n\n#undef RND\n\n#endif\n\n /* feedback */\n for (i = 0; i < 8; i++) {\n s->state[i] = s->state[i] + S[i];\n }\n}\n\n#ifdef LTC_CLEAN_STACK\nstatic int sha256_compress(hash_state * md, unsigned char *buf)\n{\n int err;\n err = _sha256_compress(md, buf);\n burn_stack(sizeof(uint32_t) * 74);\n return err;\n}\n#endif\n\n/**\n Initialize the hash state\n @param md The hash state you wish to initialize\n @return CRYPT_OK if successful\n*/\nvoid SHA256_Init(SHA256_CTX *s)\n{\n s->curlen = 0;\n s->length = 0;\n s->state[0] = 0x6A09E667UL;\n s->state[1] = 0xBB67AE85UL;\n s->state[2] = 0x3C6EF372UL;\n s->state[3] = 0xA54FF53AUL;\n s->state[4] = 0x510E527FUL;\n s->state[5] = 0x9B05688CUL;\n s->state[6] = 0x1F83D9ABUL;\n s->state[7] = 0x5BE0CD19UL;\n}\n\nvoid SHA256_Update(SHA256_CTX *s, const uint8_t *in, unsigned long inlen)\n{\n unsigned long n;\n\n if (s->curlen > sizeof(s->buf)) {\n abort();\n }\n if ((s->length + inlen) < s->length) {\n abort();\n }\n while (inlen > 0) {\n if (s->curlen == 0 && inlen >= 64) {\n sha256_compress(s, (unsigned char *)in);\n s->length += 64 * 8;\n in += 64;\n inlen -= 64;\n } else {\n n = min_int(inlen, 64 - s->curlen);\n memcpy(s->buf + s->curlen, in, (size_t)n);\n s->curlen += n;\n in += n;\n inlen -= n;\n if (s->curlen == 64) {\n sha256_compress(s, s->buf);\n s->length += 8*64;\n s->curlen = 0;\n }\n }\n } }\n\n/**\n Terminate the hash to get the digest\n @param md The hash state\n @param out [out] The destination of the hash (32 bytes)\n @return CRYPT_OK if successful\n*/\nvoid SHA256_Final(uint8_t *out, SHA256_CTX *s)\n{\n int i;\n\n if (s->curlen >= sizeof(s->buf)) {\n abort();\n }\n\n\n /* increase the length of the message */\n s->length += s->curlen * 8;\n\n /* append the '1' bit */\n s->buf[s->curlen++] = (unsigned char)0x80;\n\n /* if the length is currently above 56 bytes we append zeros\n * then compress. Then we can fall back to padding zeros and length\n * encoding like normal.\n */\n if (s->curlen > 56) {\n while (s->curlen < 64) {\n s->buf[s->curlen++] = (unsigned char)0;\n }\n sha256_compress(s, s->buf);\n s->curlen = 0;\n }\n\n /* pad upto 56 bytes of zeroes */\n while (s->curlen < 56) {\n s->buf[s->curlen++] = (unsigned char)0;\n }\n\n /* store length */\n STORE64H(s->length, s->buf+56);\n sha256_compress(s, s->buf);\n\n /* copy output */\n for (i = 0; i < 8; i++) {\n STORE32H(s->state[i], out+(4*i));\n }\n#ifdef LTC_CLEAN_STACK\n zeromem(md, sizeof(hash_state));\n#endif\n}\n\nvoid SHA256(const uint8_t *buf, int buf_len, uint8_t *out)\n{\n SHA256_CTX ctx;\n\n SHA256_Init(&ctx);\n SHA256_Update(&ctx, buf, buf_len);\n SHA256_Final(out, &ctx);\n}\n\n#if 0\n/**\n Self-test the hash\n @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled\n*/\nint sha256_test(void)\n{\n #ifndef LTC_TEST\n return CRYPT_NOP;\n #else\n static const struct {\n char *msg;\n unsigned char hash[32];\n } tests[] = {\n { \"abc\",\n { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,\n 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,\n 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,\n 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }\n },\n { \"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\",\n { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,\n 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,\n 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,\n 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }\n },\n };\n\n int i;\n unsigned char tmp[32];\n hash_state md;\n\n for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {\n sha256_init(&md);\n sha256_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));\n sha256_done(&md, tmp);\n if (XMEMCMP(tmp, tests[i].hash, 32) != 0) {\n return CRYPT_FAIL_TESTVECTOR;\n }\n }\n return CRYPT_OK;\n #endif\n}\n\n#endif\n"], ["/linuxpdf/tinyemu/slirp/if.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n#define ifs_init(ifm) ((ifm)->ifs_next = (ifm)->ifs_prev = (ifm))\n\nstatic void\nifs_insque(struct mbuf *ifm, struct mbuf *ifmhead)\n{\n\tifm->ifs_next = ifmhead->ifs_next;\n\tifmhead->ifs_next = ifm;\n\tifm->ifs_prev = ifmhead;\n\tifm->ifs_next->ifs_prev = ifm;\n}\n\nstatic void\nifs_remque(struct mbuf *ifm)\n{\n\tifm->ifs_prev->ifs_next = ifm->ifs_next;\n\tifm->ifs_next->ifs_prev = ifm->ifs_prev;\n}\n\nvoid\nif_init(Slirp *slirp)\n{\n slirp->if_fastq.ifq_next = slirp->if_fastq.ifq_prev = &slirp->if_fastq;\n slirp->if_batchq.ifq_next = slirp->if_batchq.ifq_prev = &slirp->if_batchq;\n slirp->next_m = &slirp->if_batchq;\n}\n\n/*\n * if_output: Queue packet into an output queue.\n * There are 2 output queue's, if_fastq and if_batchq.\n * Each output queue is a doubly linked list of double linked lists\n * of mbufs, each list belonging to one \"session\" (socket). This\n * way, we can output packets fairly by sending one packet from each\n * session, instead of all the packets from one session, then all packets\n * from the next session, etc. Packets on the if_fastq get absolute\n * priority, but if one session hogs the link, it gets \"downgraded\"\n * to the batchq until it runs out of packets, then it'll return\n * to the fastq (eg. if the user does an ls -alR in a telnet session,\n * it'll temporarily get downgraded to the batchq)\n */\nvoid\nif_output(struct socket *so, struct mbuf *ifm)\n{\n\tSlirp *slirp = ifm->slirp;\n\tstruct mbuf *ifq;\n\tint on_fastq = 1;\n\n\tDEBUG_CALL(\"if_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"ifm = %lx\", (long)ifm);\n\n\t/*\n\t * First remove the mbuf from m_usedlist,\n\t * since we're gonna use m_next and m_prev ourselves\n\t * XXX Shouldn't need this, gotta change dtom() etc.\n\t */\n\tif (ifm->m_flags & M_USEDLIST) {\n\t\tremque(ifm);\n\t\tifm->m_flags &= ~M_USEDLIST;\n\t}\n\n\t/*\n\t * See if there's already a batchq list for this session.\n\t * This can include an interactive session, which should go on fastq,\n\t * but gets too greedy... hence it'll be downgraded from fastq to batchq.\n\t * We mustn't put this packet back on the fastq (or we'll send it out of order)\n\t * XXX add cache here?\n\t */\n\tfor (ifq = slirp->if_batchq.ifq_prev; ifq != &slirp->if_batchq;\n\t ifq = ifq->ifq_prev) {\n\t\tif (so == ifq->ifq_so) {\n\t\t\t/* A match! */\n\t\t\tifm->ifq_so = so;\n\t\t\tifs_insque(ifm, ifq->ifs_prev);\n\t\t\tgoto diddit;\n\t\t}\n\t}\n\n\t/* No match, check which queue to put it on */\n\tif (so && (so->so_iptos & IPTOS_LOWDELAY)) {\n\t\tifq = slirp->if_fastq.ifq_prev;\n\t\ton_fastq = 1;\n\t\t/*\n\t\t * Check if this packet is a part of the last\n\t\t * packet's session\n\t\t */\n\t\tif (ifq->ifq_so == so) {\n\t\t\tifm->ifq_so = so;\n\t\t\tifs_insque(ifm, ifq->ifs_prev);\n\t\t\tgoto diddit;\n\t\t}\n\t} else\n\t\tifq = slirp->if_batchq.ifq_prev;\n\n\t/* Create a new doubly linked list for this session */\n\tifm->ifq_so = so;\n\tifs_init(ifm);\n\tinsque(ifm, ifq);\n\ndiddit:\n\tslirp->if_queued++;\n\n\tif (so) {\n\t\t/* Update *_queued */\n\t\tso->so_queued++;\n\t\tso->so_nqueued++;\n\t\t/*\n\t\t * Check if the interactive session should be downgraded to\n\t\t * the batchq. A session is downgraded if it has queued 6\n\t\t * packets without pausing, and at least 3 of those packets\n\t\t * have been sent over the link\n\t\t * (XXX These are arbitrary numbers, probably not optimal..)\n\t\t */\n\t\tif (on_fastq && ((so->so_nqueued >= 6) &&\n\t\t\t\t (so->so_nqueued - so->so_queued) >= 3)) {\n\n\t\t\t/* Remove from current queue... */\n\t\t\tremque(ifm->ifs_next);\n\n\t\t\t/* ...And insert in the new. That'll teach ya! */\n\t\t\tinsque(ifm->ifs_next, &slirp->if_batchq);\n\t\t}\n\t}\n\n#ifndef FULL_BOLT\n\t/*\n\t * This prevents us from malloc()ing too many mbufs\n\t */\n\tif_start(ifm->slirp);\n#endif\n}\n\n/*\n * Send a packet\n * We choose a packet based on it's position in the output queues;\n * If there are packets on the fastq, they are sent FIFO, before\n * everything else. Otherwise we choose the first packet from the\n * batchq and send it. the next packet chosen will be from the session\n * after this one, then the session after that one, and so on.. So,\n * for example, if there are 3 ftp session's fighting for bandwidth,\n * one packet will be sent from the first session, then one packet\n * from the second session, then one packet from the third, then back\n * to the first, etc. etc.\n */\nvoid\nif_start(Slirp *slirp)\n{\n\tstruct mbuf *ifm, *ifqt;\n\n\tDEBUG_CALL(\"if_start\");\n\n\tif (slirp->if_queued == 0)\n\t return; /* Nothing to do */\n\n again:\n /* check if we can really output */\n if (!slirp_can_output(slirp->opaque))\n return;\n\n\t/*\n\t * See which queue to get next packet from\n\t * If there's something in the fastq, select it immediately\n\t */\n\tif (slirp->if_fastq.ifq_next != &slirp->if_fastq) {\n\t\tifm = slirp->if_fastq.ifq_next;\n\t} else {\n\t\t/* Nothing on fastq, see if next_m is valid */\n\t\tif (slirp->next_m != &slirp->if_batchq)\n\t\t ifm = slirp->next_m;\n\t\telse\n\t\t ifm = slirp->if_batchq.ifq_next;\n\n\t\t/* Set which packet to send on next iteration */\n\t\tslirp->next_m = ifm->ifq_next;\n\t}\n\t/* Remove it from the queue */\n\tifqt = ifm->ifq_prev;\n\tremque(ifm);\n\tslirp->if_queued--;\n\n\t/* If there are more packets for this session, re-queue them */\n\tif (ifm->ifs_next != /* ifm->ifs_prev != */ ifm) {\n\t\tinsque(ifm->ifs_next, ifqt);\n\t\tifs_remque(ifm);\n\t}\n\n\t/* Update so_queued */\n\tif (ifm->ifq_so) {\n\t\tif (--ifm->ifq_so->so_queued == 0)\n\t\t /* If there's no more queued, reset nqueued */\n\t\t ifm->ifq_so->so_nqueued = 0;\n\t}\n\n\t/* Encapsulate the packet for sending */\n if_encap(slirp, (uint8_t *)ifm->m_data, ifm->m_len);\n\n m_free(ifm);\n\n\tif (slirp->if_queued)\n\t goto again;\n}\n"], ["/linuxpdf/tinyemu/softfp.c", "/*\n * SoftFP Library\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"softfp.h\"\n\nstatic inline int clz32(uint32_t a)\n{\n int r;\n if (a == 0) {\n r = 32;\n } else {\n r = __builtin_clz(a);\n }\n return r;\n}\n\nstatic inline int clz64(uint64_t a)\n{\n int r;\n if (a == 0) {\n r = 64;\n } else \n {\n r = __builtin_clzll(a);\n }\n return r;\n}\n\n#ifdef HAVE_INT128\nstatic inline int clz128(uint128_t a)\n{\n int r;\n if (a == 0) {\n r = 128;\n } else \n {\n uint64_t ah, al;\n ah = a >> 64;\n al = a;\n if (ah != 0)\n r = __builtin_clzll(ah);\n else\n r = __builtin_clzll(al) + 64;\n }\n return r;\n}\n#endif\n\n#define F_SIZE 32\n#include \"softfp_template.h\"\n\n#define F_SIZE 64\n#include \"softfp_template.h\"\n\n#ifdef HAVE_INT128\n\n#define F_SIZE 128\n#include \"softfp_template.h\"\n\n#endif\n\n"], ["/linuxpdf/tinyemu/aes.c", "/**\n *\n * aes.c - integrated in QEMU by Fabrice Bellard from the OpenSSL project.\n */\n/*\n * rijndael-alg-fst.c\n *\n * @version 3.0 (December 2000)\n *\n * Optimised ANSI C code for the Rijndael cipher (now AES)\n *\n * @author Vincent Rijmen \n * @author Antoon Bosselaers \n * @author Paulo Barreto \n *\n * This code is hereby placed in the public domain.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS\n * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n#include \n#include \n#include \"aes.h\"\n\n#ifndef NDEBUG\n#define NDEBUG\n#endif\n\n#include \n\ntypedef uint32_t u32;\ntypedef uint16_t u16;\ntypedef uint8_t u8;\n\n#define MAXKC (256/32)\n#define MAXKB (256/8)\n#define MAXNR 14\n\n/* This controls loop-unrolling in aes_core.c */\n#undef FULL_UNROLL\n# define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3]))\n# define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); }\n\n/*\nTe0[x] = S [x].[02, 01, 01, 03];\nTe1[x] = S [x].[03, 02, 01, 01];\nTe2[x] = S [x].[01, 03, 02, 01];\nTe3[x] = S [x].[01, 01, 03, 02];\nTe4[x] = S [x].[01, 01, 01, 01];\n\nTd0[x] = Si[x].[0e, 09, 0d, 0b];\nTd1[x] = Si[x].[0b, 0e, 09, 0d];\nTd2[x] = Si[x].[0d, 0b, 0e, 09];\nTd3[x] = Si[x].[09, 0d, 0b, 0e];\nTd4[x] = Si[x].[01, 01, 01, 01];\n*/\n\nstatic const u32 Te0[256] = {\n 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU,\n 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U,\n 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU,\n 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU,\n 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U,\n 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU,\n 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU,\n 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU,\n 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU,\n 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU,\n 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U,\n 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU,\n 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU,\n 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U,\n 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU,\n 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU,\n 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU,\n 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU,\n 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU,\n 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U,\n 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU,\n 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU,\n 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU,\n 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU,\n 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U,\n 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U,\n 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U,\n 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U,\n 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU,\n 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U,\n 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U,\n 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU,\n 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU,\n 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U,\n 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U,\n 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U,\n 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU,\n 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U,\n 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU,\n 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U,\n 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU,\n 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U,\n 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U,\n 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU,\n 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U,\n 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U,\n 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U,\n 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U,\n 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U,\n 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U,\n 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U,\n 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U,\n 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU,\n 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U,\n 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U,\n 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U,\n 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U,\n 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U,\n 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U,\n 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU,\n 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U,\n 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U,\n 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U,\n 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU,\n};\nstatic const u32 Te1[256] = {\n 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU,\n 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U,\n 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU,\n 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U,\n 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU,\n 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U,\n 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU,\n 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U,\n 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U,\n 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU,\n 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U,\n 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U,\n 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U,\n 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU,\n 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U,\n 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U,\n 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU,\n 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U,\n 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U,\n 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U,\n 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU,\n 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU,\n 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U,\n 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU,\n 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU,\n 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U,\n 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU,\n 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U,\n 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU,\n 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U,\n 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U,\n 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U,\n 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU,\n 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U,\n 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU,\n 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U,\n 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU,\n 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U,\n 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U,\n 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU,\n 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU,\n 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU,\n 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U,\n 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U,\n 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU,\n 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U,\n 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU,\n 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U,\n 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU,\n 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U,\n 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU,\n 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU,\n 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U,\n 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU,\n 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U,\n 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU,\n 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U,\n 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U,\n 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U,\n 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU,\n 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU,\n 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U,\n 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU,\n 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U,\n};\nstatic const u32 Te2[256] = {\n 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU,\n 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U,\n 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU,\n 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U,\n 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU,\n 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U,\n 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU,\n 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U,\n 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U,\n 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU,\n 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U,\n 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U,\n 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U,\n 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU,\n 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U,\n 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U,\n 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU,\n 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U,\n 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U,\n 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U,\n 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU,\n 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU,\n 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U,\n 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU,\n 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU,\n 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U,\n 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU,\n 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U,\n 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU,\n 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U,\n 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U,\n 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U,\n 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU,\n 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U,\n 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU,\n 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U,\n 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU,\n 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U,\n 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U,\n 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU,\n 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU,\n 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU,\n 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U,\n 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U,\n 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU,\n 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U,\n 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU,\n 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U,\n 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU,\n 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U,\n 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU,\n 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU,\n 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U,\n 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU,\n 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U,\n 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU,\n 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U,\n 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U,\n 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U,\n 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU,\n 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU,\n 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U,\n 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU,\n 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U,\n};\nstatic const u32 Te3[256] = {\n\n 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U,\n 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U,\n 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U,\n 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU,\n 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU,\n 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU,\n 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U,\n 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU,\n 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU,\n 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U,\n 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U,\n 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU,\n 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU,\n 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU,\n 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU,\n 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU,\n 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U,\n 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU,\n 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU,\n 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U,\n 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U,\n 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U,\n 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U,\n 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U,\n 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU,\n 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U,\n 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU,\n 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU,\n 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U,\n 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U,\n 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U,\n 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU,\n 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U,\n 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU,\n 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU,\n 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U,\n 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U,\n 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU,\n 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U,\n 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU,\n 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U,\n 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U,\n 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U,\n 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U,\n 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU,\n 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U,\n 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU,\n 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U,\n 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU,\n 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U,\n 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU,\n 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU,\n 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU,\n 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU,\n 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U,\n 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U,\n 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U,\n 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U,\n 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U,\n 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U,\n 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU,\n 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U,\n 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU,\n 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU,\n};\nstatic const u32 Te4[256] = {\n 0x63636363U, 0x7c7c7c7cU, 0x77777777U, 0x7b7b7b7bU,\n 0xf2f2f2f2U, 0x6b6b6b6bU, 0x6f6f6f6fU, 0xc5c5c5c5U,\n 0x30303030U, 0x01010101U, 0x67676767U, 0x2b2b2b2bU,\n 0xfefefefeU, 0xd7d7d7d7U, 0xababababU, 0x76767676U,\n 0xcacacacaU, 0x82828282U, 0xc9c9c9c9U, 0x7d7d7d7dU,\n 0xfafafafaU, 0x59595959U, 0x47474747U, 0xf0f0f0f0U,\n 0xadadadadU, 0xd4d4d4d4U, 0xa2a2a2a2U, 0xafafafafU,\n 0x9c9c9c9cU, 0xa4a4a4a4U, 0x72727272U, 0xc0c0c0c0U,\n 0xb7b7b7b7U, 0xfdfdfdfdU, 0x93939393U, 0x26262626U,\n 0x36363636U, 0x3f3f3f3fU, 0xf7f7f7f7U, 0xccccccccU,\n 0x34343434U, 0xa5a5a5a5U, 0xe5e5e5e5U, 0xf1f1f1f1U,\n 0x71717171U, 0xd8d8d8d8U, 0x31313131U, 0x15151515U,\n 0x04040404U, 0xc7c7c7c7U, 0x23232323U, 0xc3c3c3c3U,\n 0x18181818U, 0x96969696U, 0x05050505U, 0x9a9a9a9aU,\n 0x07070707U, 0x12121212U, 0x80808080U, 0xe2e2e2e2U,\n 0xebebebebU, 0x27272727U, 0xb2b2b2b2U, 0x75757575U,\n 0x09090909U, 0x83838383U, 0x2c2c2c2cU, 0x1a1a1a1aU,\n 0x1b1b1b1bU, 0x6e6e6e6eU, 0x5a5a5a5aU, 0xa0a0a0a0U,\n 0x52525252U, 0x3b3b3b3bU, 0xd6d6d6d6U, 0xb3b3b3b3U,\n 0x29292929U, 0xe3e3e3e3U, 0x2f2f2f2fU, 0x84848484U,\n 0x53535353U, 0xd1d1d1d1U, 0x00000000U, 0xededededU,\n 0x20202020U, 0xfcfcfcfcU, 0xb1b1b1b1U, 0x5b5b5b5bU,\n 0x6a6a6a6aU, 0xcbcbcbcbU, 0xbebebebeU, 0x39393939U,\n 0x4a4a4a4aU, 0x4c4c4c4cU, 0x58585858U, 0xcfcfcfcfU,\n 0xd0d0d0d0U, 0xefefefefU, 0xaaaaaaaaU, 0xfbfbfbfbU,\n 0x43434343U, 0x4d4d4d4dU, 0x33333333U, 0x85858585U,\n 0x45454545U, 0xf9f9f9f9U, 0x02020202U, 0x7f7f7f7fU,\n 0x50505050U, 0x3c3c3c3cU, 0x9f9f9f9fU, 0xa8a8a8a8U,\n 0x51515151U, 0xa3a3a3a3U, 0x40404040U, 0x8f8f8f8fU,\n 0x92929292U, 0x9d9d9d9dU, 0x38383838U, 0xf5f5f5f5U,\n 0xbcbcbcbcU, 0xb6b6b6b6U, 0xdadadadaU, 0x21212121U,\n 0x10101010U, 0xffffffffU, 0xf3f3f3f3U, 0xd2d2d2d2U,\n 0xcdcdcdcdU, 0x0c0c0c0cU, 0x13131313U, 0xececececU,\n 0x5f5f5f5fU, 0x97979797U, 0x44444444U, 0x17171717U,\n 0xc4c4c4c4U, 0xa7a7a7a7U, 0x7e7e7e7eU, 0x3d3d3d3dU,\n 0x64646464U, 0x5d5d5d5dU, 0x19191919U, 0x73737373U,\n 0x60606060U, 0x81818181U, 0x4f4f4f4fU, 0xdcdcdcdcU,\n 0x22222222U, 0x2a2a2a2aU, 0x90909090U, 0x88888888U,\n 0x46464646U, 0xeeeeeeeeU, 0xb8b8b8b8U, 0x14141414U,\n 0xdedededeU, 0x5e5e5e5eU, 0x0b0b0b0bU, 0xdbdbdbdbU,\n 0xe0e0e0e0U, 0x32323232U, 0x3a3a3a3aU, 0x0a0a0a0aU,\n 0x49494949U, 0x06060606U, 0x24242424U, 0x5c5c5c5cU,\n 0xc2c2c2c2U, 0xd3d3d3d3U, 0xacacacacU, 0x62626262U,\n 0x91919191U, 0x95959595U, 0xe4e4e4e4U, 0x79797979U,\n 0xe7e7e7e7U, 0xc8c8c8c8U, 0x37373737U, 0x6d6d6d6dU,\n 0x8d8d8d8dU, 0xd5d5d5d5U, 0x4e4e4e4eU, 0xa9a9a9a9U,\n 0x6c6c6c6cU, 0x56565656U, 0xf4f4f4f4U, 0xeaeaeaeaU,\n 0x65656565U, 0x7a7a7a7aU, 0xaeaeaeaeU, 0x08080808U,\n 0xbabababaU, 0x78787878U, 0x25252525U, 0x2e2e2e2eU,\n 0x1c1c1c1cU, 0xa6a6a6a6U, 0xb4b4b4b4U, 0xc6c6c6c6U,\n 0xe8e8e8e8U, 0xddddddddU, 0x74747474U, 0x1f1f1f1fU,\n 0x4b4b4b4bU, 0xbdbdbdbdU, 0x8b8b8b8bU, 0x8a8a8a8aU,\n 0x70707070U, 0x3e3e3e3eU, 0xb5b5b5b5U, 0x66666666U,\n 0x48484848U, 0x03030303U, 0xf6f6f6f6U, 0x0e0e0e0eU,\n 0x61616161U, 0x35353535U, 0x57575757U, 0xb9b9b9b9U,\n 0x86868686U, 0xc1c1c1c1U, 0x1d1d1d1dU, 0x9e9e9e9eU,\n 0xe1e1e1e1U, 0xf8f8f8f8U, 0x98989898U, 0x11111111U,\n 0x69696969U, 0xd9d9d9d9U, 0x8e8e8e8eU, 0x94949494U,\n 0x9b9b9b9bU, 0x1e1e1e1eU, 0x87878787U, 0xe9e9e9e9U,\n 0xcecececeU, 0x55555555U, 0x28282828U, 0xdfdfdfdfU,\n 0x8c8c8c8cU, 0xa1a1a1a1U, 0x89898989U, 0x0d0d0d0dU,\n 0xbfbfbfbfU, 0xe6e6e6e6U, 0x42424242U, 0x68686868U,\n 0x41414141U, 0x99999999U, 0x2d2d2d2dU, 0x0f0f0f0fU,\n 0xb0b0b0b0U, 0x54545454U, 0xbbbbbbbbU, 0x16161616U,\n};\nstatic const u32 Td0[256] = {\n 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U,\n 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U,\n 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U,\n 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU,\n 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U,\n 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U,\n 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU,\n 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U,\n 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU,\n 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U,\n 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U,\n 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U,\n 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U,\n 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU,\n 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U,\n 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU,\n 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U,\n 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU,\n 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U,\n 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U,\n 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U,\n 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU,\n 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U,\n 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU,\n 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U,\n 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU,\n 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U,\n 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU,\n 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU,\n 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U,\n 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU,\n 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U,\n 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU,\n 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U,\n 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U,\n 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U,\n 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU,\n 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U,\n 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U,\n 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU,\n 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U,\n 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U,\n 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U,\n 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U,\n 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U,\n 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU,\n 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U,\n 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U,\n 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U,\n 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U,\n 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U,\n 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU,\n 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU,\n 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU,\n 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU,\n 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U,\n 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U,\n 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU,\n 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU,\n 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U,\n 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU,\n 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U,\n 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U,\n 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U,\n};\nstatic const u32 Td1[256] = {\n 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU,\n 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U,\n 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU,\n 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U,\n 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U,\n 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U,\n 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U,\n 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U,\n 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U,\n 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU,\n 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU,\n 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU,\n 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U,\n 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU,\n 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U,\n 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U,\n 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U,\n 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU,\n 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU,\n 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U,\n 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU,\n 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U,\n 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU,\n 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU,\n 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U,\n 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U,\n 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U,\n 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU,\n 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U,\n 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU,\n 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U,\n 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U,\n 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U,\n 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU,\n 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U,\n 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U,\n 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U,\n 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U,\n 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U,\n 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U,\n 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU,\n 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU,\n 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U,\n 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU,\n 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U,\n 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU,\n 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU,\n 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U,\n 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU,\n 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U,\n 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U,\n 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U,\n 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U,\n 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U,\n 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U,\n 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U,\n 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU,\n 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U,\n 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U,\n 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU,\n 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U,\n 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U,\n 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U,\n 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U,\n};\nstatic const u32 Td2[256] = {\n 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U,\n 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U,\n 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U,\n 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U,\n 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU,\n 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U,\n 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U,\n 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U,\n 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U,\n 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU,\n 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U,\n 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U,\n 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU,\n 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U,\n 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U,\n 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U,\n 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U,\n 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U,\n 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U,\n 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU,\n\n 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U,\n 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U,\n 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U,\n 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U,\n 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U,\n 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU,\n 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU,\n 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U,\n 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU,\n 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U,\n 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU,\n 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU,\n 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU,\n 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU,\n 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U,\n 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U,\n 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U,\n 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U,\n 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U,\n 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U,\n 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U,\n 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU,\n 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU,\n 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U,\n 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U,\n 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU,\n 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU,\n 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U,\n 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U,\n 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U,\n 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U,\n 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U,\n 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U,\n 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U,\n 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU,\n 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U,\n 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U,\n 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U,\n 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U,\n 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U,\n 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U,\n 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU,\n 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U,\n 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U,\n};\nstatic const u32 Td3[256] = {\n 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU,\n 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU,\n 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U,\n 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U,\n 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU,\n 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU,\n 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U,\n 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU,\n 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U,\n 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU,\n 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U,\n 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U,\n 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U,\n 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U,\n 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U,\n 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU,\n 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU,\n 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U,\n 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U,\n 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU,\n 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU,\n 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U,\n 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U,\n 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U,\n 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U,\n 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU,\n 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U,\n 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U,\n 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU,\n 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU,\n 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U,\n 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U,\n 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U,\n 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU,\n 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U,\n 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U,\n 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U,\n 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U,\n 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U,\n 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U,\n 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U,\n 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU,\n 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U,\n 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U,\n 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU,\n 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU,\n 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U,\n 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU,\n 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U,\n 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U,\n 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U,\n 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U,\n 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U,\n 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U,\n 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU,\n 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU,\n 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU,\n 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU,\n 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U,\n 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U,\n 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U,\n 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU,\n 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U,\n 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U,\n};\nstatic const u32 Td4[256] = {\n 0x52525252U, 0x09090909U, 0x6a6a6a6aU, 0xd5d5d5d5U,\n 0x30303030U, 0x36363636U, 0xa5a5a5a5U, 0x38383838U,\n 0xbfbfbfbfU, 0x40404040U, 0xa3a3a3a3U, 0x9e9e9e9eU,\n 0x81818181U, 0xf3f3f3f3U, 0xd7d7d7d7U, 0xfbfbfbfbU,\n 0x7c7c7c7cU, 0xe3e3e3e3U, 0x39393939U, 0x82828282U,\n 0x9b9b9b9bU, 0x2f2f2f2fU, 0xffffffffU, 0x87878787U,\n 0x34343434U, 0x8e8e8e8eU, 0x43434343U, 0x44444444U,\n 0xc4c4c4c4U, 0xdedededeU, 0xe9e9e9e9U, 0xcbcbcbcbU,\n 0x54545454U, 0x7b7b7b7bU, 0x94949494U, 0x32323232U,\n 0xa6a6a6a6U, 0xc2c2c2c2U, 0x23232323U, 0x3d3d3d3dU,\n 0xeeeeeeeeU, 0x4c4c4c4cU, 0x95959595U, 0x0b0b0b0bU,\n 0x42424242U, 0xfafafafaU, 0xc3c3c3c3U, 0x4e4e4e4eU,\n 0x08080808U, 0x2e2e2e2eU, 0xa1a1a1a1U, 0x66666666U,\n 0x28282828U, 0xd9d9d9d9U, 0x24242424U, 0xb2b2b2b2U,\n 0x76767676U, 0x5b5b5b5bU, 0xa2a2a2a2U, 0x49494949U,\n 0x6d6d6d6dU, 0x8b8b8b8bU, 0xd1d1d1d1U, 0x25252525U,\n 0x72727272U, 0xf8f8f8f8U, 0xf6f6f6f6U, 0x64646464U,\n 0x86868686U, 0x68686868U, 0x98989898U, 0x16161616U,\n 0xd4d4d4d4U, 0xa4a4a4a4U, 0x5c5c5c5cU, 0xccccccccU,\n 0x5d5d5d5dU, 0x65656565U, 0xb6b6b6b6U, 0x92929292U,\n 0x6c6c6c6cU, 0x70707070U, 0x48484848U, 0x50505050U,\n 0xfdfdfdfdU, 0xededededU, 0xb9b9b9b9U, 0xdadadadaU,\n 0x5e5e5e5eU, 0x15151515U, 0x46464646U, 0x57575757U,\n 0xa7a7a7a7U, 0x8d8d8d8dU, 0x9d9d9d9dU, 0x84848484U,\n 0x90909090U, 0xd8d8d8d8U, 0xababababU, 0x00000000U,\n 0x8c8c8c8cU, 0xbcbcbcbcU, 0xd3d3d3d3U, 0x0a0a0a0aU,\n 0xf7f7f7f7U, 0xe4e4e4e4U, 0x58585858U, 0x05050505U,\n 0xb8b8b8b8U, 0xb3b3b3b3U, 0x45454545U, 0x06060606U,\n 0xd0d0d0d0U, 0x2c2c2c2cU, 0x1e1e1e1eU, 0x8f8f8f8fU,\n 0xcacacacaU, 0x3f3f3f3fU, 0x0f0f0f0fU, 0x02020202U,\n 0xc1c1c1c1U, 0xafafafafU, 0xbdbdbdbdU, 0x03030303U,\n 0x01010101U, 0x13131313U, 0x8a8a8a8aU, 0x6b6b6b6bU,\n 0x3a3a3a3aU, 0x91919191U, 0x11111111U, 0x41414141U,\n 0x4f4f4f4fU, 0x67676767U, 0xdcdcdcdcU, 0xeaeaeaeaU,\n 0x97979797U, 0xf2f2f2f2U, 0xcfcfcfcfU, 0xcecececeU,\n 0xf0f0f0f0U, 0xb4b4b4b4U, 0xe6e6e6e6U, 0x73737373U,\n 0x96969696U, 0xacacacacU, 0x74747474U, 0x22222222U,\n 0xe7e7e7e7U, 0xadadadadU, 0x35353535U, 0x85858585U,\n 0xe2e2e2e2U, 0xf9f9f9f9U, 0x37373737U, 0xe8e8e8e8U,\n 0x1c1c1c1cU, 0x75757575U, 0xdfdfdfdfU, 0x6e6e6e6eU,\n 0x47474747U, 0xf1f1f1f1U, 0x1a1a1a1aU, 0x71717171U,\n 0x1d1d1d1dU, 0x29292929U, 0xc5c5c5c5U, 0x89898989U,\n 0x6f6f6f6fU, 0xb7b7b7b7U, 0x62626262U, 0x0e0e0e0eU,\n 0xaaaaaaaaU, 0x18181818U, 0xbebebebeU, 0x1b1b1b1bU,\n 0xfcfcfcfcU, 0x56565656U, 0x3e3e3e3eU, 0x4b4b4b4bU,\n 0xc6c6c6c6U, 0xd2d2d2d2U, 0x79797979U, 0x20202020U,\n 0x9a9a9a9aU, 0xdbdbdbdbU, 0xc0c0c0c0U, 0xfefefefeU,\n 0x78787878U, 0xcdcdcdcdU, 0x5a5a5a5aU, 0xf4f4f4f4U,\n 0x1f1f1f1fU, 0xddddddddU, 0xa8a8a8a8U, 0x33333333U,\n 0x88888888U, 0x07070707U, 0xc7c7c7c7U, 0x31313131U,\n 0xb1b1b1b1U, 0x12121212U, 0x10101010U, 0x59595959U,\n 0x27272727U, 0x80808080U, 0xececececU, 0x5f5f5f5fU,\n 0x60606060U, 0x51515151U, 0x7f7f7f7fU, 0xa9a9a9a9U,\n 0x19191919U, 0xb5b5b5b5U, 0x4a4a4a4aU, 0x0d0d0d0dU,\n 0x2d2d2d2dU, 0xe5e5e5e5U, 0x7a7a7a7aU, 0x9f9f9f9fU,\n 0x93939393U, 0xc9c9c9c9U, 0x9c9c9c9cU, 0xefefefefU,\n 0xa0a0a0a0U, 0xe0e0e0e0U, 0x3b3b3b3bU, 0x4d4d4d4dU,\n 0xaeaeaeaeU, 0x2a2a2a2aU, 0xf5f5f5f5U, 0xb0b0b0b0U,\n 0xc8c8c8c8U, 0xebebebebU, 0xbbbbbbbbU, 0x3c3c3c3cU,\n 0x83838383U, 0x53535353U, 0x99999999U, 0x61616161U,\n 0x17171717U, 0x2b2b2b2bU, 0x04040404U, 0x7e7e7e7eU,\n 0xbabababaU, 0x77777777U, 0xd6d6d6d6U, 0x26262626U,\n 0xe1e1e1e1U, 0x69696969U, 0x14141414U, 0x63636363U,\n 0x55555555U, 0x21212121U, 0x0c0c0c0cU, 0x7d7d7d7dU,\n};\nstatic const u32 rcon[] = {\n\t0x01000000, 0x02000000, 0x04000000, 0x08000000,\n\t0x10000000, 0x20000000, 0x40000000, 0x80000000,\n\t0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */\n};\n\n/**\n * Expand the cipher key into the encryption key schedule.\n */\nint AES_set_encrypt_key(const unsigned char *userKey, const int bits,\n\t\t\tAES_KEY *key) {\n\n\tu32 *rk;\n \tint i = 0;\n\tu32 temp;\n\n\tif (!userKey || !key)\n\t\treturn -1;\n\tif (bits != 128 && bits != 192 && bits != 256)\n\t\treturn -2;\n\n\trk = key->rd_key;\n\n\tif (bits==128)\n\t\tkey->rounds = 10;\n\telse if (bits==192)\n\t\tkey->rounds = 12;\n\telse\n\t\tkey->rounds = 14;\n\n\trk[0] = GETU32(userKey );\n\trk[1] = GETU32(userKey + 4);\n\trk[2] = GETU32(userKey + 8);\n\trk[3] = GETU32(userKey + 12);\n\tif (bits == 128) {\n\t\twhile (1) {\n\t\t\ttemp = rk[3];\n\t\t\trk[4] = rk[0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[5] = rk[1] ^ rk[4];\n\t\t\trk[6] = rk[2] ^ rk[5];\n\t\t\trk[7] = rk[3] ^ rk[6];\n\t\t\tif (++i == 10) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\trk += 4;\n\t\t}\n\t}\n\trk[4] = GETU32(userKey + 16);\n\trk[5] = GETU32(userKey + 20);\n\tif (bits == 192) {\n\t\twhile (1) {\n\t\t\ttemp = rk[ 5];\n\t\t\trk[ 6] = rk[ 0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[ 7] = rk[ 1] ^ rk[ 6];\n\t\t\trk[ 8] = rk[ 2] ^ rk[ 7];\n\t\t\trk[ 9] = rk[ 3] ^ rk[ 8];\n\t\t\tif (++i == 8) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\trk[10] = rk[ 4] ^ rk[ 9];\n\t\t\trk[11] = rk[ 5] ^ rk[10];\n\t\t\trk += 6;\n\t\t}\n\t}\n\trk[6] = GETU32(userKey + 24);\n\trk[7] = GETU32(userKey + 28);\n\tif (bits == 256) {\n\t\twhile (1) {\n\t\t\ttemp = rk[ 7];\n\t\t\trk[ 8] = rk[ 0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[ 9] = rk[ 1] ^ rk[ 8];\n\t\t\trk[10] = rk[ 2] ^ rk[ 9];\n\t\t\trk[11] = rk[ 3] ^ rk[10];\n\t\t\tif (++i == 7) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\ttemp = rk[11];\n\t\t\trk[12] = rk[ 4] ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x000000ff);\n\t\t\trk[13] = rk[ 5] ^ rk[12];\n\t\t\trk[14] = rk[ 6] ^ rk[13];\n\t\t\trk[15] = rk[ 7] ^ rk[14];\n\n\t\t\trk += 8;\n \t}\n\t}\n\treturn 0;\n}\n\n/**\n * Expand the cipher key into the decryption key schedule.\n */\nint AES_set_decrypt_key(const unsigned char *userKey, const int bits,\n\t\t\t AES_KEY *key) {\n\n u32 *rk;\n\tint i, j, status;\n\tu32 temp;\n\n\t/* first, start with an encryption schedule */\n\tstatus = AES_set_encrypt_key(userKey, bits, key);\n\tif (status < 0)\n\t\treturn status;\n\n\trk = key->rd_key;\n\n\t/* invert the order of the round keys: */\n\tfor (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) {\n\t\ttemp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp;\n\t\ttemp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;\n\t\ttemp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;\n\t\ttemp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;\n\t}\n\t/* apply the inverse MixColumn transform to all round keys but the first and the last: */\n\tfor (i = 1; i < (key->rounds); i++) {\n\t\trk += 4;\n\t\trk[0] =\n\t\t\tTd0[Te4[(rk[0] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[0] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[0] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[0] ) & 0xff] & 0xff];\n\t\trk[1] =\n\t\t\tTd0[Te4[(rk[1] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[1] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[1] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[1] ) & 0xff] & 0xff];\n\t\trk[2] =\n\t\t\tTd0[Te4[(rk[2] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[2] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[2] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[2] ) & 0xff] & 0xff];\n\t\trk[3] =\n\t\t\tTd0[Te4[(rk[3] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[3] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[3] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[3] ) & 0xff] & 0xff];\n\t}\n\treturn 0;\n}\n\n#ifndef AES_ASM\n/*\n * Encrypt a single block\n * in and out can overlap\n */\nvoid AES_encrypt(const unsigned char *in, unsigned char *out,\n\t\t const AES_KEY *key) {\n\n\tconst u32 *rk;\n\tu32 s0, s1, s2, s3, t0, t1, t2, t3;\n#ifndef FULL_UNROLL\n\tint r;\n#endif /* ?FULL_UNROLL */\n\n\tassert(in && out && key);\n\trk = key->rd_key;\n\n\t/*\n\t * map byte array block to cipher state\n\t * and add initial round key:\n\t */\n\ts0 = GETU32(in ) ^ rk[0];\n\ts1 = GETU32(in + 4) ^ rk[1];\n\ts2 = GETU32(in + 8) ^ rk[2];\n\ts3 = GETU32(in + 12) ^ rk[3];\n#ifdef FULL_UNROLL\n\t/* round 1: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7];\n \t/* round 2: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11];\n\t/* round 3: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15];\n \t/* round 4: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19];\n\t/* round 5: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23];\n \t/* round 6: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27];\n\t/* round 7: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31];\n \t/* round 8: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35];\n\t/* round 9: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39];\n if (key->rounds > 10) {\n /* round 10: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43];\n /* round 11: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47];\n if (key->rounds > 12) {\n /* round 12: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51];\n /* round 13: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55];\n }\n }\n rk += key->rounds << 2;\n#else /* !FULL_UNROLL */\n /*\n * Nr - 1 full rounds:\n */\n r = key->rounds >> 1;\n for (;;) {\n t0 =\n Te0[(s0 >> 24) ] ^\n Te1[(s1 >> 16) & 0xff] ^\n Te2[(s2 >> 8) & 0xff] ^\n Te3[(s3 ) & 0xff] ^\n rk[4];\n t1 =\n Te0[(s1 >> 24) ] ^\n Te1[(s2 >> 16) & 0xff] ^\n Te2[(s3 >> 8) & 0xff] ^\n Te3[(s0 ) & 0xff] ^\n rk[5];\n t2 =\n Te0[(s2 >> 24) ] ^\n Te1[(s3 >> 16) & 0xff] ^\n Te2[(s0 >> 8) & 0xff] ^\n Te3[(s1 ) & 0xff] ^\n rk[6];\n t3 =\n Te0[(s3 >> 24) ] ^\n Te1[(s0 >> 16) & 0xff] ^\n Te2[(s1 >> 8) & 0xff] ^\n Te3[(s2 ) & 0xff] ^\n rk[7];\n\n rk += 8;\n if (--r == 0) {\n break;\n }\n\n s0 =\n Te0[(t0 >> 24) ] ^\n Te1[(t1 >> 16) & 0xff] ^\n Te2[(t2 >> 8) & 0xff] ^\n Te3[(t3 ) & 0xff] ^\n rk[0];\n s1 =\n Te0[(t1 >> 24) ] ^\n Te1[(t2 >> 16) & 0xff] ^\n Te2[(t3 >> 8) & 0xff] ^\n Te3[(t0 ) & 0xff] ^\n rk[1];\n s2 =\n Te0[(t2 >> 24) ] ^\n Te1[(t3 >> 16) & 0xff] ^\n Te2[(t0 >> 8) & 0xff] ^\n Te3[(t1 ) & 0xff] ^\n rk[2];\n s3 =\n Te0[(t3 >> 24) ] ^\n Te1[(t0 >> 16) & 0xff] ^\n Te2[(t1 >> 8) & 0xff] ^\n Te3[(t2 ) & 0xff] ^\n rk[3];\n }\n#endif /* ?FULL_UNROLL */\n /*\n\t * apply last round and\n\t * map cipher state to byte array block:\n\t */\n\ts0 =\n\t\t(Te4[(t0 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t3 ) & 0xff] & 0x000000ff) ^\n\t\trk[0];\n\tPUTU32(out , s0);\n\ts1 =\n\t\t(Te4[(t1 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t0 ) & 0xff] & 0x000000ff) ^\n\t\trk[1];\n\tPUTU32(out + 4, s1);\n\ts2 =\n\t\t(Te4[(t2 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t1 ) & 0xff] & 0x000000ff) ^\n\t\trk[2];\n\tPUTU32(out + 8, s2);\n\ts3 =\n\t\t(Te4[(t3 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t2 ) & 0xff] & 0x000000ff) ^\n\t\trk[3];\n\tPUTU32(out + 12, s3);\n}\n\n/*\n * Decrypt a single block\n * in and out can overlap\n */\nvoid AES_decrypt(const unsigned char *in, unsigned char *out,\n\t\t const AES_KEY *key) {\n\n\tconst u32 *rk;\n\tu32 s0, s1, s2, s3, t0, t1, t2, t3;\n#ifndef FULL_UNROLL\n\tint r;\n#endif /* ?FULL_UNROLL */\n\n\tassert(in && out && key);\n\trk = key->rd_key;\n\n\t/*\n\t * map byte array block to cipher state\n\t * and add initial round key:\n\t */\n s0 = GETU32(in ) ^ rk[0];\n s1 = GETU32(in + 4) ^ rk[1];\n s2 = GETU32(in + 8) ^ rk[2];\n s3 = GETU32(in + 12) ^ rk[3];\n#ifdef FULL_UNROLL\n /* round 1: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[ 4];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[ 5];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[ 6];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[ 7];\n /* round 2: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[ 8];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[ 9];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11];\n /* round 3: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15];\n /* round 4: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19];\n /* round 5: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23];\n /* round 6: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27];\n /* round 7: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31];\n /* round 8: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35];\n /* round 9: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39];\n if (key->rounds > 10) {\n /* round 10: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43];\n /* round 11: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47];\n if (key->rounds > 12) {\n /* round 12: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51];\n /* round 13: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55];\n }\n }\n\trk += key->rounds << 2;\n#else /* !FULL_UNROLL */\n /*\n * Nr - 1 full rounds:\n */\n r = key->rounds >> 1;\n for (;;) {\n t0 =\n Td0[(s0 >> 24) ] ^\n Td1[(s3 >> 16) & 0xff] ^\n Td2[(s2 >> 8) & 0xff] ^\n Td3[(s1 ) & 0xff] ^\n rk[4];\n t1 =\n Td0[(s1 >> 24) ] ^\n Td1[(s0 >> 16) & 0xff] ^\n Td2[(s3 >> 8) & 0xff] ^\n Td3[(s2 ) & 0xff] ^\n rk[5];\n t2 =\n Td0[(s2 >> 24) ] ^\n Td1[(s1 >> 16) & 0xff] ^\n Td2[(s0 >> 8) & 0xff] ^\n Td3[(s3 ) & 0xff] ^\n rk[6];\n t3 =\n Td0[(s3 >> 24) ] ^\n Td1[(s2 >> 16) & 0xff] ^\n Td2[(s1 >> 8) & 0xff] ^\n Td3[(s0 ) & 0xff] ^\n rk[7];\n\n rk += 8;\n if (--r == 0) {\n break;\n }\n\n s0 =\n Td0[(t0 >> 24) ] ^\n Td1[(t3 >> 16) & 0xff] ^\n Td2[(t2 >> 8) & 0xff] ^\n Td3[(t1 ) & 0xff] ^\n rk[0];\n s1 =\n Td0[(t1 >> 24) ] ^\n Td1[(t0 >> 16) & 0xff] ^\n Td2[(t3 >> 8) & 0xff] ^\n Td3[(t2 ) & 0xff] ^\n rk[1];\n s2 =\n Td0[(t2 >> 24) ] ^\n Td1[(t1 >> 16) & 0xff] ^\n Td2[(t0 >> 8) & 0xff] ^\n Td3[(t3 ) & 0xff] ^\n rk[2];\n s3 =\n Td0[(t3 >> 24) ] ^\n Td1[(t2 >> 16) & 0xff] ^\n Td2[(t1 >> 8) & 0xff] ^\n Td3[(t0 ) & 0xff] ^\n rk[3];\n }\n#endif /* ?FULL_UNROLL */\n /*\n\t * apply last round and\n\t * map cipher state to byte array block:\n\t */\n \ts0 =\n \t\t(Td4[(t0 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t3 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t2 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t1 ) & 0xff] & 0x000000ff) ^\n \t\trk[0];\n\tPUTU32(out , s0);\n \ts1 =\n \t\t(Td4[(t1 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t0 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t3 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t2 ) & 0xff] & 0x000000ff) ^\n \t\trk[1];\n\tPUTU32(out + 4, s1);\n \ts2 =\n \t\t(Td4[(t2 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t1 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t0 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t3 ) & 0xff] & 0x000000ff) ^\n \t\trk[2];\n\tPUTU32(out + 8, s2);\n \ts3 =\n \t\t(Td4[(t3 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t2 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t1 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t0 ) & 0xff] & 0x000000ff) ^\n \t\trk[3];\n\tPUTU32(out + 12, s3);\n}\n\n#endif /* AES_ASM */\n\nvoid AES_cbc_encrypt(const unsigned char *in, unsigned char *out,\n\t\t const unsigned long length, const AES_KEY *key,\n\t\t unsigned char *ivec, const int enc)\n{\n\n\tunsigned long n;\n\tunsigned long len = length;\n\tunsigned char tmp[AES_BLOCK_SIZE];\n\n\tassert(in && out && key && ivec);\n\n\tif (enc) {\n\t\twhile (len >= AES_BLOCK_SIZE) {\n\t\t\tfor(n=0; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\ttmp[n] = in[n] ^ ivec[n];\n\t\t\tAES_encrypt(tmp, out, key);\n\t\t\tmemcpy(ivec, out, AES_BLOCK_SIZE);\n\t\t\tlen -= AES_BLOCK_SIZE;\n\t\t\tin += AES_BLOCK_SIZE;\n\t\t\tout += AES_BLOCK_SIZE;\n\t\t}\n\t\tif (len) {\n\t\t\tfor(n=0; n < len; ++n)\n\t\t\t\ttmp[n] = in[n] ^ ivec[n];\n\t\t\tfor(n=len; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\ttmp[n] = ivec[n];\n\t\t\tAES_encrypt(tmp, tmp, key);\n\t\t\tmemcpy(out, tmp, AES_BLOCK_SIZE);\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t}\n\t} else {\n\t\twhile (len >= AES_BLOCK_SIZE) {\n\t\t\tmemcpy(tmp, in, AES_BLOCK_SIZE);\n\t\t\tAES_decrypt(in, out, key);\n\t\t\tfor(n=0; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\tout[n] ^= ivec[n];\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t\tlen -= AES_BLOCK_SIZE;\n\t\t\tin += AES_BLOCK_SIZE;\n\t\t\tout += AES_BLOCK_SIZE;\n\t\t}\n\t\tif (len) {\n\t\t\tmemcpy(tmp, in, AES_BLOCK_SIZE);\n\t\t\tAES_decrypt(tmp, tmp, key);\n\t\t\tfor(n=0; n < len; ++n)\n\t\t\t\tout[n] = tmp[n] ^ ivec[n];\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t}\n\t}\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_output.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_output.c\t8.3 (Berkeley) 1/21/94\n * ip_output.c,v 1.9 1994/11/16 10:17:10 jkh Exp\n */\n\n/*\n * Changes and additions relating to SLiRP are\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n/* Number of packets queued before we start sending\n * (to prevent allocing too many mbufs) */\n#define IF_THRESH 10\n\n/*\n * IP output. The packet in mbuf chain m contains a skeletal IP\n * header (with len, off, ttl, proto, tos, src, dst).\n * The mbuf chain containing the packet will be freed.\n * The mbuf opt, if present, will not be freed.\n */\nint\nip_output(struct socket *so, struct mbuf *m0)\n{\n\tSlirp *slirp = m0->slirp;\n\tregister struct ip *ip;\n\tregister struct mbuf *m = m0;\n\tregister int hlen = sizeof(struct ip );\n\tint len, off, error = 0;\n\n\tDEBUG_CALL(\"ip_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m0 = %lx\", (long)m0);\n\n\tip = mtod(m, struct ip *);\n\t/*\n\t * Fill in IP header.\n\t */\n\tip->ip_v = IPVERSION;\n\tip->ip_off &= IP_DF;\n\tip->ip_id = htons(slirp->ip_id++);\n\tip->ip_hl = hlen >> 2;\n\n\t/*\n\t * If small enough for interface, can just send directly.\n\t */\n\tif ((uint16_t)ip->ip_len <= IF_MTU) {\n\t\tip->ip_len = htons((uint16_t)ip->ip_len);\n\t\tip->ip_off = htons((uint16_t)ip->ip_off);\n\t\tip->ip_sum = 0;\n\t\tip->ip_sum = cksum(m, hlen);\n\n\t\tif_output(so, m);\n\t\tgoto done;\n\t}\n\n\t/*\n\t * Too large for interface; fragment if possible.\n\t * Must be able to put at least 8 bytes per fragment.\n\t */\n\tif (ip->ip_off & IP_DF) {\n\t\terror = -1;\n\t\tgoto bad;\n\t}\n\n\tlen = (IF_MTU - hlen) &~ 7; /* ip databytes per packet */\n\tif (len < 8) {\n\t\terror = -1;\n\t\tgoto bad;\n\t}\n\n {\n\tint mhlen, firstlen = len;\n\tstruct mbuf **mnext = &m->m_nextpkt;\n\n\t/*\n\t * Loop through length of segment after first fragment,\n\t * make new header and copy data of each part and link onto chain.\n\t */\n\tm0 = m;\n\tmhlen = sizeof (struct ip);\n\tfor (off = hlen + len; off < (uint16_t)ip->ip_len; off += len) {\n\t register struct ip *mhip;\n\t m = m_get(slirp);\n if (m == NULL) {\n\t error = -1;\n\t goto sendorfree;\n\t }\n\t m->m_data += IF_MAXLINKHDR;\n\t mhip = mtod(m, struct ip *);\n\t *mhip = *ip;\n\n\t m->m_len = mhlen;\n\t mhip->ip_off = ((off - hlen) >> 3) + (ip->ip_off & ~IP_MF);\n\t if (ip->ip_off & IP_MF)\n\t mhip->ip_off |= IP_MF;\n\t if (off + len >= (uint16_t)ip->ip_len)\n\t len = (uint16_t)ip->ip_len - off;\n\t else\n\t mhip->ip_off |= IP_MF;\n\t mhip->ip_len = htons((uint16_t)(len + mhlen));\n\n\t if (m_copy(m, m0, off, len) < 0) {\n\t error = -1;\n\t goto sendorfree;\n\t }\n\n\t mhip->ip_off = htons((uint16_t)mhip->ip_off);\n\t mhip->ip_sum = 0;\n\t mhip->ip_sum = cksum(m, mhlen);\n\t *mnext = m;\n\t mnext = &m->m_nextpkt;\n\t}\n\t/*\n\t * Update first fragment by trimming what's been copied out\n\t * and updating header, then send each fragment (in order).\n\t */\n\tm = m0;\n\tm_adj(m, hlen + firstlen - (uint16_t)ip->ip_len);\n\tip->ip_len = htons((uint16_t)m->m_len);\n\tip->ip_off = htons((uint16_t)(ip->ip_off | IP_MF));\n\tip->ip_sum = 0;\n\tip->ip_sum = cksum(m, hlen);\nsendorfree:\n\tfor (m = m0; m; m = m0) {\n\t\tm0 = m->m_nextpkt;\n m->m_nextpkt = NULL;\n\t\tif (error == 0)\n\t\t\tif_output(so, m);\n\t\telse\n\t\t\tm_freem(m);\n\t}\n }\n\ndone:\n\treturn (error);\n\nbad:\n\tm_freem(m0);\n\tgoto done;\n}\n"], ["/linuxpdf/tinyemu/slirp/cksum.c", "/*\n * Copyright (c) 1988, 1992, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)in_cksum.c\t8.1 (Berkeley) 6/10/93\n * in_cksum.c,v 1.2 1994/08/02 07:48:16 davidg Exp\n */\n\n#include \"slirp.h\"\n\n/*\n * Checksum routine for Internet Protocol family headers (Portable Version).\n *\n * This routine is very heavily used in the network\n * code and should be modified for each CPU to be as fast as possible.\n *\n * XXX Since we will never span more than 1 mbuf, we can optimise this\n */\n\n#define ADDCARRY(x) (x > 65535 ? x -= 65535 : x)\n#define REDUCE {l_util.l = sum; sum = l_util.s[0] + l_util.s[1]; \\\n (void)ADDCARRY(sum);}\n\nint cksum(struct mbuf *m, int len)\n{\n\tregister uint16_t *w;\n\tregister int sum = 0;\n\tregister int mlen = 0;\n\tint byte_swapped = 0;\n\n\tunion {\n\t\tuint8_t c[2];\n\t\tuint16_t s;\n\t} s_util;\n\tunion {\n\t\tuint16_t s[2];\n\t\tuint32_t l;\n\t} l_util;\n\n\tif (m->m_len == 0)\n\t goto cont;\n\tw = mtod(m, uint16_t *);\n\n\tmlen = m->m_len;\n\n\tif (len < mlen)\n\t mlen = len;\n#ifdef DEBUG\n\tlen -= mlen;\n#endif\n\t/*\n\t * Force to even boundary.\n\t */\n\tif ((1 & (long) w) && (mlen > 0)) {\n\t\tREDUCE;\n\t\tsum <<= 8;\n\t\ts_util.c[0] = *(uint8_t *)w;\n\t\tw = (uint16_t *)((int8_t *)w + 1);\n\t\tmlen--;\n\t\tbyte_swapped = 1;\n\t}\n\t/*\n\t * Unroll the loop to make overhead from\n\t * branches &c small.\n\t */\n\twhile ((mlen -= 32) >= 0) {\n\t\tsum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];\n\t\tsum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];\n\t\tsum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];\n\t\tsum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];\n\t\tw += 16;\n\t}\n\tmlen += 32;\n\twhile ((mlen -= 8) >= 0) {\n\t\tsum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];\n\t\tw += 4;\n\t}\n\tmlen += 8;\n\tif (mlen == 0 && byte_swapped == 0)\n\t goto cont;\n\tREDUCE;\n\twhile ((mlen -= 2) >= 0) {\n\t\tsum += *w++;\n\t}\n\n\tif (byte_swapped) {\n\t\tREDUCE;\n\t\tsum <<= 8;\n\t\tif (mlen == -1) {\n\t\t\ts_util.c[1] = *(uint8_t *)w;\n\t\t\tsum += s_util.s;\n\t\t\tmlen = 0;\n\t\t} else\n\n\t\t mlen = -1;\n\t} else if (mlen == -1)\n\t s_util.c[0] = *(uint8_t *)w;\n\ncont:\n#ifdef DEBUG\n\tif (len) {\n\t\tDEBUG_ERROR((dfd, \"cksum: out of data\\n\"));\n\t\tDEBUG_ERROR((dfd, \" len = %d\\n\", len));\n\t}\n#endif\n\tif (mlen == -1) {\n\t\t/* The last mbuf has odd # of bytes. Follow the\n\t\t standard (the odd byte may be shifted left by 8 bits\n\t\t\t or not as determined by endian-ness of the machine) */\n\t\ts_util.c[1] = 0;\n\t\tsum += s_util.s;\n\t}\n\tREDUCE;\n\treturn (~sum & 0xffff);\n}\n"], ["/linuxpdf/tinyemu/slirp/sbuf.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\nstatic void sbappendsb(struct sbuf *sb, struct mbuf *m);\n\nvoid\nsbfree(struct sbuf *sb)\n{\n\tfree(sb->sb_data);\n}\n\nvoid\nsbdrop(struct sbuf *sb, int num)\n{\n\t/*\n\t * We can only drop how much we have\n\t * This should never succeed\n\t */\n\tif(num > sb->sb_cc)\n\t\tnum = sb->sb_cc;\n\tsb->sb_cc -= num;\n\tsb->sb_rptr += num;\n\tif(sb->sb_rptr >= sb->sb_data + sb->sb_datalen)\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n}\n\nvoid\nsbreserve(struct sbuf *sb, int size)\n{\n\tif (sb->sb_data) {\n\t\t/* Already alloced, realloc if necessary */\n\t\tif (sb->sb_datalen != size) {\n\t\t\tsb->sb_wptr = sb->sb_rptr = sb->sb_data = (char *)realloc(sb->sb_data, size);\n\t\t\tsb->sb_cc = 0;\n\t\t\tif (sb->sb_wptr)\n\t\t\t sb->sb_datalen = size;\n\t\t\telse\n\t\t\t sb->sb_datalen = 0;\n\t\t}\n\t} else {\n\t\tsb->sb_wptr = sb->sb_rptr = sb->sb_data = (char *)malloc(size);\n\t\tsb->sb_cc = 0;\n\t\tif (sb->sb_wptr)\n\t\t sb->sb_datalen = size;\n\t\telse\n\t\t sb->sb_datalen = 0;\n\t}\n}\n\n/*\n * Try and write() to the socket, whatever doesn't get written\n * append to the buffer... for a host with a fast net connection,\n * this prevents an unnecessary copy of the data\n * (the socket is non-blocking, so we won't hang)\n */\nvoid\nsbappend(struct socket *so, struct mbuf *m)\n{\n\tint ret = 0;\n\n\tDEBUG_CALL(\"sbappend\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"m->m_len = %d\", m->m_len);\n\n\t/* Shouldn't happen, but... e.g. foreign host closes connection */\n\tif (m->m_len <= 0) {\n\t\tm_free(m);\n\t\treturn;\n\t}\n\n\t/*\n\t * If there is urgent data, call sosendoob\n\t * if not all was sent, sowrite will take care of the rest\n\t * (The rest of this function is just an optimisation)\n\t */\n\tif (so->so_urgc) {\n\t\tsbappendsb(&so->so_rcv, m);\n\t\tm_free(m);\n\t\tsosendoob(so);\n\t\treturn;\n\t}\n\n\t/*\n\t * We only write if there's nothing in the buffer,\n\t * ottherwise it'll arrive out of order, and hence corrupt\n\t */\n\tif (!so->so_rcv.sb_cc)\n\t ret = slirp_send(so, m->m_data, m->m_len, 0);\n\n\tif (ret <= 0) {\n\t\t/*\n\t\t * Nothing was written\n\t\t * It's possible that the socket has closed, but\n\t\t * we don't need to check because if it has closed,\n\t\t * it will be detected in the normal way by soread()\n\t\t */\n\t\tsbappendsb(&so->so_rcv, m);\n\t} else if (ret != m->m_len) {\n\t\t/*\n\t\t * Something was written, but not everything..\n\t\t * sbappendsb the rest\n\t\t */\n\t\tm->m_len -= ret;\n\t\tm->m_data += ret;\n\t\tsbappendsb(&so->so_rcv, m);\n\t} /* else */\n\t/* Whatever happened, we free the mbuf */\n\tm_free(m);\n}\n\n/*\n * Copy the data from m into sb\n * The caller is responsible to make sure there's enough room\n */\nstatic void\nsbappendsb(struct sbuf *sb, struct mbuf *m)\n{\n\tint len, n, nn;\n\n\tlen = m->m_len;\n\n\tif (sb->sb_wptr < sb->sb_rptr) {\n\t\tn = sb->sb_rptr - sb->sb_wptr;\n\t\tif (n > len) n = len;\n\t\tmemcpy(sb->sb_wptr, m->m_data, n);\n\t} else {\n\t\t/* Do the right edge first */\n\t\tn = sb->sb_data + sb->sb_datalen - sb->sb_wptr;\n\t\tif (n > len) n = len;\n\t\tmemcpy(sb->sb_wptr, m->m_data, n);\n\t\tlen -= n;\n\t\tif (len) {\n\t\t\t/* Now the left edge */\n\t\t\tnn = sb->sb_rptr - sb->sb_data;\n\t\t\tif (nn > len) nn = len;\n\t\t\tmemcpy(sb->sb_data,m->m_data+n,nn);\n\t\t\tn += nn;\n\t\t}\n\t}\n\n\tsb->sb_cc += n;\n\tsb->sb_wptr += n;\n\tif (sb->sb_wptr >= sb->sb_data + sb->sb_datalen)\n\t\tsb->sb_wptr -= sb->sb_datalen;\n}\n\n/*\n * Copy data from sbuf to a normal, straight buffer\n * Don't update the sbuf rptr, this will be\n * done in sbdrop when the data is acked\n */\nvoid\nsbcopy(struct sbuf *sb, int off, int len, char *to)\n{\n\tchar *from;\n\n\tfrom = sb->sb_rptr + off;\n\tif (from >= sb->sb_data + sb->sb_datalen)\n\t\tfrom -= sb->sb_datalen;\n\n\tif (from < sb->sb_wptr) {\n\t\tif (len > sb->sb_cc) len = sb->sb_cc;\n\t\tmemcpy(to,from,len);\n\t} else {\n\t\t/* re-use off */\n\t\toff = (sb->sb_data + sb->sb_datalen) - from;\n\t\tif (off > len) off = len;\n\t\tmemcpy(to,from,off);\n\t\tlen -= off;\n\t\tif (len)\n\t\t memcpy(to+off,sb->sb_data,len);\n\t}\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 17:59:23", "created_task_model": "DeepSeek-R1", "function_skeleton": "static const uint32_t *default_get_dirty_bits(PhysMemoryMap *map,\n PhysMemoryRange *pr) {}", "code_description": "This code segment functions to: Track modified memory regions by cycling between monitoring buffers, trigger cache invalidation when changes are detected, and reset tracking state for subsequent write operations."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c\n[TASK_BEGIN]\nstatic const uint32_t *default_get_dirty_bits(PhysMemoryMap *map,\n PhysMemoryRange *pr) {\n const uint32_t *ret;\n int new_index;\n \n new_index = (pr->dirty_bits_index + 1) % 2;\n ret = pr->dirty_bits_tab[pr->dirty_bits_index];\n pr->dirty_bits_index = new_index;\n pr->dirty_bits = pr->dirty_bits_tab[new_index];\n return ret;\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 17-59-54"}, "editdistance_info": {"edit_distance": 32.6923, "calculate_time": "2025-08-20 17:59:54", "true_code_clean": "static const uint32_t *default_get_dirty_bits(PhysMemoryMap *map,\n PhysMemoryRange *pr)\n{\n uint32_t *dirty_bits;\n BOOL has_dirty_bits;\n size_t n, i;\n dirty_bits = pr->dirty_bits;\n has_dirty_bits = FALSE;\n n = pr->dirty_bits_size / sizeof(uint32_t);\n for(i = 0; i < n; i++) {\n if (dirty_bits[i] != 0) {\n has_dirty_bits = TRUE;\n break;\n }\n }\n if (has_dirty_bits && pr->size != 0) {\n map->flush_tlb_write_range(map->opaque, pr->phys_mem, pr->org_size);\n }\n pr->dirty_bits_index ^= 1;\n pr->dirty_bits = pr->dirty_bits_tab[pr->dirty_bits_index];\n memset(pr->dirty_bits, 0, pr->dirty_bits_size);\n return dirty_bits;\n}", "predict_code_clean": "static const uint32_t *default_get_dirty_bits(PhysMemoryMap *map,\n PhysMemoryRange *pr) {\n const uint32_t *ret;\n int new_index;\n new_index = (pr->dirty_bits_index + 1) % 2;\n ret = pr->dirty_bits_tab[pr->dirty_bits_index];\n pr->dirty_bits_index = new_index;\n pr->dirty_bits = pr->dirty_bits_tab[new_index];\n return ret;\n}"}} {"repo_name": "linuxpdf", "file_name": "/linuxpdf/tinyemu/x86_machine.c", "inference_info": {"prefix_code": "/*\n * PC emulator\n * \n * Copyright (c) 2011-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"x86_cpu.h\"\n#include \"machine.h\"\n#include \"pci.h\"\n#include \"ide.h\"\n#include \"ps2.h\"\n\n#if defined(__linux__) && (defined(__i386__) || defined(__x86_64__))\n#define USE_KVM\n#endif\n\n#ifdef USE_KVM\n#include \n#include \n#include \n#include \n#include \n#endif\n\n//#define DEBUG_BIOS\n//#define DUMP_IOPORT\n\n/***********************************************************/\n/* cmos emulation */\n\n//#define DEBUG_CMOS\n\n#define RTC_SECONDS 0\n#define RTC_SECONDS_ALARM 1\n#define RTC_MINUTES 2\n#define RTC_MINUTES_ALARM 3\n#define RTC_HOURS 4\n#define RTC_HOURS_ALARM 5\n#define RTC_ALARM_DONT_CARE 0xC0\n\n#define RTC_DAY_OF_WEEK 6\n#define RTC_DAY_OF_MONTH 7\n#define RTC_MONTH 8\n#define RTC_YEAR 9\n\n#define RTC_REG_A 10\n#define RTC_REG_B 11\n#define RTC_REG_C 12\n#define RTC_REG_D 13\n\n#define REG_A_UIP 0x80\n\n#define REG_B_SET 0x80\n#define REG_B_PIE 0x40\n#define REG_B_AIE 0x20\n#define REG_B_UIE 0x10\n\ntypedef struct {\n uint8_t cmos_index;\n uint8_t cmos_data[128];\n IRQSignal *irq;\n BOOL use_local_time;\n /* used for the periodic irq */\n uint32_t irq_timeout;\n uint32_t irq_period;\n} CMOSState;\n\nstatic void cmos_write(void *opaque, uint32_t offset,\n uint32_t data, int size_log2);\nstatic uint32_t cmos_read(void *opaque, uint32_t offset, int size_log2);\n\nstatic int to_bcd(CMOSState *s, unsigned int a)\n{\n if (s->cmos_data[RTC_REG_B] & 0x04) {\n return a;\n } else {\n return ((a / 10) << 4) | (a % 10);\n }\n}\n\nstatic void cmos_update_time(CMOSState *s, BOOL set_century)\n{\n struct timeval tv;\n struct tm tm;\n time_t ti;\n int val;\n \n gettimeofday(&tv, NULL);\n ti = tv.tv_sec;\n if (s->use_local_time) {\n localtime_r(&ti, &tm);\n } else {\n gmtime_r(&ti, &tm);\n }\n \n s->cmos_data[RTC_SECONDS] = to_bcd(s, tm.tm_sec);\n s->cmos_data[RTC_MINUTES] = to_bcd(s, tm.tm_min);\n if (s->cmos_data[RTC_REG_B] & 0x02) {\n s->cmos_data[RTC_HOURS] = to_bcd(s, tm.tm_hour);\n } else {\n s->cmos_data[RTC_HOURS] = to_bcd(s, tm.tm_hour % 12);\n if (tm.tm_hour >= 12)\n s->cmos_data[RTC_HOURS] |= 0x80;\n }\n s->cmos_data[RTC_DAY_OF_WEEK] = to_bcd(s, tm.tm_wday);\n s->cmos_data[RTC_DAY_OF_MONTH] = to_bcd(s, tm.tm_mday);\n s->cmos_data[RTC_MONTH] = to_bcd(s, tm.tm_mon + 1);\n s->cmos_data[RTC_YEAR] = to_bcd(s, tm.tm_year % 100);\n\n if (set_century) {\n /* not set by the hardware, but easier to do it here */\n val = to_bcd(s, (tm.tm_year / 100) + 19);\n s->cmos_data[0x32] = val;\n s->cmos_data[0x37] = val;\n }\n \n /* update in progress flag: 8/32768 seconds after change */\n if (tv.tv_usec < 244) {\n s->cmos_data[RTC_REG_A] |= REG_A_UIP;\n } else {\n s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;\n }\n}\n\nCMOSState *cmos_init(PhysMemoryMap *port_map, int addr,\n IRQSignal *irq, BOOL use_local_time)\n{\n CMOSState *s;\n \n s = mallocz(sizeof(*s));\n s->use_local_time = use_local_time;\n \n s->cmos_index = 0;\n\n s->cmos_data[RTC_REG_A] = 0x26;\n s->cmos_data[RTC_REG_B] = 0x02;\n s->cmos_data[RTC_REG_C] = 0x00;\n s->cmos_data[RTC_REG_D] = 0x80;\n\n cmos_update_time(s, TRUE);\n \n s->irq = irq;\n \n cpu_register_device(port_map, addr, 2, s, cmos_read, cmos_write, \n DEVIO_SIZE8);\n return s;\n}\n\n#define CMOS_FREQ 32768\n\nstatic uint32_t cmos_get_timer(CMOSState *s)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint32_t)ts.tv_sec * CMOS_FREQ +\n ((uint64_t)ts.tv_nsec * CMOS_FREQ / 1000000000);\n}\n\nstatic void cmos_update_timer(CMOSState *s)\n{\n int period_code;\n\n period_code = s->cmos_data[RTC_REG_A] & 0x0f;\n if ((s->cmos_data[RTC_REG_B] & REG_B_PIE) &&\n period_code != 0) {\n if (period_code <= 2)\n period_code += 7;\n s->irq_period = 1 << (period_code - 1);\n s->irq_timeout = (cmos_get_timer(s) + s->irq_period) &\n ~(s->irq_period - 1);\n }\n}\n\n/* XXX: could return a delay, but we don't need high precision\n (Windows 2000 uses it for delay calibration) */\nstatic void cmos_update_irq(CMOSState *s)\n{\n uint32_t d;\n if (s->cmos_data[RTC_REG_B] & REG_B_PIE) {\n d = cmos_get_timer(s) - s->irq_timeout;\n if ((int32_t)d >= 0) {\n /* this is not what the real RTC does. Here we sent the IRQ\n immediately */\n s->cmos_data[RTC_REG_C] |= 0xc0;\n set_irq(s->irq, 1);\n /* update for the next irq */\n s->irq_timeout += s->irq_period;\n }\n }\n}\n\nstatic void cmos_write(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n CMOSState *s = opaque;\n\n if (offset == 0) {\n s->cmos_index = data & 0x7f;\n } else {\n#ifdef DEBUG_CMOS\n printf(\"cmos_write: reg=0x%02x val=0x%02x\\n\", s->cmos_index, data);\n#endif\n switch(s->cmos_index) {\n case RTC_REG_A:\n s->cmos_data[RTC_REG_A] = (data & ~REG_A_UIP) |\n (s->cmos_data[RTC_REG_A] & REG_A_UIP);\n cmos_update_timer(s);\n break;\n case RTC_REG_B:\n s->cmos_data[s->cmos_index] = data;\n cmos_update_timer(s);\n break;\n default:\n s->cmos_data[s->cmos_index] = data;\n break;\n }\n }\n}\n\nstatic uint32_t cmos_read(void *opaque, uint32_t offset, int size_log2)\n{\n CMOSState *s = opaque;\n int ret;\n\n if (offset == 0) {\n return 0xff;\n } else {\n switch(s->cmos_index) {\n case RTC_SECONDS:\n case RTC_MINUTES:\n case RTC_HOURS:\n case RTC_DAY_OF_WEEK:\n case RTC_DAY_OF_MONTH:\n case RTC_MONTH:\n case RTC_YEAR:\n case RTC_REG_A:\n cmos_update_time(s, FALSE);\n ret = s->cmos_data[s->cmos_index];\n break;\n case RTC_REG_C:\n ret = s->cmos_data[s->cmos_index];\n s->cmos_data[RTC_REG_C] = 0x00;\n set_irq(s->irq, 0);\n break;\n default:\n ret = s->cmos_data[s->cmos_index];\n }\n#ifdef DEBUG_CMOS\n printf(\"cmos_read: reg=0x%02x val=0x%02x\\n\", s->cmos_index, ret);\n#endif\n return ret;\n }\n}\n\n/***********************************************************/\n/* 8259 pic emulation */\n\n//#define DEBUG_PIC\n\ntypedef void PICUpdateIRQFunc(void *opaque);\n\ntypedef struct {\n uint8_t last_irr; /* edge detection */\n uint8_t irr; /* interrupt request register */\n uint8_t imr; /* interrupt mask register */\n uint8_t isr; /* interrupt service register */\n uint8_t priority_add; /* used to compute irq priority */\n uint8_t irq_base;\n uint8_t read_reg_select;\n uint8_t special_mask;\n uint8_t init_state;\n uint8_t auto_eoi;\n uint8_t rotate_on_autoeoi;\n uint8_t init4; /* true if 4 byte init */\n uint8_t elcr; /* PIIX edge/trigger selection*/\n uint8_t elcr_mask;\n PICUpdateIRQFunc *update_irq;\n void *opaque;\n} PICState;\n\nstatic void pic_reset(PICState *s);\nstatic void pic_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pic_read(void *opaque, uint32_t offset, int size_log2);\nstatic void pic_elcr_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pic_elcr_read(void *opaque, uint32_t offset, int size_log2);\n\nPICState *pic_init(PhysMemoryMap *port_map, int port, int elcr_port,\n int elcr_mask,\n PICUpdateIRQFunc *update_irq, void *opaque)\n{\n PICState *s;\n\n s = mallocz(sizeof(*s));\n s->elcr_mask = elcr_mask;\n s->update_irq = update_irq;\n s->opaque = opaque;\n cpu_register_device(port_map, port, 2, s,\n pic_read, pic_write, DEVIO_SIZE8);\n cpu_register_device(port_map, elcr_port, 1, s,\n pic_elcr_read, pic_elcr_write, DEVIO_SIZE8);\n pic_reset(s);\n return s;\n}\n\nstatic void pic_reset(PICState *s)\n{\n /* all 8 bit registers */\n s->last_irr = 0; /* edge detection */\n s->irr = 0; /* interrupt request register */\n s->imr = 0; /* interrupt mask register */\n s->isr = 0; /* interrupt service register */\n s->priority_add = 0; /* used to compute irq priority */\n s->irq_base = 0;\n s->read_reg_select = 0;\n s->special_mask = 0;\n s->init_state = 0;\n s->auto_eoi = 0;\n s->rotate_on_autoeoi = 0;\n s->init4 = 0; /* true if 4 byte init */\n}\n\n/* set irq level. If an edge is detected, then the IRR is set to 1 */\nstatic void pic_set_irq1(PICState *s, int irq, int level)\n{\n int mask;\n mask = 1 << irq;\n if (s->elcr & mask) {\n /* level triggered */\n if (level) {\n s->irr |= mask;\n s->last_irr |= mask;\n } else {\n s->irr &= ~mask;\n s->last_irr &= ~mask;\n }\n } else {\n /* edge triggered */\n if (level) {\n if ((s->last_irr & mask) == 0)\n s->irr |= mask;\n s->last_irr |= mask;\n } else {\n s->last_irr &= ~mask;\n }\n }\n}\n \nstatic int pic_get_priority(PICState *s, int mask)\n{\n int priority;\n if (mask == 0)\n return -1;\n priority = 7;\n while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)\n priority--;\n return priority;\n}\n\n/* return the pic wanted interrupt. return -1 if none */\nstatic int pic_get_irq(PICState *s)\n{\n int mask, cur_priority, priority;\n\n mask = s->irr & ~s->imr;\n priority = pic_get_priority(s, mask);\n if (priority < 0)\n return -1;\n /* compute current priority */\n cur_priority = pic_get_priority(s, s->isr);\n if (priority > cur_priority) {\n /* higher priority found: an irq should be generated */\n return priority;\n } else {\n return -1;\n }\n}\n \n/* acknowledge interrupt 'irq' */\nstatic void pic_intack(PICState *s, int irq)\n{\n if (s->auto_eoi) {\n if (s->rotate_on_autoeoi)\n s->priority_add = (irq + 1) & 7;\n } else {\n s->isr |= (1 << irq);\n }\n /* We don't clear a level sensitive interrupt here */\n if (!(s->elcr & (1 << irq)))\n s->irr &= ~(1 << irq);\n}\n\nstatic void pic_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PICState *s = opaque;\n int priority, addr;\n \n addr = offset & 1;\n#ifdef DEBUG_PIC\n console.log(\"pic_write: addr=\" + toHex2(addr) + \" val=\" + toHex2(val));\n#endif\n if (addr == 0) {\n if (val & 0x10) {\n /* init */\n pic_reset(s);\n s->init_state = 1;\n s->init4 = val & 1;\n if (val & 0x02)\n abort(); /* \"single mode not supported\" */\n if (val & 0x08)\n abort(); /* \"level sensitive irq not supported\" */\n } else if (val & 0x08) {\n if (val & 0x02)\n s->read_reg_select = val & 1;\n if (val & 0x40)\n s->special_mask = (val >> 5) & 1;\n } else {\n switch(val) {\n case 0x00:\n case 0x80:\n s->rotate_on_autoeoi = val >> 7;\n break;\n case 0x20: /* end of interrupt */\n case 0xa0:\n priority = pic_get_priority(s, s->isr);\n if (priority >= 0) {\n s->isr &= ~(1 << ((priority + s->priority_add) & 7));\n }\n if (val == 0xa0)\n s->priority_add = (s->priority_add + 1) & 7;\n break;\n case 0x60:\n case 0x61:\n case 0x62:\n case 0x63:\n case 0x64:\n case 0x65:\n case 0x66:\n case 0x67:\n priority = val & 7;\n s->isr &= ~(1 << priority);\n break;\n case 0xc0:\n case 0xc1:\n case 0xc2:\n case 0xc3:\n case 0xc4:\n case 0xc5:\n case 0xc6:\n case 0xc7:\n s->priority_add = (val + 1) & 7;\n break;\n case 0xe0:\n case 0xe1:\n case 0xe2:\n case 0xe3:\n case 0xe4:\n case 0xe5:\n case 0xe6:\n case 0xe7:\n priority = val & 7;\n s->isr &= ~(1 << priority);\n s->priority_add = (priority + 1) & 7;\n break;\n }\n }\n } else {\n switch(s->init_state) {\n case 0:\n /* normal mode */\n s->imr = val;\n s->update_irq(s->opaque);\n break;\n case 1:\n s->irq_base = val & 0xf8;\n s->init_state = 2;\n break;\n case 2:\n if (s->init4) {\n s->init_state = 3;\n } else {\n s->init_state = 0;\n }\n break;\n case 3:\n s->auto_eoi = (val >> 1) & 1;\n s->init_state = 0;\n break;\n }\n }\n}\n\nstatic uint32_t pic_read(void *opaque, uint32_t offset, int size_log2)\n{\n PICState *s = opaque;\n int addr, ret;\n\n addr = offset & 1;\n if (addr == 0) {\n if (s->read_reg_select)\n ret = s->isr;\n else\n ret = s->irr;\n } else {\n ret = s->imr;\n }\n#ifdef DEBUG_PIC\n console.log(\"pic_read: addr=\" + toHex2(addr1) + \" val=\" + toHex2(ret));\n#endif\n return ret;\n}\n\nstatic void pic_elcr_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PICState *s = opaque;\n s->elcr = val & s->elcr_mask;\n}\n\nstatic uint32_t pic_elcr_read(void *opaque, uint32_t offset, int size_log2)\n{\n PICState *s = opaque;\n return s->elcr;\n}\n\ntypedef struct {\n PICState *pics[2];\n int irq_requested;\n void (*cpu_set_irq)(void *opaque, int level);\n void *opaque;\n#if defined(DEBUG_PIC)\n uint8_t irq_level[16];\n#endif\n IRQSignal *irqs;\n} PIC2State;\n\nstatic void pic2_update_irq(void *opaque);\nstatic void pic2_set_irq(void *opaque, int irq, int level);\n\nPIC2State *pic2_init(PhysMemoryMap *port_map, uint32_t addr0, uint32_t addr1,\n uint32_t elcr_addr0, uint32_t elcr_addr1, \n void (*cpu_set_irq)(void *opaque, int level),\n void *opaque, IRQSignal *irqs)\n{\n PIC2State *s;\n int i;\n \n s = mallocz(sizeof(*s));\n\n for(i = 0; i < 16; i++) {\n irq_init(&irqs[i], pic2_set_irq, s, i);\n }\n s->cpu_set_irq = cpu_set_irq;\n s->opaque = opaque;\n s->pics[0] = pic_init(port_map, addr0, elcr_addr0, 0xf8, pic2_update_irq, s);\n s->pics[1] = pic_init(port_map, addr1, elcr_addr1, 0xde, pic2_update_irq, s);\n s->irq_requested = 0;\n return s;\n}\n\nvoid pic2_set_elcr(PIC2State *s, const uint8_t *elcr)\n{\n int i;\n for(i = 0; i < 2; i++) {\n s->pics[i]->elcr = elcr[i] & s->pics[i]->elcr_mask;\n }\n}\n\n/* raise irq to CPU if necessary. must be called every time the active\n irq may change */\nstatic void pic2_update_irq(void *opaque)\n{\n PIC2State *s = opaque;\n int irq2, irq;\n\n /* first look at slave pic */\n irq2 = pic_get_irq(s->pics[1]);\n if (irq2 >= 0) {\n /* if irq request by slave pic, signal master PIC */\n pic_set_irq1(s->pics[0], 2, 1);\n pic_set_irq1(s->pics[0], 2, 0);\n }\n /* look at requested irq */\n irq = pic_get_irq(s->pics[0]);\n#if 0\n console.log(\"irr=\" + toHex2(s->pics[0].irr) + \" imr=\" + toHex2(s->pics[0].imr) + \" isr=\" + toHex2(s->pics[0].isr) + \" irq=\"+ irq);\n#endif\n if (irq >= 0) {\n /* raise IRQ request on the CPU */\n s->cpu_set_irq(s->opaque, 1);\n } else {\n /* lower irq */\n s->cpu_set_irq(s->opaque, 0);\n }\n}\n\nstatic void pic2_set_irq(void *opaque, int irq, int level)\n{\n PIC2State *s = opaque;\n#if defined(DEBUG_PIC)\n if (irq != 0 && level != s->irq_level[irq]) {\n console.log(\"pic_set_irq: irq=\" + irq + \" level=\" + level);\n s->irq_level[irq] = level;\n }\n#endif\n pic_set_irq1(s->pics[irq >> 3], irq & 7, level);\n pic2_update_irq(s);\n}\n\n/* called from the CPU to get the hardware interrupt number */\nstatic int pic2_get_hard_intno(PIC2State *s)\n{\n int irq, irq2, intno;\n\n irq = pic_get_irq(s->pics[0]);\n if (irq >= 0) {\n pic_intack(s->pics[0], irq);\n if (irq == 2) {\n irq2 = pic_get_irq(s->pics[1]);\n if (irq2 >= 0) {\n pic_intack(s->pics[1], irq2);\n } else {\n /* spurious IRQ on slave controller */\n irq2 = 7;\n }\n intno = s->pics[1]->irq_base + irq2;\n irq = irq2 + 8;\n } else {\n intno = s->pics[0]->irq_base + irq;\n }\n } else {\n /* spurious IRQ on host controller */\n irq = 7;\n intno = s->pics[0]->irq_base + irq;\n }\n pic2_update_irq(s);\n\n#if defined(DEBUG_PIC)\n if (irq != 0 && irq != 14)\n printf(\"pic_interrupt: irq=%d\\n\", irq);\n#endif\n return intno;\n}\n\n/***********************************************************/\n/* 8253 PIT emulation */\n\n#define PIT_FREQ 1193182\n\n#define RW_STATE_LSB 0\n#define RW_STATE_MSB 1\n#define RW_STATE_WORD0 2\n#define RW_STATE_WORD1 3\n#define RW_STATE_LATCHED_WORD0 4\n#define RW_STATE_LATCHED_WORD1 5\n\n//#define DEBUG_PIT\n\ntypedef int64_t PITGetTicksFunc(void *opaque);\n\ntypedef struct PITState PITState;\n\ntypedef struct {\n PITState *pit_state;\n uint32_t count;\n uint32_t latched_count;\n uint8_t rw_state;\n uint8_t mode;\n uint8_t bcd;\n uint8_t gate;\n int64_t count_load_time;\n int64_t last_irq_time;\n} PITChannel;\n\nstruct PITState {\n PITChannel pit_channels[3];\n uint8_t speaker_data_on;\n PITGetTicksFunc *get_ticks;\n IRQSignal *irq;\n void *opaque;\n};\n\nstatic void pit_load_count(PITChannel *pc, int val);\nstatic void pit_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pit_read(void *opaque, uint32_t offset, int size_log2);\nstatic void speaker_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t speaker_read(void *opaque, uint32_t offset, int size_log2);\n\nPITState *pit_init(PhysMemoryMap *port_map, int addr0, int addr1,\n IRQSignal *irq,\n PITGetTicksFunc *get_ticks, void *opaque)\n{\n PITState *s;\n PITChannel *pc;\n int i;\n\n s = mallocz(sizeof(*s));\n\n s->irq = irq;\n s->get_ticks = get_ticks;\n s->opaque = opaque;\n \n for(i = 0; i < 3; i++) {\n pc = &s->pit_channels[i];\n pc->pit_state = s;\n pc->mode = 3;\n pc->gate = (i != 2) >> 0;\n pit_load_count(pc, 0);\n }\n s->speaker_data_on = 0;\n\n cpu_register_device(port_map, addr0, 4, s, pit_read, pit_write, \n DEVIO_SIZE8);\n\n cpu_register_device(port_map, addr1, 1, s, speaker_read, speaker_write, \n DEVIO_SIZE8);\n return s;\n}\n\n/* unit = PIT frequency */\nstatic int64_t pit_get_time(PITChannel *pc)\n{\n PITState *s = pc->pit_state;\n return s->get_ticks(s->opaque);\n}\n\nstatic uint32_t pit_get_count(PITChannel *pc)\n{\n uint32_t counter;\n uint64_t d;\n \n d = pit_get_time(pc) - pc->count_load_time;\n switch(pc->mode) {\n case 0:\n case 1:\n case 4:\n case 5:\n counter = (pc->count - d) & 0xffff;\n break;\n default:\n counter = pc->count - (d % pc->count);\n break;\n }\n return counter;\n}\n\n/* get pit output bit */\nstatic int pit_get_out(PITChannel *pc)\n{\n int out;\n int64_t d;\n \n d = pit_get_time(pc) - pc->count_load_time;\n switch(pc->mode) {\n default:\n case 0:\n out = (d >= pc->count) >> 0;\n break;\n case 1:\n out = (d < pc->count) >> 0;\n break;\n case 2:\n /* mode used by Linux */\n if ((d % pc->count) == 0 && d != 0)\n out = 1;\n else\n out = 0;\n break;\n case 3:\n out = ((d % pc->count) < (pc->count >> 1)) >> 0;\n break;\n case 4:\n case 5:\n out = (d == pc->count) >> 0;\n break;\n }\n return out;\n}\n\nstatic void pit_load_count(PITChannel *s, int val)\n{\n if (val == 0)\n val = 0x10000;\n s->count_load_time = pit_get_time(s);\n s->last_irq_time = 0;\n s->count = val;\n}\n\nstatic void pit_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PITState *pit = opaque;\n int channel, access, addr;\n PITChannel *s;\n\n addr = offset & 3;\n#ifdef DEBUG_PIT\n printf(\"pit_write: off=%d val=0x%02x\\n\", addr, val);\n#endif\n if (addr == 3) {\n channel = val >> 6;\n if (channel == 3)\n return;\n s = &pit->pit_channels[channel];\n access = (val >> 4) & 3;\n switch(access) {\n case 0:\n s->latched_count = pit_get_count(s);\n s->rw_state = RW_STATE_LATCHED_WORD0;\n break;\n default:\n s->mode = (val >> 1) & 7;\n s->bcd = val & 1;\n s->rw_state = access - 1 + RW_STATE_LSB;\n break;\n }\n } else {\n s = &pit->pit_channels[addr];\n switch(s->rw_state) {\n case RW_STATE_LSB:\n pit_load_count(s, val);\n break;\n case RW_STATE_MSB:\n pit_load_count(s, val << 8);\n break;\n case RW_STATE_WORD0:\n case RW_STATE_WORD1:\n if (s->rw_state & 1) {\n pit_load_count(s, (s->latched_count & 0xff) | (val << 8));\n } else {\n s->latched_count = val;\n }\n s->rw_state ^= 1;\n break;\n }\n }\n}\n\nstatic uint32_t pit_read(void *opaque, uint32_t offset, int size_log2)\n{\n PITState *pit = opaque;\n PITChannel *s;\n int ret, count, addr;\n \n addr = offset & 3;\n if (addr == 3)\n return 0xff;\n\n s = &pit->pit_channels[addr];\n switch(s->rw_state) {\n case RW_STATE_LSB:\n case RW_STATE_MSB:\n case RW_STATE_WORD0:\n case RW_STATE_WORD1:\n count = pit_get_count(s);\n if (s->rw_state & 1)\n ret = (count >> 8) & 0xff;\n else\n ret = count & 0xff;\n if (s->rw_state & 2)\n s->rw_state ^= 1;\n break;\n default:\n case RW_STATE_LATCHED_WORD0:\n case RW_STATE_LATCHED_WORD1:\n if (s->rw_state & 1)\n ret = s->latched_count >> 8;\n else\n ret = s->latched_count & 0xff;\n s->rw_state ^= 1;\n break;\n }\n#ifdef DEBUG_PIT\n printf(\"pit_read: off=%d val=0x%02x\\n\", addr, ret);\n#endif\n return ret;\n}\n\nstatic void speaker_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PITState *pit = opaque;\n pit->speaker_data_on = (val >> 1) & 1;\n pit->pit_channels[2].gate = val & 1;\n}\n\nstatic uint32_t speaker_read(void *opaque, uint32_t offset, int size_log2)\n{\n PITState *pit = opaque;\n PITChannel *s;\n int out, val;\n\n s = &pit->pit_channels[2];\n out = pit_get_out(s);\n val = (pit->speaker_data_on << 1) | s->gate | (out << 5);\n#ifdef DEBUG_PIT\n // console.log(\"speaker_read: addr=\" + toHex2(addr) + \" val=\" + toHex2(val));\n#endif\n return val;\n}\n\n/* set the IRQ if necessary and return the delay in ms until the next\n IRQ. Note: The code does not handle all the PIT configurations. */\nstatic int pit_update_irq(PITState *pit)\n{\n PITChannel *s;\n int64_t d, delay;\n \n s = &pit->pit_channels[0];\n \n delay = PIT_FREQ; /* could be infinity delay */\n \n d = pit_get_time(s) - s->count_load_time;\n switch(s->mode) {\n default:\n case 0:\n case 1:\n case 4:\n case 5:\n if (s->last_irq_time == 0) {\n delay = s->count - d;\n if (delay <= 0) {\n set_irq(pit->irq, 1);\n set_irq(pit->irq, 0);\n s->last_irq_time = d;\n }\n }\n break;\n case 2: /* mode used by Linux */\n case 3:\n delay = s->last_irq_time + s->count - d;\n if (delay <= 0) {\n set_irq(pit->irq, 1);\n set_irq(pit->irq, 0);\n s->last_irq_time += s->count;\n }\n break;\n }\n\n if (delay <= 0)\n return 0;\n else\n return delay / (PIT_FREQ / 1000);\n}\n \n/***********************************************************/\n/* serial port emulation */\n\n#define UART_LCR_DLAB\t0x80\t/* Divisor latch access bit */\n\n#define UART_IER_MSI\t0x08\t/* Enable Modem status interrupt */\n#define UART_IER_RLSI\t0x04\t/* Enable receiver line status interrupt */\n#define UART_IER_THRI\t0x02\t/* Enable Transmitter holding register int. */\n#define UART_IER_RDI\t0x01\t/* Enable receiver data interrupt */\n\n#define UART_IIR_NO_INT\t0x01\t/* No interrupts pending */\n#define UART_IIR_ID\t0x06\t/* Mask for the interrupt ID */\n\n#define UART_IIR_MSI\t0x00\t/* Modem status interrupt */\n#define UART_IIR_THRI\t0x02\t/* Transmitter holding register empty */\n#define UART_IIR_RDI\t0x04\t/* Receiver data interrupt */\n#define UART_IIR_RLSI\t0x06\t/* Receiver line status interrupt */\n#define UART_IIR_FE 0xC0 /* Fifo enabled */\n\n#define UART_LSR_TEMT\t0x40\t/* Transmitter empty */\n#define UART_LSR_THRE\t0x20\t/* Transmit-hold-register empty */\n#define UART_LSR_BI\t0x10\t/* Break interrupt indicator */\n#define UART_LSR_FE\t0x08\t/* Frame error indicator */\n#define UART_LSR_PE\t0x04\t/* Parity error indicator */\n#define UART_LSR_OE\t0x02\t/* Overrun error indicator */\n#define UART_LSR_DR\t0x01\t/* Receiver data ready */\n\n#define UART_FCR_XFR 0x04 /* XMIT Fifo Reset */\n#define UART_FCR_RFR 0x02 /* RCVR Fifo Reset */\n#define UART_FCR_FE 0x01 /* FIFO Enable */\n\n#define UART_FIFO_LENGTH 16 /* 16550A Fifo Length */\n\ntypedef struct {\n uint8_t divider; \n uint8_t rbr; /* receive register */\n uint8_t ier;\n uint8_t iir; /* read only */\n uint8_t lcr;\n uint8_t mcr;\n uint8_t lsr; /* read only */\n uint8_t msr;\n uint8_t scr;\n uint8_t fcr;\n IRQSignal *irq;\n void (*write_func)(void *opaque, const uint8_t *buf, int buf_len);\n void *opaque;\n} SerialState;\n\nstatic void serial_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t serial_read(void *opaque, uint32_t offset, int size_log2);\n\nSerialState *serial_init(PhysMemoryMap *port_map, int addr,\n IRQSignal *irq,\n void (*write_func)(void *opaque, const uint8_t *buf, int buf_len), void *opaque)\n{\n SerialState *s;\n s = mallocz(sizeof(*s));\n \n /* all 8 bit registers */\n s->divider = 0; \n s->rbr = 0; /* receive register */\n s->ier = 0;\n s->iir = UART_IIR_NO_INT; /* read only */\n s->lcr = 0;\n s->mcr = 0;\n s->lsr = UART_LSR_TEMT | UART_LSR_THRE; /* read only */\n s->msr = 0;\n s->scr = 0;\n s->fcr = 0;\n\n s->irq = irq;\n s->write_func = write_func;\n s->opaque = opaque;\n\n cpu_register_device(port_map, addr, 8, s, serial_read, serial_write, \n DEVIO_SIZE8);\n return s;\n}\n\nstatic void serial_update_irq(SerialState *s)\n{\n if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {\n s->iir = UART_IIR_RDI;\n } else if ((s->lsr & UART_LSR_THRE) && (s->ier & UART_IER_THRI)) {\n s->iir = UART_IIR_THRI;\n } else {\n s->iir = UART_IIR_NO_INT;\n }\n if (s->iir != UART_IIR_NO_INT) {\n set_irq(s->irq, 1);\n } else {\n set_irq(s->irq, 0);\n }\n}\n\n#if 0\n/* send remainining chars in fifo */\nSerial.prototype.write_tx_fifo = function()\n{\n if (s->tx_fifo != \"\") {\n s->write_func(s->tx_fifo);\n s->tx_fifo = \"\";\n \n s->lsr |= UART_LSR_THRE;\n s->lsr |= UART_LSR_TEMT;\n s->update_irq();\n }\n}\n#endif\n \nstatic void serial_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n SerialState *s = opaque;\n int addr;\n\n addr = offset & 7;\n switch(addr) {\n default:\n case 0:\n if (s->lcr & UART_LCR_DLAB) {\n s->divider = (s->divider & 0xff00) | val;\n } else {\n#if 0\n if (s->fcr & UART_FCR_FE) {\n s->tx_fifo += String.fromCharCode(val);\n s->lsr &= ~UART_LSR_THRE;\n serial_update_irq(s);\n if (s->tx_fifo.length >= UART_FIFO_LENGTH) {\n /* write to the terminal */\n s->write_tx_fifo();\n }\n } else\n#endif\n {\n uint8_t ch;\n s->lsr &= ~UART_LSR_THRE;\n serial_update_irq(s);\n \n /* write to the terminal */\n ch = val;\n s->write_func(s->opaque, &ch, 1);\n s->lsr |= UART_LSR_THRE;\n s->lsr |= UART_LSR_TEMT;\n serial_update_irq(s);\n }\n }\n break;\n case 1:\n if (s->lcr & UART_LCR_DLAB) {\n s->divider = (s->divider & 0x00ff) | (val << 8);\n } else {\n s->ier = val;\n serial_update_irq(s);\n }\n break;\n case 2:\n#if 0\n if ((s->fcr ^ val) & UART_FCR_FE) {\n /* clear fifos */\n val |= UART_FCR_XFR | UART_FCR_RFR;\n }\n if (val & UART_FCR_XFR)\n s->tx_fifo = \"\";\n if (val & UART_FCR_RFR)\n s->rx_fifo = \"\";\n s->fcr = val & UART_FCR_FE;\n#endif\n break;\n case 3:\n s->lcr = val;\n break;\n case 4:\n s->mcr = val;\n break;\n case 5:\n break;\n case 6:\n s->msr = val;\n break;\n case 7:\n s->scr = val;\n break;\n }\n}\n\nstatic uint32_t serial_read(void *opaque, uint32_t offset, int size_log2)\n{\n SerialState *s = opaque;\n int ret, addr;\n\n addr = offset & 7;\n switch(addr) {\n default:\n case 0:\n if (s->lcr & UART_LCR_DLAB) {\n ret = s->divider & 0xff; \n } else {\n ret = s->rbr;\n s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);\n serial_update_irq(s);\n#if 0\n /* try to receive next chars */\n s->send_char_from_fifo();\n#endif\n }\n break;\n case 1:\n if (s->lcr & UART_LCR_DLAB) {\n ret = (s->divider >> 8) & 0xff;\n } else {\n ret = s->ier;\n }\n break;\n case 2:\n ret = s->iir;\n if (s->fcr & UART_FCR_FE)\n ret |= UART_IIR_FE;\n break;\n case 3:\n ret = s->lcr;\n break;\n case 4:\n ret = s->mcr;\n break;\n case 5:\n ret = s->lsr;\n break;\n case 6:\n ret = s->msr;\n break;\n case 7:\n ret = s->scr;\n break;\n }\n return ret;\n}\n\nvoid serial_send_break(SerialState *s)\n{\n s->rbr = 0;\n s->lsr |= UART_LSR_BI | UART_LSR_DR;\n serial_update_irq(s);\n}\n\n#if 0\nstatic void serial_send_char(SerialState *s, int ch)\n{\n s->rbr = ch;\n s->lsr |= UART_LSR_DR;\n serial_update_irq(s);\n}\n\nSerial.prototype.send_char_from_fifo = function()\n{\n var fifo;\n\n fifo = s->rx_fifo;\n if (fifo != \"\" && !(s->lsr & UART_LSR_DR)) {\n s->send_char(fifo.charCodeAt(0));\n s->rx_fifo = fifo.substr(1, fifo.length - 1);\n }\n}\n\n/* queue the string in the UART receive fifo and send it ASAP */\nSerial.prototype.send_chars = function(str)\n{\n s->rx_fifo += str;\n s->send_char_from_fifo();\n}\n \n#endif\n\n#ifdef DEBUG_BIOS\nstatic void bios_debug_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n#ifdef EMSCRIPTEN\n static char line_buf[256];\n static int line_buf_index;\n line_buf[line_buf_index++] = val;\n if (val == '\\n' || line_buf_index >= sizeof(line_buf) - 1) {\n line_buf[line_buf_index] = '\\0';\n printf(\"%s\", line_buf);\n line_buf_index = 0;\n }\n#else\n putchar(val & 0xff);\n#endif\n}\n\nstatic uint32_t bios_debug_read(void *opaque, uint32_t offset, int size_log2)\n{\n return 0;\n}\n#endif\n\ntypedef struct PCMachine {\n VirtMachine common;\n uint64_t ram_size;\n PhysMemoryMap *mem_map;\n PhysMemoryMap *port_map;\n \n X86CPUState *cpu_state;\n PIC2State *pic_state;\n IRQSignal pic_irq[16];\n PITState *pit_state;\n I440FXState *i440fx_state;\n CMOSState *cmos_state;\n SerialState *serial_state;\n\n /* input */\n VIRTIODevice *keyboard_dev;\n VIRTIODevice *mouse_dev;\n KBDState *kbd_state;\n PS2MouseState *ps2_mouse;\n VMMouseState *vm_mouse;\n PS2KbdState *ps2_kbd;\n\n#ifdef USE_KVM\n BOOL kvm_enabled;\n int kvm_fd;\n int vm_fd;\n int vcpu_fd;\n int kvm_run_size;\n struct kvm_run *kvm_run;\n#endif\n} PCMachine;\n\nstatic void copy_kernel(PCMachine *s, const uint8_t *buf, int buf_len,\n const char *cmd_line);\n\nstatic void port80_write(void *opaque, uint32_t offset,\n uint32_t val64, int size_log2)\n{\n}\n\nstatic uint32_t port80_read(void *opaque, uint32_t offset, int size_log2)\n{\n return 0xff;\n}\n\nstatic void port92_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n}\n\nstatic uint32_t port92_read(void *opaque, uint32_t offset, int size_log2)\n{\n int a20 = 1; /* A20=0 is not supported */\n return a20 << 1;\n}\n\n#define VMPORT_MAGIC 0x564D5868\n#define REG_EAX 0\n#define REG_EBX 1\n#define REG_ECX 2\n#define REG_EDX 3\n#define REG_ESI 4\n#define REG_EDI 5\n\nstatic uint32_t vmport_read(void *opaque, uint32_t addr, int size_log2)\n{\n PCMachine *s = opaque;\n uint32_t regs[6];\n\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n struct kvm_regs r;\n\n ioctl(s->vcpu_fd, KVM_GET_REGS, &r);\n regs[REG_EAX] = r.rax;\n regs[REG_EBX] = r.rbx;\n regs[REG_ECX] = r.rcx;\n regs[REG_EDX] = r.rdx;\n regs[REG_ESI] = r.rsi;\n regs[REG_EDI] = r.rdi;\n\n if (regs[REG_EAX] == VMPORT_MAGIC) {\n \n vmmouse_handler(s->vm_mouse, regs);\n \n /* Note: in 64 bits the high parts are reset to zero\n in all cases. */\n r.rax = regs[REG_EAX];\n r.rbx = regs[REG_EBX];\n r.rcx = regs[REG_ECX];\n r.rdx = regs[REG_EDX];\n r.rsi = regs[REG_ESI];\n r.rdi = regs[REG_EDI];\n ioctl(s->vcpu_fd, KVM_SET_REGS, &r);\n }\n } else\n#endif\n {\n regs[REG_EAX] = x86_cpu_get_reg(s->cpu_state, 0);\n regs[REG_EBX] = x86_cpu_get_reg(s->cpu_state, 3);\n regs[REG_ECX] = x86_cpu_get_reg(s->cpu_state, 1);\n regs[REG_EDX] = x86_cpu_get_reg(s->cpu_state, 2);\n regs[REG_ESI] = x86_cpu_get_reg(s->cpu_state, 6);\n regs[REG_EDI] = x86_cpu_get_reg(s->cpu_state, 7);\n\n if (regs[REG_EAX] == VMPORT_MAGIC) {\n vmmouse_handler(s->vm_mouse, regs);\n\n x86_cpu_set_reg(s->cpu_state, 0, regs[REG_EAX]);\n x86_cpu_set_reg(s->cpu_state, 3, regs[REG_EBX]);\n x86_cpu_set_reg(s->cpu_state, 1, regs[REG_ECX]);\n x86_cpu_set_reg(s->cpu_state, 2, regs[REG_EDX]);\n x86_cpu_set_reg(s->cpu_state, 6, regs[REG_ESI]);\n x86_cpu_set_reg(s->cpu_state, 7, regs[REG_EDI]);\n }\n }\n return regs[REG_EAX];\n}\n\nstatic void vmport_write(void *opaque, uint32_t addr, uint32_t val,\n int size_log2)\n{\n}\n\nstatic void pic_set_irq_cb(void *opaque, int level)\n{\n PCMachine *s = opaque;\n x86_cpu_set_irq(s->cpu_state, level);\n}\n\nstatic void serial_write_cb(void *opaque, const uint8_t *buf, int buf_len)\n{\n PCMachine *s = opaque;\n if (s->common.console) {\n s->common.console->write_data(s->common.console->opaque, buf, buf_len);\n }\n}\n\nstatic int get_hard_intno_cb(void *opaque)\n{\n PCMachine *s = opaque;\n return pic2_get_hard_intno(s->pic_state);\n}\n\nstatic int64_t pit_get_ticks_cb(void *opaque)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * PIT_FREQ +\n ((uint64_t)ts.tv_nsec * PIT_FREQ / 1000000000);\n}\n\n#define FRAMEBUFFER_BASE_ADDR 0xf0400000\n\nstatic uint8_t *get_ram_ptr(PCMachine *s, uint64_t paddr)\n{\n PhysMemoryRange *pr;\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr || !pr->is_ram)\n return NULL;\n return pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n}\n\n#ifdef DUMP_IOPORT\nstatic BOOL dump_port(int port)\n{\n return !((port >= 0x1f0 && port <= 0x1f7) ||\n (port >= 0x20 && port <= 0x21) ||\n (port >= 0xa0 && port <= 0xa1));\n}\n#endif\n\nstatic void st_port(void *opaque, uint32_t port, uint32_t val, int size_log2)\n{\n PCMachine *s = opaque;\n PhysMemoryRange *pr;\n#ifdef DUMP_IOPORT\n if (dump_port(port))\n printf(\"write port=0x%x val=0x%x s=%d\\n\", port, val, 1 << size_log2);\n#endif\n pr = get_phys_mem_range(s->port_map, port);\n if (!pr) {\n return;\n }\n port -= pr->addr;\n if ((pr->devio_flags >> size_log2) & 1) {\n pr->write_func(pr->opaque, port, (uint32_t)val, size_log2);\n } else if (size_log2 == 1 && (pr->devio_flags & DEVIO_SIZE8)) {\n pr->write_func(pr->opaque, port, val & 0xff, 0);\n pr->write_func(pr->opaque, port + 1, (val >> 8) & 0xff, 0);\n }\n}\n\nstatic uint32_t ld_port(void *opaque, uint32_t port1, int size_log2)\n{\n PCMachine *s = opaque;\n PhysMemoryRange *pr;\n uint32_t val, port;\n \n port = port1;\n pr = get_phys_mem_range(s->port_map, port);\n if (!pr) {\n val = -1;\n } else {\n port -= pr->addr;\n if ((pr->devio_flags >> size_log2) & 1) {\n val = pr->read_func(pr->opaque, port, size_log2);\n } else if (size_log2 == 1 && (pr->devio_flags & DEVIO_SIZE8)) {\n val = pr->read_func(pr->opaque, port, 0) & 0xff;\n val |= (pr->read_func(pr->opaque, port + 1, 0) & 0xff) << 8;\n } else {\n val = -1;\n }\n }\n#ifdef DUMP_IOPORT\n if (dump_port(port1))\n printf(\"read port=0x%x val=0x%x s=%d\\n\", port1, val, 1 << size_log2);\n#endif\n return val;\n}\n\nstatic void pc_machine_set_defaults(VirtMachineParams *p)\n{\n p->accel_enable = TRUE;\n}\n\n#ifdef USE_KVM\n\nstatic void sigalrm_handler(int sig)\n{\n}\n\n#define CPUID_APIC (1 << 9)\n#define CPUID_ACPI (1 << 22)\n\nstatic void kvm_set_cpuid(PCMachine *s)\n{\n struct kvm_cpuid2 *kvm_cpuid;\n int n_ent_max, i;\n struct kvm_cpuid_entry2 *ent;\n \n n_ent_max = 128;\n kvm_cpuid = mallocz(sizeof(struct kvm_cpuid2) + n_ent_max * sizeof(kvm_cpuid->entries[0]));\n \n kvm_cpuid->nent = n_ent_max;\n if (ioctl(s->kvm_fd, KVM_GET_SUPPORTED_CPUID, kvm_cpuid) < 0) {\n perror(\"KVM_GET_SUPPORTED_CPUID\");\n exit(1);\n }\n\n for(i = 0; i < kvm_cpuid->nent; i++) {\n ent = &kvm_cpuid->entries[i];\n /* remove the APIC & ACPI to be in sync with the emulator */\n if (ent->function == 1 || ent->function == 0x80000001) {\n ent->edx &= ~(CPUID_APIC | CPUID_ACPI);\n }\n }\n \n if (ioctl(s->vcpu_fd, KVM_SET_CPUID2, kvm_cpuid) < 0) {\n perror(\"KVM_SET_CPUID2\");\n exit(1);\n }\n free(kvm_cpuid);\n}\n\n/* XXX: should check overlapping mappings */\nstatic void kvm_map_ram(PhysMemoryMap *mem_map, PhysMemoryRange *pr)\n{\n PCMachine *s = mem_map->opaque;\n struct kvm_userspace_memory_region region;\n int flags;\n\n region.slot = pr - mem_map->phys_mem_range;\n flags = 0;\n if (pr->devram_flags & DEVRAM_FLAG_ROM)\n flags |= KVM_MEM_READONLY;\n if (pr->devram_flags & DEVRAM_FLAG_DIRTY_BITS)\n flags |= KVM_MEM_LOG_DIRTY_PAGES;\n region.flags = flags;\n region.guest_phys_addr = pr->addr;\n region.memory_size = pr->size;\n#if 0\n printf(\"map slot %d: %08lx %08lx\\n\",\n region.slot, pr->addr, pr->size);\n#endif\n region.userspace_addr = (uintptr_t)pr->phys_mem;\n if (ioctl(s->vm_fd, KVM_SET_USER_MEMORY_REGION, ®ion) < 0) {\n perror(\"KVM_SET_USER_MEMORY_REGION\");\n exit(1);\n }\n}\n\n/* XXX: just for one region */\nstatic PhysMemoryRange *kvm_register_ram(PhysMemoryMap *mem_map, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n uint8_t *phys_mem;\n \n pr = register_ram_entry(mem_map, addr, size, devram_flags);\n\n phys_mem = mmap(NULL, size, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n if (!phys_mem)\n return NULL;\n pr->phys_mem = phys_mem;\n if (devram_flags & DEVRAM_FLAG_DIRTY_BITS) {\n int n_pages = size >> 12;\n pr->dirty_bits_size = ((n_pages + 63) / 64) * 8;\n pr->dirty_bits = mallocz(pr->dirty_bits_size);\n }\n\n if (pr->size != 0) {\n kvm_map_ram(mem_map, pr);\n }\n return pr;\n}\n\nstatic void kvm_set_ram_addr(PhysMemoryMap *mem_map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n if (enabled) {\n if (pr->size == 0 || addr != pr->addr) {\n /* move or create the region */\n pr->size = pr->org_size;\n pr->addr = addr;\n kvm_map_ram(mem_map, pr);\n }\n } else {\n if (pr->size != 0) {\n pr->addr = 0;\n pr->size = 0;\n /* map a zero size region to disable */\n kvm_map_ram(mem_map, pr);\n }\n }\n}\n\nstatic const uint32_t *kvm_get_dirty_bits(PhysMemoryMap *mem_map,\n PhysMemoryRange *pr)\n{\n PCMachine *s = mem_map->opaque;\n struct kvm_dirty_log dlog;\n \n if (pr->size == 0) {\n /* not mapped: we assume no modification was made */\n memset(pr->dirty_bits, 0, pr->dirty_bits_size);\n } else {\n dlog.slot = pr - mem_map->phys_mem_range;\n dlog.dirty_bitmap = pr->dirty_bits;\n if (ioctl(s->vm_fd, KVM_GET_DIRTY_LOG, &dlog) < 0) {\n perror(\"KVM_GET_DIRTY_LOG\");\n exit(1);\n }\n }\n return pr->dirty_bits;\n}\n\nstatic void kvm_free_ram(PhysMemoryMap *mem_map, PhysMemoryRange *pr)\n{\n /* XXX: do it */\n munmap(pr->phys_mem, pr->org_size);\n free(pr->dirty_bits);\n}\n\nstatic void kvm_pic_set_irq(void *opaque, int irq_num, int level)\n{\n PCMachine *s = opaque;\n struct kvm_irq_level irq_level;\n irq_level.irq = irq_num;\n irq_level.level = level;\n if (ioctl(s->vm_fd, KVM_IRQ_LINE, &irq_level) < 0) {\n perror(\"KVM_IRQ_LINE\");\n exit(1);\n }\n}\n\nstatic void kvm_init(PCMachine *s)\n{\n int ret, i;\n struct sigaction act;\n struct kvm_pit_config pit_config;\n uint64_t base_addr;\n \n s->kvm_enabled = FALSE;\n s->kvm_fd = open(\"/dev/kvm\", O_RDWR);\n if (s->kvm_fd < 0) {\n fprintf(stderr, \"KVM not available\\n\");\n return;\n }\n ret = ioctl(s->kvm_fd, KVM_GET_API_VERSION, 0);\n if (ret < 0) {\n perror(\"KVM_GET_API_VERSION\");\n exit(1);\n }\n if (ret != 12) {\n fprintf(stderr, \"Unsupported KVM version\\n\");\n close(s->kvm_fd);\n s->kvm_fd = -1;\n return;\n }\n s->vm_fd = ioctl(s->kvm_fd, KVM_CREATE_VM, 0);\n if (s->vm_fd < 0) {\n perror(\"KVM_CREATE_VM\");\n exit(1);\n }\n\n /* just before the BIOS */\n base_addr = 0xfffbc000;\n if (ioctl(s->vm_fd, KVM_SET_IDENTITY_MAP_ADDR, &base_addr) < 0) {\n perror(\"KVM_SET_IDENTITY_MAP_ADDR\");\n exit(1);\n }\n \n if (ioctl(s->vm_fd, KVM_SET_TSS_ADDR, (long)(base_addr + 0x1000)) < 0) {\n perror(\"KVM_SET_TSS_ADDR\");\n exit(1);\n }\n \n if (ioctl(s->vm_fd, KVM_CREATE_IRQCHIP, 0) < 0) {\n perror(\"KVM_CREATE_IRQCHIP\");\n exit(1);\n }\n\n memset(&pit_config, 0, sizeof(pit_config));\n pit_config.flags = KVM_PIT_SPEAKER_DUMMY;\n if (ioctl(s->vm_fd, KVM_CREATE_PIT2, &pit_config)) {\n perror(\"KVM_CREATE_PIT2\");\n exit(1);\n }\n \n s->vcpu_fd = ioctl(s->vm_fd, KVM_CREATE_VCPU, 0);\n if (s->vcpu_fd < 0) {\n perror(\"KVM_CREATE_VCPU\");\n exit(1);\n }\n\n kvm_set_cpuid(s);\n \n /* map the kvm_run structure */\n s->kvm_run_size = ioctl(s->kvm_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);\n if (s->kvm_run_size < 0) {\n perror(\"KVM_GET_VCPU_MMAP_SIZE\");\n exit(1);\n }\n\n s->kvm_run = mmap(NULL, s->kvm_run_size, PROT_READ | PROT_WRITE,\n MAP_SHARED, s->vcpu_fd, 0);\n if (!s->kvm_run) {\n perror(\"mmap kvm_run\");\n exit(1);\n }\n\n for(i = 0; i < 16; i++) {\n irq_init(&s->pic_irq[i], kvm_pic_set_irq, s, i);\n }\n\n act.sa_handler = sigalrm_handler;\n sigemptyset(&act.sa_mask);\n act.sa_flags = 0;\n sigaction(SIGALRM, &act, NULL);\n\n s->kvm_enabled = TRUE;\n\n s->mem_map->register_ram = kvm_register_ram;\n s->mem_map->free_ram = kvm_free_ram;\n s->mem_map->get_dirty_bits = kvm_get_dirty_bits;\n s->mem_map->set_ram_addr = kvm_set_ram_addr;\n s->mem_map->opaque = s;\n}\n\nstatic void kvm_exit_io(PCMachine *s, struct kvm_run *run)\n{\n uint8_t *ptr;\n int i;\n \n ptr = (uint8_t *)run + run->io.data_offset;\n // printf(\"port: addr=%04x\\n\", run->io.port);\n \n for(i = 0; i < run->io.count; i++) {\n if (run->io.direction == KVM_EXIT_IO_OUT) {\n switch(run->io.size) {\n case 1:\n st_port(s, run->io.port, *(uint8_t *)ptr, 0);\n break;\n case 2:\n st_port(s, run->io.port, *(uint16_t *)ptr, 1);\n break;\n case 4:\n st_port(s, run->io.port, *(uint32_t *)ptr, 2);\n break;\n default:\n abort();\n }\n } else {\n switch(run->io.size) {\n case 1:\n *(uint8_t *)ptr = ld_port(s, run->io.port, 0);\n break;\n case 2:\n *(uint16_t *)ptr = ld_port(s, run->io.port, 1);\n break;\n case 4:\n *(uint32_t *)ptr = ld_port(s, run->io.port, 2);\n break;\n default:\n abort();\n }\n }\n ptr += run->io.size;\n }\n}\n\nstatic void kvm_exit_mmio(PCMachine *s, struct kvm_run *run)\n{\n uint8_t *data = run->mmio.data;\n PhysMemoryRange *pr;\n uint64_t addr;\n \n pr = get_phys_mem_range(s->mem_map, run->mmio.phys_addr);\n if (run->mmio.is_write) {\n if (!pr || pr->is_ram)\n return;\n addr = run->mmio.phys_addr - pr->addr;\n switch(run->mmio.len) {\n case 1:\n if (pr->devio_flags & DEVIO_SIZE8) {\n pr->write_func(pr->opaque, addr, *(uint8_t *)data, 0);\n }\n break;\n case 2:\n if (pr->devio_flags & DEVIO_SIZE16) {\n pr->write_func(pr->opaque, addr, *(uint16_t *)data, 1);\n }\n break;\n case 4:\n if (pr->devio_flags & DEVIO_SIZE32) {\n pr->write_func(pr->opaque, addr, *(uint32_t *)data, 2);\n }\n break;\n case 8:\n if (pr->devio_flags & DEVIO_SIZE32) {\n pr->write_func(pr->opaque, addr, *(uint32_t *)data, 2);\n pr->write_func(pr->opaque, addr + 4, *(uint32_t *)(data + 4), 2);\n }\n break;\n default:\n abort();\n }\n } else {\n if (!pr || pr->is_ram)\n goto no_dev;\n addr = run->mmio.phys_addr - pr->addr;\n switch(run->mmio.len) {\n case 1:\n if (!(pr->devio_flags & DEVIO_SIZE8))\n goto no_dev;\n *(uint8_t *)data = pr->read_func(pr->opaque, addr, 0);\n break;\n case 2:\n if (!(pr->devio_flags & DEVIO_SIZE16))\n goto no_dev;\n *(uint16_t *)data = pr->read_func(pr->opaque, addr, 1);\n break;\n case 4:\n if (!(pr->devio_flags & DEVIO_SIZE32))\n goto no_dev;\n *(uint32_t *)data = pr->read_func(pr->opaque, addr, 2);\n break;\n case 8:\n if (pr->devio_flags & DEVIO_SIZE32) {\n *(uint32_t *)data =\n pr->read_func(pr->opaque, addr, 2);\n *(uint32_t *)(data + 4) =\n pr->read_func(pr->opaque, addr + 4, 2);\n } else {\n no_dev:\n memset(run->mmio.data, 0, run->mmio.len);\n }\n break;\n default:\n abort();\n }\n \n }\n}\n\nstatic void kvm_exec(PCMachine *s)\n{\n struct kvm_run *run = s->kvm_run;\n struct itimerval ival;\n int ret;\n \n /* Not efficient but simple: we use a timer to interrupt the\n execution after a given time */\n ival.it_interval.tv_sec = 0;\n ival.it_interval.tv_usec = 0;\n ival.it_value.tv_sec = 0;\n ival.it_value.tv_usec = 10 * 1000; /* 10 ms max */\n setitimer(ITIMER_REAL, &ival, NULL);\n\n ret = ioctl(s->vcpu_fd, KVM_RUN, 0);\n if (ret < 0) {\n if (errno == EINTR || errno == EAGAIN) {\n /* timeout */\n return;\n }\n perror(\"KVM_RUN\");\n exit(1);\n }\n // printf(\"exit=%d\\n\", run->exit_reason);\n switch(run->exit_reason) {\n case KVM_EXIT_HLT:\n break;\n case KVM_EXIT_IO:\n kvm_exit_io(s, run);\n break;\n case KVM_EXIT_MMIO:\n kvm_exit_mmio(s, run);\n break;\n case KVM_EXIT_FAIL_ENTRY:\n fprintf(stderr, \"KVM_EXIT_FAIL_ENTRY: reason=0x%\" PRIx64 \"\\n\",\n (uint64_t)run->fail_entry.hardware_entry_failure_reason);\n#if 0\n {\n struct kvm_regs regs;\n if (ioctl(s->vcpu_fd, KVM_GET_REGS, ®s) < 0) {\n perror(\"KVM_SET_REGS\");\n exit(1);\n }\n printf(\"RIP=%016\" PRIx64 \"\\n\", (uint64_t)regs.rip);\n }\n#endif\n exit(1);\n case KVM_EXIT_INTERNAL_ERROR:\n fprintf(stderr, \"KVM_EXIT_INTERNAL_ERROR: suberror=0x%x\\n\",\n (uint32_t)run->internal.suberror);\n exit(1);\n default:\n fprintf(stderr, \"KVM: unsupported exit_reason=%d\\n\", run->exit_reason);\n exit(1);\n }\n}\n#endif\n\n#if defined(EMSCRIPTEN)\n/* with Javascript clock_gettime() is not enough precise enough to\n have a reliable TSC counter. XXX: increment the cycles during the\n power down time */\nstatic uint64_t cpu_get_tsc(void *opaque)\n{\n PCMachine *s = opaque;\n uint64_t c;\n c = x86_cpu_get_cycles(s->cpu_state);\n return c;\n}\n#else\n\n#define TSC_FREQ 100000000\n\nstatic uint64_t cpu_get_tsc(void *opaque)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * TSC_FREQ +\n (ts.tv_nsec / (1000000000 / TSC_FREQ));\n}\n#endif\n\nstatic void pc_flush_tlb_write_range(void *opaque, uint8_t *ram_addr,\n size_t ram_size)\n{\n PCMachine *s = opaque;\n x86_cpu_flush_tlb_write_range_ram(s->cpu_state, ram_addr, ram_size);\n}\n\nstatic VirtMachine *pc_machine_init(const VirtMachineParams *p)\n{\n PCMachine *s;\n int i, piix3_devfn;\n PCIBus *pci_bus;\n VIRTIOBusDef vbus_s, *vbus = &vbus_s;\n \n if (strcmp(p->machine_name, \"pc\") != 0) {\n vm_error(\"unsupported machine: %s\\n\", p->machine_name);\n return NULL;\n }\n\n assert(p->ram_size >= (1 << 20));\n\n s = mallocz(sizeof(*s));\n s->common.vmc = p->vmc;\n s->ram_size = p->ram_size;\n \n s->port_map = phys_mem_map_init();\n s->mem_map = phys_mem_map_init();\n\n#ifdef USE_KVM\n if (p->accel_enable) {\n kvm_init(s);\n }\n#endif\n\n#ifdef USE_KVM\n if (!s->kvm_enabled)\n#endif\n {\n s->cpu_state = x86_cpu_init(s->mem_map);\n x86_cpu_set_get_tsc(s->cpu_state, cpu_get_tsc, s);\n x86_cpu_set_port_io(s->cpu_state, ld_port, st_port, s);\n \n /* needed to handle the RAM dirty bits */\n s->mem_map->opaque = s;\n s->mem_map->flush_tlb_write_range = pc_flush_tlb_write_range;\n }\n\n /* set the RAM mapping and leave the VGA addresses empty */\n cpu_register_ram(s->mem_map, 0xc0000, p->ram_size - 0xc0000, 0);\n cpu_register_ram(s->mem_map, 0, 0xa0000, 0);\n \n /* devices */\n cpu_register_device(s->port_map, 0x80, 2, s, port80_read, port80_write, \n DEVIO_SIZE8);\n cpu_register_device(s->port_map, 0x92, 2, s, port92_read, port92_write, \n DEVIO_SIZE8);\n \n /* setup the bios */\n if (p->files[VM_FILE_BIOS].len > 0) {\n int bios_size, bios_size1;\n uint8_t *bios_buf, *ptr;\n uint32_t bios_addr;\n \n bios_size = p->files[VM_FILE_BIOS].len;\n bios_buf = p->files[VM_FILE_BIOS].buf;\n assert((bios_size % 65536) == 0 && bios_size != 0);\n bios_addr = -bios_size;\n /* at the top of the 4GB memory */\n cpu_register_ram(s->mem_map, bios_addr, bios_size, DEVRAM_FLAG_ROM);\n ptr = get_ram_ptr(s, bios_addr);\n memcpy(ptr, bios_buf, bios_size);\n /* in the lower 1MB memory (currently set as RAM) */\n bios_size1 = min_int(bios_size, 128 * 1024);\n ptr = get_ram_ptr(s, 0x100000 - bios_size1);\n memcpy(ptr, bios_buf + bios_size - bios_size1, bios_size1);\n#ifdef DEBUG_BIOS\n cpu_register_device(s->port_map, 0x402, 2, s,\n bios_debug_read, bios_debug_write, \n DEVIO_SIZE8);\n#endif\n }\n\n#ifdef USE_KVM\n if (!s->kvm_enabled)\n#endif\n {\n s->pic_state = pic2_init(s->port_map, 0x20, 0xa0,\n 0x4d0, 0x4d1,\n pic_set_irq_cb, s,\n s->pic_irq);\n x86_cpu_set_get_hard_intno(s->cpu_state, get_hard_intno_cb, s);\n s->pit_state = pit_init(s->port_map, 0x40, 0x61, &s->pic_irq[0],\n pit_get_ticks_cb, s);\n }\n\n s->cmos_state = cmos_init(s->port_map, 0x70, &s->pic_irq[8],\n p->rtc_local_time);\n\n /* various cmos data */\n {\n int size;\n /* memory size */\n size = min_int((s->ram_size - (1 << 20)) >> 10, 65535);\n put_le16(s->cmos_state->cmos_data + 0x30, size);\n if (s->ram_size >= (16 << 20)) {\n size = min_int((s->ram_size - (16 << 20)) >> 16, 65535);\n put_le16(s->cmos_state->cmos_data + 0x34, size);\n }\n s->cmos_state->cmos_data[0x14] = 0x06; /* mouse + FPU present */\n }\n \n s->i440fx_state = i440fx_init(&pci_bus, &piix3_devfn, s->mem_map,\n s->port_map, s->pic_irq);\n \n s->common.console = p->console;\n /* serial console */\n if (0) {\n s->serial_state = serial_init(s->port_map, 0x3f8, &s->pic_irq[4],\n serial_write_cb, s);\n }\n \n memset(vbus, 0, sizeof(*vbus));\n vbus->pci_bus = pci_bus;\n\n if (p->console) {\n /* virtio console */\n s->common.console_dev = virtio_console_init(vbus, p->console);\n }\n \n /* block devices */\n for(i = 0; i < p->drive_count;) {\n const VMDriveEntry *de = &p->tab_drive[i];\n\n if (!de->device || !strcmp(de->device, \"virtio\")) {\n virtio_block_init(vbus, p->tab_drive[i].block_dev);\n i++;\n } else if (!strcmp(de->device, \"ide\")) {\n BlockDevice *tab_bs[2];\n \n tab_bs[0] = p->tab_drive[i++].block_dev;\n tab_bs[1] = NULL;\n if (i < p->drive_count)\n tab_bs[1] = p->tab_drive[i++].block_dev;\n ide_init(s->port_map, 0x1f0, 0x3f6, &s->pic_irq[14], tab_bs);\n piix3_ide_init(pci_bus, piix3_devfn + 1);\n }\n }\n \n /* virtio filesystem */\n for(i = 0; i < p->fs_count; i++) {\n virtio_9p_init(vbus, p->tab_fs[i].fs_dev,\n p->tab_fs[i].tag);\n }\n\n if (p->display_device) {\n FBDevice *fb_dev;\n\n fb_dev = mallocz(sizeof(*fb_dev));\n s->common.fb_dev = fb_dev;\n if (!strcmp(p->display_device, \"vga\")) {\n int bios_size;\n uint8_t *bios_buf;\n bios_size = p->files[VM_FILE_VGA_BIOS].len;\n bios_buf = p->files[VM_FILE_VGA_BIOS].buf;\n pci_vga_init(pci_bus, fb_dev, p->width, p->height,\n bios_buf, bios_size);\n } else if (!strcmp(p->display_device, \"simplefb\")) {\n simplefb_init(s->mem_map,\n FRAMEBUFFER_BASE_ADDR,\n fb_dev, p->width, p->height);\n } else {\n vm_error(\"unsupported display device: %s\\n\", p->display_device);\n exit(1);\n }\n }\n\n if (p->input_device) {\n if (!strcmp(p->input_device, \"virtio\")) {\n s->keyboard_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_KEYBOARD);\n \n s->mouse_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_TABLET);\n } else if (!strcmp(p->input_device, \"ps2\")) {\n s->kbd_state = i8042_init(&s->ps2_kbd, &s->ps2_mouse,\n s->port_map,\n &s->pic_irq[1], &s->pic_irq[12], 0x60);\n /* vmmouse */\n cpu_register_device(s->port_map, 0x5658, 1, s,\n vmport_read, vmport_write, \n DEVIO_SIZE32);\n s->vm_mouse = vmmouse_init(s->ps2_mouse);\n } else {\n vm_error(\"unsupported input device: %s\\n\", p->input_device);\n exit(1);\n }\n }\n \n /* virtio net device */\n for(i = 0; i < p->eth_count; i++) {\n virtio_net_init(vbus, p->tab_eth[i].net);\n s->common.net = p->tab_eth[i].net;\n }\n\n if (p->files[VM_FILE_KERNEL].buf) {\n copy_kernel(s, p->files[VM_FILE_KERNEL].buf,\n p->files[VM_FILE_KERNEL].len,\n p->cmdline ? p->cmdline : \"\");\n }\n\n return (VirtMachine *)s;\n}\n\n", "suffix_code": "\n\nstatic void pc_vm_send_key_event(VirtMachine *s1, BOOL is_down, uint16_t key_code)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->keyboard_dev) {\n virtio_input_send_key_event(s->keyboard_dev, is_down, key_code);\n } else if (s->ps2_kbd) {\n ps2_put_keycode(s->ps2_kbd, is_down, key_code);\n }\n}\n\nstatic BOOL pc_vm_mouse_is_absolute(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->mouse_dev) {\n return TRUE;\n } else if (s->vm_mouse) {\n return vmmouse_is_absolute(s->vm_mouse);\n } else {\n return FALSE;\n }\n}\n\nstatic void pc_vm_send_mouse_event(VirtMachine *s1, int dx, int dy, int dz,\n unsigned int buttons)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->mouse_dev) {\n virtio_input_send_mouse_event(s->mouse_dev, dx, dy, dz, buttons);\n } else if (s->vm_mouse) {\n vmmouse_send_mouse_event(s->vm_mouse, dx, dy, dz, buttons);\n }\n}\n\nstruct screen_info {\n} __attribute__((packed));\n\n/* from plex86 (BSD license) */\nstruct __attribute__ ((packed)) linux_params {\n /* screen_info structure */\n uint8_t orig_x;\t\t/* 0x00 */\n uint8_t orig_y;\t\t/* 0x01 */\n uint16_t ext_mem_k;\t/* 0x02 */\n uint16_t orig_video_page;\t/* 0x04 */\n uint8_t orig_video_mode;\t/* 0x06 */\n uint8_t orig_video_cols;\t/* 0x07 */\n uint8_t flags;\t\t/* 0x08 */\n uint8_t unused2;\t\t/* 0x09 */\n uint16_t orig_video_ega_bx;/* 0x0a */\n uint16_t unused3;\t\t/* 0x0c */\n uint8_t orig_video_lines;\t/* 0x0e */\n uint8_t orig_video_isVGA;\t/* 0x0f */\n uint16_t orig_video_points;/* 0x10 */\n \n /* VESA graphic mode -- linear frame buffer */\n uint16_t lfb_width;\t/* 0x12 */\n uint16_t lfb_height;\t/* 0x14 */\n uint16_t lfb_depth;\t/* 0x16 */\n uint32_t lfb_base;\t\t/* 0x18 */\n uint32_t lfb_size;\t\t/* 0x1c */\n uint16_t cl_magic, cl_offset; /* 0x20 */\n uint16_t lfb_linelength;\t/* 0x24 */\n uint8_t red_size;\t\t/* 0x26 */\n uint8_t red_pos;\t\t/* 0x27 */\n uint8_t green_size;\t/* 0x28 */\n uint8_t green_pos;\t/* 0x29 */\n uint8_t blue_size;\t/* 0x2a */\n uint8_t blue_pos;\t\t/* 0x2b */\n uint8_t rsvd_size;\t/* 0x2c */\n uint8_t rsvd_pos;\t\t/* 0x2d */\n uint16_t vesapm_seg;\t/* 0x2e */\n uint16_t vesapm_off;\t/* 0x30 */\n uint16_t pages;\t\t/* 0x32 */\n uint16_t vesa_attributes;\t/* 0x34 */\n uint32_t capabilities; /* 0x36 */\n uint32_t ext_lfb_base;\t/* 0x3a */\n uint8_t _reserved[2];\t/* 0x3e */\n \n /* 0x040 */ uint8_t apm_bios_info[20]; // struct apm_bios_info\n /* 0x054 */ uint8_t pad2[0x80 - 0x54];\n\n // Following 2 from 'struct drive_info_struct' in drivers/block/cciss.h.\n // Might be truncated?\n /* 0x080 */ uint8_t hd0_info[16]; // hd0-disk-parameter from intvector 0x41\n /* 0x090 */ uint8_t hd1_info[16]; // hd1-disk-parameter from intvector 0x46\n\n // System description table truncated to 16 bytes\n // From 'struct sys_desc_table_struct' in linux/arch/i386/kernel/setup.c.\n /* 0x0a0 */ uint16_t sys_description_len;\n /* 0x0a2 */ uint8_t sys_description_table[14];\n // [0] machine id\n // [1] machine submodel id\n // [2] BIOS revision\n // [3] bit1: MCA bus\n\n /* 0x0b0 */ uint8_t pad3[0x1e0 - 0xb0];\n /* 0x1e0 */ uint32_t alt_mem_k;\n /* 0x1e4 */ uint8_t pad4[4];\n /* 0x1e8 */ uint8_t e820map_entries;\n /* 0x1e9 */ uint8_t eddbuf_entries; // EDD_NR\n /* 0x1ea */ uint8_t pad5[0x1f1 - 0x1ea];\n /* 0x1f1 */ uint8_t setup_sects; // size of setup.S, number of sectors\n /* 0x1f2 */ uint16_t mount_root_rdonly; // MOUNT_ROOT_RDONLY (if !=0)\n /* 0x1f4 */ uint16_t sys_size; // size of compressed kernel-part in the\n // (b)zImage-file (in 16 byte units, rounded up)\n /* 0x1f6 */ uint16_t swap_dev; // (unused AFAIK)\n /* 0x1f8 */ uint16_t ramdisk_flags;\n /* 0x1fa */ uint16_t vga_mode; // (old one)\n /* 0x1fc */ uint16_t orig_root_dev; // (high=Major, low=minor)\n /* 0x1fe */ uint8_t pad6[1];\n /* 0x1ff */ uint8_t aux_device_info;\n /* 0x200 */ uint16_t jump_setup; // Jump to start of setup code,\n // aka \"reserved\" field.\n /* 0x202 */ uint8_t setup_signature[4]; // Signature for SETUP-header, =\"HdrS\"\n /* 0x206 */ uint16_t header_format_version; // Version number of header format;\n /* 0x208 */ uint8_t setup_S_temp0[8]; // Used by setup.S for communication with\n // boot loaders, look there.\n /* 0x210 */ uint8_t loader_type;\n // 0 for old one.\n // else 0xTV:\n // T=0: LILO\n // T=1: Loadlin\n // T=2: bootsect-loader\n // T=3: SYSLINUX\n // T=4: ETHERBOOT\n // V=version\n /* 0x211 */ uint8_t loadflags;\n // bit0 = 1: kernel is loaded high (bzImage)\n // bit7 = 1: Heap and pointer (see below) set by boot\n // loader.\n /* 0x212 */ uint16_t setup_S_temp1;\n /* 0x214 */ uint32_t kernel_start;\n /* 0x218 */ uint32_t initrd_start;\n /* 0x21c */ uint32_t initrd_size;\n /* 0x220 */ uint8_t setup_S_temp2[4];\n /* 0x224 */ uint16_t setup_S_heap_end_pointer;\n /* 0x226 */ uint16_t pad70;\n /* 0x228 */ uint32_t cmd_line_ptr;\n /* 0x22c */ uint8_t pad7[0x2d0 - 0x22c];\n\n /* 0x2d0 : Int 15, ax=e820 memory map. */\n // (linux/include/asm-i386/e820.h, 'struct e820entry')\n#define E820MAX 32\n#define E820_RAM 1\n#define E820_RESERVED 2\n#define E820_ACPI 3 /* usable as RAM once ACPI tables have been read */\n#define E820_NVS 4\n struct {\n uint64_t addr;\n uint64_t size;\n uint32_t type;\n } e820map[E820MAX];\n\n /* 0x550 */ uint8_t pad8[0x600 - 0x550];\n\n // BIOS Enhanced Disk Drive Services.\n // (From linux/include/asm-i386/edd.h, 'struct edd_info')\n // Each 'struct edd_info is 78 bytes, times a max of 6 structs in array.\n /* 0x600 */ uint8_t eddbuf[0x7d4 - 0x600];\n\n /* 0x7d4 */ uint8_t pad9[0x800 - 0x7d4];\n /* 0x800 */ uint8_t commandline[0x800];\n\n uint64_t gdt_table[4];\n};\n\n#define KERNEL_PARAMS_ADDR 0x00090000\n\nstatic void copy_kernel(PCMachine *s, const uint8_t *buf, int buf_len,\n const char *cmd_line)\n{\n uint8_t *ram_ptr;\n int setup_sects, header_len, copy_len, setup_hdr_start, setup_hdr_end;\n uint32_t load_address;\n struct linux_params *params;\n FBDevice *fb_dev;\n \n if (buf_len < 1024) {\n too_small:\n fprintf(stderr, \"Kernel too small\\n\");\n exit(1);\n }\n if (buf[0x1fe] != 0x55 || buf[0x1ff] != 0xaa) {\n fprintf(stderr, \"Invalid kernel magic\\n\");\n exit(1);\n }\n setup_sects = buf[0x1f1];\n if (setup_sects == 0)\n setup_sects = 4;\n header_len = (setup_sects + 1) * 512;\n if (buf_len < header_len)\n goto too_small;\n if (memcmp(buf + 0x202, \"HdrS\", 4) != 0) {\n fprintf(stderr, \"Kernel too old\\n\");\n exit(1);\n }\n load_address = 0x100000; /* we don't support older protocols */\n\n ram_ptr = get_ram_ptr(s, load_address);\n copy_len = buf_len - header_len;\n if (copy_len > (s->ram_size - load_address)) {\n fprintf(stderr, \"Not enough RAM\\n\");\n exit(1);\n }\n memcpy(ram_ptr, buf + header_len, copy_len);\n\n params = (void *)get_ram_ptr(s, KERNEL_PARAMS_ADDR);\n \n memset(params, 0, sizeof(struct linux_params));\n\n /* copy the setup header */\n setup_hdr_start = 0x1f1;\n setup_hdr_end = 0x202 + buf[0x201];\n memcpy((uint8_t *)params + setup_hdr_start, buf + setup_hdr_start,\n setup_hdr_end - setup_hdr_start);\n\n strcpy((char *)params->commandline, cmd_line);\n\n params->mount_root_rdonly = 0;\n params->cmd_line_ptr = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, commandline);\n params->alt_mem_k = (s->ram_size / 1024) - 1024;\n params->loader_type = 0x01;\n#if 0\n if (initrd_size > 0) {\n params->initrd_start = INITRD_LOAD_ADDR;\n params->initrd_size = initrd_size;\n }\n#endif\n params->orig_video_lines = 0;\n params->orig_video_cols = 0;\n\n fb_dev = s->common.fb_dev;\n if (fb_dev) {\n \n params->orig_video_isVGA = 0x23; /* VIDEO_TYPE_VLFB */\n\n params->lfb_depth = 32;\n params->red_size = 8;\n params->red_pos = 16;\n params->green_size = 8;\n params->green_pos = 8;\n params->blue_size = 8;\n params->blue_pos = 0;\n params->rsvd_size = 8;\n params->rsvd_pos = 24;\n\n params->lfb_width = fb_dev->width;\n params->lfb_height = fb_dev->height;\n params->lfb_linelength = fb_dev->stride;\n params->lfb_size = fb_dev->fb_size;\n params->lfb_base = FRAMEBUFFER_BASE_ADDR;\n }\n \n params->gdt_table[2] = 0x00cf9b000000ffffLL; /* CS */\n params->gdt_table[3] = 0x00cf93000000ffffLL; /* DS */\n \n#ifdef USE_KVM\n if (s->kvm_enabled) {\n struct kvm_sregs sregs;\n struct kvm_segment seg;\n struct kvm_regs regs;\n \n /* init flat protected mode */\n\n if (ioctl(s->vcpu_fd, KVM_GET_SREGS, &sregs) < 0) {\n perror(\"KVM_GET_SREGS\");\n exit(1);\n }\n\n sregs.cr0 |= (1 << 0); /* CR0_PE */\n sregs.gdt.base = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, gdt_table);\n sregs.gdt.limit = sizeof(params->gdt_table) - 1;\n \n memset(&seg, 0, sizeof(seg));\n seg.limit = 0xffffffff;\n seg.present = 1;\n seg.db = 1;\n seg.s = 1; /* code/data */\n seg.g = 1; /* 4KB granularity */\n\n seg.type = 0xb; /* code */\n seg.selector = 2 << 3;\n sregs.cs = seg;\n\n seg.type = 0x3; /* data */\n seg.selector = 3 << 3;\n sregs.ds = seg;\n sregs.es = seg;\n sregs.ss = seg;\n sregs.fs = seg;\n sregs.gs = seg;\n \n if (ioctl(s->vcpu_fd, KVM_SET_SREGS, &sregs) < 0) {\n perror(\"KVM_SET_SREGS\");\n exit(1);\n }\n \n memset(®s, 0, sizeof(regs));\n regs.rip = load_address;\n regs.rsi = KERNEL_PARAMS_ADDR;\n regs.rflags = 0x2;\n if (ioctl(s->vcpu_fd, KVM_SET_REGS, ®s) < 0) {\n perror(\"KVM_SET_REGS\");\n exit(1);\n }\n } else\n#endif\n {\n int i;\n X86CPUSeg sd;\n uint32_t val;\n val = x86_cpu_get_reg(s->cpu_state, X86_CPU_REG_CR0);\n x86_cpu_set_reg(s->cpu_state, X86_CPU_REG_CR0, val | (1 << 0));\n \n sd.base = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, gdt_table);\n sd.limit = sizeof(params->gdt_table) - 1;\n x86_cpu_set_seg(s->cpu_state, X86_CPU_SEG_GDT, &sd);\n sd.sel = 2 << 3;\n sd.base = 0;\n sd.limit = 0xffffffff;\n sd.flags = 0xc09b;\n x86_cpu_set_seg(s->cpu_state, X86_CPU_SEG_CS, &sd);\n sd.sel = 3 << 3;\n sd.flags = 0xc093;\n for(i = 0; i < 6; i++) {\n if (i != X86_CPU_SEG_CS) {\n x86_cpu_set_seg(s->cpu_state, i, &sd);\n }\n }\n \n x86_cpu_set_reg(s->cpu_state, X86_CPU_REG_EIP, load_address);\n x86_cpu_set_reg(s->cpu_state, 6, KERNEL_PARAMS_ADDR); /* esi */\n }\n\n /* map PCI interrupts (no BIOS, so we must do it) */\n {\n uint8_t elcr[2];\n static const uint8_t pci_irqs[4] = { 9, 10, 11, 12 };\n\n i440fx_map_interrupts(s->i440fx_state, elcr, pci_irqs);\n /* XXX: KVM support */\n if (s->pic_state) {\n pic2_set_elcr(s->pic_state, elcr);\n }\n }\n}\n\n/* in ms */\nstatic int pc_machine_get_sleep_duration(VirtMachine *s1, int delay)\n{\n PCMachine *s = (PCMachine *)s1;\n\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n /* XXX: improve */\n cmos_update_irq(s->cmos_state);\n delay = 0;\n } else\n#endif\n {\n cmos_update_irq(s->cmos_state);\n delay = min_int(delay, pit_update_irq(s->pit_state));\n if (!x86_cpu_get_power_down(s->cpu_state))\n delay = 0;\n }\n return delay;\n}\n\nstatic void pc_machine_interp(VirtMachine *s1, int max_exec_cycles)\n{\n PCMachine *s = (PCMachine *)s1;\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n kvm_exec(s);\n } else \n#endif\n {\n x86_cpu_interp(s->cpu_state, max_exec_cycles);\n }\n}\n\nconst VirtMachineClass pc_machine_class = {\n \"pc\",\n pc_machine_set_defaults,\n pc_machine_init,\n pc_machine_end,\n pc_machine_get_sleep_duration,\n pc_machine_interp,\n pc_vm_mouse_is_absolute,\n pc_vm_send_mouse_event,\n pc_vm_send_key_event,\n};\n", "middle_code": "static void pc_machine_end(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->cpu_state) {\n x86_cpu_end(s->cpu_state);\n }\n phys_mem_map_end(s->mem_map);\n phys_mem_map_end(s->port_map);\n free(s);\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c", "sub_task_type": null}, "context_code": [["/linuxpdf/tinyemu/riscv_machine.c", "/*\n * RISCV machine\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"riscv_cpu.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n/* RISCV machine */\n\ntypedef struct RISCVMachine {\n VirtMachine common;\n PhysMemoryMap *mem_map;\n int max_xlen;\n RISCVCPUState *cpu_state;\n uint64_t ram_size;\n /* RTC */\n BOOL rtc_real_time;\n uint64_t rtc_start_time;\n uint64_t timecmp;\n /* PLIC */\n uint32_t plic_pending_irq, plic_served_irq;\n IRQSignal plic_irq[32]; /* IRQ 0 is not used */\n /* HTIF */\n uint64_t htif_tohost, htif_fromhost;\n\n VIRTIODevice *keyboard_dev;\n VIRTIODevice *mouse_dev;\n\n int virtio_count;\n} RISCVMachine;\n\n#define LOW_RAM_SIZE 0x00010000 /* 64KB */\n#define RAM_BASE_ADDR 0x80000000\n#define CLINT_BASE_ADDR 0x02000000\n#define CLINT_SIZE 0x000c0000\n#define HTIF_BASE_ADDR 0x40008000\n#define IDE_BASE_ADDR 0x40009000\n#define VIRTIO_BASE_ADDR 0x40010000\n#define VIRTIO_SIZE 0x1000\n#define VIRTIO_IRQ 1\n#define PLIC_BASE_ADDR 0x40100000\n#define PLIC_SIZE 0x00400000\n#define FRAMEBUFFER_BASE_ADDR 0x41000000\n\n#define RTC_FREQ 10000000\n#define RTC_FREQ_DIV 16 /* arbitrary, relative to CPU freq to have a\n 10 MHz frequency */\n\nstatic uint64_t rtc_get_real_time(RISCVMachine *s)\n{\n struct timespec ts;\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * RTC_FREQ +\n (ts.tv_nsec / (1000000000 / RTC_FREQ));\n}\n\nstatic uint64_t rtc_get_time(RISCVMachine *m)\n{\n uint64_t val;\n if (m->rtc_real_time) {\n val = rtc_get_real_time(m) - m->rtc_start_time;\n } else {\n val = riscv_cpu_get_cycles(m->cpu_state) / RTC_FREQ_DIV;\n }\n // printf(\"rtc_time=%\" PRId64 \"\\n\", val);\n return val;\n}\n\nstatic uint32_t htif_read(void *opaque, uint32_t offset,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n uint32_t val;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0:\n val = s->htif_tohost;\n break;\n case 4:\n val = s->htif_tohost >> 32;\n break;\n case 8:\n val = s->htif_fromhost;\n break;\n case 12:\n val = s->htif_fromhost >> 32;\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n\nstatic void htif_handle_cmd(RISCVMachine *s)\n{\n uint32_t device, cmd;\n\n device = s->htif_tohost >> 56;\n cmd = (s->htif_tohost >> 48) & 0xff;\n if (s->htif_tohost == 1) {\n /* shuthost */\n printf(\"\\nPower off.\\n\");\n exit(0);\n } else if (device == 1 && cmd == 1) {\n uint8_t buf[1];\n buf[0] = s->htif_tohost & 0xff;\n s->common.console->write_data(s->common.console->opaque, buf, 1);\n s->htif_tohost = 0;\n s->htif_fromhost = ((uint64_t)device << 56) | ((uint64_t)cmd << 48);\n } else if (device == 1 && cmd == 0) {\n /* request keyboard interrupt */\n s->htif_tohost = 0;\n } else {\n printf(\"HTIF: unsupported tohost=0x%016\" PRIx64 \"\\n\", s->htif_tohost);\n }\n}\n\nstatic void htif_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0:\n s->htif_tohost = (s->htif_tohost & ~0xffffffff) | val;\n break;\n case 4:\n s->htif_tohost = (s->htif_tohost & 0xffffffff) | ((uint64_t)val << 32);\n htif_handle_cmd(s);\n break;\n case 8:\n s->htif_fromhost = (s->htif_fromhost & ~0xffffffff) | val;\n break;\n case 12:\n s->htif_fromhost = (s->htif_fromhost & 0xffffffff) |\n (uint64_t)val << 32;\n break;\n default:\n break;\n }\n}\n\n#if 0\nstatic void htif_poll(RISCVMachine *s)\n{\n uint8_t buf[1];\n int ret;\n\n if (s->htif_fromhost == 0) {\n ret = s->console->read_data(s->console->opaque, buf, 1);\n if (ret == 1) {\n s->htif_fromhost = ((uint64_t)1 << 56) | ((uint64_t)0 << 48) |\n buf[0];\n }\n }\n}\n#endif\n\nstatic uint32_t clint_read(void *opaque, uint32_t offset, int size_log2)\n{\n RISCVMachine *m = opaque;\n uint32_t val;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0xbff8:\n val = rtc_get_time(m);\n break;\n case 0xbffc:\n val = rtc_get_time(m) >> 32;\n break;\n case 0x4000:\n val = m->timecmp;\n break;\n case 0x4004:\n val = m->timecmp >> 32;\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n \nstatic void clint_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *m = opaque;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0x4000:\n m->timecmp = (m->timecmp & ~0xffffffff) | val;\n riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP);\n break;\n case 0x4004:\n m->timecmp = (m->timecmp & 0xffffffff) | ((uint64_t)val << 32);\n riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP);\n break;\n default:\n break;\n }\n}\n\nstatic void plic_update_mip(RISCVMachine *s)\n{\n RISCVCPUState *cpu = s->cpu_state;\n uint32_t mask;\n mask = s->plic_pending_irq & ~s->plic_served_irq;\n if (mask) {\n riscv_cpu_set_mip(cpu, MIP_MEIP | MIP_SEIP);\n } else {\n riscv_cpu_reset_mip(cpu, MIP_MEIP | MIP_SEIP);\n }\n}\n\n#define PLIC_HART_BASE 0x200000\n#define PLIC_HART_SIZE 0x1000\n\nstatic uint32_t plic_read(void *opaque, uint32_t offset, int size_log2)\n{\n RISCVMachine *s = opaque;\n uint32_t val, mask;\n int i;\n assert(size_log2 == 2);\n switch(offset) {\n case PLIC_HART_BASE:\n val = 0;\n break;\n case PLIC_HART_BASE + 4:\n mask = s->plic_pending_irq & ~s->plic_served_irq;\n if (mask != 0) {\n i = ctz32(mask);\n s->plic_served_irq |= 1 << i;\n plic_update_mip(s);\n val = i + 1;\n } else {\n val = 0;\n }\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n\nstatic void plic_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n \n assert(size_log2 == 2);\n switch(offset) {\n case PLIC_HART_BASE + 4:\n val--;\n if (val < 32) {\n s->plic_served_irq &= ~(1 << val);\n plic_update_mip(s);\n }\n break;\n default:\n break;\n }\n}\n\nstatic void plic_set_irq(void *opaque, int irq_num, int state)\n{\n RISCVMachine *s = opaque;\n uint32_t mask;\n\n mask = 1 << (irq_num - 1);\n if (state) \n s->plic_pending_irq |= mask;\n else\n s->plic_pending_irq &= ~mask;\n plic_update_mip(s);\n}\n\nstatic uint8_t *get_ram_ptr(RISCVMachine *s, uint64_t paddr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(s->mem_map, paddr, is_rw);\n}\n\n/* FDT machine description */\n\n#define FDT_MAGIC\t0xd00dfeed\n#define FDT_VERSION\t17\n\nstruct fdt_header {\n uint32_t magic;\n uint32_t totalsize;\n uint32_t off_dt_struct;\n uint32_t off_dt_strings;\n uint32_t off_mem_rsvmap;\n uint32_t version;\n uint32_t last_comp_version; /* <= 17 */\n uint32_t boot_cpuid_phys;\n uint32_t size_dt_strings;\n uint32_t size_dt_struct;\n};\n\nstruct fdt_reserve_entry {\n uint64_t address;\n uint64_t size;\n};\n\n#define FDT_BEGIN_NODE\t1\n#define FDT_END_NODE\t2\n#define FDT_PROP\t3\n#define FDT_NOP\t\t4\n#define FDT_END\t\t9\n\ntypedef struct {\n uint32_t *tab;\n int tab_len;\n int tab_size;\n int open_node_count;\n \n char *string_table;\n int string_table_len;\n int string_table_size;\n} FDTState;\n\nstatic FDTState *fdt_init(void)\n{\n FDTState *s;\n s = mallocz(sizeof(*s));\n return s;\n}\n\nstatic void fdt_alloc_len(FDTState *s, int len)\n{\n int new_size;\n if (unlikely(len > s->tab_size)) {\n new_size = max_int(len, s->tab_size * 3 / 2);\n s->tab = realloc(s->tab, new_size * sizeof(uint32_t));\n s->tab_size = new_size;\n }\n}\n\nstatic void fdt_put32(FDTState *s, int v)\n{\n fdt_alloc_len(s, s->tab_len + 1);\n s->tab[s->tab_len++] = cpu_to_be32(v);\n}\n\n/* the data is zero padded */\nstatic void fdt_put_data(FDTState *s, const uint8_t *data, int len)\n{\n int len1;\n \n len1 = (len + 3) / 4;\n fdt_alloc_len(s, s->tab_len + len1);\n memcpy(s->tab + s->tab_len, data, len);\n memset((uint8_t *)(s->tab + s->tab_len) + len, 0, -len & 3);\n s->tab_len += len1;\n}\n\nstatic void fdt_begin_node(FDTState *s, const char *name)\n{\n fdt_put32(s, FDT_BEGIN_NODE);\n fdt_put_data(s, (uint8_t *)name, strlen(name) + 1);\n s->open_node_count++;\n}\n\nstatic void fdt_begin_node_num(FDTState *s, const char *name, uint64_t n)\n{\n char buf[256];\n snprintf(buf, sizeof(buf), \"%s@%\" PRIx64, name, n);\n fdt_begin_node(s, buf);\n}\n\nstatic void fdt_end_node(FDTState *s)\n{\n fdt_put32(s, FDT_END_NODE);\n s->open_node_count--;\n}\n\nstatic int fdt_get_string_offset(FDTState *s, const char *name)\n{\n int pos, new_size, name_size, new_len;\n\n pos = 0;\n while (pos < s->string_table_len) {\n if (!strcmp(s->string_table + pos, name))\n return pos;\n pos += strlen(s->string_table + pos) + 1;\n }\n /* add a new string */\n name_size = strlen(name) + 1;\n new_len = s->string_table_len + name_size;\n if (new_len > s->string_table_size) {\n new_size = max_int(new_len, s->string_table_size * 3 / 2);\n s->string_table = realloc(s->string_table, new_size);\n s->string_table_size = new_size;\n }\n pos = s->string_table_len;\n memcpy(s->string_table + pos, name, name_size);\n s->string_table_len = new_len;\n return pos;\n}\n\nstatic void fdt_prop(FDTState *s, const char *prop_name,\n const void *data, int data_len)\n{\n fdt_put32(s, FDT_PROP);\n fdt_put32(s, data_len);\n fdt_put32(s, fdt_get_string_offset(s, prop_name));\n fdt_put_data(s, data, data_len);\n}\n\nstatic void fdt_prop_tab_u32(FDTState *s, const char *prop_name,\n uint32_t *tab, int tab_len)\n{\n int i;\n fdt_put32(s, FDT_PROP);\n fdt_put32(s, tab_len * sizeof(uint32_t));\n fdt_put32(s, fdt_get_string_offset(s, prop_name));\n for(i = 0; i < tab_len; i++)\n fdt_put32(s, tab[i]);\n}\n\nstatic void fdt_prop_u32(FDTState *s, const char *prop_name, uint32_t val)\n{\n fdt_prop_tab_u32(s, prop_name, &val, 1);\n}\n\nstatic void fdt_prop_tab_u64(FDTState *s, const char *prop_name,\n uint64_t v0)\n{\n uint32_t tab[2];\n tab[0] = v0 >> 32;\n tab[1] = v0;\n fdt_prop_tab_u32(s, prop_name, tab, 2);\n}\n\nstatic void fdt_prop_tab_u64_2(FDTState *s, const char *prop_name,\n uint64_t v0, uint64_t v1)\n{\n uint32_t tab[4];\n tab[0] = v0 >> 32;\n tab[1] = v0;\n tab[2] = v1 >> 32;\n tab[3] = v1;\n fdt_prop_tab_u32(s, prop_name, tab, 4);\n}\n\nstatic void fdt_prop_str(FDTState *s, const char *prop_name,\n const char *str)\n{\n fdt_prop(s, prop_name, str, strlen(str) + 1);\n}\n\n/* NULL terminated string list */\nstatic void fdt_prop_tab_str(FDTState *s, const char *prop_name,\n ...)\n{\n va_list ap;\n int size, str_size;\n char *ptr, *tab;\n\n va_start(ap, prop_name);\n size = 0;\n for(;;) {\n ptr = va_arg(ap, char *);\n if (!ptr)\n break;\n str_size = strlen(ptr) + 1;\n size += str_size;\n }\n va_end(ap);\n \n tab = malloc(size);\n va_start(ap, prop_name);\n size = 0;\n for(;;) {\n ptr = va_arg(ap, char *);\n if (!ptr)\n break;\n str_size = strlen(ptr) + 1;\n memcpy(tab + size, ptr, str_size);\n size += str_size;\n }\n va_end(ap);\n \n fdt_prop(s, prop_name, tab, size);\n free(tab);\n}\n\n/* write the FDT to 'dst1'. return the FDT size in bytes */\nint fdt_output(FDTState *s, uint8_t *dst)\n{\n struct fdt_header *h;\n struct fdt_reserve_entry *re;\n int dt_struct_size;\n int dt_strings_size;\n int pos;\n\n assert(s->open_node_count == 0);\n \n fdt_put32(s, FDT_END);\n \n dt_struct_size = s->tab_len * sizeof(uint32_t);\n dt_strings_size = s->string_table_len;\n\n h = (struct fdt_header *)dst;\n h->magic = cpu_to_be32(FDT_MAGIC);\n h->version = cpu_to_be32(FDT_VERSION);\n h->last_comp_version = cpu_to_be32(16);\n h->boot_cpuid_phys = cpu_to_be32(0);\n h->size_dt_strings = cpu_to_be32(dt_strings_size);\n h->size_dt_struct = cpu_to_be32(dt_struct_size);\n\n pos = sizeof(struct fdt_header);\n\n h->off_dt_struct = cpu_to_be32(pos);\n memcpy(dst + pos, s->tab, dt_struct_size);\n pos += dt_struct_size;\n\n /* align to 8 */\n while ((pos & 7) != 0) {\n dst[pos++] = 0;\n }\n h->off_mem_rsvmap = cpu_to_be32(pos);\n re = (struct fdt_reserve_entry *)(dst + pos);\n re->address = 0; /* no reserved entry */\n re->size = 0;\n pos += sizeof(struct fdt_reserve_entry);\n\n h->off_dt_strings = cpu_to_be32(pos);\n memcpy(dst + pos, s->string_table, dt_strings_size);\n pos += dt_strings_size;\n\n /* align to 8, just in case */\n while ((pos & 7) != 0) {\n dst[pos++] = 0;\n }\n\n h->totalsize = cpu_to_be32(pos);\n return pos;\n}\n\nvoid fdt_end(FDTState *s)\n{\n free(s->tab);\n free(s->string_table);\n free(s);\n}\n\nstatic int riscv_build_fdt(RISCVMachine *m, uint8_t *dst,\n uint64_t kernel_start, uint64_t kernel_size,\n uint64_t initrd_start, uint64_t initrd_size,\n const char *cmd_line)\n{\n FDTState *s;\n int size, max_xlen, i, cur_phandle, intc_phandle, plic_phandle;\n char isa_string[128], *q;\n uint32_t misa;\n uint32_t tab[4];\n FBDevice *fb_dev;\n \n s = fdt_init();\n\n cur_phandle = 1;\n \n fdt_begin_node(s, \"\");\n fdt_prop_u32(s, \"#address-cells\", 2);\n fdt_prop_u32(s, \"#size-cells\", 2);\n fdt_prop_str(s, \"compatible\", \"ucbbar,riscvemu-bar_dev\");\n fdt_prop_str(s, \"model\", \"ucbbar,riscvemu-bare\");\n\n /* CPU list */\n fdt_begin_node(s, \"cpus\");\n fdt_prop_u32(s, \"#address-cells\", 1);\n fdt_prop_u32(s, \"#size-cells\", 0);\n fdt_prop_u32(s, \"timebase-frequency\", RTC_FREQ);\n\n /* cpu */\n fdt_begin_node_num(s, \"cpu\", 0);\n fdt_prop_str(s, \"device_type\", \"cpu\");\n fdt_prop_u32(s, \"reg\", 0);\n fdt_prop_str(s, \"status\", \"okay\");\n fdt_prop_str(s, \"compatible\", \"riscv\");\n\n max_xlen = m->max_xlen;\n misa = riscv_cpu_get_misa(m->cpu_state);\n q = isa_string;\n q += snprintf(isa_string, sizeof(isa_string), \"rv%d\", max_xlen);\n for(i = 0; i < 26; i++) {\n if (misa & (1 << i))\n *q++ = 'a' + i;\n }\n *q = '\\0';\n fdt_prop_str(s, \"riscv,isa\", isa_string);\n \n fdt_prop_str(s, \"mmu-type\", max_xlen <= 32 ? \"riscv,sv32\" : \"riscv,sv48\");\n fdt_prop_u32(s, \"clock-frequency\", 2000000000);\n\n fdt_begin_node(s, \"interrupt-controller\");\n fdt_prop_u32(s, \"#interrupt-cells\", 1);\n fdt_prop(s, \"interrupt-controller\", NULL, 0);\n fdt_prop_str(s, \"compatible\", \"riscv,cpu-intc\");\n intc_phandle = cur_phandle++;\n fdt_prop_u32(s, \"phandle\", intc_phandle);\n fdt_end_node(s); /* interrupt-controller */\n \n fdt_end_node(s); /* cpu */\n \n fdt_end_node(s); /* cpus */\n\n fdt_begin_node_num(s, \"memory\", RAM_BASE_ADDR);\n fdt_prop_str(s, \"device_type\", \"memory\");\n tab[0] = (uint64_t)RAM_BASE_ADDR >> 32;\n tab[1] = RAM_BASE_ADDR;\n tab[2] = m->ram_size >> 32;\n tab[3] = m->ram_size;\n fdt_prop_tab_u32(s, \"reg\", tab, 4);\n \n fdt_end_node(s); /* memory */\n\n fdt_begin_node(s, \"htif\");\n fdt_prop_str(s, \"compatible\", \"ucb,htif0\");\n fdt_end_node(s); /* htif */\n\n fdt_begin_node(s, \"soc\");\n fdt_prop_u32(s, \"#address-cells\", 2);\n fdt_prop_u32(s, \"#size-cells\", 2);\n fdt_prop_tab_str(s, \"compatible\",\n \"ucbbar,riscvemu-bar-soc\", \"simple-bus\", NULL);\n fdt_prop(s, \"ranges\", NULL, 0);\n\n fdt_begin_node_num(s, \"clint\", CLINT_BASE_ADDR);\n fdt_prop_str(s, \"compatible\", \"riscv,clint0\");\n\n tab[0] = intc_phandle;\n tab[1] = 3; /* M IPI irq */\n tab[2] = intc_phandle;\n tab[3] = 7; /* M timer irq */\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 4);\n\n fdt_prop_tab_u64_2(s, \"reg\", CLINT_BASE_ADDR, CLINT_SIZE);\n \n fdt_end_node(s); /* clint */\n\n fdt_begin_node_num(s, \"plic\", PLIC_BASE_ADDR);\n fdt_prop_u32(s, \"#interrupt-cells\", 1);\n fdt_prop(s, \"interrupt-controller\", NULL, 0);\n fdt_prop_str(s, \"compatible\", \"riscv,plic0\");\n fdt_prop_u32(s, \"riscv,ndev\", 31);\n fdt_prop_tab_u64_2(s, \"reg\", PLIC_BASE_ADDR, PLIC_SIZE);\n\n tab[0] = intc_phandle;\n tab[1] = 9; /* S ext irq */\n tab[2] = intc_phandle;\n tab[3] = 11; /* M ext irq */\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 4);\n\n plic_phandle = cur_phandle++;\n fdt_prop_u32(s, \"phandle\", plic_phandle);\n\n fdt_end_node(s); /* plic */\n \n for(i = 0; i < m->virtio_count; i++) {\n fdt_begin_node_num(s, \"virtio\", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE);\n fdt_prop_str(s, \"compatible\", \"virtio,mmio\");\n fdt_prop_tab_u64_2(s, \"reg\", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE,\n VIRTIO_SIZE);\n tab[0] = plic_phandle;\n tab[1] = VIRTIO_IRQ + i;\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 2);\n fdt_end_node(s); /* virtio */\n }\n\n fb_dev = m->common.fb_dev;\n if (fb_dev) {\n fdt_begin_node_num(s, \"framebuffer\", FRAMEBUFFER_BASE_ADDR);\n fdt_prop_str(s, \"compatible\", \"simple-framebuffer\");\n fdt_prop_tab_u64_2(s, \"reg\", FRAMEBUFFER_BASE_ADDR, fb_dev->fb_size);\n fdt_prop_u32(s, \"width\", fb_dev->width);\n fdt_prop_u32(s, \"height\", fb_dev->height);\n fdt_prop_u32(s, \"stride\", fb_dev->stride);\n fdt_prop_str(s, \"format\", \"a8r8g8b8\");\n fdt_end_node(s); /* framebuffer */\n }\n \n fdt_end_node(s); /* soc */\n\n fdt_begin_node(s, \"chosen\");\n fdt_prop_str(s, \"bootargs\", cmd_line ? cmd_line : \"\");\n if (kernel_size > 0) {\n fdt_prop_tab_u64(s, \"riscv,kernel-start\", kernel_start);\n fdt_prop_tab_u64(s, \"riscv,kernel-end\", kernel_start + kernel_size);\n }\n if (initrd_size > 0) {\n fdt_prop_tab_u64(s, \"linux,initrd-start\", initrd_start);\n fdt_prop_tab_u64(s, \"linux,initrd-end\", initrd_start + initrd_size);\n }\n \n\n fdt_end_node(s); /* chosen */\n \n fdt_end_node(s); /* / */\n\n size = fdt_output(s, dst);\n#if 0\n {\n FILE *f;\n f = fopen(\"/tmp/riscvemu.dtb\", \"wb\");\n fwrite(dst, 1, size, f);\n fclose(f);\n }\n#endif\n fdt_end(s);\n return size;\n}\n\nstatic void copy_bios(RISCVMachine *s, const uint8_t *buf, int buf_len,\n const uint8_t *kernel_buf, int kernel_buf_len,\n const uint8_t *initrd_buf, int initrd_buf_len,\n const char *cmd_line)\n{\n uint32_t fdt_addr, align, kernel_base, initrd_base;\n uint8_t *ram_ptr;\n uint32_t *q;\n\n if (buf_len > s->ram_size) {\n vm_error(\"BIOS too big\\n\");\n exit(1);\n }\n\n ram_ptr = get_ram_ptr(s, RAM_BASE_ADDR, TRUE);\n memcpy(ram_ptr, buf, buf_len);\n\n kernel_base = 0;\n if (kernel_buf_len > 0) {\n /* copy the kernel if present */\n if (s->max_xlen == 32)\n align = 4 << 20; /* 4 MB page align */\n else\n align = 2 << 20; /* 2 MB page align */\n kernel_base = (buf_len + align - 1) & ~(align - 1);\n memcpy(ram_ptr + kernel_base, kernel_buf, kernel_buf_len);\n if (kernel_buf_len + kernel_base > s->ram_size) {\n vm_error(\"kernel too big\");\n exit(1);\n }\n }\n\n initrd_base = 0;\n if (initrd_buf_len > 0) {\n /* same allocation as QEMU */\n initrd_base = s->ram_size / 2;\n if (initrd_base > (128 << 20))\n initrd_base = 128 << 20;\n memcpy(ram_ptr + initrd_base, initrd_buf, initrd_buf_len);\n if (initrd_buf_len + initrd_base > s->ram_size) {\n vm_error(\"initrd too big\");\n exit(1);\n }\n }\n \n ram_ptr = get_ram_ptr(s, 0, TRUE);\n \n fdt_addr = 0x1000 + 8 * 8;\n\n riscv_build_fdt(s, ram_ptr + fdt_addr,\n RAM_BASE_ADDR + kernel_base, kernel_buf_len,\n RAM_BASE_ADDR + initrd_base, initrd_buf_len,\n cmd_line);\n\n /* jump_addr = 0x80000000 */\n \n q = (uint32_t *)(ram_ptr + 0x1000);\n q[0] = 0x297 + 0x80000000 - 0x1000; /* auipc t0, jump_addr */\n q[1] = 0x597; /* auipc a1, dtb */\n q[2] = 0x58593 + ((fdt_addr - 4) << 20); /* addi a1, a1, dtb */\n q[3] = 0xf1402573; /* csrr a0, mhartid */\n q[4] = 0x00028067; /* jalr zero, t0, jump_addr */\n}\n\nstatic void riscv_flush_tlb_write_range(void *opaque, uint8_t *ram_addr,\n size_t ram_size)\n{\n RISCVMachine *s = opaque;\n riscv_cpu_flush_tlb_write_range_ram(s->cpu_state, ram_addr, ram_size);\n}\n\nstatic void riscv_machine_set_defaults(VirtMachineParams *p)\n{\n}\n\nstatic VirtMachine *riscv_machine_init(const VirtMachineParams *p)\n{\n RISCVMachine *s;\n VIRTIODevice *blk_dev;\n int irq_num, i, max_xlen, ram_flags;\n VIRTIOBusDef vbus_s, *vbus = &vbus_s;\n\n\n if (!strcmp(p->machine_name, \"riscv32\")) {\n max_xlen = 32;\n } else if (!strcmp(p->machine_name, \"riscv64\")) {\n max_xlen = 64;\n } else if (!strcmp(p->machine_name, \"riscv128\")) {\n max_xlen = 128;\n } else {\n vm_error(\"unsupported machine: %s\\n\", p->machine_name);\n return NULL;\n }\n \n s = mallocz(sizeof(*s));\n s->common.vmc = p->vmc;\n s->ram_size = p->ram_size;\n s->max_xlen = max_xlen;\n s->mem_map = phys_mem_map_init();\n /* needed to handle the RAM dirty bits */\n s->mem_map->opaque = s;\n s->mem_map->flush_tlb_write_range = riscv_flush_tlb_write_range;\n\n s->cpu_state = riscv_cpu_init(s->mem_map, max_xlen);\n if (!s->cpu_state) {\n vm_error(\"unsupported max_xlen=%d\\n\", max_xlen);\n /* XXX: should free resources */\n return NULL;\n }\n /* RAM */\n ram_flags = 0;\n cpu_register_ram(s->mem_map, RAM_BASE_ADDR, p->ram_size, ram_flags);\n cpu_register_ram(s->mem_map, 0x00000000, LOW_RAM_SIZE, 0);\n s->rtc_real_time = p->rtc_real_time;\n if (p->rtc_real_time) {\n s->rtc_start_time = rtc_get_real_time(s);\n }\n \n cpu_register_device(s->mem_map, CLINT_BASE_ADDR, CLINT_SIZE, s,\n clint_read, clint_write, DEVIO_SIZE32);\n cpu_register_device(s->mem_map, PLIC_BASE_ADDR, PLIC_SIZE, s,\n plic_read, plic_write, DEVIO_SIZE32);\n for(i = 1; i < 32; i++) {\n irq_init(&s->plic_irq[i], plic_set_irq, s, i);\n }\n\n cpu_register_device(s->mem_map, HTIF_BASE_ADDR, 16,\n s, htif_read, htif_write, DEVIO_SIZE32);\n s->common.console = p->console;\n\n memset(vbus, 0, sizeof(*vbus));\n vbus->mem_map = s->mem_map;\n vbus->addr = VIRTIO_BASE_ADDR;\n irq_num = VIRTIO_IRQ;\n \n /* virtio console */\n if (p->console) {\n vbus->irq = &s->plic_irq[irq_num];\n s->common.console_dev = virtio_console_init(vbus, p->console);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n \n /* virtio net device */\n for(i = 0; i < p->eth_count; i++) {\n vbus->irq = &s->plic_irq[irq_num];\n virtio_net_init(vbus, p->tab_eth[i].net);\n s->common.net = p->tab_eth[i].net;\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n /* virtio block device */\n for(i = 0; i < p->drive_count; i++) {\n vbus->irq = &s->plic_irq[irq_num];\n blk_dev = virtio_block_init(vbus, p->tab_drive[i].block_dev);\n (void)blk_dev;\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n /* virtio filesystem */\n for(i = 0; i < p->fs_count; i++) {\n VIRTIODevice *fs_dev;\n vbus->irq = &s->plic_irq[irq_num];\n fs_dev = virtio_9p_init(vbus, p->tab_fs[i].fs_dev,\n p->tab_fs[i].tag);\n (void)fs_dev;\n // virtio_set_debug(fs_dev, VIRTIO_DEBUG_9P);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n if (p->display_device) {\n FBDevice *fb_dev;\n fb_dev = mallocz(sizeof(*fb_dev));\n s->common.fb_dev = fb_dev;\n if (!strcmp(p->display_device, \"simplefb\")) {\n simplefb_init(s->mem_map,\n FRAMEBUFFER_BASE_ADDR,\n fb_dev,\n p->width, p->height);\n \n } else {\n vm_error(\"unsupported display device: %s\\n\", p->display_device);\n exit(1);\n }\n }\n\n if (p->input_device) {\n if (!strcmp(p->input_device, \"virtio\")) {\n vbus->irq = &s->plic_irq[irq_num];\n s->keyboard_dev = virtio_input_init(vbus,\n VIRTIO_INPUT_TYPE_KEYBOARD);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n\n vbus->irq = &s->plic_irq[irq_num];\n s->mouse_dev = virtio_input_init(vbus,\n VIRTIO_INPUT_TYPE_TABLET);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n } else {\n vm_error(\"unsupported input device: %s\\n\", p->input_device);\n exit(1);\n }\n }\n \n if (!p->files[VM_FILE_BIOS].buf) {\n vm_error(\"No bios found\");\n }\n\n copy_bios(s, p->files[VM_FILE_BIOS].buf, p->files[VM_FILE_BIOS].len,\n p->files[VM_FILE_KERNEL].buf, p->files[VM_FILE_KERNEL].len,\n p->files[VM_FILE_INITRD].buf, p->files[VM_FILE_INITRD].len,\n p->cmdline);\n \n return (VirtMachine *)s;\n}\n\nstatic void riscv_machine_end(VirtMachine *s1)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n /* XXX: stop all */\n riscv_cpu_end(s->cpu_state);\n phys_mem_map_end(s->mem_map);\n free(s);\n}\n\n/* in ms */\nstatic int riscv_machine_get_sleep_duration(VirtMachine *s1, int delay)\n{\n RISCVMachine *m = (RISCVMachine *)s1;\n RISCVCPUState *s = m->cpu_state;\n int64_t delay1;\n \n /* wait for an event: the only asynchronous event is the RTC timer */\n if (!(riscv_cpu_get_mip(s) & MIP_MTIP)) {\n delay1 = m->timecmp - rtc_get_time(m);\n if (delay1 <= 0) {\n riscv_cpu_set_mip(s, MIP_MTIP);\n delay = 0;\n } else {\n /* convert delay to ms */\n delay1 = delay1 / (RTC_FREQ / 1000);\n if (delay1 < delay)\n delay = delay1;\n }\n }\n if (!riscv_cpu_get_power_down(s))\n delay = 0;\n return delay;\n}\n\nstatic void riscv_machine_interp(VirtMachine *s1, int max_exec_cycle)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n riscv_cpu_interp(s->cpu_state, max_exec_cycle);\n}\n\nstatic void riscv_vm_send_key_event(VirtMachine *s1, BOOL is_down,\n uint16_t key_code)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n if (s->keyboard_dev) {\n virtio_input_send_key_event(s->keyboard_dev, is_down, key_code);\n }\n}\n\nstatic BOOL riscv_vm_mouse_is_absolute(VirtMachine *s)\n{\n return TRUE;\n}\n\nstatic void riscv_vm_send_mouse_event(VirtMachine *s1, int dx, int dy, int dz,\n unsigned int buttons)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n if (s->mouse_dev) {\n virtio_input_send_mouse_event(s->mouse_dev, dx, dy, dz, buttons);\n }\n}\n\nconst VirtMachineClass riscv_machine_class = {\n \"riscv32,riscv64,riscv128\",\n riscv_machine_set_defaults,\n riscv_machine_init,\n riscv_machine_end,\n riscv_machine_get_sleep_duration,\n riscv_machine_interp,\n riscv_vm_mouse_is_absolute,\n riscv_vm_send_mouse_event,\n riscv_vm_send_key_event,\n};\n"], ["/linuxpdf/tinyemu/pci.c", "/*\n * Simple PCI bus driver\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"pci.h\"\n\n//#define DEBUG_CONFIG\n\ntypedef struct {\n uint32_t size; /* 0 means no mapping defined */\n uint8_t type;\n uint8_t enabled; /* true if mapping is enabled */\n void *opaque;\n PCIBarSetFunc *bar_set;\n} PCIIORegion;\n\nstruct PCIDevice {\n PCIBus *bus;\n uint8_t devfn;\n IRQSignal irq[4];\n uint8_t config[256];\n uint8_t next_cap_offset; /* offset of the next capability */\n char *name; /* for debug only */\n PCIIORegion io_regions[PCI_NUM_REGIONS];\n};\n\nstruct PCIBus {\n int bus_num;\n PCIDevice *device[256];\n PhysMemoryMap *mem_map;\n PhysMemoryMap *port_map;\n uint32_t irq_state[4][8]; /* one bit per device */\n IRQSignal irq[4];\n};\n\nstatic int bus_map_irq(PCIDevice *d, int irq_num)\n{\n int slot_addend;\n slot_addend = (d->devfn >> 3) - 1;\n return (irq_num + slot_addend) & 3;\n}\n\nstatic void pci_device_set_irq(void *opaque, int irq_num, int level)\n{\n PCIDevice *d = opaque;\n PCIBus *b = d->bus;\n uint32_t mask;\n int i, irq_level;\n \n // printf(\"%s: pci_device_seq_irq: %d %d\\n\", d->name, irq_num, level);\n irq_num = bus_map_irq(d, irq_num);\n mask = 1 << (d->devfn & 0x1f);\n if (level)\n b->irq_state[irq_num][d->devfn >> 5] |= mask;\n else\n b->irq_state[irq_num][d->devfn >> 5] &= ~mask;\n\n /* compute the IRQ state */\n mask = 0;\n for(i = 0; i < 8; i++)\n mask |= b->irq_state[irq_num][i];\n irq_level = (mask != 0);\n set_irq(&b->irq[irq_num], irq_level);\n}\n\nstatic int devfn_alloc(PCIBus *b)\n{\n int devfn;\n for(devfn = 0; devfn < 256; devfn += 8) {\n if (!b->device[devfn])\n return devfn;\n }\n return -1;\n}\n\n/* devfn < 0 means to allocate it */\nPCIDevice *pci_register_device(PCIBus *b, const char *name, int devfn,\n uint16_t vendor_id, uint16_t device_id,\n uint8_t revision, uint16_t class_id)\n{\n PCIDevice *d;\n int i;\n \n if (devfn < 0) {\n devfn = devfn_alloc(b);\n if (devfn < 0)\n return NULL;\n }\n if (b->device[devfn])\n return NULL;\n\n d = mallocz(sizeof(PCIDevice));\n d->bus = b;\n d->name = strdup(name);\n d->devfn = devfn;\n\n put_le16(d->config + 0x00, vendor_id);\n put_le16(d->config + 0x02, device_id);\n d->config[0x08] = revision;\n put_le16(d->config + 0x0a, class_id);\n d->config[0x0e] = 0x00; /* header type */\n d->next_cap_offset = 0x40;\n \n for(i = 0; i < 4; i++)\n irq_init(&d->irq[i], pci_device_set_irq, d, i);\n b->device[devfn] = d;\n\n return d;\n}\n\nIRQSignal *pci_device_get_irq(PCIDevice *d, unsigned int irq_num)\n{\n assert(irq_num < 4);\n return &d->irq[irq_num];\n}\n\nstatic uint32_t pci_device_config_read(PCIDevice *d, uint32_t addr,\n int size_log2)\n{\n uint32_t val;\n switch(size_log2) {\n case 0:\n val = *(uint8_t *)(d->config + addr);\n break;\n case 1:\n /* Note: may be unaligned */\n if (addr <= 0xfe)\n val = get_le16(d->config + addr);\n else\n val = *(uint8_t *)(d->config + addr);\n break;\n case 2:\n /* always aligned */\n val = get_le32(d->config + addr);\n break;\n default:\n abort();\n }\n#ifdef DEBUG_CONFIG\n printf(\"pci_config_read: dev=%s addr=0x%02x val=0x%x s=%d\\n\",\n d->name, addr, val, 1 << size_log2);\n#endif\n return val;\n}\n\nPhysMemoryMap *pci_device_get_mem_map(PCIDevice *d)\n{\n return d->bus->mem_map;\n}\n\nPhysMemoryMap *pci_device_get_port_map(PCIDevice *d)\n{\n return d->bus->port_map;\n}\n\nvoid pci_register_bar(PCIDevice *d, unsigned int bar_num,\n uint32_t size, int type,\n void *opaque, PCIBarSetFunc *bar_set)\n{\n PCIIORegion *r;\n uint32_t val, config_addr;\n \n assert(bar_num < PCI_NUM_REGIONS);\n assert((size & (size - 1)) == 0); /* power of two */\n assert(size >= 4);\n r = &d->io_regions[bar_num];\n assert(r->size == 0);\n r->size = size;\n r->type = type;\n r->enabled = FALSE;\n r->opaque = opaque;\n r->bar_set = bar_set;\n /* set the config value */\n val = 0;\n if (bar_num == PCI_ROM_SLOT) {\n config_addr = 0x30;\n } else {\n val |= r->type;\n config_addr = 0x10 + 4 * bar_num;\n }\n put_le32(&d->config[config_addr], val);\n}\n\nstatic void pci_update_mappings(PCIDevice *d)\n{\n int cmd, i, offset;\n uint32_t new_addr;\n BOOL new_enabled;\n PCIIORegion *r;\n \n cmd = get_le16(&d->config[PCI_COMMAND]);\n\n for(i = 0; i < PCI_NUM_REGIONS; i++) {\n r = &d->io_regions[i];\n if (i == PCI_ROM_SLOT) {\n offset = 0x30;\n } else {\n offset = 0x10 + i * 4;\n }\n new_addr = get_le32(&d->config[offset]);\n new_enabled = FALSE;\n if (r->size != 0) {\n if ((r->type & PCI_ADDRESS_SPACE_IO) &&\n (cmd & PCI_COMMAND_IO)) {\n new_enabled = TRUE;\n } else {\n if (cmd & PCI_COMMAND_MEMORY) {\n if (i == PCI_ROM_SLOT) {\n new_enabled = (new_addr & 1);\n } else {\n new_enabled = TRUE;\n }\n }\n }\n }\n if (new_enabled) {\n /* new address */\n new_addr = get_le32(&d->config[offset]) & ~(r->size - 1);\n r->bar_set(r->opaque, i, new_addr, TRUE);\n r->enabled = TRUE;\n } else if (r->enabled) {\n r->bar_set(r->opaque, i, 0, FALSE);\n r->enabled = FALSE;\n }\n }\n}\n\n/* return != 0 if write is not handled */\nstatic int pci_write_bar(PCIDevice *d, uint32_t addr,\n uint32_t val)\n{\n PCIIORegion *r;\n int reg;\n \n if (addr == 0x30)\n reg = PCI_ROM_SLOT;\n else\n reg = (addr - 0x10) >> 2;\n // printf(\"%s: write bar addr=%x data=%x\\n\", d->name, addr, val);\n r = &d->io_regions[reg];\n if (r->size == 0)\n return -1;\n if (reg == PCI_ROM_SLOT) {\n val = val & ((~(r->size - 1)) | 1);\n } else {\n val = (val & ~(r->size - 1)) | r->type;\n }\n put_le32(d->config + addr, val);\n pci_update_mappings(d);\n return 0;\n}\n\nstatic void pci_device_config_write8(PCIDevice *d, uint32_t addr,\n uint32_t data)\n{\n int can_write;\n\n if (addr == PCI_STATUS || addr == (PCI_STATUS + 1)) {\n /* write 1 reset bits */\n d->config[addr] &= ~data;\n return;\n }\n \n switch(d->config[0x0e]) {\n case 0x00:\n case 0x80:\n switch(addr) {\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x08:\n case 0x09:\n case 0x0a:\n case 0x0b:\n case 0x0e:\n case 0x10 ... 0x27: /* base */\n case 0x30 ... 0x33: /* rom */\n case 0x3d:\n can_write = 0;\n break;\n default:\n can_write = 1;\n break;\n }\n break;\n default:\n case 0x01:\n switch(addr) {\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x08:\n case 0x09:\n case 0x0a:\n case 0x0b:\n case 0x0e:\n case 0x38 ... 0x3b: /* rom */\n case 0x3d:\n can_write = 0;\n break;\n default:\n can_write = 1;\n break;\n }\n break;\n }\n if (can_write)\n d->config[addr] = data;\n}\n \n\nstatic void pci_device_config_write(PCIDevice *d, uint32_t addr,\n uint32_t data, int size_log2)\n{\n int size, i;\n uint32_t addr1;\n \n#ifdef DEBUG_CONFIG\n printf(\"pci_config_write: dev=%s addr=0x%02x val=0x%x s=%d\\n\",\n d->name, addr, data, 1 << size_log2);\n#endif\n if (size_log2 == 2 &&\n ((addr >= 0x10 && addr < 0x10 + 4 * 6) ||\n addr == 0x30)) {\n if (pci_write_bar(d, addr, data) == 0)\n return;\n }\n size = 1 << size_log2;\n for(i = 0; i < size; i++) {\n addr1 = addr + i;\n if (addr1 <= 0xff) {\n pci_device_config_write8(d, addr1, (data >> (i * 8)) & 0xff);\n }\n }\n if (PCI_COMMAND >= addr && PCI_COMMAND < addr + size) {\n pci_update_mappings(d);\n }\n}\n\n\nstatic void pci_data_write(PCIBus *s, uint32_t addr,\n uint32_t data, int size_log2)\n{\n PCIDevice *d;\n int bus_num, devfn, config_addr;\n \n bus_num = (addr >> 16) & 0xff;\n if (bus_num != s->bus_num)\n return;\n devfn = (addr >> 8) & 0xff;\n d = s->device[devfn];\n if (!d)\n return;\n config_addr = addr & 0xff;\n pci_device_config_write(d, config_addr, data, size_log2);\n}\n\nstatic const uint32_t val_ones[3] = { 0xff, 0xffff, 0xffffffff };\n\nstatic uint32_t pci_data_read(PCIBus *s, uint32_t addr, int size_log2)\n{\n PCIDevice *d;\n int bus_num, devfn, config_addr;\n \n bus_num = (addr >> 16) & 0xff;\n if (bus_num != s->bus_num)\n return val_ones[size_log2];\n devfn = (addr >> 8) & 0xff;\n d = s->device[devfn];\n if (!d)\n return val_ones[size_log2];\n config_addr = addr & 0xff;\n return pci_device_config_read(d, config_addr, size_log2);\n}\n\n/* warning: only valid for one DEVIO page. Return NULL if no memory at\n the given address */\nuint8_t *pci_device_get_dma_ptr(PCIDevice *d, uint64_t addr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(d->bus->mem_map, addr, is_rw);\n}\n\nvoid pci_device_set_config8(PCIDevice *d, uint8_t addr, uint8_t val)\n{\n d->config[addr] = val;\n}\n\nvoid pci_device_set_config16(PCIDevice *d, uint8_t addr, uint16_t val)\n{\n put_le16(&d->config[addr], val);\n}\n\nint pci_device_get_devfn(PCIDevice *d)\n{\n return d->devfn;\n}\n\n/* return the offset of the capability or < 0 if error. */\nint pci_add_capability(PCIDevice *d, const uint8_t *buf, int size)\n{\n int offset;\n \n offset = d->next_cap_offset;\n if ((offset + size) > 256)\n return -1;\n d->next_cap_offset += size;\n d->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;\n memcpy(d->config + offset, buf, size);\n d->config[offset + 1] = d->config[PCI_CAPABILITY_LIST];\n d->config[PCI_CAPABILITY_LIST] = offset;\n return offset;\n}\n\n/* i440FX host bridge */\n\nstruct I440FXState {\n PCIBus *pci_bus;\n PCIDevice *pci_dev;\n PCIDevice *piix3_dev;\n uint32_t config_reg;\n uint8_t pic_irq_state[16];\n IRQSignal *pic_irqs; /* 16 irqs */\n};\n\nstatic void i440fx_write_addr(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n I440FXState *s = opaque;\n s->config_reg = data;\n}\n\nstatic uint32_t i440fx_read_addr(void *opaque, uint32_t offset, int size_log2)\n{\n I440FXState *s = opaque;\n return s->config_reg;\n}\n\nstatic void i440fx_write_data(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n I440FXState *s = opaque;\n if (s->config_reg & 0x80000000) {\n if (size_log2 == 2) {\n /* it is simpler to assume 32 bit config accesses are\n always aligned */\n pci_data_write(s->pci_bus, s->config_reg & ~3, data, size_log2);\n } else {\n pci_data_write(s->pci_bus, s->config_reg | offset, data, size_log2);\n }\n }\n}\n\nstatic uint32_t i440fx_read_data(void *opaque, uint32_t offset, int size_log2)\n{\n I440FXState *s = opaque;\n if (!(s->config_reg & 0x80000000))\n return val_ones[size_log2];\n if (size_log2 == 2) {\n /* it is simpler to assume 32 bit config accesses are\n always aligned */\n return pci_data_read(s->pci_bus, s->config_reg & ~3, size_log2);\n } else {\n return pci_data_read(s->pci_bus, s->config_reg | offset, size_log2);\n }\n}\n\nstatic void i440fx_set_irq(void *opaque, int irq_num, int irq_level)\n{\n I440FXState *s = opaque;\n PCIDevice *hd = s->piix3_dev;\n int pic_irq;\n \n /* map to the PIC irq (different IRQs can be mapped to the same\n PIC irq) */\n hd->config[0x60 + irq_num] &= ~0x80;\n pic_irq = hd->config[0x60 + irq_num];\n if (pic_irq < 16) {\n if (irq_level)\n s->pic_irq_state[pic_irq] |= 1 << irq_num;\n else\n s->pic_irq_state[pic_irq] &= ~(1 << irq_num);\n set_irq(&s->pic_irqs[pic_irq], (s->pic_irq_state[pic_irq] != 0));\n }\n}\n\nI440FXState *i440fx_init(PCIBus **pbus, int *ppiix3_devfn,\n PhysMemoryMap *mem_map, PhysMemoryMap *port_map,\n IRQSignal *pic_irqs)\n{\n I440FXState *s;\n PCIBus *b;\n PCIDevice *d;\n int i;\n \n s = mallocz(sizeof(*s));\n \n b = mallocz(sizeof(PCIBus));\n b->bus_num = 0;\n b->mem_map = mem_map;\n b->port_map = port_map;\n\n s->pic_irqs = pic_irqs;\n for(i = 0; i < 4; i++) {\n irq_init(&b->irq[i], i440fx_set_irq, s, i);\n }\n \n cpu_register_device(port_map, 0xcf8, 1, s, i440fx_read_addr, i440fx_write_addr, \n DEVIO_SIZE32);\n cpu_register_device(port_map, 0xcfc, 4, s, i440fx_read_data, i440fx_write_data, \n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32);\n d = pci_register_device(b, \"i440FX\", 0, 0x8086, 0x1237, 0x02, 0x0600);\n put_le16(&d->config[PCI_SUBSYSTEM_VENDOR_ID], 0x1af4); /* Red Hat, Inc. */\n put_le16(&d->config[PCI_SUBSYSTEM_ID], 0x1100); /* QEMU virtual machine */\n \n s->pci_dev = d;\n s->pci_bus = b;\n\n s->piix3_dev = pci_register_device(b, \"PIIX3\", 8, 0x8086, 0x7000,\n 0x00, 0x0601);\n pci_device_set_config8(s->piix3_dev, 0x0e, 0x80); /* header type */\n\n *pbus = b;\n *ppiix3_devfn = s->piix3_dev->devfn;\n return s;\n}\n\n/* in case no BIOS is used, map the interrupts. */\nvoid i440fx_map_interrupts(I440FXState *s, uint8_t *elcr,\n const uint8_t *pci_irqs)\n{\n PCIBus *b = s->pci_bus;\n PCIDevice *d, *hd;\n int irq_num, pic_irq, devfn, i;\n \n /* set a default PCI IRQ mapping to PIC IRQs */\n hd = s->piix3_dev;\n\n elcr[0] = 0;\n elcr[1] = 0;\n for(i = 0; i < 4; i++) {\n irq_num = pci_irqs[i];\n hd->config[0x60 + i] = irq_num;\n elcr[irq_num >> 3] |= (1 << (irq_num & 7));\n }\n\n for(devfn = 0; devfn < 256; devfn++) {\n d = b->device[devfn];\n if (!d)\n continue;\n if (d->config[PCI_INTERRUPT_PIN]) {\n irq_num = 0;\n irq_num = bus_map_irq(d, irq_num);\n pic_irq = hd->config[0x60 + irq_num];\n if (pic_irq < 16) {\n d->config[PCI_INTERRUPT_LINE] = pic_irq;\n }\n }\n }\n}\n"], ["/linuxpdf/tinyemu/riscv_cpu.c", "/*\n * RISCV CPU emulator\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"riscv_cpu.h\"\n\n#ifndef MAX_XLEN\n#error MAX_XLEN must be defined\n#endif\n#ifndef CONFIG_RISCV_MAX_XLEN\n#error CONFIG_RISCV_MAX_XLEN must be defined\n#endif\n\n//#define DUMP_INVALID_MEM_ACCESS\n//#define DUMP_MMU_EXCEPTIONS\n//#define DUMP_INTERRUPTS\n//#define DUMP_INVALID_CSR\n//#define DUMP_EXCEPTIONS\n//#define DUMP_CSR\n//#define CONFIG_LOGFILE\n\n#include \"riscv_cpu_priv.h\"\n\n#if FLEN > 0\n#include \"softfp.h\"\n#endif\n\n#ifdef USE_GLOBAL_STATE\nstatic RISCVCPUState riscv_cpu_global_state;\n#endif\n#ifdef USE_GLOBAL_VARIABLES\n#define code_ptr s->__code_ptr\n#define code_end s->__code_end\n#define code_to_pc_addend s->__code_to_pc_addend\n#endif\n\n#ifdef CONFIG_LOGFILE\nstatic FILE *log_file;\n\nstatic void log_vprintf(const char *fmt, va_list ap)\n{\n if (!log_file)\n log_file = fopen(\"/tmp/riscemu.log\", \"wb\");\n vfprintf(log_file, fmt, ap);\n}\n#else\nstatic void log_vprintf(const char *fmt, va_list ap)\n{\n vprintf(fmt, ap);\n}\n#endif\n\nstatic void __attribute__((format(printf, 1, 2), unused)) log_printf(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n log_vprintf(fmt, ap);\n va_end(ap);\n}\n\n#if MAX_XLEN == 128\nstatic void fprint_target_ulong(FILE *f, target_ulong a)\n{\n fprintf(f, \"%016\" PRIx64 \"%016\" PRIx64, (uint64_t)(a >> 64), (uint64_t)a);\n}\n#else\nstatic void fprint_target_ulong(FILE *f, target_ulong a)\n{\n fprintf(f, \"%\" PR_target_ulong, a);\n}\n#endif\n\nstatic void print_target_ulong(target_ulong a)\n{\n fprint_target_ulong(stdout, a);\n}\n\nstatic char *reg_name[32] = {\n\"zero\", \"ra\", \"sp\", \"gp\", \"tp\", \"t0\", \"t1\", \"t2\",\n\"s0\", \"s1\", \"a0\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\",\n\"a6\", \"a7\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\", \"s7\",\n\"s8\", \"s9\", \"s10\", \"s11\", \"t3\", \"t4\", \"t5\", \"t6\"\n};\n\nstatic void dump_regs(RISCVCPUState *s)\n{\n int i, cols;\n const char priv_str[4] = \"USHM\";\n cols = 256 / MAX_XLEN;\n printf(\"pc =\");\n print_target_ulong(s->pc);\n printf(\" \");\n for(i = 1; i < 32; i++) {\n printf(\"%-3s=\", reg_name[i]);\n print_target_ulong(s->reg[i]);\n if ((i & (cols - 1)) == (cols - 1))\n printf(\"\\n\");\n else\n printf(\" \");\n }\n printf(\"priv=%c\", priv_str[s->priv]);\n printf(\" mstatus=\");\n print_target_ulong(s->mstatus);\n printf(\" cycles=%\" PRId64, s->insn_counter);\n printf(\"\\n\");\n#if 1\n printf(\" mideleg=\");\n print_target_ulong(s->mideleg);\n printf(\" mie=\");\n print_target_ulong(s->mie);\n printf(\" mip=\");\n print_target_ulong(s->mip);\n printf(\"\\n\");\n#endif\n}\n\nstatic __attribute__((unused)) void cpu_abort(RISCVCPUState *s)\n{\n dump_regs(s);\n abort();\n}\n\n/* addr must be aligned. Only RAM accesses are supported */\n#define PHYS_MEM_READ_WRITE(size, uint_type) \\\nstatic __maybe_unused inline void phys_write_u ## size(RISCVCPUState *s, target_ulong addr,\\\n uint_type val) \\\n{\\\n PhysMemoryRange *pr = get_phys_mem_range(s->mem_map, addr);\\\n if (!pr || !pr->is_ram)\\\n return;\\\n *(uint_type *)(pr->phys_mem + \\\n (uintptr_t)(addr - pr->addr)) = val;\\\n}\\\n\\\nstatic __maybe_unused inline uint_type phys_read_u ## size(RISCVCPUState *s, target_ulong addr) \\\n{\\\n PhysMemoryRange *pr = get_phys_mem_range(s->mem_map, addr);\\\n if (!pr || !pr->is_ram)\\\n return 0;\\\n return *(uint_type *)(pr->phys_mem + \\\n (uintptr_t)(addr - pr->addr)); \\\n}\n\nPHYS_MEM_READ_WRITE(8, uint8_t)\nPHYS_MEM_READ_WRITE(32, uint32_t)\nPHYS_MEM_READ_WRITE(64, uint64_t)\n\n#define PTE_V_MASK (1 << 0)\n#define PTE_U_MASK (1 << 4)\n#define PTE_A_MASK (1 << 6)\n#define PTE_D_MASK (1 << 7)\n\n#define ACCESS_READ 0\n#define ACCESS_WRITE 1\n#define ACCESS_CODE 2\n\n/* access = 0: read, 1 = write, 2 = code. Set the exception_pending\n field if necessary. return 0 if OK, -1 if translation error */\nstatic int get_phys_addr(RISCVCPUState *s,\n target_ulong *ppaddr, target_ulong vaddr,\n int access)\n{\n int mode, levels, pte_bits, pte_idx, pte_mask, pte_size_log2, xwr, priv;\n int need_write, vaddr_shift, i, pte_addr_bits;\n target_ulong pte_addr, pte, vaddr_mask, paddr;\n\n if ((s->mstatus & MSTATUS_MPRV) && access != ACCESS_CODE) {\n /* use previous priviledge */\n priv = (s->mstatus >> MSTATUS_MPP_SHIFT) & 3;\n } else {\n priv = s->priv;\n }\n\n if (priv == PRV_M) {\n if (s->cur_xlen < MAX_XLEN) {\n /* truncate virtual address */\n *ppaddr = vaddr & (((target_ulong)1 << s->cur_xlen) - 1);\n } else {\n *ppaddr = vaddr;\n }\n return 0;\n }\n#if MAX_XLEN == 32\n /* 32 bits */\n mode = s->satp >> 31;\n if (mode == 0) {\n /* bare: no translation */\n *ppaddr = vaddr;\n return 0;\n } else {\n /* sv32 */\n levels = 2;\n pte_size_log2 = 2;\n pte_addr_bits = 22;\n }\n#else\n mode = (s->satp >> 60) & 0xf;\n if (mode == 0) {\n /* bare: no translation */\n *ppaddr = vaddr;\n return 0;\n } else {\n /* sv39/sv48 */\n levels = mode - 8 + 3;\n pte_size_log2 = 3;\n vaddr_shift = MAX_XLEN - (PG_SHIFT + levels * 9);\n if ((((target_long)vaddr << vaddr_shift) >> vaddr_shift) != vaddr)\n return -1;\n pte_addr_bits = 44;\n }\n#endif\n pte_addr = (s->satp & (((target_ulong)1 << pte_addr_bits) - 1)) << PG_SHIFT;\n pte_bits = 12 - pte_size_log2;\n pte_mask = (1 << pte_bits) - 1;\n for(i = 0; i < levels; i++) {\n vaddr_shift = PG_SHIFT + pte_bits * (levels - 1 - i);\n pte_idx = (vaddr >> vaddr_shift) & pte_mask;\n pte_addr += pte_idx << pte_size_log2;\n if (pte_size_log2 == 2)\n pte = phys_read_u32(s, pte_addr);\n else\n pte = phys_read_u64(s, pte_addr);\n //printf(\"pte=0x%08\" PRIx64 \"\\n\", pte);\n if (!(pte & PTE_V_MASK))\n return -1; /* invalid PTE */\n paddr = (pte >> 10) << PG_SHIFT;\n xwr = (pte >> 1) & 7;\n if (xwr != 0) {\n if (xwr == 2 || xwr == 6)\n return -1;\n /* priviledge check */\n if (priv == PRV_S) {\n if ((pte & PTE_U_MASK) && !(s->mstatus & MSTATUS_SUM))\n return -1;\n } else {\n if (!(pte & PTE_U_MASK))\n return -1;\n }\n /* protection check */\n /* MXR allows read access to execute-only pages */\n if (s->mstatus & MSTATUS_MXR)\n xwr |= (xwr >> 2);\n\n if (((xwr >> access) & 1) == 0)\n return -1;\n need_write = !(pte & PTE_A_MASK) ||\n (!(pte & PTE_D_MASK) && access == ACCESS_WRITE);\n pte |= PTE_A_MASK;\n if (access == ACCESS_WRITE)\n pte |= PTE_D_MASK;\n if (need_write) {\n if (pte_size_log2 == 2)\n phys_write_u32(s, pte_addr, pte);\n else\n phys_write_u64(s, pte_addr, pte);\n }\n vaddr_mask = ((target_ulong)1 << vaddr_shift) - 1;\n *ppaddr = (vaddr & vaddr_mask) | (paddr & ~vaddr_mask);\n return 0;\n } else {\n pte_addr = paddr;\n }\n }\n return -1;\n}\n\n/* return 0 if OK, != 0 if exception */\nint target_read_slow(RISCVCPUState *s, mem_uint_t *pval,\n target_ulong addr, int size_log2)\n{\n int size, tlb_idx, err, al;\n target_ulong paddr, offset;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n mem_uint_t ret;\n\n /* first handle unaligned accesses */\n size = 1 << size_log2;\n al = addr & (size - 1);\n if (al != 0) {\n switch(size_log2) {\n case 1:\n {\n uint8_t v0, v1;\n err = target_read_u8(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u8(s, &v1, addr + 1);\n if (err)\n return err;\n ret = v0 | (v1 << 8);\n }\n break;\n case 2:\n {\n uint32_t v0, v1;\n addr -= al;\n err = target_read_u32(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u32(s, &v1, addr + 4);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (32 - al * 8));\n }\n break;\n#if MLEN >= 64\n case 3:\n {\n uint64_t v0, v1;\n addr -= al;\n err = target_read_u64(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u64(s, &v1, addr + 8);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (64 - al * 8));\n }\n break;\n#endif\n#if MLEN >= 128\n case 4:\n {\n uint128_t v0, v1;\n addr -= al;\n err = target_read_u128(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u128(s, &v1, addr + 16);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (128 - al * 8));\n }\n break;\n#endif\n default:\n abort();\n }\n } else {\n if (get_phys_addr(s, &paddr, addr, ACCESS_READ)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_LOAD_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr) {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"target_read_slow: invalid physical address 0x\");\n print_target_ulong(paddr);\n printf(\"\\n\");\n#endif\n return 0;\n } else if (pr->is_ram) {\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_read[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_read[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n switch(size_log2) {\n case 0:\n ret = *(uint8_t *)ptr;\n break;\n case 1:\n ret = *(uint16_t *)ptr;\n break;\n case 2:\n ret = *(uint32_t *)ptr;\n break;\n#if MLEN >= 64\n case 3:\n ret = *(uint64_t *)ptr;\n break;\n#endif\n#if MLEN >= 128\n case 4:\n ret = *(uint128_t *)ptr;\n break;\n#endif\n default:\n abort();\n }\n } else {\n offset = paddr - pr->addr;\n if (((pr->devio_flags >> size_log2) & 1) != 0) {\n ret = pr->read_func(pr->opaque, offset, size_log2);\n }\n#if MLEN >= 64\n else if ((pr->devio_flags & DEVIO_SIZE32) && size_log2 == 3) {\n /* emulate 64 bit access */\n ret = pr->read_func(pr->opaque, offset, 2);\n ret |= (uint64_t)pr->read_func(pr->opaque, offset + 4, 2) << 32;\n \n }\n#endif\n else {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"unsupported device read access: addr=0x\");\n print_target_ulong(paddr);\n printf(\" width=%d bits\\n\", 1 << (3 + size_log2));\n#endif\n ret = 0;\n }\n }\n }\n *pval = ret;\n return 0;\n}\n\n/* return 0 if OK, != 0 if exception */\nint target_write_slow(RISCVCPUState *s, target_ulong addr,\n mem_uint_t val, int size_log2)\n{\n int size, i, tlb_idx, err;\n target_ulong paddr, offset;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n \n /* first handle unaligned accesses */\n size = 1 << size_log2;\n if ((addr & (size - 1)) != 0) {\n /* XXX: should avoid modifying the memory in case of exception */\n for(i = 0; i < size; i++) {\n err = target_write_u8(s, addr + i, (val >> (8 * i)) & 0xff);\n if (err)\n return err;\n }\n } else {\n if (get_phys_addr(s, &paddr, addr, ACCESS_WRITE)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_STORE_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr) {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"target_write_slow: invalid physical address 0x\");\n print_target_ulong(paddr);\n printf(\"\\n\");\n#endif\n } else if (pr->is_ram) {\n phys_mem_set_dirty_bit(pr, paddr - pr->addr);\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_write[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_write[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n switch(size_log2) {\n case 0:\n *(uint8_t *)ptr = val;\n break;\n case 1:\n *(uint16_t *)ptr = val;\n break;\n case 2:\n *(uint32_t *)ptr = val;\n break;\n#if MLEN >= 64\n case 3:\n *(uint64_t *)ptr = val;\n break;\n#endif\n#if MLEN >= 128\n case 4:\n *(uint128_t *)ptr = val;\n break;\n#endif\n default:\n abort();\n }\n } else {\n offset = paddr - pr->addr;\n if (((pr->devio_flags >> size_log2) & 1) != 0) {\n pr->write_func(pr->opaque, offset, val, size_log2);\n }\n#if MLEN >= 64\n else if ((pr->devio_flags & DEVIO_SIZE32) && size_log2 == 3) {\n /* emulate 64 bit access */\n pr->write_func(pr->opaque, offset,\n val & 0xffffffff, 2);\n pr->write_func(pr->opaque, offset + 4,\n (val >> 32) & 0xffffffff, 2);\n }\n#endif\n else {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"unsupported device write access: addr=0x\");\n print_target_ulong(paddr);\n printf(\" width=%d bits\\n\", 1 << (3 + size_log2));\n#endif\n }\n }\n }\n return 0;\n}\n\nstruct __attribute__((packed)) unaligned_u32 {\n uint32_t u32;\n};\n\n/* unaligned access at an address known to be a multiple of 2 */\nstatic uint32_t get_insn32(uint8_t *ptr)\n{\n#if defined(EMSCRIPTEN)\n return ((uint16_t *)ptr)[0] | (((uint16_t *)ptr)[1] << 16);\n#else\n return ((struct unaligned_u32 *)ptr)->u32;\n#endif\n}\n\n/* return 0 if OK, != 0 if exception */\nstatic no_inline __exception int target_read_insn_slow(RISCVCPUState *s,\n uint8_t **pptr,\n target_ulong addr)\n{\n int tlb_idx;\n target_ulong paddr;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n \n if (get_phys_addr(s, &paddr, addr, ACCESS_CODE)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_FETCH_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr || !pr->is_ram) {\n /* XXX: we only access to execute code from RAM */\n s->pending_tval = addr;\n s->pending_exception = CAUSE_FAULT_FETCH;\n return -1;\n }\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_code[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_code[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n *pptr = ptr;\n return 0;\n}\n\n/* addr must be aligned */\nstatic inline __exception int target_read_insn_u16(RISCVCPUState *s, uint16_t *pinsn,\n target_ulong addr)\n{\n uint32_t tlb_idx;\n uint8_t *ptr;\n \n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n if (likely(s->tlb_code[tlb_idx].vaddr == (addr & ~PG_MASK))) {\n ptr = (uint8_t *)(s->tlb_code[tlb_idx].mem_addend +\n (uintptr_t)addr);\n } else {\n if (target_read_insn_slow(s, &ptr, addr))\n return -1;\n }\n *pinsn = *(uint16_t *)ptr;\n return 0;\n}\n\nstatic void tlb_init(RISCVCPUState *s)\n{\n int i;\n \n for(i = 0; i < TLB_SIZE; i++) {\n s->tlb_read[i].vaddr = -1;\n s->tlb_write[i].vaddr = -1;\n s->tlb_code[i].vaddr = -1;\n }\n}\n\nstatic void tlb_flush_all(RISCVCPUState *s)\n{\n tlb_init(s);\n}\n\nstatic void tlb_flush_vaddr(RISCVCPUState *s, target_ulong vaddr)\n{\n tlb_flush_all(s);\n}\n\n/* XXX: inefficient but not critical as long as it is seldom used */\nstatic void glue(riscv_cpu_flush_tlb_write_range_ram,\n MAX_XLEN)(RISCVCPUState *s,\n uint8_t *ram_ptr, size_t ram_size)\n{\n uint8_t *ptr, *ram_end;\n int i;\n \n ram_end = ram_ptr + ram_size;\n for(i = 0; i < TLB_SIZE; i++) {\n if (s->tlb_write[i].vaddr != -1) {\n ptr = (uint8_t *)(s->tlb_write[i].mem_addend +\n (uintptr_t)s->tlb_write[i].vaddr);\n if (ptr >= ram_ptr && ptr < ram_end) {\n s->tlb_write[i].vaddr = -1;\n }\n }\n }\n}\n\n\n#define SSTATUS_MASK0 (MSTATUS_UIE | MSTATUS_SIE | \\\n MSTATUS_UPIE | MSTATUS_SPIE | \\\n MSTATUS_SPP | \\\n MSTATUS_FS | MSTATUS_XS | \\\n MSTATUS_SUM | MSTATUS_MXR)\n#if MAX_XLEN >= 64\n#define SSTATUS_MASK (SSTATUS_MASK0 | MSTATUS_UXL_MASK)\n#else\n#define SSTATUS_MASK SSTATUS_MASK0\n#endif\n\n\n#define MSTATUS_MASK (MSTATUS_UIE | MSTATUS_SIE | MSTATUS_MIE | \\\n MSTATUS_UPIE | MSTATUS_SPIE | MSTATUS_MPIE | \\\n MSTATUS_SPP | MSTATUS_MPP | \\\n MSTATUS_FS | \\\n MSTATUS_MPRV | MSTATUS_SUM | MSTATUS_MXR)\n\n/* cycle and insn counters */\n#define COUNTEREN_MASK ((1 << 0) | (1 << 2))\n\n/* return the complete mstatus with the SD bit */\nstatic target_ulong get_mstatus(RISCVCPUState *s, target_ulong mask)\n{\n target_ulong val;\n BOOL sd;\n val = s->mstatus | (s->fs << MSTATUS_FS_SHIFT);\n val &= mask;\n sd = ((val & MSTATUS_FS) == MSTATUS_FS) |\n ((val & MSTATUS_XS) == MSTATUS_XS);\n if (sd)\n val |= (target_ulong)1 << (s->cur_xlen - 1);\n return val;\n}\n \nstatic int get_base_from_xlen(int xlen)\n{\n if (xlen == 32)\n return 1;\n else if (xlen == 64)\n return 2;\n else\n return 3;\n}\n\nstatic void set_mstatus(RISCVCPUState *s, target_ulong val)\n{\n target_ulong mod, mask;\n \n /* flush the TLBs if change of MMU config */\n mod = s->mstatus ^ val;\n if ((mod & (MSTATUS_MPRV | MSTATUS_SUM | MSTATUS_MXR)) != 0 ||\n ((s->mstatus & MSTATUS_MPRV) && (mod & MSTATUS_MPP) != 0)) {\n tlb_flush_all(s);\n }\n s->fs = (val >> MSTATUS_FS_SHIFT) & 3;\n\n mask = MSTATUS_MASK & ~MSTATUS_FS;\n#if MAX_XLEN >= 64\n {\n int uxl, sxl;\n uxl = (val >> MSTATUS_UXL_SHIFT) & 3;\n if (uxl >= 1 && uxl <= get_base_from_xlen(MAX_XLEN))\n mask |= MSTATUS_UXL_MASK;\n sxl = (val >> MSTATUS_UXL_SHIFT) & 3;\n if (sxl >= 1 && sxl <= get_base_from_xlen(MAX_XLEN))\n mask |= MSTATUS_SXL_MASK;\n }\n#endif\n s->mstatus = (s->mstatus & ~mask) | (val & mask);\n}\n\n/* return -1 if invalid CSR. 0 if OK. 'will_write' indicate that the\n csr will be written after (used for CSR access check) */\nstatic int csr_read(RISCVCPUState *s, target_ulong *pval, uint32_t csr,\n BOOL will_write)\n{\n target_ulong val;\n\n if (((csr & 0xc00) == 0xc00) && will_write)\n return -1; /* read-only CSR */\n if (s->priv < ((csr >> 8) & 3))\n return -1; /* not enough priviledge */\n \n switch(csr) {\n#if FLEN > 0\n case 0x001: /* fflags */\n if (s->fs == 0)\n return -1;\n val = s->fflags;\n break;\n case 0x002: /* frm */\n if (s->fs == 0)\n return -1;\n val = s->frm;\n break;\n case 0x003:\n if (s->fs == 0)\n return -1;\n val = s->fflags | (s->frm << 5);\n break;\n#endif\n case 0xc00: /* ucycle */\n case 0xc02: /* uinstret */\n {\n uint32_t counteren;\n if (s->priv < PRV_M) {\n if (s->priv < PRV_S)\n counteren = s->scounteren;\n else\n counteren = s->mcounteren;\n if (((counteren >> (csr & 0x1f)) & 1) == 0)\n goto invalid_csr;\n }\n }\n val = (int64_t)s->insn_counter;\n break;\n case 0xc80: /* mcycleh */\n case 0xc82: /* minstreth */\n if (s->cur_xlen != 32)\n goto invalid_csr;\n {\n uint32_t counteren;\n if (s->priv < PRV_M) {\n if (s->priv < PRV_S)\n counteren = s->scounteren;\n else\n counteren = s->mcounteren;\n if (((counteren >> (csr & 0x1f)) & 1) == 0)\n goto invalid_csr;\n }\n }\n val = s->insn_counter >> 32;\n break;\n \n case 0x100:\n val = get_mstatus(s, SSTATUS_MASK);\n break;\n case 0x104: /* sie */\n val = s->mie & s->mideleg;\n break;\n case 0x105:\n val = s->stvec;\n break;\n case 0x106:\n val = s->scounteren;\n break;\n case 0x140:\n val = s->sscratch;\n break;\n case 0x141:\n val = s->sepc;\n break;\n case 0x142:\n val = s->scause;\n break;\n case 0x143:\n val = s->stval;\n break;\n case 0x144: /* sip */\n val = s->mip & s->mideleg;\n break;\n case 0x180:\n val = s->satp;\n break;\n case 0x300:\n val = get_mstatus(s, (target_ulong)-1);\n break;\n case 0x301:\n val = s->misa;\n val |= (target_ulong)s->mxl << (s->cur_xlen - 2);\n break;\n case 0x302:\n val = s->medeleg;\n break;\n case 0x303:\n val = s->mideleg;\n break;\n case 0x304:\n val = s->mie;\n break;\n case 0x305:\n val = s->mtvec;\n break;\n case 0x306:\n val = s->mcounteren;\n break;\n case 0x340:\n val = s->mscratch;\n break;\n case 0x341:\n val = s->mepc;\n break;\n case 0x342:\n val = s->mcause;\n break;\n case 0x343:\n val = s->mtval;\n break;\n case 0x344:\n val = s->mip;\n break;\n case 0xb00: /* mcycle */\n case 0xb02: /* minstret */\n val = (int64_t)s->insn_counter;\n break;\n case 0xb80: /* mcycleh */\n case 0xb82: /* minstreth */\n if (s->cur_xlen != 32)\n goto invalid_csr;\n val = s->insn_counter >> 32;\n break;\n case 0xf14:\n val = s->mhartid;\n break;\n default:\n invalid_csr:\n#ifdef DUMP_INVALID_CSR\n /* the 'time' counter is usually emulated */\n if (csr != 0xc01 && csr != 0xc81) {\n printf(\"csr_read: invalid CSR=0x%x\\n\", csr);\n }\n#endif\n *pval = 0;\n return -1;\n }\n *pval = val;\n return 0;\n}\n\n#if FLEN > 0\nstatic void set_frm(RISCVCPUState *s, unsigned int val)\n{\n if (val >= 5)\n val = 0;\n s->frm = val;\n}\n\n/* return -1 if invalid roundind mode */\nstatic int get_insn_rm(RISCVCPUState *s, unsigned int rm)\n{\n if (rm == 7)\n return s->frm;\n if (rm >= 5)\n return -1;\n else\n return rm;\n}\n#endif\n\n/* return -1 if invalid CSR, 0 if OK, 1 if the interpreter loop must be\n exited (e.g. XLEN was modified), 2 if TLBs have been flushed. */\nstatic int csr_write(RISCVCPUState *s, uint32_t csr, target_ulong val)\n{\n target_ulong mask;\n\n#if defined(DUMP_CSR)\n printf(\"csr_write: csr=0x%03x val=0x\", csr);\n print_target_ulong(val);\n printf(\"\\n\");\n#endif\n switch(csr) {\n#if FLEN > 0\n case 0x001: /* fflags */\n s->fflags = val & 0x1f;\n s->fs = 3;\n break;\n case 0x002: /* frm */\n set_frm(s, val & 7);\n s->fs = 3;\n break;\n case 0x003: /* fcsr */\n set_frm(s, (val >> 5) & 7);\n s->fflags = val & 0x1f;\n s->fs = 3;\n break;\n#endif\n case 0x100: /* sstatus */\n set_mstatus(s, (s->mstatus & ~SSTATUS_MASK) | (val & SSTATUS_MASK));\n break;\n case 0x104: /* sie */\n mask = s->mideleg;\n s->mie = (s->mie & ~mask) | (val & mask);\n break;\n case 0x105:\n s->stvec = val & ~3;\n break;\n case 0x106:\n s->scounteren = val & COUNTEREN_MASK;\n break;\n case 0x140:\n s->sscratch = val;\n break;\n case 0x141:\n s->sepc = val & ~1;\n break;\n case 0x142:\n s->scause = val;\n break;\n case 0x143:\n s->stval = val;\n break;\n case 0x144: /* sip */\n mask = s->mideleg;\n s->mip = (s->mip & ~mask) | (val & mask);\n break;\n case 0x180:\n /* no ASID implemented */\n#if MAX_XLEN == 32\n {\n int new_mode;\n new_mode = (val >> 31) & 1;\n s->satp = (val & (((target_ulong)1 << 22) - 1)) |\n (new_mode << 31);\n }\n#else\n {\n int mode, new_mode;\n mode = s->satp >> 60;\n new_mode = (val >> 60) & 0xf;\n if (new_mode == 0 || (new_mode >= 8 && new_mode <= 9))\n mode = new_mode;\n s->satp = (val & (((uint64_t)1 << 44) - 1)) |\n ((uint64_t)mode << 60);\n }\n#endif\n tlb_flush_all(s);\n return 2;\n \n case 0x300:\n set_mstatus(s, val);\n break;\n case 0x301: /* misa */\n#if MAX_XLEN >= 64\n {\n int new_mxl;\n new_mxl = (val >> (s->cur_xlen - 2)) & 3;\n if (new_mxl >= 1 && new_mxl <= get_base_from_xlen(MAX_XLEN)) {\n /* Note: misa is only modified in M level, so cur_xlen\n = 2^(mxl + 4) */\n if (s->mxl != new_mxl) {\n s->mxl = new_mxl;\n s->cur_xlen = 1 << (new_mxl + 4);\n return 1;\n }\n }\n }\n#endif\n break;\n case 0x302:\n mask = (1 << (CAUSE_STORE_PAGE_FAULT + 1)) - 1;\n s->medeleg = (s->medeleg & ~mask) | (val & mask);\n break;\n case 0x303:\n mask = MIP_SSIP | MIP_STIP | MIP_SEIP;\n s->mideleg = (s->mideleg & ~mask) | (val & mask);\n break;\n case 0x304:\n mask = MIP_MSIP | MIP_MTIP | MIP_SSIP | MIP_STIP | MIP_SEIP;\n s->mie = (s->mie & ~mask) | (val & mask);\n break;\n case 0x305:\n s->mtvec = val & ~3;\n break;\n case 0x306:\n s->mcounteren = val & COUNTEREN_MASK;\n break;\n case 0x340:\n s->mscratch = val;\n break;\n case 0x341:\n s->mepc = val & ~1;\n break;\n case 0x342:\n s->mcause = val;\n break;\n case 0x343:\n s->mtval = val;\n break;\n case 0x344:\n mask = MIP_SSIP | MIP_STIP;\n s->mip = (s->mip & ~mask) | (val & mask);\n break;\n default:\n#ifdef DUMP_INVALID_CSR\n printf(\"csr_write: invalid CSR=0x%x\\n\", csr);\n#endif\n return -1;\n }\n return 0;\n}\n\nstatic void set_priv(RISCVCPUState *s, int priv)\n{\n if (s->priv != priv) {\n tlb_flush_all(s);\n#if MAX_XLEN >= 64\n /* change the current xlen */\n {\n int mxl;\n if (priv == PRV_S)\n mxl = (s->mstatus >> MSTATUS_SXL_SHIFT) & 3;\n else if (priv == PRV_U)\n mxl = (s->mstatus >> MSTATUS_UXL_SHIFT) & 3;\n else\n mxl = s->mxl;\n s->cur_xlen = 1 << (4 + mxl);\n }\n#endif\n s->priv = priv;\n }\n}\n\nstatic void raise_exception2(RISCVCPUState *s, uint32_t cause,\n target_ulong tval)\n{\n BOOL deleg;\n target_ulong causel;\n \n#if defined(DUMP_EXCEPTIONS) || defined(DUMP_MMU_EXCEPTIONS) || defined(DUMP_INTERRUPTS)\n {\n int flag;\n flag = 0;\n#ifdef DUMP_MMU_EXCEPTIONS\n if (cause == CAUSE_FAULT_FETCH ||\n cause == CAUSE_FAULT_LOAD ||\n cause == CAUSE_FAULT_STORE ||\n cause == CAUSE_FETCH_PAGE_FAULT ||\n cause == CAUSE_LOAD_PAGE_FAULT ||\n cause == CAUSE_STORE_PAGE_FAULT)\n flag = 1;\n#endif\n#ifdef DUMP_INTERRUPTS\n flag |= (cause & CAUSE_INTERRUPT) != 0;\n#endif\n#ifdef DUMP_EXCEPTIONS\n flag = 1;\n flag = (cause & CAUSE_INTERRUPT) == 0;\n if (cause == CAUSE_SUPERVISOR_ECALL || cause == CAUSE_ILLEGAL_INSTRUCTION)\n flag = 0;\n#endif\n if (flag) {\n log_printf(\"raise_exception: cause=0x%08x tval=0x\", cause);\n#ifdef CONFIG_LOGFILE\n fprint_target_ulong(log_file, tval);\n#else\n print_target_ulong(tval);\n#endif\n log_printf(\"\\n\");\n dump_regs(s);\n }\n }\n#endif\n\n if (s->priv <= PRV_S) {\n /* delegate the exception to the supervisor priviledge */\n if (cause & CAUSE_INTERRUPT)\n deleg = (s->mideleg >> (cause & (MAX_XLEN - 1))) & 1;\n else\n deleg = (s->medeleg >> cause) & 1;\n } else {\n deleg = 0;\n }\n \n causel = cause & 0x7fffffff;\n if (cause & CAUSE_INTERRUPT)\n causel |= (target_ulong)1 << (s->cur_xlen - 1);\n \n if (deleg) {\n s->scause = causel;\n s->sepc = s->pc;\n s->stval = tval;\n s->mstatus = (s->mstatus & ~MSTATUS_SPIE) |\n (((s->mstatus >> s->priv) & 1) << MSTATUS_SPIE_SHIFT);\n s->mstatus = (s->mstatus & ~MSTATUS_SPP) |\n (s->priv << MSTATUS_SPP_SHIFT);\n s->mstatus &= ~MSTATUS_SIE;\n set_priv(s, PRV_S);\n s->pc = s->stvec;\n } else {\n s->mcause = causel;\n s->mepc = s->pc;\n s->mtval = tval;\n s->mstatus = (s->mstatus & ~MSTATUS_MPIE) |\n (((s->mstatus >> s->priv) & 1) << MSTATUS_MPIE_SHIFT);\n s->mstatus = (s->mstatus & ~MSTATUS_MPP) |\n (s->priv << MSTATUS_MPP_SHIFT);\n s->mstatus &= ~MSTATUS_MIE;\n set_priv(s, PRV_M);\n s->pc = s->mtvec;\n }\n}\n\nstatic void raise_exception(RISCVCPUState *s, uint32_t cause)\n{\n raise_exception2(s, cause, 0);\n}\n\nstatic void handle_sret(RISCVCPUState *s)\n{\n int spp, spie;\n spp = (s->mstatus >> MSTATUS_SPP_SHIFT) & 1;\n /* set the IE state to previous IE state */\n spie = (s->mstatus >> MSTATUS_SPIE_SHIFT) & 1;\n s->mstatus = (s->mstatus & ~(1 << spp)) |\n (spie << spp);\n /* set SPIE to 1 */\n s->mstatus |= MSTATUS_SPIE;\n /* set SPP to U */\n s->mstatus &= ~MSTATUS_SPP;\n set_priv(s, spp);\n s->pc = s->sepc;\n}\n\nstatic void handle_mret(RISCVCPUState *s)\n{\n int mpp, mpie;\n mpp = (s->mstatus >> MSTATUS_MPP_SHIFT) & 3;\n /* set the IE state to previous IE state */\n mpie = (s->mstatus >> MSTATUS_MPIE_SHIFT) & 1;\n s->mstatus = (s->mstatus & ~(1 << mpp)) |\n (mpie << mpp);\n /* set MPIE to 1 */\n s->mstatus |= MSTATUS_MPIE;\n /* set MPP to U */\n s->mstatus &= ~MSTATUS_MPP;\n set_priv(s, mpp);\n s->pc = s->mepc;\n}\n\nstatic inline uint32_t get_pending_irq_mask(RISCVCPUState *s)\n{\n uint32_t pending_ints, enabled_ints;\n\n pending_ints = s->mip & s->mie;\n if (pending_ints == 0)\n return 0;\n\n enabled_ints = 0;\n switch(s->priv) {\n case PRV_M:\n if (s->mstatus & MSTATUS_MIE)\n enabled_ints = ~s->mideleg;\n break;\n case PRV_S:\n enabled_ints = ~s->mideleg;\n if (s->mstatus & MSTATUS_SIE)\n enabled_ints |= s->mideleg;\n break;\n default:\n case PRV_U:\n enabled_ints = -1;\n break;\n }\n return pending_ints & enabled_ints;\n}\n\nstatic __exception int raise_interrupt(RISCVCPUState *s)\n{\n uint32_t mask;\n int irq_num;\n\n mask = get_pending_irq_mask(s);\n if (mask == 0)\n return 0;\n irq_num = ctz32(mask);\n raise_exception(s, irq_num | CAUSE_INTERRUPT);\n return -1;\n}\n\nstatic inline int32_t sext(int32_t val, int n)\n{\n return (val << (32 - n)) >> (32 - n);\n}\n\nstatic inline uint32_t get_field1(uint32_t val, int src_pos, \n int dst_pos, int dst_pos_max)\n{\n int mask;\n assert(dst_pos_max >= dst_pos);\n mask = ((1 << (dst_pos_max - dst_pos + 1)) - 1) << dst_pos;\n if (dst_pos >= src_pos)\n return (val << (dst_pos - src_pos)) & mask;\n else\n return (val >> (src_pos - dst_pos)) & mask;\n}\n\n#define XLEN 32\n#include \"riscv_cpu_template.h\"\n\n#if MAX_XLEN >= 64\n#define XLEN 64\n#include \"riscv_cpu_template.h\"\n#endif\n\n#if MAX_XLEN >= 128\n#define XLEN 128\n#include \"riscv_cpu_template.h\"\n#endif\n\nstatic void glue(riscv_cpu_interp, MAX_XLEN)(RISCVCPUState *s, int n_cycles)\n{\n#ifdef USE_GLOBAL_STATE\n s = &riscv_cpu_global_state;\n#endif\n uint64_t timeout;\n\n timeout = s->insn_counter + n_cycles;\n while (!s->power_down_flag &&\n (int)(timeout - s->insn_counter) > 0) {\n n_cycles = timeout - s->insn_counter;\n switch(s->cur_xlen) {\n case 32:\n riscv_cpu_interp_x32(s, n_cycles);\n break;\n#if MAX_XLEN >= 64\n case 64:\n riscv_cpu_interp_x64(s, n_cycles);\n break;\n#endif\n#if MAX_XLEN >= 128\n case 128:\n riscv_cpu_interp_x128(s, n_cycles);\n break;\n#endif\n default:\n abort();\n }\n }\n}\n\n/* Note: the value is not accurate when called in riscv_cpu_interp() */\nstatic uint64_t glue(riscv_cpu_get_cycles, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->insn_counter;\n}\n\nstatic void glue(riscv_cpu_set_mip, MAX_XLEN)(RISCVCPUState *s, uint32_t mask)\n{\n s->mip |= mask;\n /* exit from power down if an interrupt is pending */\n if (s->power_down_flag && (s->mip & s->mie) != 0)\n s->power_down_flag = FALSE;\n}\n\nstatic void glue(riscv_cpu_reset_mip, MAX_XLEN)(RISCVCPUState *s, uint32_t mask)\n{\n s->mip &= ~mask;\n}\n\nstatic uint32_t glue(riscv_cpu_get_mip, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->mip;\n}\n\nstatic BOOL glue(riscv_cpu_get_power_down, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->power_down_flag;\n}\n\nstatic RISCVCPUState *glue(riscv_cpu_init, MAX_XLEN)(PhysMemoryMap *mem_map)\n{\n RISCVCPUState *s;\n \n#ifdef USE_GLOBAL_STATE\n s = &riscv_cpu_global_state;\n#else\n s = mallocz(sizeof(*s));\n#endif\n s->common.class_ptr = &glue(riscv_cpu_class, MAX_XLEN);\n s->mem_map = mem_map;\n s->pc = 0x1000;\n s->priv = PRV_M;\n s->cur_xlen = MAX_XLEN;\n s->mxl = get_base_from_xlen(MAX_XLEN);\n s->mstatus = ((uint64_t)s->mxl << MSTATUS_UXL_SHIFT) |\n ((uint64_t)s->mxl << MSTATUS_SXL_SHIFT);\n s->misa |= MCPUID_SUPER | MCPUID_USER | MCPUID_I | MCPUID_M | MCPUID_A;\n#if FLEN >= 32\n s->misa |= MCPUID_F;\n#endif\n#if FLEN >= 64\n s->misa |= MCPUID_D;\n#endif\n#if FLEN >= 128\n s->misa |= MCPUID_Q;\n#endif\n#ifdef CONFIG_EXT_C\n s->misa |= MCPUID_C;\n#endif\n tlb_init(s);\n return s;\n}\n\nstatic void glue(riscv_cpu_end, MAX_XLEN)(RISCVCPUState *s)\n{\n#ifdef USE_GLOBAL_STATE\n free(s);\n#endif\n}\n\nstatic uint32_t glue(riscv_cpu_get_misa, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->misa;\n}\n\nconst RISCVCPUClass glue(riscv_cpu_class, MAX_XLEN) = {\n glue(riscv_cpu_init, MAX_XLEN),\n glue(riscv_cpu_end, MAX_XLEN),\n glue(riscv_cpu_interp, MAX_XLEN),\n glue(riscv_cpu_get_cycles, MAX_XLEN),\n glue(riscv_cpu_set_mip, MAX_XLEN),\n glue(riscv_cpu_reset_mip, MAX_XLEN),\n glue(riscv_cpu_get_mip, MAX_XLEN),\n glue(riscv_cpu_get_power_down, MAX_XLEN),\n glue(riscv_cpu_get_misa, MAX_XLEN),\n glue(riscv_cpu_flush_tlb_write_range_ram, MAX_XLEN),\n};\n\n#if CONFIG_RISCV_MAX_XLEN == MAX_XLEN\nRISCVCPUState *riscv_cpu_init(PhysMemoryMap *mem_map, int max_xlen)\n{\n const RISCVCPUClass *c;\n switch(max_xlen) {\n /* with emscripten we compile a single CPU */\n#if defined(EMSCRIPTEN)\n case MAX_XLEN:\n c = &glue(riscv_cpu_class, MAX_XLEN);\n break;\n#else\n case 32:\n c = &riscv_cpu_class32;\n break;\n case 64:\n c = &riscv_cpu_class64;\n break;\n#if CONFIG_RISCV_MAX_XLEN == 128\n case 128:\n c = &riscv_cpu_class128;\n break;\n#endif\n#endif /* !EMSCRIPTEN */\n default:\n return NULL;\n }\n return c->riscv_cpu_init(mem_map);\n}\n#endif /* CONFIG_RISCV_MAX_XLEN == MAX_XLEN */\n\n"], ["/linuxpdf/tinyemu/vga.c", "/*\n * Dummy VGA device\n * \n * Copyright (c) 2003-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n//#define DEBUG_VBE\n\n#define MSR_COLOR_EMULATION 0x01\n#define MSR_PAGE_SELECT 0x20\n\n#define ST01_V_RETRACE 0x08\n#define ST01_DISP_ENABLE 0x01\n\n#define VBE_DISPI_INDEX_ID 0x0\n#define VBE_DISPI_INDEX_XRES 0x1\n#define VBE_DISPI_INDEX_YRES 0x2\n#define VBE_DISPI_INDEX_BPP 0x3\n#define VBE_DISPI_INDEX_ENABLE 0x4\n#define VBE_DISPI_INDEX_BANK 0x5\n#define VBE_DISPI_INDEX_VIRT_WIDTH 0x6\n#define VBE_DISPI_INDEX_VIRT_HEIGHT 0x7\n#define VBE_DISPI_INDEX_X_OFFSET 0x8\n#define VBE_DISPI_INDEX_Y_OFFSET 0x9\n#define VBE_DISPI_INDEX_VIDEO_MEMORY_64K 0xa\n#define VBE_DISPI_INDEX_NB 0xb\n\n#define VBE_DISPI_ID0 0xB0C0\n#define VBE_DISPI_ID1 0xB0C1\n#define VBE_DISPI_ID2 0xB0C2\n#define VBE_DISPI_ID3 0xB0C3\n#define VBE_DISPI_ID4 0xB0C4\n#define VBE_DISPI_ID5 0xB0C5\n\n#define VBE_DISPI_DISABLED 0x00\n#define VBE_DISPI_ENABLED 0x01\n#define VBE_DISPI_GETCAPS 0x02\n#define VBE_DISPI_8BIT_DAC 0x20\n#define VBE_DISPI_LFB_ENABLED 0x40\n#define VBE_DISPI_NOCLEARMEM 0x80\n\n#define FB_ALLOC_ALIGN (1 << 20)\n\n#define MAX_TEXT_WIDTH 132\n#define MAX_TEXT_HEIGHT 60\n\nstruct VGAState {\n FBDevice *fb_dev;\n int fb_page_count;\n PhysMemoryRange *mem_range;\n PhysMemoryRange *mem_range2;\n PCIDevice *pci_dev;\n PhysMemoryRange *rom_range;\n\n uint8_t *vga_ram; /* 128K at 0xa0000 */\n \n uint8_t sr_index;\n uint8_t sr[8];\n uint8_t gr_index;\n uint8_t gr[16];\n uint8_t ar_index;\n uint8_t ar[21];\n int ar_flip_flop;\n uint8_t cr_index;\n uint8_t cr[256]; /* CRT registers */\n uint8_t msr; /* Misc Output Register */\n uint8_t fcr; /* Feature Control Register */\n uint8_t st00; /* status 0 */\n uint8_t st01; /* status 1 */\n uint8_t dac_state;\n uint8_t dac_sub_index;\n uint8_t dac_read_index;\n uint8_t dac_write_index;\n uint8_t dac_cache[3]; /* used when writing */\n uint8_t palette[768];\n \n /* text mode state */\n uint32_t last_palette[16];\n uint16_t last_ch_attr[MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT];\n uint32_t last_width;\n uint32_t last_height;\n uint16_t last_line_offset;\n uint16_t last_start_addr;\n uint16_t last_cursor_offset;\n uint8_t last_cursor_start;\n uint8_t last_cursor_end;\n \n /* VBE extension */\n uint16_t vbe_index;\n uint16_t vbe_regs[VBE_DISPI_INDEX_NB];\n};\n\nstatic void vga_draw_glyph8(uint8_t *d, int linesize,\n const uint8_t *font_ptr, int h,\n uint32_t fgcol, uint32_t bgcol)\n{\n uint32_t font_data, xorcol;\n\n xorcol = bgcol ^ fgcol;\n do {\n font_data = font_ptr[0];\n ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol;\n ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[7] = (-((font_data >> 0) & 1) & xorcol) ^ bgcol;\n font_ptr++;\n d += linesize;\n } while (--h);\n}\n\nstatic void vga_draw_glyph9(uint8_t *d, int linesize,\n const uint8_t *font_ptr, int h,\n uint32_t fgcol, uint32_t bgcol,\n int dup9)\n{\n uint32_t font_data, xorcol, v;\n\n xorcol = bgcol ^ fgcol;\n do {\n font_data = font_ptr[0];\n ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol;\n ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol;\n v = (-((font_data >> 0) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[7] = v;\n if (dup9)\n ((uint32_t *)d)[8] = v;\n else\n ((uint32_t *)d)[8] = bgcol;\n font_ptr++;\n d += linesize;\n } while (--h);\n}\n\nstatic const uint8_t cursor_glyph[32] = {\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n};\n\nstatic inline int c6_to_8(int v)\n{\n int b;\n v &= 0x3f;\n b = v & 1;\n return (v << 2) | (b << 1) | b;\n}\n\nstatic int update_palette16(VGAState *s, uint32_t *palette)\n{\n int full_update, i;\n uint32_t v, col;\n\n full_update = 0;\n for(i = 0; i < 16; i++) {\n v = s->ar[i];\n if (s->ar[0x10] & 0x80)\n v = ((s->ar[0x14] & 0xf) << 4) | (v & 0xf);\n else\n v = ((s->ar[0x14] & 0xc) << 4) | (v & 0x3f);\n v = v * 3;\n col = (c6_to_8(s->palette[v]) << 16) |\n (c6_to_8(s->palette[v + 1]) << 8) |\n c6_to_8(s->palette[v + 2]);\n if (col != palette[i]) {\n full_update = 1;\n palette[i] = col;\n }\n }\n return full_update;\n}\n\n/* the text refresh is just for debugging and initial boot message, so\n it is very incomplete */\nstatic void vga_text_refresh(VGAState *s,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n FBDevice *fb_dev = s->fb_dev;\n int width, height, cwidth, cheight, cy, cx, x1, y1, width1, height1;\n int cx_min, cx_max, dup9;\n uint32_t ch_attr, line_offset, start_addr, ch_addr, ch_addr1, ch, cattr;\n uint8_t *vga_ram, *font_ptr, *dst;\n uint32_t fgcol, bgcol, cursor_offset, cursor_start, cursor_end;\n BOOL full_update;\n\n full_update = update_palette16(s, s->last_palette);\n\n vga_ram = s->vga_ram;\n \n line_offset = s->cr[0x13];\n line_offset <<= 3;\n line_offset >>= 1;\n\n start_addr = s->cr[0x0d] | (s->cr[0x0c] << 8);\n \n cheight = (s->cr[9] & 0x1f) + 1;\n cwidth = 8;\n if (!(s->sr[1] & 0x01))\n cwidth++;\n \n width = (s->cr[0x01] + 1);\n height = s->cr[0x12] |\n ((s->cr[0x07] & 0x02) << 7) |\n ((s->cr[0x07] & 0x40) << 3);\n height = (height + 1) / cheight;\n \n width1 = width * cwidth;\n height1 = height * cheight;\n if (fb_dev->width < width1 || fb_dev->height < height1 ||\n width > MAX_TEXT_WIDTH || height > MAX_TEXT_HEIGHT)\n return; /* not enough space */\n if (s->last_line_offset != line_offset ||\n s->last_start_addr != start_addr ||\n s->last_width != width ||\n s->last_height != height) {\n s->last_line_offset = line_offset;\n s->last_start_addr = start_addr;\n s->last_width = width;\n s->last_height = height;\n full_update = TRUE;\n }\n \n /* update cursor position */\n cursor_offset = ((s->cr[0x0e] << 8) | s->cr[0x0f]) - start_addr;\n cursor_start = s->cr[0xa];\n cursor_end = s->cr[0xb];\n if (cursor_offset != s->last_cursor_offset ||\n cursor_start != s->last_cursor_start ||\n cursor_end != s->last_cursor_end) {\n /* force refresh of characters with the cursor */\n if (s->last_cursor_offset < MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT)\n s->last_ch_attr[s->last_cursor_offset] = -1;\n if (cursor_offset < MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT)\n s->last_ch_attr[cursor_offset] = -1;\n s->last_cursor_offset = cursor_offset;\n s->last_cursor_start = cursor_start;\n s->last_cursor_end = cursor_end;\n }\n\n ch_addr1 = 0x18000 + (start_addr * 2);\n cursor_offset = 0x18000 + (start_addr + cursor_offset) * 2;\n \n x1 = (fb_dev->width - width1) / 2;\n y1 = (fb_dev->height - height1) / 2;\n#if 0\n printf(\"text refresh %dx%d font=%dx%d start_addr=0x%x line_offset=0x%x\\n\",\n width, height, cwidth, cheight, start_addr, line_offset);\n#endif\n for(cy = 0; cy < height; cy++) {\n ch_addr = ch_addr1;\n dst = fb_dev->fb_data + (y1 + cy * cheight) * fb_dev->stride + x1 * 4;\n cx_min = width;\n cx_max = -1;\n for(cx = 0; cx < width; cx++) {\n ch_attr = *(uint16_t *)(vga_ram + (ch_addr & 0x1fffe));\n if (full_update || ch_attr != s->last_ch_attr[cy * width + cx]) {\n s->last_ch_attr[cy * width + cx] = ch_attr;\n cx_min = min_int(cx_min, cx);\n cx_max = max_int(cx_max, cx);\n ch = ch_attr & 0xff;\n cattr = ch_attr >> 8;\n font_ptr = vga_ram + 32 * ch;\n bgcol = s->last_palette[cattr >> 4];\n fgcol = s->last_palette[cattr & 0x0f];\n if (cwidth == 8) {\n vga_draw_glyph8(dst, fb_dev->stride, font_ptr, cheight,\n fgcol, bgcol);\n } else {\n dup9 = 0;\n if (ch >= 0xb0 && ch <= 0xdf && (s->ar[0x10] & 0x04))\n dup9 = 1;\n vga_draw_glyph9(dst, fb_dev->stride, font_ptr, cheight,\n fgcol, bgcol, dup9);\n }\n /* cursor display */\n if (cursor_offset == ch_addr && !(cursor_start & 0x20)) {\n int line_start, line_last, h;\n uint8_t *dst1;\n line_start = cursor_start & 0x1f;\n line_last = min_int(cursor_end & 0x1f, cheight - 1);\n\n if (line_last >= line_start && line_start < cheight) {\n h = line_last - line_start + 1;\n dst1 = dst + fb_dev->stride * line_start;\n if (cwidth == 8) {\n vga_draw_glyph8(dst1, fb_dev->stride,\n cursor_glyph,\n h, fgcol, bgcol);\n } else {\n vga_draw_glyph9(dst1, fb_dev->stride,\n cursor_glyph,\n h, fgcol, bgcol, 1);\n }\n }\n }\n }\n ch_addr += 2;\n dst += 4 * cwidth;\n }\n if (cx_max >= cx_min) {\n // printf(\"redraw %d %d %d\\n\", cy, cx_min, cx_max);\n redraw_func(fb_dev, opaque,\n x1 + cx_min * cwidth, y1 + cy * cheight,\n (cx_max - cx_min + 1) * cwidth, cheight);\n }\n ch_addr1 += line_offset;\n }\n}\n\nstatic void vga_refresh(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n VGAState *s = fb_dev->device_opaque;\n\n if (!(s->ar_index & 0x20)) {\n /* blank */\n } else if (s->gr[0x06] & 1) {\n /* graphic mode (VBE) */\n simplefb_refresh(fb_dev, redraw_func, opaque, s->mem_range, s->fb_page_count);\n } else {\n /* text mode */\n vga_text_refresh(s, redraw_func, opaque);\n }\n}\n\n/* force some bits to zero */\nstatic const uint8_t sr_mask[8] = {\n (uint8_t)~0xfc,\n (uint8_t)~0xc2,\n (uint8_t)~0xf0,\n (uint8_t)~0xc0,\n (uint8_t)~0xf1,\n (uint8_t)~0xff,\n (uint8_t)~0xff,\n (uint8_t)~0x00,\n};\n\nstatic const uint8_t gr_mask[16] = {\n (uint8_t)~0xf0, /* 0x00 */\n (uint8_t)~0xf0, /* 0x01 */\n (uint8_t)~0xf0, /* 0x02 */\n (uint8_t)~0xe0, /* 0x03 */\n (uint8_t)~0xfc, /* 0x04 */\n (uint8_t)~0x84, /* 0x05 */\n (uint8_t)~0xf0, /* 0x06 */\n (uint8_t)~0xf0, /* 0x07 */\n (uint8_t)~0x00, /* 0x08 */\n (uint8_t)~0xff, /* 0x09 */\n (uint8_t)~0xff, /* 0x0a */\n (uint8_t)~0xff, /* 0x0b */\n (uint8_t)~0xff, /* 0x0c */\n (uint8_t)~0xff, /* 0x0d */\n (uint8_t)~0xff, /* 0x0e */\n (uint8_t)~0xff, /* 0x0f */\n};\n\nstatic uint32_t vga_ioport_read(VGAState *s, uint32_t addr)\n{\n int val, index;\n\n /* check port range access depending on color/monochrome mode */\n if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION)) ||\n (addr >= 0x3d0 && addr <= 0x3df && !(s->msr & MSR_COLOR_EMULATION))) {\n val = 0xff;\n } else {\n switch(addr) {\n case 0x3c0:\n if (s->ar_flip_flop == 0) {\n val = s->ar_index;\n } else {\n val = 0;\n }\n break;\n case 0x3c1:\n index = s->ar_index & 0x1f;\n if (index < 21)\n val = s->ar[index];\n else\n val = 0;\n break;\n case 0x3c2:\n val = s->st00;\n break;\n case 0x3c4:\n val = s->sr_index;\n break;\n case 0x3c5:\n val = s->sr[s->sr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n break;\n case 0x3c7:\n val = s->dac_state;\n break;\n\tcase 0x3c8:\n\t val = s->dac_write_index;\n\t break;\n case 0x3c9:\n val = s->palette[s->dac_read_index * 3 + s->dac_sub_index];\n if (++s->dac_sub_index == 3) {\n s->dac_sub_index = 0;\n s->dac_read_index++;\n }\n break;\n case 0x3ca:\n val = s->fcr;\n break;\n case 0x3cc:\n val = s->msr;\n break;\n case 0x3ce:\n val = s->gr_index;\n break;\n case 0x3cf:\n val = s->gr[s->gr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n break;\n case 0x3b4:\n case 0x3d4:\n val = s->cr_index;\n break;\n case 0x3b5:\n case 0x3d5:\n val = s->cr[s->cr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n break;\n case 0x3ba:\n case 0x3da:\n /* just toggle to fool polling */\n s->st01 ^= ST01_V_RETRACE | ST01_DISP_ENABLE;\n val = s->st01;\n s->ar_flip_flop = 0;\n break;\n default:\n val = 0x00;\n break;\n }\n }\n#if defined(DEBUG_VGA)\n printf(\"VGA: read addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n return val;\n}\n\nstatic void vga_ioport_write(VGAState *s, uint32_t addr, uint32_t val)\n{\n int index;\n\n /* check port range access depending on color/monochrome mode */\n if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION)) ||\n (addr >= 0x3d0 && addr <= 0x3df && !(s->msr & MSR_COLOR_EMULATION)))\n return;\n\n#ifdef DEBUG_VGA\n printf(\"VGA: write addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n\n switch(addr) {\n case 0x3c0:\n if (s->ar_flip_flop == 0) {\n val &= 0x3f;\n s->ar_index = val;\n } else {\n index = s->ar_index & 0x1f;\n switch(index) {\n case 0x00 ... 0x0f:\n s->ar[index] = val & 0x3f;\n break;\n case 0x10:\n s->ar[index] = val & ~0x10;\n break;\n case 0x11:\n s->ar[index] = val;\n break;\n case 0x12:\n s->ar[index] = val & ~0xc0;\n break;\n case 0x13:\n s->ar[index] = val & ~0xf0;\n break;\n case 0x14:\n s->ar[index] = val & ~0xf0;\n break;\n default:\n break;\n }\n }\n s->ar_flip_flop ^= 1;\n break;\n case 0x3c2:\n s->msr = val & ~0x10;\n break;\n case 0x3c4:\n s->sr_index = val & 7;\n break;\n case 0x3c5:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n s->sr[s->sr_index] = val & sr_mask[s->sr_index];\n break;\n case 0x3c7:\n s->dac_read_index = val;\n s->dac_sub_index = 0;\n s->dac_state = 3;\n break;\n case 0x3c8:\n s->dac_write_index = val;\n s->dac_sub_index = 0;\n s->dac_state = 0;\n break;\n case 0x3c9:\n s->dac_cache[s->dac_sub_index] = val;\n if (++s->dac_sub_index == 3) {\n memcpy(&s->palette[s->dac_write_index * 3], s->dac_cache, 3);\n s->dac_sub_index = 0;\n s->dac_write_index++;\n }\n break;\n case 0x3ce:\n s->gr_index = val & 0x0f;\n break;\n case 0x3cf:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n s->gr[s->gr_index] = val & gr_mask[s->gr_index];\n break;\n case 0x3b4:\n case 0x3d4:\n s->cr_index = val;\n break;\n case 0x3b5:\n case 0x3d5:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n /* handle CR0-7 protection */\n if ((s->cr[0x11] & 0x80) && s->cr_index <= 7) {\n /* can always write bit 4 of CR7 */\n if (s->cr_index == 7)\n s->cr[7] = (s->cr[7] & ~0x10) | (val & 0x10);\n return;\n }\n switch(s->cr_index) {\n case 0x01: /* horizontal display end */\n case 0x07:\n case 0x09:\n case 0x0c:\n case 0x0d:\n case 0x12: /* vertical display end */\n s->cr[s->cr_index] = val;\n break;\n default:\n s->cr[s->cr_index] = val;\n break;\n }\n break;\n case 0x3ba:\n case 0x3da:\n s->fcr = val & 0x10;\n break;\n }\n}\n\n#define VGA_IO(base) \\\nstatic uint32_t vga_read_ ## base(void *opaque, uint32_t addr, int size_log2)\\\n{\\\n return vga_ioport_read(opaque, base + addr);\\\n}\\\nstatic void vga_write_ ## base(void *opaque, uint32_t addr, uint32_t val, int size_log2)\\\n{\\\n return vga_ioport_write(opaque, base + addr, val);\\\n}\n\nVGA_IO(0x3c0)\nVGA_IO(0x3b4)\nVGA_IO(0x3d4)\nVGA_IO(0x3ba)\nVGA_IO(0x3da)\n\nstatic void vbe_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n VGAState *s = opaque;\n FBDevice *fb_dev = s->fb_dev;\n \n if (offset == 0) {\n s->vbe_index = val;\n } else {\n#ifdef DEBUG_VBE\n printf(\"VBE write: index=0x%04x val=0x%04x\\n\", s->vbe_index, val);\n#endif\n switch(s->vbe_index) {\n case VBE_DISPI_INDEX_ID:\n if (val >= VBE_DISPI_ID0 && val <= VBE_DISPI_ID5)\n s->vbe_regs[s->vbe_index] = val;\n break;\n case VBE_DISPI_INDEX_ENABLE:\n if ((val & VBE_DISPI_ENABLED) &&\n !(s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED)) {\n /* set graphic mode */\n /* XXX: resolution change not really supported */\n if (s->vbe_regs[VBE_DISPI_INDEX_XRES] <= 4096 &&\n s->vbe_regs[VBE_DISPI_INDEX_YRES] <= 4096 &&\n (s->vbe_regs[VBE_DISPI_INDEX_XRES] * 4 *\n s->vbe_regs[VBE_DISPI_INDEX_YRES]) <= fb_dev->fb_size) {\n fb_dev->width = s->vbe_regs[VBE_DISPI_INDEX_XRES];\n fb_dev->height = s->vbe_regs[VBE_DISPI_INDEX_YRES];\n fb_dev->stride = fb_dev->width * 4;\n }\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] =\n s->vbe_regs[VBE_DISPI_INDEX_XRES];\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_HEIGHT] =\n s->vbe_regs[VBE_DISPI_INDEX_YRES];\n s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET] = 0;\n s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET] = 0;\n }\n s->vbe_regs[s->vbe_index] = val;\n break;\n case VBE_DISPI_INDEX_XRES:\n case VBE_DISPI_INDEX_YRES:\n case VBE_DISPI_INDEX_BPP:\n case VBE_DISPI_INDEX_BANK:\n case VBE_DISPI_INDEX_VIRT_WIDTH:\n case VBE_DISPI_INDEX_VIRT_HEIGHT:\n case VBE_DISPI_INDEX_X_OFFSET:\n case VBE_DISPI_INDEX_Y_OFFSET:\n s->vbe_regs[s->vbe_index] = val;\n break;\n }\n }\n}\n\nstatic uint32_t vbe_read(void *opaque, uint32_t offset, int size_log2)\n{\n VGAState *s = opaque;\n uint32_t val;\n\n if (offset == 0) {\n val = s->vbe_index;\n } else {\n if (s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_GETCAPS) {\n switch(s->vbe_index) {\n case VBE_DISPI_INDEX_XRES:\n val = s->fb_dev->width;\n break;\n case VBE_DISPI_INDEX_YRES:\n val = s->fb_dev->height;\n break;\n case VBE_DISPI_INDEX_BPP:\n val = 32;\n break;\n default:\n goto read_reg;\n }\n } else {\n read_reg:\n if (s->vbe_index < VBE_DISPI_INDEX_NB)\n val = s->vbe_regs[s->vbe_index];\n else\n val = 0;\n }\n#ifdef DEBUG_VBE\n printf(\"VBE read: index=0x%04x val=0x%04x\\n\", s->vbe_index, val);\n#endif\n }\n return val;\n}\n\n\nstatic void simplefb_bar_set(void *opaque, int bar_num,\n uint32_t addr, BOOL enabled)\n{\n VGAState *s = opaque;\n if (bar_num == 0)\n phys_mem_set_addr(s->mem_range, addr, enabled);\n else\n phys_mem_set_addr(s->rom_range, addr, enabled);\n}\n\nVGAState *pci_vga_init(PCIBus *bus, FBDevice *fb_dev,\n int width, int height,\n const uint8_t *vga_rom_buf, int vga_rom_size)\n{\n VGAState *s;\n PCIDevice *d;\n uint32_t bar_size;\n PhysMemoryMap *mem_map, *port_map;\n \n d = pci_register_device(bus, \"VGA\", -1, 0x1234, 0x1111, 0x00, 0x0300);\n \n mem_map = pci_device_get_mem_map(d);\n port_map = pci_device_get_port_map(d);\n\n s = mallocz(sizeof(*s));\n s->fb_dev = fb_dev;\n \n fb_dev->width = width;\n fb_dev->height = height;\n fb_dev->stride = width * 4;\n\n fb_dev->fb_size = (height * fb_dev->stride + FB_ALLOC_ALIGN - 1) & ~(FB_ALLOC_ALIGN - 1);\n s->fb_page_count = fb_dev->fb_size >> DEVRAM_PAGE_SIZE_LOG2;\n\n s->mem_range =\n cpu_register_ram(mem_map, 0, fb_dev->fb_size,\n DEVRAM_FLAG_DIRTY_BITS | DEVRAM_FLAG_DISABLED);\n \n fb_dev->fb_data = s->mem_range->phys_mem;\n\n s->pci_dev = d;\n bar_size = 1;\n while (bar_size < fb_dev->fb_size)\n bar_size <<= 1;\n pci_register_bar(d, 0, bar_size, PCI_ADDRESS_SPACE_MEM, s,\n simplefb_bar_set);\n\n if (vga_rom_size > 0) {\n int rom_size;\n /* align to page size */\n rom_size = (vga_rom_size + DEVRAM_PAGE_SIZE - 1) & ~(DEVRAM_PAGE_SIZE - 1);\n s->rom_range = cpu_register_ram(mem_map, 0, rom_size,\n DEVRAM_FLAG_ROM | DEVRAM_FLAG_DISABLED);\n memcpy(s->rom_range->phys_mem, vga_rom_buf, vga_rom_size);\n\n bar_size = 1;\n while (bar_size < rom_size)\n bar_size <<= 1;\n pci_register_bar(d, PCI_ROM_SLOT, bar_size, PCI_ADDRESS_SPACE_MEM, s,\n simplefb_bar_set);\n }\n\n /* VGA memory (for simple text mode no need for callbacks) */\n s->mem_range2 = cpu_register_ram(mem_map, 0xa0000, 0x20000, 0);\n s->vga_ram = s->mem_range2->phys_mem;\n \n /* standard VGA ports */\n \n cpu_register_device(port_map, 0x3c0, 16, s, vga_read_0x3c0, vga_write_0x3c0,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3b4, 2, s, vga_read_0x3b4, vga_write_0x3b4,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3d4, 2, s, vga_read_0x3d4, vga_write_0x3d4,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3ba, 1, s, vga_read_0x3ba, vga_write_0x3ba,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3da, 1, s, vga_read_0x3da, vga_write_0x3da,\n DEVIO_SIZE8);\n \n /* VBE extension */\n cpu_register_device(port_map, 0x1ce, 2, s, vbe_read, vbe_write, \n DEVIO_SIZE16);\n \n s->vbe_regs[VBE_DISPI_INDEX_ID] = VBE_DISPI_ID5;\n s->vbe_regs[VBE_DISPI_INDEX_VIDEO_MEMORY_64K] = fb_dev->fb_size >> 16;\n\n fb_dev->device_opaque = s;\n fb_dev->refresh = vga_refresh;\n return s;\n}\n"], ["/linuxpdf/tinyemu/virtio.c", "/*\n * VIRTIO driver\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"virtio.h\"\n\n//#define DEBUG_VIRTIO\n\n/* MMIO addresses - from the Linux kernel */\n#define VIRTIO_MMIO_MAGIC_VALUE\t\t0x000\n#define VIRTIO_MMIO_VERSION\t\t0x004\n#define VIRTIO_MMIO_DEVICE_ID\t\t0x008\n#define VIRTIO_MMIO_VENDOR_ID\t\t0x00c\n#define VIRTIO_MMIO_DEVICE_FEATURES\t0x010\n#define VIRTIO_MMIO_DEVICE_FEATURES_SEL\t0x014\n#define VIRTIO_MMIO_DRIVER_FEATURES\t0x020\n#define VIRTIO_MMIO_DRIVER_FEATURES_SEL\t0x024\n#define VIRTIO_MMIO_GUEST_PAGE_SIZE\t0x028 /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_SEL\t\t0x030\n#define VIRTIO_MMIO_QUEUE_NUM_MAX\t0x034\n#define VIRTIO_MMIO_QUEUE_NUM\t\t0x038\n#define VIRTIO_MMIO_QUEUE_ALIGN\t\t0x03c /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_PFN\t\t0x040 /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_READY\t\t0x044\n#define VIRTIO_MMIO_QUEUE_NOTIFY\t0x050\n#define VIRTIO_MMIO_INTERRUPT_STATUS\t0x060\n#define VIRTIO_MMIO_INTERRUPT_ACK\t0x064\n#define VIRTIO_MMIO_STATUS\t\t0x070\n#define VIRTIO_MMIO_QUEUE_DESC_LOW\t0x080\n#define VIRTIO_MMIO_QUEUE_DESC_HIGH\t0x084\n#define VIRTIO_MMIO_QUEUE_AVAIL_LOW\t0x090\n#define VIRTIO_MMIO_QUEUE_AVAIL_HIGH\t0x094\n#define VIRTIO_MMIO_QUEUE_USED_LOW\t0x0a0\n#define VIRTIO_MMIO_QUEUE_USED_HIGH\t0x0a4\n#define VIRTIO_MMIO_CONFIG_GENERATION\t0x0fc\n#define VIRTIO_MMIO_CONFIG\t\t0x100\n\n/* PCI registers */\n#define VIRTIO_PCI_DEVICE_FEATURE_SEL\t0x000\n#define VIRTIO_PCI_DEVICE_FEATURE\t0x004\n#define VIRTIO_PCI_GUEST_FEATURE_SEL\t0x008\n#define VIRTIO_PCI_GUEST_FEATURE\t0x00c\n#define VIRTIO_PCI_MSIX_CONFIG 0x010\n#define VIRTIO_PCI_NUM_QUEUES 0x012\n#define VIRTIO_PCI_DEVICE_STATUS 0x014\n#define VIRTIO_PCI_CONFIG_GENERATION 0x015\n#define VIRTIO_PCI_QUEUE_SEL\t\t0x016\n#define VIRTIO_PCI_QUEUE_SIZE\t 0x018\n#define VIRTIO_PCI_QUEUE_MSIX_VECTOR 0x01a\n#define VIRTIO_PCI_QUEUE_ENABLE 0x01c\n#define VIRTIO_PCI_QUEUE_NOTIFY_OFF 0x01e\n#define VIRTIO_PCI_QUEUE_DESC_LOW\t0x020\n#define VIRTIO_PCI_QUEUE_DESC_HIGH\t0x024\n#define VIRTIO_PCI_QUEUE_AVAIL_LOW\t0x028\n#define VIRTIO_PCI_QUEUE_AVAIL_HIGH\t0x02c\n#define VIRTIO_PCI_QUEUE_USED_LOW\t0x030\n#define VIRTIO_PCI_QUEUE_USED_HIGH\t0x034\n\n#define VIRTIO_PCI_CFG_OFFSET 0x0000\n#define VIRTIO_PCI_ISR_OFFSET 0x1000\n#define VIRTIO_PCI_CONFIG_OFFSET 0x2000\n#define VIRTIO_PCI_NOTIFY_OFFSET 0x3000\n\n#define VIRTIO_PCI_CAP_LEN 16\n\n#define MAX_QUEUE 8\n#define MAX_CONFIG_SPACE_SIZE 256\n#define MAX_QUEUE_NUM 16\n\ntypedef struct {\n uint32_t ready; /* 0 or 1 */\n uint32_t num;\n uint16_t last_avail_idx;\n virtio_phys_addr_t desc_addr;\n virtio_phys_addr_t avail_addr;\n virtio_phys_addr_t used_addr;\n BOOL manual_recv; /* if TRUE, the device_recv() callback is not called */\n} QueueState;\n\n#define VRING_DESC_F_NEXT\t1\n#define VRING_DESC_F_WRITE\t2\n#define VRING_DESC_F_INDIRECT\t4\n\ntypedef struct {\n uint64_t addr;\n uint32_t len;\n uint16_t flags; /* VRING_DESC_F_x */\n uint16_t next;\n} VIRTIODesc;\n\n/* return < 0 to stop the notification (it must be manually restarted\n later), 0 if OK */\ntypedef int VIRTIODeviceRecvFunc(VIRTIODevice *s1, int queue_idx,\n int desc_idx, int read_size,\n int write_size);\n\n/* return NULL if no RAM at this address. The mapping is valid for one page */\ntypedef uint8_t *VIRTIOGetRAMPtrFunc(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw);\n\nstruct VIRTIODevice {\n PhysMemoryMap *mem_map;\n PhysMemoryRange *mem_range;\n /* PCI only */\n PCIDevice *pci_dev;\n /* MMIO only */\n IRQSignal *irq;\n VIRTIOGetRAMPtrFunc *get_ram_ptr;\n int debug;\n\n uint32_t int_status;\n uint32_t status;\n uint32_t device_features_sel;\n uint32_t queue_sel; /* currently selected queue */\n QueueState queue[MAX_QUEUE];\n\n /* device specific */\n uint32_t device_id;\n uint32_t vendor_id;\n uint32_t device_features;\n VIRTIODeviceRecvFunc *device_recv;\n void (*config_write)(VIRTIODevice *s); /* called after the config\n is written */\n uint32_t config_space_size; /* in bytes, must be multiple of 4 */\n uint8_t config_space[MAX_CONFIG_SPACE_SIZE];\n};\n\nstatic uint32_t virtio_mmio_read(void *opaque, uint32_t offset1, int size_log2);\nstatic void virtio_mmio_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t virtio_pci_read(void *opaque, uint32_t offset, int size_log2);\nstatic void virtio_pci_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\n\nstatic void virtio_reset(VIRTIODevice *s)\n{\n int i;\n\n s->status = 0;\n s->queue_sel = 0;\n s->device_features_sel = 0;\n s->int_status = 0;\n for(i = 0; i < MAX_QUEUE; i++) {\n QueueState *qs = &s->queue[i];\n qs->ready = 0;\n qs->num = MAX_QUEUE_NUM;\n qs->desc_addr = 0;\n qs->avail_addr = 0;\n qs->used_addr = 0;\n qs->last_avail_idx = 0;\n }\n}\n\nstatic uint8_t *virtio_pci_get_ram_ptr(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw)\n{\n return pci_device_get_dma_ptr(s->pci_dev, paddr, is_rw);\n}\n\nstatic uint8_t *virtio_mmio_get_ram_ptr(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(s->mem_map, paddr, is_rw);\n}\n\nstatic void virtio_add_pci_capability(VIRTIODevice *s, int cfg_type,\n int bar, uint32_t offset, uint32_t len,\n uint32_t mult)\n{\n uint8_t cap[20];\n int cap_len;\n if (cfg_type == 2)\n cap_len = 20;\n else\n cap_len = 16;\n memset(cap, 0, cap_len);\n cap[0] = 0x09; /* vendor specific */\n cap[2] = cap_len; /* set by pci_add_capability() */\n cap[3] = cfg_type;\n cap[4] = bar;\n put_le32(cap + 8, offset);\n put_le32(cap + 12, len);\n if (cfg_type == 2)\n put_le32(cap + 16, mult);\n pci_add_capability(s->pci_dev, cap, cap_len);\n}\n\nstatic void virtio_pci_bar_set(void *opaque, int bar_num,\n uint32_t addr, BOOL enabled)\n{\n VIRTIODevice *s = opaque;\n phys_mem_set_addr(s->mem_range, addr, enabled);\n}\n\nstatic void virtio_init(VIRTIODevice *s, VIRTIOBusDef *bus,\n uint32_t device_id, int config_space_size,\n VIRTIODeviceRecvFunc *device_recv)\n{\n memset(s, 0, sizeof(*s));\n\n if (bus->pci_bus) {\n uint16_t pci_device_id, class_id;\n char name[32];\n int bar_num;\n \n switch(device_id) {\n case 1:\n pci_device_id = 0x1000; /* net */\n class_id = 0x0200;\n break;\n case 2:\n pci_device_id = 0x1001; /* block */\n class_id = 0x0100; /* XXX: check it */\n break;\n case 3:\n pci_device_id = 0x1003; /* console */\n class_id = 0x0780;\n break;\n case 9:\n pci_device_id = 0x1040 + device_id; /* use new device ID */\n class_id = 0x2;\n break;\n case 18:\n pci_device_id = 0x1040 + device_id; /* use new device ID */\n class_id = 0x0980;\n break;\n default:\n abort();\n }\n snprintf(name, sizeof(name), \"virtio_%04x\", pci_device_id);\n s->pci_dev = pci_register_device(bus->pci_bus, name, -1,\n 0x1af4, pci_device_id, 0x00,\n class_id);\n pci_device_set_config16(s->pci_dev, 0x2c, 0x1af4);\n pci_device_set_config16(s->pci_dev, 0x2e, device_id);\n pci_device_set_config8(s->pci_dev, PCI_INTERRUPT_PIN, 1);\n\n bar_num = 4;\n virtio_add_pci_capability(s, 1, bar_num,\n VIRTIO_PCI_CFG_OFFSET, 0x1000, 0); /* common */\n virtio_add_pci_capability(s, 3, bar_num,\n VIRTIO_PCI_ISR_OFFSET, 0x1000, 0); /* isr */\n virtio_add_pci_capability(s, 4, bar_num,\n VIRTIO_PCI_CONFIG_OFFSET, 0x1000, 0); /* config */\n virtio_add_pci_capability(s, 2, bar_num,\n VIRTIO_PCI_NOTIFY_OFFSET, 0x1000, 0); /* notify */\n \n s->get_ram_ptr = virtio_pci_get_ram_ptr;\n s->irq = pci_device_get_irq(s->pci_dev, 0);\n s->mem_map = pci_device_get_mem_map(s->pci_dev);\n s->mem_range = cpu_register_device(s->mem_map, 0, 0x4000, s,\n virtio_pci_read, virtio_pci_write,\n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32 | DEVIO_DISABLED);\n pci_register_bar(s->pci_dev, bar_num, 0x4000, PCI_ADDRESS_SPACE_MEM,\n s, virtio_pci_bar_set);\n } else {\n /* MMIO case */\n s->mem_map = bus->mem_map;\n s->irq = bus->irq;\n s->mem_range = cpu_register_device(s->mem_map, bus->addr, VIRTIO_PAGE_SIZE,\n s, virtio_mmio_read, virtio_mmio_write,\n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32);\n s->get_ram_ptr = virtio_mmio_get_ram_ptr;\n }\n\n s->device_id = device_id;\n s->vendor_id = 0xffff;\n s->config_space_size = config_space_size;\n s->device_recv = device_recv;\n virtio_reset(s);\n}\n\nstatic uint16_t virtio_read16(VIRTIODevice *s, virtio_phys_addr_t addr)\n{\n uint8_t *ptr;\n if (addr & 1)\n return 0; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, FALSE);\n if (!ptr)\n return 0;\n return *(uint16_t *)ptr;\n}\n\nstatic void virtio_write16(VIRTIODevice *s, virtio_phys_addr_t addr,\n uint16_t val)\n{\n uint8_t *ptr;\n if (addr & 1)\n return; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return;\n *(uint16_t *)ptr = val;\n}\n\nstatic void virtio_write32(VIRTIODevice *s, virtio_phys_addr_t addr,\n uint32_t val)\n{\n uint8_t *ptr;\n if (addr & 3)\n return; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return;\n *(uint32_t *)ptr = val;\n}\n\nstatic int virtio_memcpy_from_ram(VIRTIODevice *s, uint8_t *buf,\n virtio_phys_addr_t addr, int count)\n{\n uint8_t *ptr;\n int l;\n\n while (count > 0) {\n l = min_int(count, VIRTIO_PAGE_SIZE - (addr & (VIRTIO_PAGE_SIZE - 1)));\n ptr = s->get_ram_ptr(s, addr, FALSE);\n if (!ptr)\n return -1;\n memcpy(buf, ptr, l);\n addr += l;\n buf += l;\n count -= l;\n }\n return 0;\n}\n\nstatic int virtio_memcpy_to_ram(VIRTIODevice *s, virtio_phys_addr_t addr, \n const uint8_t *buf, int count)\n{\n uint8_t *ptr;\n int l;\n\n while (count > 0) {\n l = min_int(count, VIRTIO_PAGE_SIZE - (addr & (VIRTIO_PAGE_SIZE - 1)));\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return -1;\n memcpy(ptr, buf, l);\n addr += l;\n buf += l;\n count -= l;\n }\n return 0;\n}\n\nstatic int get_desc(VIRTIODevice *s, VIRTIODesc *desc, \n int queue_idx, int desc_idx)\n{\n QueueState *qs = &s->queue[queue_idx];\n return virtio_memcpy_from_ram(s, (void *)desc, qs->desc_addr +\n desc_idx * sizeof(VIRTIODesc),\n sizeof(VIRTIODesc));\n}\n\nstatic int memcpy_to_from_queue(VIRTIODevice *s, uint8_t *buf,\n int queue_idx, int desc_idx,\n int offset, int count, BOOL to_queue)\n{\n VIRTIODesc desc;\n int l, f_write_flag;\n\n if (count == 0)\n return 0;\n\n get_desc(s, &desc, queue_idx, desc_idx);\n\n if (to_queue) {\n f_write_flag = VRING_DESC_F_WRITE;\n /* find the first write descriptor */\n for(;;) {\n if ((desc.flags & VRING_DESC_F_WRITE) == f_write_flag)\n break;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n } else {\n f_write_flag = 0;\n }\n\n /* find the descriptor at offset */\n for(;;) {\n if ((desc.flags & VRING_DESC_F_WRITE) != f_write_flag)\n return -1;\n if (offset < desc.len)\n break;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n offset -= desc.len;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n\n for(;;) {\n l = min_int(count, desc.len - offset);\n if (to_queue)\n virtio_memcpy_to_ram(s, desc.addr + offset, buf, l);\n else\n virtio_memcpy_from_ram(s, buf, desc.addr + offset, l);\n count -= l;\n if (count == 0)\n break;\n offset += l;\n buf += l;\n if (offset == desc.len) {\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n if ((desc.flags & VRING_DESC_F_WRITE) != f_write_flag)\n return -1;\n offset = 0;\n }\n }\n return 0;\n}\n\nstatic int memcpy_from_queue(VIRTIODevice *s, void *buf,\n int queue_idx, int desc_idx,\n int offset, int count)\n{\n return memcpy_to_from_queue(s, buf, queue_idx, desc_idx, offset, count,\n FALSE);\n}\n\nstatic int memcpy_to_queue(VIRTIODevice *s,\n int queue_idx, int desc_idx,\n int offset, const void *buf, int count)\n{\n return memcpy_to_from_queue(s, (void *)buf, queue_idx, desc_idx, offset,\n count, TRUE);\n}\n\n/* signal that the descriptor has been consumed */\nstatic void virtio_consume_desc(VIRTIODevice *s,\n int queue_idx, int desc_idx, int desc_len)\n{\n QueueState *qs = &s->queue[queue_idx];\n virtio_phys_addr_t addr;\n uint32_t index;\n\n addr = qs->used_addr + 2;\n index = virtio_read16(s, addr);\n virtio_write16(s, addr, index + 1);\n\n addr = qs->used_addr + 4 + (index & (qs->num - 1)) * 8;\n virtio_write32(s, addr, desc_idx);\n virtio_write32(s, addr + 4, desc_len);\n\n s->int_status |= 1;\n set_irq(s->irq, 1);\n}\n\nstatic int get_desc_rw_size(VIRTIODevice *s, \n int *pread_size, int *pwrite_size,\n int queue_idx, int desc_idx)\n{\n VIRTIODesc desc;\n int read_size, write_size;\n\n read_size = 0;\n write_size = 0;\n get_desc(s, &desc, queue_idx, desc_idx);\n\n for(;;) {\n if (desc.flags & VRING_DESC_F_WRITE)\n break;\n read_size += desc.len;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n goto done;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n \n for(;;) {\n if (!(desc.flags & VRING_DESC_F_WRITE))\n return -1;\n write_size += desc.len;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n break;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n\n done:\n *pread_size = read_size;\n *pwrite_size = write_size;\n return 0;\n}\n\n/* XXX: test if the queue is ready ? */\nstatic void queue_notify(VIRTIODevice *s, int queue_idx)\n{\n QueueState *qs = &s->queue[queue_idx];\n uint16_t avail_idx;\n int desc_idx, read_size, write_size;\n\n if (qs->manual_recv)\n return;\n\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n while (qs->last_avail_idx != avail_idx) {\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (!get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx)) {\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"queue_notify: idx=%d read_size=%d write_size=%d\\n\",\n queue_idx, read_size, write_size);\n }\n#endif\n if (s->device_recv(s, queue_idx, desc_idx,\n read_size, write_size) < 0)\n break;\n }\n qs->last_avail_idx++;\n }\n}\n\nstatic uint32_t virtio_config_read(VIRTIODevice *s, uint32_t offset,\n int size_log2)\n{\n uint32_t val;\n switch(size_log2) {\n case 0:\n if (offset < s->config_space_size) {\n val = s->config_space[offset];\n } else {\n val = 0;\n }\n break;\n case 1:\n if (offset < (s->config_space_size - 1)) {\n val = get_le16(&s->config_space[offset]);\n } else {\n val = 0;\n }\n break;\n case 2:\n if (offset < (s->config_space_size - 3)) {\n val = get_le32(s->config_space + offset);\n } else {\n val = 0;\n }\n break;\n default:\n abort();\n }\n return val;\n}\n\nstatic void virtio_config_write(VIRTIODevice *s, uint32_t offset,\n uint32_t val, int size_log2)\n{\n switch(size_log2) {\n case 0:\n if (offset < s->config_space_size) {\n s->config_space[offset] = val;\n if (s->config_write)\n s->config_write(s);\n }\n break;\n case 1:\n if (offset < s->config_space_size - 1) {\n put_le16(s->config_space + offset, val);\n if (s->config_write)\n s->config_write(s);\n }\n break;\n case 2:\n if (offset < s->config_space_size - 3) {\n put_le32(s->config_space + offset, val);\n if (s->config_write)\n s->config_write(s);\n }\n break;\n }\n}\n\nstatic uint32_t virtio_mmio_read(void *opaque, uint32_t offset, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t val;\n\n if (offset >= VIRTIO_MMIO_CONFIG) {\n return virtio_config_read(s, offset - VIRTIO_MMIO_CONFIG, size_log2);\n }\n\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_MMIO_MAGIC_VALUE:\n val = 0x74726976;\n break;\n case VIRTIO_MMIO_VERSION:\n val = 2;\n break;\n case VIRTIO_MMIO_DEVICE_ID:\n val = s->device_id;\n break;\n case VIRTIO_MMIO_VENDOR_ID:\n val = s->vendor_id;\n break;\n case VIRTIO_MMIO_DEVICE_FEATURES:\n switch(s->device_features_sel) {\n case 0:\n val = s->device_features;\n break;\n case 1:\n val = 1; /* version 1 */\n break;\n default:\n val = 0;\n break;\n }\n break;\n case VIRTIO_MMIO_DEVICE_FEATURES_SEL:\n val = s->device_features_sel;\n break;\n case VIRTIO_MMIO_QUEUE_SEL:\n val = s->queue_sel;\n break;\n case VIRTIO_MMIO_QUEUE_NUM_MAX:\n val = MAX_QUEUE_NUM;\n break;\n case VIRTIO_MMIO_QUEUE_NUM:\n val = s->queue[s->queue_sel].num;\n break;\n case VIRTIO_MMIO_QUEUE_DESC_LOW:\n val = s->queue[s->queue_sel].desc_addr;\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_LOW:\n val = s->queue[s->queue_sel].avail_addr;\n break;\n case VIRTIO_MMIO_QUEUE_USED_LOW:\n val = s->queue[s->queue_sel].used_addr;\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_MMIO_QUEUE_DESC_HIGH:\n val = s->queue[s->queue_sel].desc_addr >> 32;\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_HIGH:\n val = s->queue[s->queue_sel].avail_addr >> 32;\n break;\n case VIRTIO_MMIO_QUEUE_USED_HIGH:\n val = s->queue[s->queue_sel].used_addr >> 32;\n break;\n#endif\n case VIRTIO_MMIO_QUEUE_READY:\n val = s->queue[s->queue_sel].ready;\n break;\n case VIRTIO_MMIO_INTERRUPT_STATUS:\n val = s->int_status;\n break;\n case VIRTIO_MMIO_STATUS:\n val = s->status;\n break;\n case VIRTIO_MMIO_CONFIG_GENERATION:\n val = 0;\n break;\n default:\n val = 0;\n break;\n }\n } else {\n val = 0;\n }\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_mmio_read: offset=0x%x val=0x%x size=%d\\n\", \n offset, val, 1 << size_log2);\n }\n#endif\n return val;\n}\n\n#if VIRTIO_ADDR_BITS == 64\nstatic void set_low32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = (*paddr & ~(virtio_phys_addr_t)0xffffffff) | val;\n}\n\nstatic void set_high32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = (*paddr & 0xffffffff) | ((virtio_phys_addr_t)val << 32);\n}\n#else\nstatic void set_low32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = val;\n}\n#endif\n\nstatic void virtio_mmio_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n VIRTIODevice *s = opaque;\n \n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_mmio_write: offset=0x%x val=0x%x size=%d\\n\",\n offset, val, 1 << size_log2);\n }\n#endif\n\n if (offset >= VIRTIO_MMIO_CONFIG) {\n virtio_config_write(s, offset - VIRTIO_MMIO_CONFIG, val, size_log2);\n return;\n }\n\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_MMIO_DEVICE_FEATURES_SEL:\n s->device_features_sel = val;\n break;\n case VIRTIO_MMIO_QUEUE_SEL:\n if (val < MAX_QUEUE)\n s->queue_sel = val;\n break;\n case VIRTIO_MMIO_QUEUE_NUM:\n if ((val & (val - 1)) == 0 && val > 0) {\n s->queue[s->queue_sel].num = val;\n }\n break;\n case VIRTIO_MMIO_QUEUE_DESC_LOW:\n set_low32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_LOW:\n set_low32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_USED_LOW:\n set_low32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_MMIO_QUEUE_DESC_HIGH:\n set_high32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_HIGH:\n set_high32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_USED_HIGH:\n set_high32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#endif\n case VIRTIO_MMIO_STATUS:\n s->status = val;\n if (val == 0) {\n /* reset */\n set_irq(s->irq, 0);\n virtio_reset(s);\n }\n break;\n case VIRTIO_MMIO_QUEUE_READY:\n s->queue[s->queue_sel].ready = val & 1;\n break;\n case VIRTIO_MMIO_QUEUE_NOTIFY:\n if (val < MAX_QUEUE)\n queue_notify(s, val);\n break;\n case VIRTIO_MMIO_INTERRUPT_ACK:\n s->int_status &= ~val;\n if (s->int_status == 0) {\n set_irq(s->irq, 0);\n }\n break;\n }\n }\n}\n\nstatic uint32_t virtio_pci_read(void *opaque, uint32_t offset1, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t offset;\n uint32_t val = 0;\n\n offset = offset1 & 0xfff;\n switch(offset1 >> 12) {\n case VIRTIO_PCI_CFG_OFFSET >> 12:\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_FEATURE:\n switch(s->device_features_sel) {\n case 0:\n val = s->device_features;\n break;\n case 1:\n val = 1; /* version 1 */\n break;\n default:\n val = 0;\n break;\n }\n break;\n case VIRTIO_PCI_DEVICE_FEATURE_SEL:\n val = s->device_features_sel;\n break;\n case VIRTIO_PCI_QUEUE_DESC_LOW:\n val = s->queue[s->queue_sel].desc_addr;\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_LOW:\n val = s->queue[s->queue_sel].avail_addr;\n break;\n case VIRTIO_PCI_QUEUE_USED_LOW:\n val = s->queue[s->queue_sel].used_addr;\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_PCI_QUEUE_DESC_HIGH:\n val = s->queue[s->queue_sel].desc_addr >> 32;\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_HIGH:\n val = s->queue[s->queue_sel].avail_addr >> 32;\n break;\n case VIRTIO_PCI_QUEUE_USED_HIGH:\n val = s->queue[s->queue_sel].used_addr >> 32;\n break;\n#endif\n }\n } else if (size_log2 == 1) {\n switch(offset) {\n case VIRTIO_PCI_NUM_QUEUES:\n val = MAX_QUEUE_NUM;\n break;\n case VIRTIO_PCI_QUEUE_SEL:\n val = s->queue_sel;\n break;\n case VIRTIO_PCI_QUEUE_SIZE:\n val = s->queue[s->queue_sel].num;\n break;\n case VIRTIO_PCI_QUEUE_ENABLE:\n val = s->queue[s->queue_sel].ready;\n break;\n case VIRTIO_PCI_QUEUE_NOTIFY_OFF:\n val = 0;\n break;\n }\n } else if (size_log2 == 0) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_STATUS:\n val = s->status;\n break;\n }\n }\n break;\n case VIRTIO_PCI_ISR_OFFSET >> 12:\n if (offset == 0 && size_log2 == 0) {\n val = s->int_status;\n s->int_status = 0;\n set_irq(s->irq, 0);\n }\n break;\n case VIRTIO_PCI_CONFIG_OFFSET >> 12:\n val = virtio_config_read(s, offset, size_log2);\n break;\n }\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_pci_read: offset=0x%x val=0x%x size=%d\\n\", \n offset1, val, 1 << size_log2);\n }\n#endif\n return val;\n}\n\nstatic void virtio_pci_write(void *opaque, uint32_t offset1,\n uint32_t val, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t offset;\n \n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_pci_write: offset=0x%x val=0x%x size=%d\\n\",\n offset1, val, 1 << size_log2);\n }\n#endif\n offset = offset1 & 0xfff;\n switch(offset1 >> 12) {\n case VIRTIO_PCI_CFG_OFFSET >> 12:\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_FEATURE_SEL:\n s->device_features_sel = val;\n break;\n case VIRTIO_PCI_QUEUE_DESC_LOW:\n set_low32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_LOW:\n set_low32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_USED_LOW:\n set_low32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_PCI_QUEUE_DESC_HIGH:\n set_high32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_HIGH:\n set_high32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_USED_HIGH:\n set_high32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#endif\n }\n } else if (size_log2 == 1) {\n switch(offset) {\n case VIRTIO_PCI_QUEUE_SEL:\n if (val < MAX_QUEUE)\n s->queue_sel = val;\n break;\n case VIRTIO_PCI_QUEUE_SIZE:\n if ((val & (val - 1)) == 0 && val > 0) {\n s->queue[s->queue_sel].num = val;\n }\n break;\n case VIRTIO_PCI_QUEUE_ENABLE:\n s->queue[s->queue_sel].ready = val & 1;\n break;\n }\n } else if (size_log2 == 0) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_STATUS:\n s->status = val;\n if (val == 0) {\n /* reset */\n set_irq(s->irq, 0);\n virtio_reset(s);\n }\n break;\n }\n }\n break;\n case VIRTIO_PCI_CONFIG_OFFSET >> 12:\n virtio_config_write(s, offset, val, size_log2);\n break;\n case VIRTIO_PCI_NOTIFY_OFFSET >> 12:\n if (val < MAX_QUEUE)\n queue_notify(s, val);\n break;\n }\n}\n\nvoid virtio_set_debug(VIRTIODevice *s, int debug)\n{\n s->debug = debug;\n}\n\nstatic void virtio_config_change_notify(VIRTIODevice *s)\n{\n /* INT_CONFIG interrupt */\n s->int_status |= 2;\n set_irq(s->irq, 1);\n}\n\n/*********************************************************************/\n/* block device */\n\ntypedef struct {\n uint32_t type;\n uint8_t *buf;\n int write_size;\n int queue_idx;\n int desc_idx;\n} BlockRequest;\n\ntypedef struct VIRTIOBlockDevice {\n VIRTIODevice common;\n BlockDevice *bs;\n\n BOOL req_in_progress;\n BlockRequest req; /* request in progress */\n} VIRTIOBlockDevice;\n\ntypedef struct {\n uint32_t type;\n uint32_t ioprio;\n uint64_t sector_num;\n} BlockRequestHeader;\n\n#define VIRTIO_BLK_T_IN 0\n#define VIRTIO_BLK_T_OUT 1\n#define VIRTIO_BLK_T_FLUSH 4\n#define VIRTIO_BLK_T_FLUSH_OUT 5\n\n#define VIRTIO_BLK_S_OK 0\n#define VIRTIO_BLK_S_IOERR 1\n#define VIRTIO_BLK_S_UNSUPP 2\n\n#define SECTOR_SIZE 512\n\nstatic void virtio_block_req_end(VIRTIODevice *s, int ret)\n{\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n int write_size;\n int queue_idx = s1->req.queue_idx;\n int desc_idx = s1->req.desc_idx;\n uint8_t *buf, buf1[1];\n\n switch(s1->req.type) {\n case VIRTIO_BLK_T_IN:\n write_size = s1->req.write_size;\n buf = s1->req.buf;\n if (ret < 0) {\n buf[write_size - 1] = VIRTIO_BLK_S_IOERR;\n } else {\n buf[write_size - 1] = VIRTIO_BLK_S_OK;\n }\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, write_size);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, write_size);\n break;\n case VIRTIO_BLK_T_OUT:\n if (ret < 0)\n buf1[0] = VIRTIO_BLK_S_IOERR;\n else\n buf1[0] = VIRTIO_BLK_S_OK;\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf1, sizeof(buf1));\n virtio_consume_desc(s, queue_idx, desc_idx, 1);\n break;\n default:\n abort();\n }\n}\n\nstatic void virtio_block_req_cb(void *opaque, int ret)\n{\n VIRTIODevice *s = opaque;\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n\n virtio_block_req_end(s, ret);\n \n s1->req_in_progress = FALSE;\n\n /* handle next requests */\n queue_notify((VIRTIODevice *)s, s1->req.queue_idx);\n}\n\n/* XXX: handle async I/O */\nstatic int virtio_block_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n BlockDevice *bs = s1->bs;\n BlockRequestHeader h;\n uint8_t *buf;\n int len, ret;\n\n if (s1->req_in_progress)\n return -1;\n \n if (memcpy_from_queue(s, &h, queue_idx, desc_idx, 0, sizeof(h)) < 0)\n return 0;\n s1->req.type = h.type;\n s1->req.queue_idx = queue_idx;\n s1->req.desc_idx = desc_idx;\n switch(h.type) {\n case VIRTIO_BLK_T_IN:\n s1->req.buf = malloc(write_size);\n s1->req.write_size = write_size;\n ret = bs->read_async(bs, h.sector_num, s1->req.buf, \n (write_size - 1) / SECTOR_SIZE,\n virtio_block_req_cb, s);\n if (ret > 0) {\n /* asyncronous read */\n s1->req_in_progress = TRUE;\n } else {\n virtio_block_req_end(s, ret);\n }\n break;\n case VIRTIO_BLK_T_OUT:\n assert(write_size >= 1);\n len = read_size - sizeof(h);\n buf = malloc(len);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, sizeof(h), len);\n ret = bs->write_async(bs, h.sector_num, buf, len / SECTOR_SIZE,\n virtio_block_req_cb, s);\n free(buf);\n if (ret > 0) {\n /* asyncronous write */\n s1->req_in_progress = TRUE;\n } else {\n virtio_block_req_end(s, ret);\n }\n break;\n default:\n break;\n }\n return 0;\n}\n\nVIRTIODevice *virtio_block_init(VIRTIOBusDef *bus, BlockDevice *bs)\n{\n VIRTIOBlockDevice *s;\n uint64_t nb_sectors;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 2, 8, virtio_block_recv_request);\n s->bs = bs;\n \n nb_sectors = bs->get_sector_count(bs);\n put_le32(s->common.config_space, nb_sectors);\n put_le32(s->common.config_space + 4, nb_sectors >> 32);\n\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* network device */\n\ntypedef struct VIRTIONetDevice {\n VIRTIODevice common;\n EthernetDevice *es;\n int header_size;\n} VIRTIONetDevice;\n\ntypedef struct {\n uint8_t flags;\n uint8_t gso_type;\n uint16_t hdr_len;\n uint16_t gso_size;\n uint16_t csum_start;\n uint16_t csum_offset;\n uint16_t num_buffers;\n} VIRTIONetHeader;\n\nstatic int virtio_net_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIONetDevice *s1 = (VIRTIONetDevice *)s;\n EthernetDevice *es = s1->es;\n VIRTIONetHeader h;\n uint8_t *buf;\n int len;\n\n if (queue_idx == 1) {\n /* send to network */\n if (memcpy_from_queue(s, &h, queue_idx, desc_idx, 0, s1->header_size) < 0)\n return 0;\n len = read_size - s1->header_size;\n buf = malloc(len);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, s1->header_size, len);\n es->write_packet(es, buf, len);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\nstatic BOOL virtio_net_can_write_packet(EthernetDevice *es)\n{\n VIRTIODevice *s = es->device_opaque;\n QueueState *qs = &s->queue[0];\n uint16_t avail_idx;\n\n if (!qs->ready)\n return FALSE;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n return qs->last_avail_idx != avail_idx;\n}\n\nstatic void virtio_net_write_packet(EthernetDevice *es, const uint8_t *buf, int buf_len)\n{\n VIRTIODevice *s = es->device_opaque;\n VIRTIONetDevice *s1 = (VIRTIONetDevice *)s;\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n VIRTIONetHeader h;\n int len, read_size, write_size;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx))\n return;\n len = s1->header_size + buf_len; \n if (len > write_size)\n return;\n memset(&h, 0, s1->header_size);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, &h, s1->header_size);\n memcpy_to_queue(s, queue_idx, desc_idx, s1->header_size, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, len);\n qs->last_avail_idx++;\n}\n\nstatic void virtio_net_set_carrier(EthernetDevice *es, BOOL carrier_state)\n{\n#if 0\n VIRTIODevice *s1 = es->device_opaque;\n VIRTIONetDevice *s = (VIRTIONetDevice *)s1;\n int cur_carrier_state;\n\n // printf(\"virtio_net_set_carrier: %d\\n\", carrier_state);\n cur_carrier_state = s->common.config_space[6] & 1;\n if (cur_carrier_state != carrier_state) {\n s->common.config_space[6] = (carrier_state << 0);\n virtio_config_change_notify(s1);\n }\n#endif\n}\n\nVIRTIODevice *virtio_net_init(VIRTIOBusDef *bus, EthernetDevice *es)\n{\n VIRTIONetDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 1, 6 + 2, virtio_net_recv_request);\n /* VIRTIO_NET_F_MAC, VIRTIO_NET_F_STATUS */\n s->common.device_features = (1 << 5) /* | (1 << 16) */;\n s->common.queue[0].manual_recv = TRUE;\n s->es = es;\n memcpy(s->common.config_space, es->mac_addr, 6);\n /* status */\n s->common.config_space[6] = 0;\n s->common.config_space[7] = 0;\n\n s->header_size = sizeof(VIRTIONetHeader);\n \n es->device_opaque = s;\n es->device_can_write_packet = virtio_net_can_write_packet;\n es->device_write_packet = virtio_net_write_packet;\n es->device_set_carrier = virtio_net_set_carrier;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* console device */\n\ntypedef struct VIRTIOConsoleDevice {\n VIRTIODevice common;\n CharacterDevice *cs;\n} VIRTIOConsoleDevice;\n\nstatic int virtio_console_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIOConsoleDevice *s1 = (VIRTIOConsoleDevice *)s;\n CharacterDevice *cs = s1->cs;\n uint8_t *buf;\n\n if (queue_idx == 1) {\n /* send to console */\n buf = malloc(read_size);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, 0, read_size);\n cs->write_data(cs->opaque, buf, read_size);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\nBOOL virtio_console_can_write_data(VIRTIODevice *s)\n{\n QueueState *qs = &s->queue[0];\n uint16_t avail_idx;\n\n if (!qs->ready)\n return FALSE;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n return qs->last_avail_idx != avail_idx;\n}\n\nint virtio_console_get_write_len(VIRTIODevice *s)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n int read_size, write_size;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return 0;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return 0;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx))\n return 0;\n return write_size;\n}\n\nint virtio_console_write_data(VIRTIODevice *s, const uint8_t *buf, int buf_len)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return 0;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return 0;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, buf_len);\n qs->last_avail_idx++;\n return buf_len;\n}\n\n/* send a resize event */\nvoid virtio_console_resize_event(VIRTIODevice *s, int width, int height)\n{\n /* indicate the console size */\n put_le16(s->config_space + 0, width);\n put_le16(s->config_space + 2, height);\n\n virtio_config_change_notify(s);\n}\n\nVIRTIODevice *virtio_console_init(VIRTIOBusDef *bus, CharacterDevice *cs)\n{\n VIRTIOConsoleDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 3, 4, virtio_console_recv_request);\n s->common.device_features = (1 << 0); /* VIRTIO_CONSOLE_F_SIZE */\n s->common.queue[0].manual_recv = TRUE;\n \n s->cs = cs;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* input device */\n\nenum {\n VIRTIO_INPUT_CFG_UNSET = 0x00,\n VIRTIO_INPUT_CFG_ID_NAME = 0x01,\n VIRTIO_INPUT_CFG_ID_SERIAL = 0x02,\n VIRTIO_INPUT_CFG_ID_DEVIDS = 0x03,\n VIRTIO_INPUT_CFG_PROP_BITS = 0x10,\n VIRTIO_INPUT_CFG_EV_BITS = 0x11,\n VIRTIO_INPUT_CFG_ABS_INFO = 0x12,\n};\n\n#define VIRTIO_INPUT_EV_SYN 0x00\n#define VIRTIO_INPUT_EV_KEY 0x01\n#define VIRTIO_INPUT_EV_REL 0x02\n#define VIRTIO_INPUT_EV_ABS 0x03\n#define VIRTIO_INPUT_EV_REP 0x14\n\n#define BTN_LEFT 0x110\n#define BTN_RIGHT 0x111\n#define BTN_MIDDLE 0x112\n#define BTN_GEAR_DOWN 0x150\n#define BTN_GEAR_UP 0x151\n\n#define REL_X 0x00\n#define REL_Y 0x01\n#define REL_Z 0x02\n#define REL_WHEEL 0x08\n\n#define ABS_X 0x00\n#define ABS_Y 0x01\n#define ABS_Z 0x02\n\ntypedef struct VIRTIOInputDevice {\n VIRTIODevice common;\n VirtioInputTypeEnum type;\n uint32_t buttons_state;\n} VIRTIOInputDevice;\n\nstatic const uint16_t buttons_list[] = {\n BTN_LEFT, BTN_RIGHT, BTN_MIDDLE\n};\n\nstatic int virtio_input_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n if (queue_idx == 1) {\n /* led & keyboard updates */\n // printf(\"%s: write_size=%d\\n\", __func__, write_size);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\n/* return < 0 if could not send key event */\nstatic int virtio_input_queue_event(VIRTIODevice *s,\n uint16_t type, uint16_t code,\n uint32_t value)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx, buf_len;\n uint16_t avail_idx;\n uint8_t buf[8];\n\n if (!qs->ready)\n return -1;\n\n put_le16(buf, type);\n put_le16(buf + 2, code);\n put_le32(buf + 4, value);\n buf_len = 8;\n \n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return -1;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n // printf(\"send: queue_idx=%d desc_idx=%d\\n\", queue_idx, desc_idx);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, buf_len);\n qs->last_avail_idx++;\n return 0;\n}\n\nint virtio_input_send_key_event(VIRTIODevice *s, BOOL is_down,\n uint16_t key_code)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n int ret;\n \n if (s1->type != VIRTIO_INPUT_TYPE_KEYBOARD)\n return -1;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_KEY, key_code, is_down);\n if (ret)\n return ret;\n return virtio_input_queue_event(s, VIRTIO_INPUT_EV_SYN, 0, 0);\n}\n\n/* also used for the tablet */\nint virtio_input_send_mouse_event(VIRTIODevice *s, int dx, int dy, int dz,\n unsigned int buttons)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n int ret, i, b, last_b;\n\n if (s1->type != VIRTIO_INPUT_TYPE_MOUSE &&\n s1->type != VIRTIO_INPUT_TYPE_TABLET)\n return -1;\n if (s1->type == VIRTIO_INPUT_TYPE_MOUSE) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_X, dx);\n if (ret != 0)\n return ret;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_Y, dy);\n if (ret != 0)\n return ret;\n } else {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_ABS, ABS_X, dx);\n if (ret != 0)\n return ret;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_ABS, ABS_Y, dy);\n if (ret != 0)\n return ret;\n }\n if (dz != 0) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_WHEEL, dz);\n if (ret != 0)\n return ret;\n }\n\n if (buttons != s1->buttons_state) {\n for(i = 0; i < countof(buttons_list); i++) {\n b = (buttons >> i) & 1;\n last_b = (s1->buttons_state >> i) & 1;\n if (b != last_b) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_KEY,\n buttons_list[i], b);\n if (ret != 0)\n return ret;\n }\n }\n s1->buttons_state = buttons;\n }\n\n return virtio_input_queue_event(s, VIRTIO_INPUT_EV_SYN, 0, 0);\n}\n\nstatic void set_bit(uint8_t *tab, int k)\n{\n tab[k >> 3] |= 1 << (k & 7);\n}\n\nstatic void virtio_input_config_write(VIRTIODevice *s)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n uint8_t *config = s->config_space;\n int i;\n \n // printf(\"config_write: %02x %02x\\n\", config[0], config[1]);\n switch(config[0]) {\n case VIRTIO_INPUT_CFG_UNSET:\n break;\n case VIRTIO_INPUT_CFG_ID_NAME:\n {\n const char *name;\n int len;\n switch(s1->type) {\n case VIRTIO_INPUT_TYPE_KEYBOARD:\n name = \"virtio_keyboard\";\n break;\n case VIRTIO_INPUT_TYPE_MOUSE:\n name = \"virtio_mouse\";\n break;\n case VIRTIO_INPUT_TYPE_TABLET:\n name = \"virtio_tablet\";\n break;\n default:\n abort();\n }\n len = strlen(name);\n config[2] = len;\n memcpy(config + 8, name, len);\n }\n break;\n default:\n case VIRTIO_INPUT_CFG_ID_SERIAL:\n case VIRTIO_INPUT_CFG_ID_DEVIDS:\n case VIRTIO_INPUT_CFG_PROP_BITS:\n config[2] = 0; /* size of reply */\n break;\n case VIRTIO_INPUT_CFG_EV_BITS:\n config[2] = 0;\n switch(s1->type) {\n case VIRTIO_INPUT_TYPE_KEYBOARD:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 128 / 8;\n memset(config + 8, 0xff, 128 / 8); /* bitmap */\n break;\n case VIRTIO_INPUT_EV_REP: /* allow key repetition */\n config[2] = 1;\n break;\n default:\n break;\n }\n break;\n case VIRTIO_INPUT_TYPE_MOUSE:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 512 / 8;\n memset(config + 8, 0, 512 / 8); /* bitmap */\n for(i = 0; i < countof(buttons_list); i++)\n set_bit(config + 8, buttons_list[i]);\n break;\n case VIRTIO_INPUT_EV_REL:\n config[2] = 2;\n config[8] = 0;\n config[9] = 0;\n set_bit(config + 8, REL_X);\n set_bit(config + 8, REL_Y);\n set_bit(config + 8, REL_WHEEL);\n break;\n default:\n break;\n }\n break;\n case VIRTIO_INPUT_TYPE_TABLET:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 512 / 8;\n memset(config + 8, 0, 512 / 8); /* bitmap */\n for(i = 0; i < countof(buttons_list); i++)\n set_bit(config + 8, buttons_list[i]);\n break;\n case VIRTIO_INPUT_EV_REL:\n config[2] = 2;\n config[8] = 0;\n config[9] = 0;\n set_bit(config + 8, REL_WHEEL);\n break;\n case VIRTIO_INPUT_EV_ABS:\n config[2] = 1;\n config[8] = 0;\n set_bit(config + 8, ABS_X);\n set_bit(config + 8, ABS_Y);\n break;\n default:\n break;\n }\n break;\n default:\n abort();\n }\n break;\n case VIRTIO_INPUT_CFG_ABS_INFO:\n if (s1->type == VIRTIO_INPUT_TYPE_TABLET && config[1] <= 1) {\n /* for ABS_X and ABS_Y */\n config[2] = 5 * 4;\n put_le32(config + 8, 0); /* min */\n put_le32(config + 12, VIRTIO_INPUT_ABS_SCALE - 1) ; /* max */\n put_le32(config + 16, 0); /* fuzz */\n put_le32(config + 20, 0); /* flat */\n put_le32(config + 24, 0); /* res */\n }\n break;\n }\n}\n\nVIRTIODevice *virtio_input_init(VIRTIOBusDef *bus, VirtioInputTypeEnum type)\n{\n VIRTIOInputDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 18, 256, virtio_input_recv_request);\n s->common.queue[0].manual_recv = TRUE;\n s->common.device_features = 0;\n s->common.config_write = virtio_input_config_write;\n s->type = type;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* 9p filesystem device */\n\ntypedef struct {\n struct list_head link;\n uint32_t fid;\n FSFile *fd;\n} FIDDesc;\n\ntypedef struct VIRTIO9PDevice {\n VIRTIODevice common;\n FSDevice *fs;\n int msize; /* maximum message size */\n struct list_head fid_list; /* list of FIDDesc */\n BOOL req_in_progress;\n} VIRTIO9PDevice;\n\nstatic FIDDesc *fid_find1(VIRTIO9PDevice *s, uint32_t fid)\n{\n struct list_head *el;\n FIDDesc *f;\n\n list_for_each(el, &s->fid_list) {\n f = list_entry(el, FIDDesc, link);\n if (f->fid == fid)\n return f;\n }\n return NULL;\n}\n\nstatic FSFile *fid_find(VIRTIO9PDevice *s, uint32_t fid)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (!f)\n return NULL;\n return f->fd;\n}\n\nstatic void fid_delete(VIRTIO9PDevice *s, uint32_t fid)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (f) {\n s->fs->fs_delete(s->fs, f->fd);\n list_del(&f->link);\n free(f);\n }\n}\n\nstatic void fid_set(VIRTIO9PDevice *s, uint32_t fid, FSFile *fd)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (f) {\n s->fs->fs_delete(s->fs, f->fd);\n f->fd = fd;\n } else {\n f = malloc(sizeof(*f));\n f->fid = fid;\n f->fd = fd;\n list_add(&f->link, &s->fid_list);\n }\n}\n\n#ifdef DEBUG_VIRTIO\n\ntypedef struct {\n uint8_t tag;\n const char *name;\n} Virtio9POPName;\n\nstatic const Virtio9POPName virtio_9p_op_names[] = {\n { 8, \"statfs\" },\n { 12, \"lopen\" },\n { 14, \"lcreate\" },\n { 16, \"symlink\" },\n { 18, \"mknod\" },\n { 22, \"readlink\" },\n { 24, \"getattr\" },\n { 26, \"setattr\" },\n { 30, \"xattrwalk\" },\n { 40, \"readdir\" },\n { 50, \"fsync\" },\n { 52, \"lock\" },\n { 54, \"getlock\" },\n { 70, \"link\" },\n { 72, \"mkdir\" },\n { 74, \"renameat\" },\n { 76, \"unlinkat\" },\n { 100, \"version\" },\n { 104, \"attach\" },\n { 108, \"flush\" },\n { 110, \"walk\" },\n { 116, \"read\" },\n { 118, \"write\" },\n { 120, \"clunk\" },\n { 0, NULL },\n};\n\nstatic const char *get_9p_op_name(int tag)\n{\n const Virtio9POPName *p;\n for(p = virtio_9p_op_names; p->name != NULL; p++) {\n if (p->tag == tag)\n return p->name;\n }\n return NULL;\n}\n\n#endif /* DEBUG_VIRTIO */\n\nstatic int marshall(VIRTIO9PDevice *s, \n uint8_t *buf1, int max_len, const char *fmt, ...)\n{\n va_list ap;\n int c;\n uint32_t val;\n uint64_t val64;\n uint8_t *buf, *buf_end;\n\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" ->\");\n#endif\n va_start(ap, fmt);\n buf = buf1;\n buf_end = buf1 + max_len;\n for(;;) {\n c = *fmt++;\n if (c == '\\0')\n break;\n switch(c) {\n case 'b':\n assert(buf + 1 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" b=%d\", val);\n#endif\n buf[0] = val;\n buf += 1;\n break;\n case 'h':\n assert(buf + 2 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" h=%d\", val);\n#endif\n put_le16(buf, val);\n buf += 2;\n break;\n case 'w':\n assert(buf + 4 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" w=%d\", val);\n#endif\n put_le32(buf, val);\n buf += 4;\n break;\n case 'd':\n assert(buf + 8 <= buf_end);\n val64 = va_arg(ap, uint64_t);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" d=%\" PRId64, val64);\n#endif\n put_le64(buf, val64);\n buf += 8;\n break;\n case 's':\n {\n char *str;\n int len;\n str = va_arg(ap, char *);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" s=\\\"%s\\\"\", str);\n#endif\n len = strlen(str);\n assert(len <= 65535);\n assert(buf + 2 + len <= buf_end);\n put_le16(buf, len);\n buf += 2;\n memcpy(buf, str, len);\n buf += len;\n }\n break;\n case 'Q':\n {\n FSQID *qid;\n assert(buf + 13 <= buf_end);\n qid = va_arg(ap, FSQID *);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" Q=%d:%d:%\" PRIu64, qid->type, qid->version, qid->path);\n#endif\n buf[0] = qid->type;\n put_le32(buf + 1, qid->version);\n put_le64(buf + 5, qid->path);\n buf += 13;\n }\n break;\n default:\n abort();\n }\n }\n va_end(ap);\n return buf - buf1;\n}\n\n/* return < 0 if error */\n/* XXX: free allocated strings in case of error */\nstatic int unmarshall(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, int *poffset, const char *fmt, ...)\n{\n VIRTIODevice *s1 = (VIRTIODevice *)s;\n va_list ap;\n int offset, c;\n uint8_t buf[16];\n\n offset = *poffset;\n va_start(ap, fmt);\n for(;;) {\n c = *fmt++;\n if (c == '\\0')\n break;\n switch(c) {\n case 'b':\n {\n uint8_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 1))\n return -1;\n ptr = va_arg(ap, uint8_t *);\n *ptr = buf[0];\n offset += 1;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" b=%d\", *ptr);\n#endif\n }\n break;\n case 'h':\n {\n uint16_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 2))\n return -1;\n ptr = va_arg(ap, uint16_t *);\n *ptr = get_le16(buf);\n offset += 2;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" h=%d\", *ptr);\n#endif\n }\n break;\n case 'w':\n {\n uint32_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 4))\n return -1;\n ptr = va_arg(ap, uint32_t *);\n *ptr = get_le32(buf);\n offset += 4;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" w=%d\", *ptr);\n#endif\n }\n break;\n case 'd':\n {\n uint64_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 8))\n return -1;\n ptr = va_arg(ap, uint64_t *);\n *ptr = get_le64(buf);\n offset += 8;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" d=%\" PRId64, *ptr);\n#endif\n }\n break;\n case 's':\n {\n char *str, **ptr;\n int len;\n\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 2))\n return -1;\n len = get_le16(buf);\n offset += 2;\n str = malloc(len + 1);\n if (memcpy_from_queue(s1, str, queue_idx, desc_idx, offset, len))\n return -1;\n str[len] = '\\0';\n offset += len;\n ptr = va_arg(ap, char **);\n *ptr = str;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" s=\\\"%s\\\"\", *ptr);\n#endif\n }\n break;\n default:\n abort();\n }\n }\n va_end(ap);\n *poffset = offset;\n return 0;\n}\n\nstatic void virtio_9p_send_reply(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, uint8_t id, uint16_t tag, \n uint8_t *buf, int buf_len)\n{\n uint8_t *buf1;\n int len;\n\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P) {\n if (id == 6)\n printf(\" (error)\");\n printf(\"\\n\");\n }\n#endif\n len = buf_len + 7;\n buf1 = malloc(len);\n put_le32(buf1, len);\n buf1[4] = id + 1;\n put_le16(buf1 + 5, tag);\n memcpy(buf1 + 7, buf, buf_len);\n memcpy_to_queue((VIRTIODevice *)s, queue_idx, desc_idx, 0, buf1, len);\n virtio_consume_desc((VIRTIODevice *)s, queue_idx, desc_idx, len);\n free(buf1);\n}\n\nstatic void virtio_9p_send_error(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, uint16_t tag, uint32_t error)\n{\n uint8_t buf[4];\n int buf_len;\n\n buf_len = marshall(s, buf, sizeof(buf), \"w\", -error);\n virtio_9p_send_reply(s, queue_idx, desc_idx, 6, tag, buf, buf_len);\n}\n\ntypedef struct {\n VIRTIO9PDevice *dev;\n int queue_idx;\n int desc_idx;\n uint16_t tag;\n} P9OpenInfo;\n\nstatic void virtio_9p_open_reply(FSDevice *fs, FSQID *qid, int err,\n P9OpenInfo *oi)\n{\n VIRTIO9PDevice *s = oi->dev;\n uint8_t buf[32];\n int buf_len;\n \n if (err < 0) {\n virtio_9p_send_error(s, oi->queue_idx, oi->desc_idx, oi->tag, err);\n } else {\n buf_len = marshall(s, buf, sizeof(buf),\n \"Qw\", qid, s->msize - 24);\n virtio_9p_send_reply(s, oi->queue_idx, oi->desc_idx, 12, oi->tag,\n buf, buf_len);\n }\n free(oi);\n}\n\nstatic void virtio_9p_open_cb(FSDevice *fs, FSQID *qid, int err,\n void *opaque)\n{\n P9OpenInfo *oi = opaque;\n VIRTIO9PDevice *s = oi->dev;\n int queue_idx = oi->queue_idx;\n \n virtio_9p_open_reply(fs, qid, err, oi);\n\n s->req_in_progress = FALSE;\n\n /* handle next requests */\n queue_notify((VIRTIODevice *)s, queue_idx);\n}\n\nstatic int virtio_9p_recv_request(VIRTIODevice *s1, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIO9PDevice *s = (VIRTIO9PDevice *)s1;\n int offset, header_len;\n uint8_t id;\n uint16_t tag;\n uint8_t buf[1024];\n int buf_len, err;\n FSDevice *fs = s->fs;\n\n if (queue_idx != 0)\n return 0;\n \n if (s->req_in_progress)\n return -1;\n \n offset = 0;\n header_len = 4 + 1 + 2;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, header_len)) {\n tag = 0;\n goto protocol_error;\n }\n //size = get_le32(buf);\n id = buf[4];\n tag = get_le16(buf + 5);\n offset += header_len;\n \n#ifdef DEBUG_VIRTIO\n if (s1->debug & VIRTIO_DEBUG_9P) {\n const char *name;\n name = get_9p_op_name(id);\n printf(\"9p: op=\");\n if (name)\n printf(\"%s\", name);\n else\n printf(\"%d\", id);\n }\n#endif\n /* Note: same subset as JOR1K */\n switch(id) {\n case 8: /* statfs */\n {\n FSStatFS st;\n\n fs->fs_statfs(fs, &st);\n buf_len = marshall(s, buf, sizeof(buf),\n \"wwddddddw\", \n 0,\n st.f_bsize,\n st.f_blocks,\n st.f_bfree,\n st.f_bavail,\n st.f_files,\n st.f_ffree,\n 0, /* id */\n 256 /* max filename length */\n );\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 12: /* lopen */\n {\n uint32_t fid, flags;\n FSFile *f;\n FSQID qid;\n P9OpenInfo *oi;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"ww\", &fid, &flags))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n oi = malloc(sizeof(*oi));\n oi->dev = s;\n oi->queue_idx = queue_idx;\n oi->desc_idx = desc_idx;\n oi->tag = tag;\n err = fs->fs_open(fs, &qid, f, flags, virtio_9p_open_cb, oi);\n if (err <= 0) {\n virtio_9p_open_reply(fs, &qid, err, oi);\n } else {\n s->req_in_progress = TRUE;\n }\n }\n break;\n case 14: /* lcreate */\n {\n uint32_t fid, flags, mode, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wswww\", &fid, &name, &flags, &mode, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_create(fs, &qid, f, name, flags, mode, gid);\n }\n free(name);\n if (err) \n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Qw\", &qid, s->msize - 24);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 16: /* symlink */\n {\n uint32_t fid, gid;\n char *name, *symgt;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wssw\", &fid, &name, &symgt, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_symlink(fs, &qid, f, name, symgt, gid);\n }\n free(name);\n free(symgt);\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 18: /* mknod */\n {\n uint32_t fid, mode, major, minor, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wswwww\", &fid, &name, &mode, &major, &minor, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_mknod(fs, &qid, f, name, mode, major, minor, gid);\n }\n free(name);\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 22: /* readlink */\n {\n uint32_t fid;\n char buf1[1024];\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"w\", &fid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_readlink(fs, buf1, sizeof(buf1), f);\n }\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"s\", buf1);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 24: /* getattr */\n {\n uint32_t fid;\n uint64_t mask;\n FSFile *f;\n FSStat st;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wd\", &fid, &mask))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_stat(fs, f, &st);\n if (err)\n goto error;\n\n buf_len = marshall(s, buf, sizeof(buf),\n \"dQwwwddddddddddddddd\", \n mask, &st.qid,\n st.st_mode, st.st_uid, st.st_gid,\n st.st_nlink, st.st_rdev, st.st_size,\n st.st_blksize, st.st_blocks,\n st.st_atime_sec, (uint64_t)st.st_atime_nsec,\n st.st_mtime_sec, (uint64_t)st.st_mtime_nsec,\n st.st_ctime_sec, (uint64_t)st.st_ctime_nsec,\n (uint64_t)0, (uint64_t)0,\n (uint64_t)0, (uint64_t)0);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 26: /* setattr */\n {\n uint32_t fid, mask, mode, uid, gid;\n uint64_t size, atime_sec, atime_nsec, mtime_sec, mtime_nsec;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wwwwwddddd\", &fid, &mask, &mode, &uid, &gid,\n &size, &atime_sec, &atime_nsec, \n &mtime_sec, &mtime_nsec))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_setattr(fs, f, mask, mode, uid, gid, size, atime_sec,\n atime_nsec, mtime_sec, mtime_nsec);\n if (err)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 30: /* xattrwalk */\n {\n /* not supported yet */\n err = -P9_ENOTSUP;\n goto error;\n }\n break;\n case 40: /* readdir */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf = malloc(count + 4);\n n = fs->fs_readdir(fs, f, offs, buf + 4, count);\n if (n < 0) {\n err = n;\n goto error;\n }\n put_le32(buf, n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, n + 4);\n free(buf);\n }\n break;\n case 50: /* fsync */\n {\n uint32_t fid;\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"w\", &fid))\n goto protocol_error;\n /* ignored */\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 52: /* lock */\n {\n uint32_t fid;\n FSFile *f;\n FSLock lock;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wbwddws\", &fid, &lock.type, &lock.flags,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n err = -P9_EPROTO;\n else\n err = fs->fs_lock(fs, f, &lock);\n free(lock.client_id);\n if (err < 0)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"b\", err);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 54: /* getlock */\n {\n uint32_t fid;\n FSFile *f;\n FSLock lock;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wbddws\", &fid, &lock.type,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n err = -P9_EPROTO;\n else\n err = fs->fs_getlock(fs, f, &lock);\n if (err < 0) {\n free(lock.client_id);\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"bddws\",\n &lock.type,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id);\n free(lock.client_id);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 70: /* link */\n {\n uint32_t dfid, fid;\n char *name;\n FSFile *f, *df;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wws\", &dfid, &fid, &name))\n goto protocol_error;\n df = fid_find(s, dfid);\n f = fid_find(s, fid);\n if (!df || !f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_link(fs, df, f, name);\n }\n free(name);\n if (err)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 72: /* mkdir */\n {\n uint32_t fid, mode, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsww\", &fid, &name, &mode, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_mkdir(fs, &qid, f, name, mode, gid);\n if (err != 0)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 74: /* renameat */\n {\n uint32_t fid, new_fid;\n char *name, *new_name;\n FSFile *f, *new_f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsws\", &fid, &name, &new_fid, &new_name))\n goto protocol_error;\n f = fid_find(s, fid);\n new_f = fid_find(s, new_fid);\n if (!f || !new_f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_renameat(fs, f, name, new_f, new_name);\n }\n free(name);\n free(new_name);\n if (err != 0)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 76: /* unlinkat */\n {\n uint32_t fid, flags;\n char *name;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsw\", &fid, &name, &flags))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_unlinkat(fs, f, name);\n }\n free(name);\n if (err != 0)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 100: /* version */\n {\n uint32_t msize;\n char *version;\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"ws\", &msize, &version))\n goto protocol_error;\n s->msize = msize;\n // printf(\"version: msize=%d version=%s\\n\", msize, version);\n free(version);\n buf_len = marshall(s, buf, sizeof(buf), \"ws\", s->msize, \"9P2000.L\");\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 104: /* attach */\n {\n uint32_t fid, afid, uid;\n char *uname, *aname;\n FSQID qid;\n FSFile *f;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"wwssw\", &fid, &afid, &uname, &aname, &uid))\n goto protocol_error;\n err = fs->fs_attach(fs, &f, &qid, uid, uname, aname);\n if (err != 0)\n goto error;\n fid_set(s, fid, f);\n free(uname);\n free(aname);\n buf_len = marshall(s, buf, sizeof(buf), \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 108: /* flush */\n {\n uint16_t oldtag;\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"h\", &oldtag))\n goto protocol_error;\n /* ignored */\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 110: /* walk */\n {\n uint32_t fid, newfid;\n uint16_t nwname;\n FSQID *qids;\n char **names;\n FSFile *f;\n int i;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"wwh\", &fid, &newfid, &nwname))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n names = mallocz(sizeof(names[0]) * nwname);\n qids = malloc(sizeof(qids[0]) * nwname);\n for(i = 0; i < nwname; i++) {\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"s\", &names[i])) {\n err = -P9_EPROTO;\n goto walk_done;\n }\n }\n err = fs->fs_walk(fs, &f, qids, f, nwname, names);\n walk_done:\n for(i = 0; i < nwname; i++) {\n free(names[i]);\n }\n free(names);\n if (err < 0) {\n free(qids);\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"h\", err);\n for(i = 0; i < err; i++) {\n buf_len += marshall(s, buf + buf_len, sizeof(buf) - buf_len,\n \"Q\", &qids[i]);\n }\n free(qids);\n fid_set(s, newfid, f);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 116: /* read */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf = malloc(count + 4);\n n = fs->fs_read(fs, f, offs, buf + 4, count);\n if (n < 0) {\n err = n;\n free(buf);\n goto error;\n }\n put_le32(buf, n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, n + 4);\n free(buf);\n }\n break;\n case 118: /* write */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf1;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf1 = malloc(count);\n if (memcpy_from_queue(s1, buf1, queue_idx, desc_idx, offset,\n count)) {\n free(buf1);\n goto protocol_error;\n }\n n = fs->fs_write(fs, f, offs, buf1, count);\n free(buf1);\n if (n < 0) {\n err = n;\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"w\", n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 120: /* clunk */\n {\n uint32_t fid;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"w\", &fid))\n goto protocol_error;\n fid_delete(s, fid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n default:\n printf(\"9p: unsupported operation id=%d\\n\", id);\n goto protocol_error;\n }\n return 0;\n error:\n virtio_9p_send_error(s, queue_idx, desc_idx, tag, err);\n return 0;\n protocol_error:\n fid_not_found:\n err = -P9_EPROTO;\n goto error;\n}\n\nVIRTIODevice *virtio_9p_init(VIRTIOBusDef *bus, FSDevice *fs,\n const char *mount_tag)\n\n{\n VIRTIO9PDevice *s;\n int len;\n uint8_t *cfg;\n\n len = strlen(mount_tag);\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 9, 2 + len, virtio_9p_recv_request);\n s->common.device_features = 1 << 0;\n\n /* set the mount tag */\n cfg = s->common.config_space;\n cfg[0] = len;\n cfg[1] = len >> 8;\n memcpy(cfg + 2, mount_tag, len);\n\n s->fs = fs;\n s->msize = 8192;\n init_list_head(&s->fid_list);\n \n return (VIRTIODevice *)s;\n}\n\n"], ["/linuxpdf/tinyemu/temu.c", "/*\n * TinyEMU\n * \n * Copyright (c) 2016-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifndef _WIN32\n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#ifdef CONFIG_FS_NET\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n#endif\n#ifdef CONFIG_SLIRP\n#include \"slirp/libslirp.h\"\n#endif\n\n#ifndef _WIN32\n\ntypedef struct {\n int stdin_fd;\n int console_esc_state;\n BOOL resize_pending;\n} STDIODevice;\n\nstatic struct termios oldtty;\nstatic int old_fd0_flags;\nstatic STDIODevice *global_stdio_device;\n\nstatic void term_exit(void)\n{\n tcsetattr (0, TCSANOW, &oldtty);\n fcntl(0, F_SETFL, old_fd0_flags);\n}\n\nstatic void term_init(BOOL allow_ctrlc)\n{\n struct termios tty;\n\n memset(&tty, 0, sizeof(tty));\n tcgetattr (0, &tty);\n oldtty = tty;\n old_fd0_flags = fcntl(0, F_GETFL);\n\n tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP\n |INLCR|IGNCR|ICRNL|IXON);\n tty.c_oflag |= OPOST;\n tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);\n if (!allow_ctrlc)\n tty.c_lflag &= ~ISIG;\n tty.c_cflag &= ~(CSIZE|PARENB);\n tty.c_cflag |= CS8;\n tty.c_cc[VMIN] = 1;\n tty.c_cc[VTIME] = 0;\n\n tcsetattr (0, TCSANOW, &tty);\n\n atexit(term_exit);\n}\n\nstatic void console_write(void *opaque, const uint8_t *buf, int len)\n{\n fwrite(buf, 1, len, stdout);\n fflush(stdout);\n}\n\nstatic int console_read(void *opaque, uint8_t *buf, int len)\n{\n STDIODevice *s = opaque;\n int ret, i, j;\n uint8_t ch;\n \n if (len <= 0)\n return 0;\n\n ret = read(s->stdin_fd, buf, len);\n if (ret < 0)\n return 0;\n if (ret == 0) {\n /* EOF */\n exit(1);\n }\n\n j = 0;\n for(i = 0; i < ret; i++) {\n ch = buf[i];\n if (s->console_esc_state) {\n s->console_esc_state = 0;\n switch(ch) {\n case 'x':\n printf(\"Terminated\\n\");\n exit(0);\n case 'h':\n printf(\"\\n\"\n \"C-a h print this help\\n\"\n \"C-a x exit emulator\\n\"\n \"C-a C-a send C-a\\n\"\n );\n break;\n case 1:\n goto output_char;\n default:\n break;\n }\n } else {\n if (ch == 1) {\n s->console_esc_state = 1;\n } else {\n output_char:\n buf[j++] = ch;\n }\n }\n }\n return j;\n}\n\nstatic void term_resize_handler(int sig)\n{\n if (global_stdio_device)\n global_stdio_device->resize_pending = TRUE;\n}\n\nstatic void console_get_size(STDIODevice *s, int *pw, int *ph)\n{\n struct winsize ws;\n int width, height;\n /* default values */\n width = 80;\n height = 25;\n if (ioctl(s->stdin_fd, TIOCGWINSZ, &ws) == 0 &&\n ws.ws_col >= 4 && ws.ws_row >= 4) {\n width = ws.ws_col;\n height = ws.ws_row;\n }\n *pw = width;\n *ph = height;\n}\n\nCharacterDevice *console_init(BOOL allow_ctrlc)\n{\n CharacterDevice *dev;\n STDIODevice *s;\n struct sigaction sig;\n\n term_init(allow_ctrlc);\n\n dev = mallocz(sizeof(*dev));\n s = mallocz(sizeof(*s));\n s->stdin_fd = 0;\n /* Note: the glibc does not properly tests the return value of\n write() in printf, so some messages on stdout may be lost */\n fcntl(s->stdin_fd, F_SETFL, O_NONBLOCK);\n\n s->resize_pending = TRUE;\n global_stdio_device = s;\n \n /* use a signal to get the host terminal resize events */\n sig.sa_handler = term_resize_handler;\n sigemptyset(&sig.sa_mask);\n sig.sa_flags = 0;\n sigaction(SIGWINCH, &sig, NULL);\n \n dev->opaque = s;\n dev->write_data = console_write;\n dev->read_data = console_read;\n return dev;\n}\n\n#endif /* !_WIN32 */\n\ntypedef enum {\n BF_MODE_RO,\n BF_MODE_RW,\n BF_MODE_SNAPSHOT,\n} BlockDeviceModeEnum;\n\n#define SECTOR_SIZE 512\n\ntypedef struct BlockDeviceFile {\n FILE *f;\n int64_t nb_sectors;\n BlockDeviceModeEnum mode;\n uint8_t **sector_table;\n} BlockDeviceFile;\n\nstatic int64_t bf_get_sector_count(BlockDevice *bs)\n{\n BlockDeviceFile *bf = bs->opaque;\n return bf->nb_sectors;\n}\n\n//#define DUMP_BLOCK_READ\n\nstatic int bf_read_async(BlockDevice *bs,\n uint64_t sector_num, uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceFile *bf = bs->opaque;\n // printf(\"bf_read_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n#ifdef DUMP_BLOCK_READ\n {\n static FILE *f;\n if (!f)\n f = fopen(\"/tmp/read_sect.txt\", \"wb\");\n fprintf(f, \"%\" PRId64 \" %d\\n\", sector_num, n);\n }\n#endif\n if (!bf->f)\n return -1;\n if (bf->mode == BF_MODE_SNAPSHOT) {\n int i;\n for(i = 0; i < n; i++) {\n if (!bf->sector_table[sector_num]) {\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fread(buf, 1, SECTOR_SIZE, bf->f);\n } else {\n memcpy(buf, bf->sector_table[sector_num], SECTOR_SIZE);\n }\n sector_num++;\n buf += SECTOR_SIZE;\n }\n } else {\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fread(buf, 1, n * SECTOR_SIZE, bf->f);\n }\n /* synchronous read */\n return 0;\n}\n\nstatic int bf_write_async(BlockDevice *bs,\n uint64_t sector_num, const uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceFile *bf = bs->opaque;\n int ret;\n\n switch(bf->mode) {\n case BF_MODE_RO:\n ret = -1; /* error */\n break;\n case BF_MODE_RW:\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fwrite(buf, 1, n * SECTOR_SIZE, bf->f);\n ret = 0;\n break;\n case BF_MODE_SNAPSHOT:\n {\n int i;\n if ((sector_num + n) > bf->nb_sectors)\n return -1;\n for(i = 0; i < n; i++) {\n if (!bf->sector_table[sector_num]) {\n bf->sector_table[sector_num] = malloc(SECTOR_SIZE);\n }\n memcpy(bf->sector_table[sector_num], buf, SECTOR_SIZE);\n sector_num++;\n buf += SECTOR_SIZE;\n }\n ret = 0;\n }\n break;\n default:\n abort();\n }\n\n return ret;\n}\n\nstatic BlockDevice *block_device_init(const char *filename,\n BlockDeviceModeEnum mode)\n{\n BlockDevice *bs;\n BlockDeviceFile *bf;\n int64_t file_size;\n FILE *f;\n const char *mode_str;\n\n if (mode == BF_MODE_RW) {\n mode_str = \"r+b\";\n } else {\n mode_str = \"rb\";\n }\n \n f = fopen(filename, mode_str);\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n file_size = ftello(f);\n\n bs = mallocz(sizeof(*bs));\n bf = mallocz(sizeof(*bf));\n\n bf->mode = mode;\n bf->nb_sectors = file_size / 512;\n bf->f = f;\n\n if (mode == BF_MODE_SNAPSHOT) {\n bf->sector_table = mallocz(sizeof(bf->sector_table[0]) *\n bf->nb_sectors);\n }\n \n bs->opaque = bf;\n bs->get_sector_count = bf_get_sector_count;\n bs->read_async = bf_read_async;\n bs->write_async = bf_write_async;\n return bs;\n}\n\n#ifndef _WIN32\n\ntypedef struct {\n int fd;\n BOOL select_filled;\n} TunState;\n\nstatic void tun_write_packet(EthernetDevice *net,\n const uint8_t *buf, int len)\n{\n TunState *s = net->opaque;\n write(s->fd, buf, len);\n}\n\nstatic void tun_select_fill(EthernetDevice *net, int *pfd_max,\n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *pdelay)\n{\n TunState *s = net->opaque;\n int net_fd = s->fd;\n\n s->select_filled = net->device_can_write_packet(net);\n if (s->select_filled) {\n FD_SET(net_fd, rfds);\n *pfd_max = max_int(*pfd_max, net_fd);\n }\n}\n\nstatic void tun_select_poll(EthernetDevice *net, \n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int select_ret)\n{\n TunState *s = net->opaque;\n int net_fd = s->fd;\n uint8_t buf[2048];\n int ret;\n \n if (select_ret <= 0)\n return;\n if (s->select_filled && FD_ISSET(net_fd, rfds)) {\n ret = read(net_fd, buf, sizeof(buf));\n if (ret > 0)\n net->device_write_packet(net, buf, ret);\n }\n \n}\n\n/* configure with:\n# bridge configuration (connect tap0 to bridge interface br0)\n ip link add br0 type bridge\n ip tuntap add dev tap0 mode tap [user x] [group x]\n ip link set tap0 master br0\n ip link set dev br0 up\n ip link set dev tap0 up\n\n# NAT configuration (eth1 is the interface connected to internet)\n ifconfig br0 192.168.3.1\n echo 1 > /proc/sys/net/ipv4/ip_forward\n iptables -D FORWARD 1\n iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE\n\n In the VM:\n ifconfig eth0 192.168.3.2\n route add -net 0.0.0.0 netmask 0.0.0.0 gw 192.168.3.1\n*/\nstatic EthernetDevice *tun_open(const char *ifname)\n{\n struct ifreq ifr;\n int fd, ret;\n EthernetDevice *net;\n TunState *s;\n \n fd = open(\"/dev/net/tun\", O_RDWR);\n if (fd < 0) {\n fprintf(stderr, \"Error: could not open /dev/net/tun\\n\");\n return NULL;\n }\n memset(&ifr, 0, sizeof(ifr));\n ifr.ifr_flags = IFF_TAP | IFF_NO_PI;\n pstrcpy(ifr.ifr_name, sizeof(ifr.ifr_name), ifname);\n ret = ioctl(fd, TUNSETIFF, (void *) &ifr);\n if (ret != 0) {\n fprintf(stderr, \"Error: could not configure /dev/net/tun\\n\");\n close(fd);\n return NULL;\n }\n fcntl(fd, F_SETFL, O_NONBLOCK);\n\n net = mallocz(sizeof(*net));\n net->mac_addr[0] = 0x02;\n net->mac_addr[1] = 0x00;\n net->mac_addr[2] = 0x00;\n net->mac_addr[3] = 0x00;\n net->mac_addr[4] = 0x00;\n net->mac_addr[5] = 0x01;\n s = mallocz(sizeof(*s));\n s->fd = fd;\n net->opaque = s;\n net->write_packet = tun_write_packet;\n net->select_fill = tun_select_fill;\n net->select_poll = tun_select_poll;\n return net;\n}\n\n#endif /* !_WIN32 */\n\n#ifdef CONFIG_SLIRP\n\n/*******************************************************/\n/* slirp */\n\nstatic Slirp *slirp_state;\n\nstatic void slirp_write_packet(EthernetDevice *net,\n const uint8_t *buf, int len)\n{\n Slirp *slirp_state = net->opaque;\n slirp_input(slirp_state, buf, len);\n}\n\nint slirp_can_output(void *opaque)\n{\n EthernetDevice *net = opaque;\n return net->device_can_write_packet(net);\n}\n\nvoid slirp_output(void *opaque, const uint8_t *pkt, int pkt_len)\n{\n EthernetDevice *net = opaque;\n return net->device_write_packet(net, pkt, pkt_len);\n}\n\nstatic void slirp_select_fill1(EthernetDevice *net, int *pfd_max,\n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *pdelay)\n{\n Slirp *slirp_state = net->opaque;\n slirp_select_fill(slirp_state, pfd_max, rfds, wfds, efds);\n}\n\nstatic void slirp_select_poll1(EthernetDevice *net, \n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int select_ret)\n{\n Slirp *slirp_state = net->opaque;\n slirp_select_poll(slirp_state, rfds, wfds, efds, (select_ret <= 0));\n}\n\nstatic EthernetDevice *slirp_open(void)\n{\n EthernetDevice *net;\n struct in_addr net_addr = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */\n struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */\n struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */\n struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */\n struct in_addr dns = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */\n const char *bootfile = NULL;\n const char *vhostname = NULL;\n int restricted = 0;\n \n if (slirp_state) {\n fprintf(stderr, \"Only a single slirp instance is allowed\\n\");\n return NULL;\n }\n net = mallocz(sizeof(*net));\n\n slirp_state = slirp_init(restricted, net_addr, mask, host, vhostname,\n \"\", bootfile, dhcp, dns, net);\n \n net->mac_addr[0] = 0x02;\n net->mac_addr[1] = 0x00;\n net->mac_addr[2] = 0x00;\n net->mac_addr[3] = 0x00;\n net->mac_addr[4] = 0x00;\n net->mac_addr[5] = 0x01;\n net->opaque = slirp_state;\n net->write_packet = slirp_write_packet;\n net->select_fill = slirp_select_fill1;\n net->select_poll = slirp_select_poll1;\n \n return net;\n}\n\n#endif /* CONFIG_SLIRP */\n\n#define MAX_EXEC_CYCLE 500000\n#define MAX_SLEEP_TIME 10 /* in ms */\n\nvoid virt_machine_run(VirtMachine *m)\n{\n fd_set rfds, wfds, efds;\n int fd_max, ret, delay;\n struct timeval tv;\n#ifndef _WIN32\n int stdin_fd;\n#endif\n \n delay = virt_machine_get_sleep_duration(m, MAX_SLEEP_TIME);\n \n /* wait for an event */\n FD_ZERO(&rfds);\n FD_ZERO(&wfds);\n FD_ZERO(&efds);\n fd_max = -1;\n#ifndef _WIN32\n if (m->console_dev && virtio_console_can_write_data(m->console_dev)) {\n STDIODevice *s = m->console->opaque;\n stdin_fd = s->stdin_fd;\n FD_SET(stdin_fd, &rfds);\n fd_max = stdin_fd;\n\n if (s->resize_pending) {\n int width, height;\n console_get_size(s, &width, &height);\n virtio_console_resize_event(m->console_dev, width, height);\n s->resize_pending = FALSE;\n }\n }\n#endif\n if (m->net) {\n m->net->select_fill(m->net, &fd_max, &rfds, &wfds, &efds, &delay);\n }\n#ifdef CONFIG_FS_NET\n fs_net_set_fdset(&fd_max, &rfds, &wfds, &efds, &delay);\n#endif\n tv.tv_sec = delay / 1000;\n tv.tv_usec = (delay % 1000) * 1000;\n ret = select(fd_max + 1, &rfds, &wfds, &efds, &tv);\n if (m->net) {\n m->net->select_poll(m->net, &rfds, &wfds, &efds, ret);\n }\n if (ret > 0) {\n#ifndef _WIN32\n if (m->console_dev && FD_ISSET(stdin_fd, &rfds)) {\n uint8_t buf[128];\n int ret, len;\n len = virtio_console_get_write_len(m->console_dev);\n len = min_int(len, sizeof(buf));\n ret = m->console->read_data(m->console->opaque, buf, len);\n if (ret > 0) {\n virtio_console_write_data(m->console_dev, buf, ret);\n }\n }\n#endif\n }\n\n#ifdef CONFIG_SDL\n sdl_refresh(m);\n#endif\n \n virt_machine_interp(m, MAX_EXEC_CYCLE);\n}\n\n/*******************************************************/\n\nstatic struct option options[] = {\n { \"help\", no_argument, NULL, 'h' },\n { \"ctrlc\", no_argument },\n { \"rw\", no_argument },\n { \"ro\", no_argument },\n { \"append\", required_argument },\n { \"no-accel\", no_argument },\n { \"build-preload\", required_argument },\n { NULL },\n};\n\nvoid help(void)\n{\n printf(\"temu version \" CONFIG_VERSION \", Copyright (c) 2016-2018 Fabrice Bellard\\n\"\n \"usage: riscvemu [options] config_file\\n\"\n \"options are:\\n\"\n \"-m ram_size set the RAM size in MB\\n\"\n \"-rw allow write access to the disk image (default=snapshot)\\n\"\n \"-ctrlc the C-c key stops the emulator instead of being sent to the\\n\"\n \" emulated software\\n\"\n \"-append cmdline append cmdline to the kernel command line\\n\"\n \"-no-accel disable VM acceleration (KVM, x86 machine only)\\n\"\n \"\\n\"\n \"Console keys:\\n\"\n \"Press C-a x to exit the emulator, C-a h to get some help.\\n\");\n exit(1);\n}\n\n#ifdef CONFIG_FS_NET\nstatic BOOL net_completed;\n\nstatic void net_start_cb(void *arg)\n{\n net_completed = TRUE;\n}\n\nstatic BOOL net_poll_cb(void *arg)\n{\n return net_completed;\n}\n\n#endif\n\nint main(int argc, char **argv)\n{\n VirtMachine *s;\n const char *path, *cmdline, *build_preload_file;\n int c, option_index, i, ram_size, accel_enable;\n BOOL allow_ctrlc;\n BlockDeviceModeEnum drive_mode;\n VirtMachineParams p_s, *p = &p_s;\n\n ram_size = -1;\n allow_ctrlc = FALSE;\n (void)allow_ctrlc;\n drive_mode = BF_MODE_SNAPSHOT;\n accel_enable = -1;\n cmdline = NULL;\n build_preload_file = NULL;\n for(;;) {\n c = getopt_long_only(argc, argv, \"hm:\", options, &option_index);\n if (c == -1)\n break;\n switch(c) {\n case 0:\n switch(option_index) {\n case 1: /* ctrlc */\n allow_ctrlc = TRUE;\n break;\n case 2: /* rw */\n drive_mode = BF_MODE_RW;\n break;\n case 3: /* ro */\n drive_mode = BF_MODE_RO;\n break;\n case 4: /* append */\n cmdline = optarg;\n break;\n case 5: /* no-accel */\n accel_enable = FALSE;\n break;\n case 6: /* build-preload */\n build_preload_file = optarg;\n break;\n default:\n fprintf(stderr, \"unknown option index: %d\\n\", option_index);\n exit(1);\n }\n break;\n case 'h':\n help();\n break;\n case 'm':\n ram_size = strtoul(optarg, NULL, 0);\n break;\n default:\n exit(1);\n }\n }\n\n if (optind >= argc) {\n help();\n }\n\n path = argv[optind++];\n\n virt_machine_set_defaults(p);\n#ifdef CONFIG_FS_NET\n fs_wget_init();\n#endif\n virt_machine_load_config_file(p, path, NULL, NULL);\n#ifdef CONFIG_FS_NET\n fs_net_event_loop(NULL, NULL);\n#endif\n\n /* override some config parameters */\n\n if (ram_size > 0) {\n p->ram_size = (uint64_t)ram_size << 20;\n }\n if (accel_enable != -1)\n p->accel_enable = accel_enable;\n if (cmdline) {\n vm_add_cmdline(p, cmdline);\n }\n \n /* open the files & devices */\n for(i = 0; i < p->drive_count; i++) {\n BlockDevice *drive;\n char *fname;\n fname = get_file_path(p->cfg_filename, p->tab_drive[i].filename);\n#ifdef CONFIG_FS_NET\n if (is_url(fname)) {\n net_completed = FALSE;\n drive = block_device_init_http(fname, 128 * 1024,\n net_start_cb, NULL);\n /* wait until the drive is initialized */\n fs_net_event_loop(net_poll_cb, NULL);\n } else\n#endif\n {\n drive = block_device_init(fname, drive_mode);\n }\n free(fname);\n p->tab_drive[i].block_dev = drive;\n }\n\n for(i = 0; i < p->fs_count; i++) {\n FSDevice *fs;\n const char *path;\n path = p->tab_fs[i].filename;\n#ifdef CONFIG_FS_NET\n if (is_url(path)) {\n fs = fs_net_init(path, NULL, NULL);\n if (!fs)\n exit(1);\n if (build_preload_file)\n fs_dump_cache_load(fs, build_preload_file);\n fs_net_event_loop(NULL, NULL);\n } else\n#endif\n {\n#ifdef _WIN32\n fprintf(stderr, \"Filesystem access not supported yet\\n\");\n exit(1);\n#else\n char *fname;\n fname = get_file_path(p->cfg_filename, path);\n fs = fs_disk_init(fname);\n if (!fs) {\n fprintf(stderr, \"%s: must be a directory\\n\", fname);\n exit(1);\n }\n free(fname);\n#endif\n }\n p->tab_fs[i].fs_dev = fs;\n }\n\n for(i = 0; i < p->eth_count; i++) {\n#ifdef CONFIG_SLIRP\n if (!strcmp(p->tab_eth[i].driver, \"user\")) {\n p->tab_eth[i].net = slirp_open();\n if (!p->tab_eth[i].net)\n exit(1);\n } else\n#endif\n#ifndef _WIN32\n if (!strcmp(p->tab_eth[i].driver, \"tap\")) {\n p->tab_eth[i].net = tun_open(p->tab_eth[i].ifname);\n if (!p->tab_eth[i].net)\n exit(1);\n } else\n#endif\n {\n fprintf(stderr, \"Unsupported network driver '%s'\\n\",\n p->tab_eth[i].driver);\n exit(1);\n }\n }\n \n#ifdef CONFIG_SDL\n if (p->display_device) {\n sdl_init(p->width, p->height);\n } else\n#endif\n {\n#ifdef _WIN32\n fprintf(stderr, \"Console not supported yet\\n\");\n exit(1);\n#else\n p->console = console_init(allow_ctrlc);\n#endif\n }\n p->rtc_real_time = TRUE;\n\n s = virt_machine_init(p);\n if (!s)\n exit(1);\n \n virt_machine_free_config(p);\n\n if (s->net) {\n s->net->device_set_carrier(s->net, TRUE);\n }\n \n for(;;) {\n virt_machine_run(s);\n }\n virt_machine_end(s);\n return 0;\n}\n"], ["/linuxpdf/tinyemu/ide.c", "/*\n * IDE emulation\n * \n * Copyright (c) 2003-2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"ide.h\"\n\n//#define DEBUG_IDE\n\n/* Bits of HD_STATUS */\n#define ERR_STAT\t\t0x01\n#define INDEX_STAT\t\t0x02\n#define ECC_STAT\t\t0x04\t/* Corrected error */\n#define DRQ_STAT\t\t0x08\n#define SEEK_STAT\t\t0x10\n#define SRV_STAT\t\t0x10\n#define WRERR_STAT\t\t0x20\n#define READY_STAT\t\t0x40\n#define BUSY_STAT\t\t0x80\n\n/* Bits for HD_ERROR */\n#define MARK_ERR\t\t0x01\t/* Bad address mark */\n#define TRK0_ERR\t\t0x02\t/* couldn't find track 0 */\n#define ABRT_ERR\t\t0x04\t/* Command aborted */\n#define MCR_ERR\t\t\t0x08\t/* media change request */\n#define ID_ERR\t\t\t0x10\t/* ID field not found */\n#define MC_ERR\t\t\t0x20\t/* media changed */\n#define ECC_ERR\t\t\t0x40\t/* Uncorrectable ECC error */\n#define BBD_ERR\t\t\t0x80\t/* pre-EIDE meaning: block marked bad */\n#define ICRC_ERR\t\t0x80\t/* new meaning: CRC error during transfer */\n\n/* Bits of HD_NSECTOR */\n#define CD\t\t\t0x01\n#define IO\t\t\t0x02\n#define REL\t\t\t0x04\n#define TAG_MASK\t\t0xf8\n\n#define IDE_CMD_RESET 0x04\n#define IDE_CMD_DISABLE_IRQ 0x02\n\n/* ATA/ATAPI Commands pre T13 Spec */\n#define WIN_NOP\t\t\t\t0x00\n/*\n *\t0x01->0x02 Reserved\n */\n#define CFA_REQ_EXT_ERROR_CODE\t\t0x03 /* CFA Request Extended Error Code */\n/*\n *\t0x04->0x07 Reserved\n */\n#define WIN_SRST\t\t\t0x08 /* ATAPI soft reset command */\n#define WIN_DEVICE_RESET\t\t0x08\n/*\n *\t0x09->0x0F Reserved\n */\n#define WIN_RECAL\t\t\t0x10\n#define WIN_RESTORE\t\t\tWIN_RECAL\n/*\n *\t0x10->0x1F Reserved\n */\n#define WIN_READ\t\t\t0x20 /* 28-Bit */\n#define WIN_READ_ONCE\t\t\t0x21 /* 28-Bit without retries */\n#define WIN_READ_LONG\t\t\t0x22 /* 28-Bit */\n#define WIN_READ_LONG_ONCE\t\t0x23 /* 28-Bit without retries */\n#define WIN_READ_EXT\t\t\t0x24 /* 48-Bit */\n#define WIN_READDMA_EXT\t\t\t0x25 /* 48-Bit */\n#define WIN_READDMA_QUEUED_EXT\t\t0x26 /* 48-Bit */\n#define WIN_READ_NATIVE_MAX_EXT\t\t0x27 /* 48-Bit */\n/*\n *\t0x28\n */\n#define WIN_MULTREAD_EXT\t\t0x29 /* 48-Bit */\n/*\n *\t0x2A->0x2F Reserved\n */\n#define WIN_WRITE\t\t\t0x30 /* 28-Bit */\n#define WIN_WRITE_ONCE\t\t\t0x31 /* 28-Bit without retries */\n#define WIN_WRITE_LONG\t\t\t0x32 /* 28-Bit */\n#define WIN_WRITE_LONG_ONCE\t\t0x33 /* 28-Bit without retries */\n#define WIN_WRITE_EXT\t\t\t0x34 /* 48-Bit */\n#define WIN_WRITEDMA_EXT\t\t0x35 /* 48-Bit */\n#define WIN_WRITEDMA_QUEUED_EXT\t\t0x36 /* 48-Bit */\n#define WIN_SET_MAX_EXT\t\t\t0x37 /* 48-Bit */\n#define CFA_WRITE_SECT_WO_ERASE\t\t0x38 /* CFA Write Sectors without erase */\n#define WIN_MULTWRITE_EXT\t\t0x39 /* 48-Bit */\n/*\n *\t0x3A->0x3B Reserved\n */\n#define WIN_WRITE_VERIFY\t\t0x3C /* 28-Bit */\n/*\n *\t0x3D->0x3F Reserved\n */\n#define WIN_VERIFY\t\t\t0x40 /* 28-Bit - Read Verify Sectors */\n#define WIN_VERIFY_ONCE\t\t\t0x41 /* 28-Bit - without retries */\n#define WIN_VERIFY_EXT\t\t\t0x42 /* 48-Bit */\n/*\n *\t0x43->0x4F Reserved\n */\n#define WIN_FORMAT\t\t\t0x50\n/*\n *\t0x51->0x5F Reserved\n */\n#define WIN_INIT\t\t\t0x60\n/*\n *\t0x61->0x5F Reserved\n */\n#define WIN_SEEK\t\t\t0x70 /* 0x70-0x7F Reserved */\n#define CFA_TRANSLATE_SECTOR\t\t0x87 /* CFA Translate Sector */\n#define WIN_DIAGNOSE\t\t\t0x90\n#define WIN_SPECIFY\t\t\t0x91 /* set drive geometry translation */\n#define WIN_DOWNLOAD_MICROCODE\t\t0x92\n#define WIN_STANDBYNOW2\t\t\t0x94\n#define WIN_STANDBY2\t\t\t0x96\n#define WIN_SETIDLE2\t\t\t0x97\n#define WIN_CHECKPOWERMODE2\t\t0x98\n#define WIN_SLEEPNOW2\t\t\t0x99\n/*\n *\t0x9A VENDOR\n */\n#define WIN_PACKETCMD\t\t\t0xA0 /* Send a packet command. */\n#define WIN_PIDENTIFY\t\t\t0xA1 /* identify ATAPI device\t*/\n#define WIN_QUEUED_SERVICE\t\t0xA2\n#define WIN_SMART\t\t\t0xB0 /* self-monitoring and reporting */\n#define CFA_ERASE_SECTORS \t0xC0\n#define WIN_MULTREAD\t\t\t0xC4 /* read sectors using multiple mode*/\n#define WIN_MULTWRITE\t\t\t0xC5 /* write sectors using multiple mode */\n#define WIN_SETMULT\t\t\t0xC6 /* enable/disable multiple mode */\n#define WIN_READDMA_QUEUED\t\t0xC7 /* read sectors using Queued DMA transfers */\n#define WIN_READDMA\t\t\t0xC8 /* read sectors using DMA transfers */\n#define WIN_READDMA_ONCE\t\t0xC9 /* 28-Bit - without retries */\n#define WIN_WRITEDMA\t\t\t0xCA /* write sectors using DMA transfers */\n#define WIN_WRITEDMA_ONCE\t\t0xCB /* 28-Bit - without retries */\n#define WIN_WRITEDMA_QUEUED\t\t0xCC /* write sectors using Queued DMA transfers */\n#define CFA_WRITE_MULTI_WO_ERASE\t0xCD /* CFA Write multiple without erase */\n#define WIN_GETMEDIASTATUS\t\t0xDA\t\n#define WIN_ACKMEDIACHANGE\t\t0xDB /* ATA-1, ATA-2 vendor */\n#define WIN_POSTBOOT\t\t\t0xDC\n#define WIN_PREBOOT\t\t\t0xDD\n#define WIN_DOORLOCK\t\t\t0xDE /* lock door on removable drives */\n#define WIN_DOORUNLOCK\t\t\t0xDF /* unlock door on removable drives */\n#define WIN_STANDBYNOW1\t\t\t0xE0\n#define WIN_IDLEIMMEDIATE\t\t0xE1 /* force drive to become \"ready\" */\n#define WIN_STANDBY \t0xE2 /* Set device in Standby Mode */\n#define WIN_SETIDLE1\t\t\t0xE3\n#define WIN_READ_BUFFER\t\t\t0xE4 /* force read only 1 sector */\n#define WIN_CHECKPOWERMODE1\t\t0xE5\n#define WIN_SLEEPNOW1\t\t\t0xE6\n#define WIN_FLUSH_CACHE\t\t\t0xE7\n#define WIN_WRITE_BUFFER\t\t0xE8 /* force write only 1 sector */\n#define WIN_WRITE_SAME\t\t\t0xE9 /* read ata-2 to use */\n\t/* SET_FEATURES 0x22 or 0xDD */\n#define WIN_FLUSH_CACHE_EXT\t\t0xEA /* 48-Bit */\n#define WIN_IDENTIFY\t\t\t0xEC /* ask drive to identify itself\t*/\n#define WIN_MEDIAEJECT\t\t\t0xED\n#define WIN_IDENTIFY_DMA\t\t0xEE /* same as WIN_IDENTIFY, but DMA */\n#define WIN_SETFEATURES\t\t\t0xEF /* set special drive features */\n#define EXABYTE_ENABLE_NEST\t\t0xF0\n#define WIN_SECURITY_SET_PASS\t\t0xF1\n#define WIN_SECURITY_UNLOCK\t\t0xF2\n#define WIN_SECURITY_ERASE_PREPARE\t0xF3\n#define WIN_SECURITY_ERASE_UNIT\t\t0xF4\n#define WIN_SECURITY_FREEZE_LOCK\t0xF5\n#define WIN_SECURITY_DISABLE\t\t0xF6\n#define WIN_READ_NATIVE_MAX\t\t0xF8 /* return the native maximum address */\n#define WIN_SET_MAX\t\t\t0xF9\n#define DISABLE_SEAGATE\t\t\t0xFB\n\n#define MAX_MULT_SECTORS 128\n\ntypedef struct IDEState IDEState;\n\ntypedef void EndTransferFunc(IDEState *);\n\nstruct IDEState {\n IDEIFState *ide_if;\n BlockDevice *bs;\n int cylinders, heads, sectors;\n int mult_sectors;\n int64_t nb_sectors;\n\n /* ide regs */\n uint8_t feature;\n uint8_t error;\n uint16_t nsector; /* 0 is 256 to ease computations */\n uint8_t sector;\n uint8_t lcyl;\n uint8_t hcyl;\n uint8_t select;\n uint8_t status;\n\n int io_nb_sectors;\n int req_nb_sectors;\n EndTransferFunc *end_transfer_func;\n \n int data_index;\n int data_end;\n uint8_t io_buffer[MAX_MULT_SECTORS*512 + 4];\n};\n\nstruct IDEIFState {\n IRQSignal *irq;\n IDEState *cur_drive;\n IDEState *drives[2];\n /* 0x3f6 command */\n uint8_t cmd;\n};\n\nstatic void ide_sector_read_cb(void *opaque, int ret);\nstatic void ide_sector_read_cb_end(IDEState *s);\nstatic void ide_sector_write_cb2(void *opaque, int ret);\n\nstatic void padstr(char *str, const char *src, int len)\n{\n int i, v;\n for(i = 0; i < len; i++) {\n if (*src)\n v = *src++;\n else\n v = ' ';\n *(char *)((long)str ^ 1) = v;\n str++;\n }\n}\n\n/* little endian assume */\nstatic void stw(uint16_t *buf, int v)\n{\n *buf = v;\n}\n\nstatic void ide_identify(IDEState *s)\n{\n uint16_t *tab;\n uint32_t oldsize;\n \n tab = (uint16_t *)s->io_buffer;\n\n memset(tab, 0, 512 * 2);\n\n stw(tab + 0, 0x0040);\n stw(tab + 1, s->cylinders); \n stw(tab + 3, s->heads);\n stw(tab + 4, 512 * s->sectors); /* sectors */\n stw(tab + 5, 512); /* sector size */\n stw(tab + 6, s->sectors); \n stw(tab + 20, 3); /* buffer type */\n stw(tab + 21, 512); /* cache size in sectors */\n stw(tab + 22, 4); /* ecc bytes */\n padstr((char *)(tab + 27), \"RISCVEMU HARDDISK\", 40);\n stw(tab + 47, 0x8000 | MAX_MULT_SECTORS);\n stw(tab + 48, 0); /* dword I/O */\n stw(tab + 49, 1 << 9); /* LBA supported, no DMA */\n stw(tab + 51, 0x200); /* PIO transfer cycle */\n stw(tab + 52, 0x200); /* DMA transfer cycle */\n stw(tab + 54, s->cylinders);\n stw(tab + 55, s->heads);\n stw(tab + 56, s->sectors);\n oldsize = s->cylinders * s->heads * s->sectors;\n stw(tab + 57, oldsize);\n stw(tab + 58, oldsize >> 16);\n if (s->mult_sectors)\n stw(tab + 59, 0x100 | s->mult_sectors);\n stw(tab + 60, s->nb_sectors);\n stw(tab + 61, s->nb_sectors >> 16);\n stw(tab + 80, (1 << 1) | (1 << 2));\n stw(tab + 82, (1 << 14));\n stw(tab + 83, (1 << 14));\n stw(tab + 84, (1 << 14));\n stw(tab + 85, (1 << 14));\n stw(tab + 86, 0);\n stw(tab + 87, (1 << 14));\n}\n\nstatic void ide_set_signature(IDEState *s) \n{\n s->select &= 0xf0;\n s->nsector = 1;\n s->sector = 1;\n s->lcyl = 0;\n s->hcyl = 0;\n}\n\nstatic void ide_abort_command(IDEState *s) \n{\n s->status = READY_STAT | ERR_STAT;\n s->error = ABRT_ERR;\n}\n\nstatic void ide_set_irq(IDEState *s) \n{\n IDEIFState *ide_if = s->ide_if;\n if (!(ide_if->cmd & IDE_CMD_DISABLE_IRQ)) {\n set_irq(ide_if->irq, 1);\n }\n}\n\n/* prepare data transfer and tell what to do after */\nstatic void ide_transfer_start(IDEState *s, int size,\n EndTransferFunc *end_transfer_func)\n{\n s->end_transfer_func = end_transfer_func;\n s->data_index = 0;\n s->data_end = size;\n}\n\nstatic void ide_transfer_stop(IDEState *s)\n{\n s->end_transfer_func = ide_transfer_stop;\n s->data_index = 0;\n s->data_end = 0;\n}\n\nstatic int64_t ide_get_sector(IDEState *s)\n{\n int64_t sector_num;\n if (s->select & 0x40) {\n /* lba */\n sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) |\n (s->lcyl << 8) | s->sector;\n } else {\n sector_num = ((s->hcyl << 8) | s->lcyl) * \n s->heads * s->sectors +\n (s->select & 0x0f) * s->sectors + (s->sector - 1);\n }\n return sector_num;\n}\n\nstatic void ide_set_sector(IDEState *s, int64_t sector_num)\n{\n unsigned int cyl, r;\n if (s->select & 0x40) {\n s->select = (s->select & 0xf0) | ((sector_num >> 24) & 0x0f);\n s->hcyl = (sector_num >> 16) & 0xff;\n s->lcyl = (sector_num >> 8) & 0xff;\n s->sector = sector_num & 0xff;\n } else {\n cyl = sector_num / (s->heads * s->sectors);\n r = sector_num % (s->heads * s->sectors);\n s->hcyl = (cyl >> 8) & 0xff;\n s->lcyl = cyl & 0xff;\n s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f);\n s->sector = (r % s->sectors) + 1;\n }\n}\n\nstatic void ide_sector_read(IDEState *s)\n{\n int64_t sector_num;\n int ret, n;\n\n sector_num = ide_get_sector(s);\n n = s->nsector;\n if (n == 0) \n n = 256;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n#if defined(DEBUG_IDE)\n printf(\"read sector=%\" PRId64 \" count=%d\\n\", sector_num, n);\n#endif\n s->io_nb_sectors = n;\n ret = s->bs->read_async(s->bs, sector_num, s->io_buffer, n, \n ide_sector_read_cb, s);\n if (ret < 0) {\n /* error */\n ide_abort_command(s);\n ide_set_irq(s);\n } else if (ret == 0) {\n /* synchronous case (needed for performance) */\n ide_sector_read_cb(s, 0);\n } else {\n /* async case */\n s->status = READY_STAT | SEEK_STAT | BUSY_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n }\n}\n\nstatic void ide_sector_read_cb(void *opaque, int ret)\n{\n IDEState *s = opaque;\n int n;\n EndTransferFunc *func;\n \n n = s->io_nb_sectors;\n ide_set_sector(s, ide_get_sector(s) + n);\n s->nsector = (s->nsector - n) & 0xff;\n if (s->nsector == 0)\n func = ide_sector_read_cb_end;\n else\n func = ide_sector_read;\n ide_transfer_start(s, 512 * n, func);\n ide_set_irq(s);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n}\n\nstatic void ide_sector_read_cb_end(IDEState *s)\n{\n /* no more sector to read from disk */\n s->status = READY_STAT | SEEK_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n ide_transfer_stop(s);\n}\n\nstatic void ide_sector_write_cb1(IDEState *s)\n{\n int64_t sector_num;\n int ret;\n\n ide_transfer_stop(s);\n sector_num = ide_get_sector(s);\n#if defined(DEBUG_IDE)\n printf(\"write sector=%\" PRId64 \" count=%d\\n\",\n sector_num, s->io_nb_sectors);\n#endif\n ret = s->bs->write_async(s->bs, sector_num, s->io_buffer, s->io_nb_sectors, \n ide_sector_write_cb2, s);\n if (ret < 0) {\n /* error */\n ide_abort_command(s);\n ide_set_irq(s);\n } else if (ret == 0) {\n /* synchronous case (needed for performance) */\n ide_sector_write_cb2(s, 0);\n } else {\n /* async case */\n s->status = READY_STAT | SEEK_STAT | BUSY_STAT;\n }\n}\n\nstatic void ide_sector_write_cb2(void *opaque, int ret)\n{\n IDEState *s = opaque;\n int n;\n\n n = s->io_nb_sectors;\n ide_set_sector(s, ide_get_sector(s) + n);\n s->nsector = (s->nsector - n) & 0xff;\n if (s->nsector == 0) {\n /* no more sectors to write */\n s->status = READY_STAT | SEEK_STAT;\n } else {\n n = s->nsector;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n s->io_nb_sectors = n;\n ide_transfer_start(s, 512 * n, ide_sector_write_cb1);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n }\n ide_set_irq(s);\n}\n\nstatic void ide_sector_write(IDEState *s)\n{\n int n;\n n = s->nsector;\n if (n == 0)\n n = 256;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n s->io_nb_sectors = n;\n ide_transfer_start(s, 512 * n, ide_sector_write_cb1);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n}\n\nstatic void ide_identify_cb(IDEState *s)\n{\n ide_transfer_stop(s);\n s->status = READY_STAT;\n}\n\nstatic void ide_exec_cmd(IDEState *s, int val)\n{\n#if defined(DEBUG_IDE)\n printf(\"ide: exec_cmd=0x%02x\\n\", val);\n#endif\n switch(val) {\n case WIN_IDENTIFY:\n ide_identify(s);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n ide_transfer_start(s, 512, ide_identify_cb);\n ide_set_irq(s);\n break;\n case WIN_SPECIFY:\n case WIN_RECAL:\n s->error = 0;\n s->status = READY_STAT | SEEK_STAT;\n ide_set_irq(s);\n break;\n case WIN_SETMULT:\n if (s->nsector > MAX_MULT_SECTORS || \n (s->nsector & (s->nsector - 1)) != 0) {\n ide_abort_command(s);\n } else {\n s->mult_sectors = s->nsector;\n#if defined(DEBUG_IDE)\n printf(\"ide: setmult=%d\\n\", s->mult_sectors);\n#endif\n s->status = READY_STAT;\n }\n ide_set_irq(s);\n break;\n case WIN_READ:\n case WIN_READ_ONCE:\n s->req_nb_sectors = 1;\n ide_sector_read(s);\n break;\n case WIN_WRITE:\n case WIN_WRITE_ONCE:\n s->req_nb_sectors = 1;\n ide_sector_write(s);\n break;\n case WIN_MULTREAD:\n if (!s->mult_sectors) {\n ide_abort_command(s);\n ide_set_irq(s);\n } else {\n s->req_nb_sectors = s->mult_sectors;\n ide_sector_read(s);\n }\n break;\n case WIN_MULTWRITE:\n if (!s->mult_sectors) {\n ide_abort_command(s);\n ide_set_irq(s);\n } else {\n s->req_nb_sectors = s->mult_sectors;\n ide_sector_write(s);\n }\n break;\n case WIN_READ_NATIVE_MAX:\n ide_set_sector(s, s->nb_sectors - 1);\n s->status = READY_STAT;\n ide_set_irq(s);\n break;\n default:\n ide_abort_command(s);\n ide_set_irq(s);\n break;\n }\n}\n\nstatic void ide_ioport_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int addr = offset + 1;\n \n#ifdef DEBUG_IDE\n printf(\"ide: write addr=0x%02x val=0x%02x\\n\", addr, val);\n#endif\n switch(addr) {\n case 0:\n break;\n case 1:\n if (s) {\n s->feature = val;\n }\n break;\n case 2:\n if (s) {\n s->nsector = val;\n }\n break;\n case 3:\n if (s) {\n s->sector = val;\n }\n break;\n case 4:\n if (s) {\n s->lcyl = val;\n }\n break;\n case 5:\n if (s) {\n s->hcyl = val;\n }\n break;\n case 6:\n /* select drive */\n s = s1->cur_drive = s1->drives[(val >> 4) & 1];\n if (s) {\n s->select = val;\n }\n break;\n default:\n case 7:\n /* command */\n if (s) {\n ide_exec_cmd(s, val);\n }\n break;\n }\n}\n\nstatic uint32_t ide_ioport_read(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int ret, addr = offset + 1;\n\n if (!s) {\n ret = 0x00;\n } else {\n switch(addr) {\n case 0:\n ret = 0xff;\n break;\n case 1:\n ret = s->error;\n break;\n case 2:\n ret = s->nsector;\n break;\n case 3:\n ret = s->sector;\n break;\n case 4:\n ret = s->lcyl;\n break;\n case 5:\n ret = s->hcyl;\n break;\n case 6:\n ret = s->select;\n break;\n default:\n case 7:\n ret = s->status;\n set_irq(s1->irq, 0);\n break;\n }\n }\n#ifdef DEBUG_IDE\n printf(\"ide: read addr=0x%02x val=0x%02x\\n\", addr, ret);\n#endif\n return ret;\n}\n\nstatic uint32_t ide_status_read(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int ret;\n\n if (s) {\n ret = s->status;\n } else {\n ret = 0;\n }\n#ifdef DEBUG_IDE\n printf(\"ide: read status=0x%02x\\n\", ret);\n#endif\n return ret;\n}\n\nstatic void ide_cmd_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s;\n int i;\n \n#ifdef DEBUG_IDE\n printf(\"ide: cmd write=0x%02x\\n\", val);\n#endif\n if (!(s1->cmd & IDE_CMD_RESET) && (val & IDE_CMD_RESET)) {\n /* low to high */\n for(i = 0; i < 2; i++) {\n s = s1->drives[i];\n if (s) {\n s->status = BUSY_STAT | SEEK_STAT;\n s->error = 0x01;\n }\n }\n } else if ((s1->cmd & IDE_CMD_RESET) && !(val & IDE_CMD_RESET)) {\n /* high to low */\n for(i = 0; i < 2; i++) {\n s = s1->drives[i];\n if (s) {\n s->status = READY_STAT | SEEK_STAT;\n ide_set_signature(s);\n }\n }\n }\n s1->cmd = val;\n}\n\nstatic void ide_data_writew(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int p;\n uint8_t *tab;\n \n if (!s)\n return;\n p = s->data_index;\n tab = s->io_buffer;\n tab[p] = val & 0xff;\n tab[p + 1] = (val >> 8) & 0xff;\n p += 2;\n s->data_index = p;\n if (p >= s->data_end)\n s->end_transfer_func(s);\n}\n\nstatic uint32_t ide_data_readw(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int p, ret;\n uint8_t *tab;\n \n if (!s) {\n ret = 0;\n } else {\n p = s->data_index;\n tab = s->io_buffer;\n ret = tab[p] | (tab[p + 1] << 8);\n p += 2;\n s->data_index = p;\n if (p >= s->data_end)\n s->end_transfer_func(s);\n }\n return ret;\n}\n\nstatic IDEState *ide_drive_init(IDEIFState *ide_if, BlockDevice *bs)\n{\n IDEState *s;\n uint32_t cylinders;\n uint64_t nb_sectors;\n\n s = malloc(sizeof(*s));\n memset(s, 0, sizeof(*s));\n\n s->ide_if = ide_if;\n s->bs = bs;\n\n nb_sectors = s->bs->get_sector_count(s->bs);\n cylinders = nb_sectors / (16 * 63);\n if (cylinders > 16383)\n cylinders = 16383;\n else if (cylinders < 2)\n cylinders = 2;\n s->cylinders = cylinders;\n s->heads = 16;\n s->sectors = 63;\n s->nb_sectors = nb_sectors;\n\n s->mult_sectors = MAX_MULT_SECTORS;\n /* ide regs */\n s->feature = 0;\n s->error = 0;\n s->nsector = 0;\n s->sector = 0;\n s->lcyl = 0;\n s->hcyl = 0;\n s->select = 0xa0;\n s->status = READY_STAT | SEEK_STAT;\n\n /* init I/O buffer */\n s->data_index = 0;\n s->data_end = 0;\n s->end_transfer_func = ide_transfer_stop;\n\n s->req_nb_sectors = 0; /* temp for read/write */\n s->io_nb_sectors = 0; /* temp for read/write */\n return s;\n}\n\nIDEIFState *ide_init(PhysMemoryMap *port_map, uint32_t addr, uint32_t addr2,\n IRQSignal *irq, BlockDevice **tab_bs)\n{\n int i;\n IDEIFState *s;\n \n s = malloc(sizeof(IDEIFState));\n memset(s, 0, sizeof(*s));\n \n s->irq = irq;\n s->cmd = 0;\n\n cpu_register_device(port_map, addr, 1, s, ide_data_readw, ide_data_writew, \n DEVIO_SIZE16);\n cpu_register_device(port_map, addr + 1, 7, s, ide_ioport_read, ide_ioport_write, \n DEVIO_SIZE8);\n if (addr2) {\n cpu_register_device(port_map, addr2, 1, s, ide_status_read, ide_cmd_write, \n DEVIO_SIZE8);\n }\n \n for(i = 0; i < 2; i++) {\n if (tab_bs[i])\n s->drives[i] = ide_drive_init(s, tab_bs[i]);\n }\n s->cur_drive = s->drives[0];\n return s;\n}\n\n/* dummy PCI device for the IDE */\nPCIDevice *piix3_ide_init(PCIBus *pci_bus, int devfn)\n{\n PCIDevice *d;\n d = pci_register_device(pci_bus, \"PIIX3 IDE\", devfn, 0x8086, 0x7010, 0x00, 0x0101);\n pci_device_set_config8(d, 0x09, 0x00); /* ISA IDE ports, no DMA */\n return d;\n}\n"], ["/linuxpdf/tinyemu/fs_net.c", "/*\n * Networked Filesystem using HTTP\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n#include \"fbuf.h\"\n\n#if defined(EMSCRIPTEN)\n#include \n#endif\n\n/*\n TODO:\n - implement fs_lock/fs_getlock\n - update fs_size with links ?\n - limit fs_size in dirent creation\n - limit filename length\n*/\n\n//#define DEBUG_CACHE\n#if !defined(EMSCRIPTEN)\n#define DUMP_CACHE_LOAD\n#endif\n\n#if defined(EMSCRIPTEN)\n#define DEFAULT_INODE_CACHE_SIZE (64 * 1024 * 1024)\n#else\n#define DEFAULT_INODE_CACHE_SIZE (256 * 1024 * 1024)\n#endif\n\ntypedef enum {\n FT_FIFO = 1,\n FT_CHR = 2,\n FT_DIR = 4,\n FT_BLK = 6,\n FT_REG = 8,\n FT_LNK = 10,\n FT_SOCK = 12,\n} FSINodeTypeEnum;\n\ntypedef enum {\n REG_STATE_LOCAL, /* local content */\n REG_STATE_UNLOADED, /* content not loaded */\n REG_STATE_LOADING, /* content is being loaded */\n REG_STATE_LOADED, /* loaded, not modified, stored in cached_inode_list */\n} FSINodeRegStateEnum;\n\ntypedef struct FSBaseURL {\n struct list_head link;\n int ref_count;\n char *base_url_id;\n char *url;\n char *user;\n char *password;\n BOOL encrypted;\n AES_KEY aes_state;\n} FSBaseURL;\n\ntypedef struct FSINode {\n struct list_head link;\n uint64_t inode_num; /* inode number */\n int32_t refcount;\n int32_t open_count;\n FSINodeTypeEnum type;\n uint32_t mode;\n uint32_t uid;\n uint32_t gid;\n uint32_t mtime_sec;\n uint32_t ctime_sec;\n uint32_t mtime_nsec;\n uint32_t ctime_nsec;\n union {\n struct {\n FSINodeRegStateEnum state;\n size_t size; /* real file size */\n FileBuffer fbuf;\n FSBaseURL *base_url;\n FSFileID file_id; /* network file ID */\n struct list_head link;\n struct FSOpenInfo *open_info; /* used in LOADING state */\n BOOL is_fscmd;\n#ifdef DUMP_CACHE_LOAD\n char *filename;\n#endif\n } reg;\n struct {\n struct list_head de_list; /* list of FSDirEntry */\n int size;\n } dir;\n struct {\n uint32_t major;\n uint32_t minor;\n } dev;\n struct {\n char *name;\n } symlink;\n } u;\n} FSINode;\n\ntypedef struct {\n struct list_head link;\n FSINode *inode;\n uint8_t mark; /* temporary use only */\n char name[0];\n} FSDirEntry;\n\ntypedef enum {\n FS_CMD_XHR,\n FS_CMD_PBKDF2,\n} FSCMDRequestEnum;\n\n#define FS_CMD_REPLY_LEN_MAX 64\n\ntypedef struct {\n FSCMDRequestEnum type;\n struct CmdXHRState *xhr_state;\n int reply_len;\n uint8_t reply_buf[FS_CMD_REPLY_LEN_MAX];\n} FSCMDRequest;\n\nstruct FSFile {\n uint32_t uid;\n FSINode *inode;\n BOOL is_opened;\n uint32_t open_flags;\n FSCMDRequest *req;\n};\n\ntypedef struct {\n struct list_head link;\n BOOL is_archive;\n const char *name;\n} PreloadFile;\n\ntypedef struct {\n struct list_head link;\n FSFileID file_id;\n struct list_head file_list; /* list of PreloadFile.link */\n} PreloadEntry;\n\ntypedef struct {\n struct list_head link;\n FSFileID file_id;\n uint64_t size;\n const char *name;\n} PreloadArchiveFile;\n\ntypedef struct {\n struct list_head link;\n const char *name;\n struct list_head file_list; /* list of PreloadArchiveFile.link */\n} PreloadArchive;\n\ntypedef struct FSDeviceMem {\n FSDevice common;\n\n struct list_head inode_list; /* list of FSINode */\n int64_t inode_count; /* current number of inodes */\n uint64_t inode_limit;\n int64_t fs_blocks;\n uint64_t fs_max_blocks;\n uint64_t inode_num_alloc;\n int block_size_log2;\n uint32_t block_size; /* for stat/statfs */\n FSINode *root_inode;\n struct list_head inode_cache_list; /* list of FSINode.u.reg.link */\n int64_t inode_cache_size;\n int64_t inode_cache_size_limit;\n struct list_head preload_list; /* list of PreloadEntry.link */\n struct list_head preload_archive_list; /* list of PreloadArchive.link */\n /* network */\n struct list_head base_url_list; /* list of FSBaseURL.link */\n char *import_dir;\n#ifdef DUMP_CACHE_LOAD\n BOOL dump_cache_load;\n BOOL dump_started;\n char *dump_preload_dir;\n FILE *dump_preload_file;\n FILE *dump_preload_archive_file;\n\n char *dump_archive_name;\n uint64_t dump_archive_size;\n FILE *dump_archive_file;\n\n int dump_archive_num;\n struct list_head dump_preload_list; /* list of PreloadFile.link */\n struct list_head dump_exclude_list; /* list of PreloadFile.link */\n#endif\n} FSDeviceMem;\n\ntypedef enum {\n FS_OPEN_WGET_REG,\n FS_OPEN_WGET_ARCHIVE,\n FS_OPEN_WGET_ARCHIVE_FILE,\n} FSOpenWgetEnum;\n\ntypedef struct FSOpenInfo {\n FSDevice *fs;\n FSOpenWgetEnum open_type;\n\n /* used for FS_OPEN_WGET_REG, FS_OPEN_WGET_ARCHIVE */\n XHRState *xhr;\n FSINode *n;\n DecryptFileState *dec_state;\n size_t cur_pos;\n\n struct list_head archive_link; /* FS_OPEN_WGET_ARCHIVE_FILE */\n uint64_t archive_offset; /* FS_OPEN_WGET_ARCHIVE_FILE */\n struct list_head archive_file_list; /* FS_OPEN_WGET_ARCHIVE */\n \n /* the following is set in case there is a fs_open callback */\n FSFile *f;\n FSOpenCompletionFunc *cb;\n void *opaque;\n} FSOpenInfo;\n\nstatic void fs_close(FSDevice *fs, FSFile *f);\nstatic void inode_decref(FSDevice *fs1, FSINode *n);\nstatic int fs_cmd_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int buf_len);\nstatic int fs_cmd_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int buf_len);\nstatic int fs_truncate(FSDevice *fs1, FSINode *n, uint64_t size);\nstatic void fs_open_end(FSOpenInfo *oi);\nstatic void fs_base_url_decref(FSDevice *fs, FSBaseURL *bu);\nstatic FSBaseURL *fs_net_set_base_url(FSDevice *fs1,\n const char *base_url_id,\n const char *url,\n const char *user, const char *password,\n AES_KEY *aes_state);\nstatic void fs_cmd_close(FSDevice *fs, FSFile *f);\nstatic void fs_error_archive(FSOpenInfo *oi);\n#ifdef DUMP_CACHE_LOAD\nstatic void dump_loaded_file(FSDevice *fs1, FSINode *n);\n#endif\n\n#if !defined(EMSCRIPTEN)\n/* file buffer (the content of the buffer can be stored elsewhere) */\nvoid file_buffer_init(FileBuffer *bs)\n{\n bs->data = NULL;\n bs->allocated_size = 0;\n}\n\nvoid file_buffer_reset(FileBuffer *bs)\n{\n free(bs->data);\n file_buffer_init(bs);\n}\n\nint file_buffer_resize(FileBuffer *bs, size_t new_size)\n{\n uint8_t *new_data;\n new_data = realloc(bs->data, new_size);\n if (!new_data && new_size != 0)\n return -1;\n bs->data = new_data;\n bs->allocated_size = new_size;\n return 0;\n}\n\nvoid file_buffer_write(FileBuffer *bs, size_t offset, const uint8_t *buf,\n size_t size)\n{\n memcpy(bs->data + offset, buf, size);\n}\n\nvoid file_buffer_set(FileBuffer *bs, size_t offset, int val, size_t size)\n{\n memset(bs->data + offset, val, size);\n}\n\nvoid file_buffer_read(FileBuffer *bs, size_t offset, uint8_t *buf,\n size_t size)\n{\n memcpy(buf, bs->data + offset, size);\n}\n#endif\n\nstatic int64_t to_blocks(FSDeviceMem *fs, uint64_t size)\n{\n return (size + fs->block_size - 1) >> fs->block_size_log2;\n}\n\nstatic FSINode *inode_incref(FSDevice *fs, FSINode *n)\n{\n n->refcount++;\n return n;\n}\n\nstatic FSINode *inode_inc_open(FSDevice *fs, FSINode *n)\n{\n n->open_count++;\n return n;\n}\n\nstatic void inode_free(FSDevice *fs1, FSINode *n)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n // printf(\"inode_free=%\" PRId64 \"\\n\", n->inode_num);\n assert(n->refcount == 0);\n assert(n->open_count == 0);\n switch(n->type) {\n case FT_REG:\n fs->fs_blocks -= to_blocks(fs, n->u.reg.size);\n assert(fs->fs_blocks >= 0);\n file_buffer_reset(&n->u.reg.fbuf);\n#ifdef DUMP_CACHE_LOAD\n free(n->u.reg.filename);\n#endif\n switch(n->u.reg.state) {\n case REG_STATE_LOADED:\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n fs_base_url_decref(fs1, n->u.reg.base_url);\n break;\n case REG_STATE_LOADING:\n {\n FSOpenInfo *oi = n->u.reg.open_info;\n if (oi->xhr)\n fs_wget_free(oi->xhr);\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE) {\n fs_error_archive(oi);\n }\n fs_open_end(oi);\n fs_base_url_decref(fs1, n->u.reg.base_url);\n }\n break;\n case REG_STATE_UNLOADED:\n fs_base_url_decref(fs1, n->u.reg.base_url);\n break;\n case REG_STATE_LOCAL:\n break;\n default:\n abort();\n }\n break;\n case FT_LNK:\n free(n->u.symlink.name);\n break;\n case FT_DIR:\n assert(list_empty(&n->u.dir.de_list));\n break;\n default:\n break;\n }\n list_del(&n->link);\n free(n);\n fs->inode_count--;\n assert(fs->inode_count >= 0);\n}\n\nstatic void inode_decref(FSDevice *fs1, FSINode *n)\n{\n assert(n->refcount >= 1);\n if (--n->refcount <= 0 && n->open_count <= 0) {\n inode_free(fs1, n);\n }\n}\n\nstatic void inode_dec_open(FSDevice *fs1, FSINode *n)\n{\n assert(n->open_count >= 1);\n if (--n->open_count <= 0 && n->refcount <= 0) {\n inode_free(fs1, n);\n }\n}\n\nstatic void inode_update_mtime(FSDevice *fs, FSINode *n)\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n n->mtime_sec = tv.tv_sec;\n n->mtime_nsec = tv.tv_usec * 1000;\n}\n\nstatic FSINode *inode_new(FSDevice *fs1, FSINodeTypeEnum type,\n uint32_t mode, uint32_t uid, uint32_t gid)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n;\n\n n = mallocz(sizeof(*n));\n n->refcount = 1;\n n->open_count = 0;\n n->inode_num = fs->inode_num_alloc;\n fs->inode_num_alloc++;\n n->type = type;\n n->mode = mode & 0xfff;\n n->uid = uid;\n n->gid = gid;\n\n switch(type) {\n case FT_REG:\n file_buffer_init(&n->u.reg.fbuf);\n break;\n case FT_DIR:\n init_list_head(&n->u.dir.de_list);\n break;\n default:\n break;\n }\n\n list_add(&n->link, &fs->inode_list);\n fs->inode_count++;\n\n inode_update_mtime(fs1, n);\n n->ctime_sec = n->mtime_sec;\n n->ctime_nsec = n->mtime_nsec;\n\n return n;\n}\n\n/* warning: the refcount of 'n1' is not incremented by this function */\n/* XXX: test FS max size */\nstatic FSDirEntry *inode_dir_add(FSDevice *fs1, FSINode *n, const char *name,\n FSINode *n1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSDirEntry *de;\n int name_len, dirent_size, new_size;\n assert(n->type == FT_DIR);\n\n name_len = strlen(name);\n de = mallocz(sizeof(*de) + name_len + 1);\n de->inode = n1;\n memcpy(de->name, name, name_len + 1);\n dirent_size = sizeof(*de) + name_len + 1;\n new_size = n->u.dir.size + dirent_size;\n fs->fs_blocks += to_blocks(fs, new_size) - to_blocks(fs, n->u.dir.size);\n n->u.dir.size = new_size;\n list_add_tail(&de->link, &n->u.dir.de_list);\n return de;\n}\n\nstatic FSDirEntry *inode_search(FSINode *n, const char *name)\n{\n struct list_head *el;\n FSDirEntry *de;\n \n if (n->type != FT_DIR)\n return NULL;\n\n list_for_each(el, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n if (!strcmp(de->name, name))\n return de;\n }\n return NULL;\n}\n\nstatic FSINode *inode_search_path1(FSDevice *fs, FSINode *n, const char *path)\n{\n char name[1024];\n const char *p, *p1;\n int len;\n FSDirEntry *de;\n \n p = path;\n if (*p == '/')\n p++;\n if (*p == '\\0')\n return n;\n for(;;) {\n p1 = strchr(p, '/');\n if (!p1) {\n len = strlen(p);\n } else {\n len = p1 - p;\n p1++;\n }\n if (len > sizeof(name) - 1)\n return NULL;\n memcpy(name, p, len);\n name[len] = '\\0';\n if (n->type != FT_DIR)\n return NULL;\n de = inode_search(n, name);\n if (!de)\n return NULL;\n n = de->inode;\n p = p1;\n if (!p)\n break;\n }\n return n;\n}\n\nstatic FSINode *inode_search_path(FSDevice *fs1, const char *path)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (!fs1)\n return NULL;\n return inode_search_path1(fs1, fs->root_inode, path);\n}\n\nstatic BOOL is_empty_dir(FSDevice *fs, FSINode *n)\n{\n struct list_head *el;\n FSDirEntry *de;\n\n list_for_each(el, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n if (strcmp(de->name, \".\") != 0 &&\n strcmp(de->name, \"..\") != 0)\n return FALSE;\n }\n return TRUE;\n}\n\nstatic void inode_dirent_delete_no_decref(FSDevice *fs1, FSINode *n, FSDirEntry *de)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int dirent_size, new_size;\n dirent_size = sizeof(*de) + strlen(de->name) + 1;\n\n new_size = n->u.dir.size - dirent_size;\n fs->fs_blocks += to_blocks(fs, new_size) - to_blocks(fs, n->u.dir.size);\n n->u.dir.size = new_size;\n assert(n->u.dir.size >= 0);\n assert(fs->fs_blocks >= 0);\n list_del(&de->link);\n free(de);\n}\n\nstatic void inode_dirent_delete(FSDevice *fs, FSINode *n, FSDirEntry *de)\n{\n FSINode *n1;\n n1 = de->inode;\n inode_dirent_delete_no_decref(fs, n, de);\n inode_decref(fs, n1);\n}\n\nstatic void flush_dir(FSDevice *fs, FSINode *n)\n{\n struct list_head *el, *el1;\n FSDirEntry *de;\n list_for_each_safe(el, el1, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n inode_dirent_delete(fs, n, de);\n }\n assert(n->u.dir.size == 0);\n}\n\nstatic void fs_delete(FSDevice *fs, FSFile *f)\n{\n fs_close(fs, f);\n inode_dec_open(fs, f->inode);\n free(f);\n}\n\nstatic FSFile *fid_create(FSDevice *fs1, FSINode *n, uint32_t uid)\n{\n FSFile *f;\n\n f = mallocz(sizeof(*f));\n f->inode = inode_inc_open(fs1, n);\n f->uid = uid;\n return f;\n}\n\nstatic void inode_to_qid(FSQID *qid, FSINode *n)\n{\n if (n->type == FT_DIR)\n qid->type = P9_QTDIR;\n else if (n->type == FT_LNK)\n qid->type = P9_QTSYMLINK;\n else\n qid->type = P9_QTFILE;\n qid->version = 0; /* no caching on client */\n qid->path = n->inode_num;\n}\n\nstatic void fs_statfs(FSDevice *fs1, FSStatFS *st)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n st->f_bsize = 1024;\n st->f_blocks = fs->fs_max_blocks <<\n (fs->block_size_log2 - 10);\n st->f_bfree = (fs->fs_max_blocks - fs->fs_blocks) <<\n (fs->block_size_log2 - 10);\n st->f_bavail = st->f_bfree;\n st->f_files = fs->inode_limit;\n st->f_ffree = fs->inode_limit - fs->inode_count;\n}\n\nstatic int fs_attach(FSDevice *fs1, FSFile **pf, FSQID *qid, uint32_t uid,\n const char *uname, const char *aname)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n *pf = fid_create(fs1, fs->root_inode, uid);\n inode_to_qid(qid, fs->root_inode);\n return 0;\n}\n\nstatic int fs_walk(FSDevice *fs, FSFile **pf, FSQID *qids,\n FSFile *f, int count, char **names)\n{\n int i;\n FSINode *n;\n FSDirEntry *de;\n\n n = f->inode;\n for(i = 0; i < count; i++) {\n de = inode_search(n, names[i]);\n if (!de)\n break;\n n = de->inode;\n inode_to_qid(&qids[i], n);\n }\n *pf = fid_create(fs, n, f->uid);\n return i;\n}\n\nstatic int fs_mkdir(FSDevice *fs, FSQID *qid, FSFile *f,\n const char *name, uint32_t mode, uint32_t gid)\n{\n FSINode *n, *n1;\n\n n = f->inode;\n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n if (inode_search(n, name))\n return -P9_EEXIST;\n n1 = inode_new(fs, FT_DIR, mode, f->uid, gid);\n inode_dir_add(fs, n1, \".\", inode_incref(fs, n1));\n inode_dir_add(fs, n1, \"..\", inode_incref(fs, n));\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\n/* remove elements in the cache considering that 'added_size' will be\n added */\nstatic void fs_trim_cache(FSDevice *fs1, int64_t added_size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el, *el1;\n FSINode *n;\n\n if ((fs->inode_cache_size + added_size) <= fs->inode_cache_size_limit)\n return;\n list_for_each_prev_safe(el, el1, &fs->inode_cache_list) {\n n = list_entry(el, FSINode, u.reg.link);\n assert(n->u.reg.state == REG_STATE_LOADED);\n /* cannot remove open files */\n // printf(\"open_count=%d\\n\", n->open_count);\n if (n->open_count != 0)\n continue;\n#ifdef DEBUG_CACHE\n printf(\"fs_trim_cache: remove '%s' size=%ld\\n\",\n n->u.reg.filename, (long)n->u.reg.size);\n#endif\n file_buffer_reset(&n->u.reg.fbuf);\n n->u.reg.state = REG_STATE_UNLOADED;\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n if ((fs->inode_cache_size + added_size) <= fs->inode_cache_size_limit)\n break;\n }\n}\n\nstatic void fs_open_end(FSOpenInfo *oi)\n{\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE_FILE) {\n list_del(&oi->archive_link);\n }\n if (oi->dec_state)\n decrypt_file_end(oi->dec_state);\n free(oi);\n}\n\nstatic int fs_open_write_cb(void *opaque, const uint8_t *data, size_t size)\n{\n FSOpenInfo *oi = opaque;\n size_t len;\n FSINode *n = oi->n;\n \n /* we ignore extraneous data */\n len = n->u.reg.size - oi->cur_pos;\n if (size < len)\n len = size;\n file_buffer_write(&n->u.reg.fbuf, oi->cur_pos, data, len);\n oi->cur_pos += len;\n return 0;\n}\n\nstatic void fs_wget_set_loaded(FSINode *n)\n{\n FSOpenInfo *oi;\n FSDeviceMem *fs;\n FSFile *f;\n FSQID qid;\n\n assert(n->u.reg.state == REG_STATE_LOADING);\n oi = n->u.reg.open_info;\n fs = (FSDeviceMem *)oi->fs;\n n->u.reg.state = REG_STATE_LOADED;\n list_add(&n->u.reg.link, &fs->inode_cache_list);\n fs->inode_cache_size += n->u.reg.size;\n \n if (oi->cb) {\n f = oi->f;\n f->is_opened = TRUE;\n inode_to_qid(&qid, n);\n oi->cb(oi->fs, &qid, 0, oi->opaque);\n }\n fs_open_end(oi);\n}\n\nstatic void fs_wget_set_error(FSINode *n)\n{\n FSOpenInfo *oi;\n assert(n->u.reg.state == REG_STATE_LOADING);\n oi = n->u.reg.open_info;\n n->u.reg.state = REG_STATE_UNLOADED;\n file_buffer_reset(&n->u.reg.fbuf);\n if (oi->cb) {\n oi->cb(oi->fs, NULL, -P9_EIO, oi->opaque);\n }\n fs_open_end(oi);\n}\n\nstatic void fs_read_archive(FSOpenInfo *oi)\n{\n FSINode *n = oi->n;\n uint64_t pos, pos1, l;\n uint8_t buf[1024];\n FSINode *n1;\n FSOpenInfo *oi1;\n struct list_head *el, *el1;\n \n list_for_each_safe(el, el1, &oi->archive_file_list) {\n oi1 = list_entry(el, FSOpenInfo, archive_link);\n n1 = oi1->n;\n /* copy the archive data to the file */\n pos = oi1->archive_offset;\n pos1 = 0;\n while (pos1 < n1->u.reg.size) {\n l = n1->u.reg.size - pos1;\n if (l > sizeof(buf))\n l = sizeof(buf);\n file_buffer_read(&n->u.reg.fbuf, pos, buf, l);\n file_buffer_write(&n1->u.reg.fbuf, pos1, buf, l);\n pos += l;\n pos1 += l;\n }\n fs_wget_set_loaded(n1);\n }\n}\n\nstatic void fs_error_archive(FSOpenInfo *oi)\n{\n FSOpenInfo *oi1;\n struct list_head *el, *el1;\n \n list_for_each_safe(el, el1, &oi->archive_file_list) {\n oi1 = list_entry(el, FSOpenInfo, archive_link);\n fs_wget_set_error(oi1->n);\n }\n}\n\nstatic void fs_open_cb(void *opaque, int err, void *data, size_t size)\n{\n FSOpenInfo *oi = opaque;\n FSINode *n = oi->n;\n \n // printf(\"open_cb: err=%d size=%ld\\n\", err, size);\n if (err < 0) {\n error:\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE)\n fs_error_archive(oi);\n fs_wget_set_error(n);\n } else {\n if (oi->dec_state) {\n if (decrypt_file(oi->dec_state, data, size) < 0)\n goto error;\n if (err == 0) {\n if (decrypt_file_flush(oi->dec_state) < 0)\n goto error;\n }\n } else {\n fs_open_write_cb(oi, data, size);\n }\n\n if (err == 0) {\n /* end of transfer */\n if (oi->cur_pos != n->u.reg.size)\n goto error;\n#ifdef DUMP_CACHE_LOAD\n dump_loaded_file(oi->fs, n);\n#endif\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE)\n fs_read_archive(oi);\n fs_wget_set_loaded(n);\n }\n }\n}\n\n\nstatic int fs_open_wget(FSDevice *fs1, FSINode *n, FSOpenWgetEnum open_type)\n{\n char *url;\n FSOpenInfo *oi;\n char fname[FILEID_SIZE_MAX];\n FSBaseURL *bu;\n\n assert(n->u.reg.state == REG_STATE_UNLOADED);\n \n fs_trim_cache(fs1, n->u.reg.size);\n \n if (file_buffer_resize(&n->u.reg.fbuf, n->u.reg.size) < 0)\n return -P9_EIO;\n n->u.reg.state = REG_STATE_LOADING;\n oi = mallocz(sizeof(*oi));\n oi->cur_pos = 0;\n oi->fs = fs1;\n oi->n = n;\n oi->open_type = open_type;\n if (open_type != FS_OPEN_WGET_ARCHIVE_FILE) {\n if (open_type == FS_OPEN_WGET_ARCHIVE)\n init_list_head(&oi->archive_file_list);\n file_id_to_filename(fname, n->u.reg.file_id);\n bu = n->u.reg.base_url;\n url = compose_path(bu->url, fname);\n if (bu->encrypted) {\n oi->dec_state = decrypt_file_init(&bu->aes_state, fs_open_write_cb, oi);\n }\n oi->xhr = fs_wget(url, bu->user, bu->password, oi, fs_open_cb, FALSE);\n }\n n->u.reg.open_info = oi;\n return 0;\n}\n\n\nstatic void fs_preload_file(FSDevice *fs1, const char *filename)\n{\n FSINode *n;\n\n n = inode_search_path(fs1, filename);\n if (n && n->type == FT_REG && n->u.reg.state == REG_STATE_UNLOADED) {\n#if defined(DEBUG_CACHE)\n printf(\"preload: %s\\n\", filename);\n#endif\n fs_open_wget(fs1, n, FS_OPEN_WGET_REG);\n }\n}\n\nstatic PreloadArchive *find_preload_archive(FSDeviceMem *fs,\n const char *filename)\n{\n PreloadArchive *pa;\n struct list_head *el;\n list_for_each(el, &fs->preload_archive_list) {\n pa = list_entry(el, PreloadArchive, link);\n if (!strcmp(pa->name, filename))\n return pa;\n }\n return NULL;\n}\n\nstatic void fs_preload_archive(FSDevice *fs1, const char *filename)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n PreloadArchive *pa;\n PreloadArchiveFile *paf;\n struct list_head *el;\n FSINode *n, *n1;\n uint64_t offset;\n BOOL has_unloaded;\n \n pa = find_preload_archive(fs, filename);\n if (!pa)\n return;\n#if defined(DEBUG_CACHE)\n printf(\"preload archive: %s\\n\", filename);\n#endif\n n = inode_search_path(fs1, filename);\n if (n && n->type == FT_REG && n->u.reg.state == REG_STATE_UNLOADED) {\n /* if all the files are loaded, no need to load the archive */\n offset = 0;\n has_unloaded = FALSE;\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n n1 = inode_search_path(fs1, paf->name);\n if (n1 && n1->type == FT_REG &&\n n1->u.reg.state == REG_STATE_UNLOADED) {\n has_unloaded = TRUE;\n }\n offset += paf->size;\n }\n if (!has_unloaded) {\n#if defined(DEBUG_CACHE)\n printf(\"archive files already loaded\\n\");\n#endif\n return;\n }\n /* check archive size consistency */\n if (offset != n->u.reg.size) {\n#if defined(DEBUG_CACHE)\n printf(\" inconsistent archive size: %\" PRId64 \" %\" PRId64 \"\\n\",\n offset, n->u.reg.size);\n#endif\n goto load_fallback;\n }\n\n /* start loading the archive */\n fs_open_wget(fs1, n, FS_OPEN_WGET_ARCHIVE);\n \n /* indicate that all the archive files are being loaded. Also\n check consistency of size and file id */\n offset = 0;\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n n1 = inode_search_path(fs1, paf->name);\n if (n1 && n1->type == FT_REG &&\n n1->u.reg.state == REG_STATE_UNLOADED) {\n if (n1->u.reg.size == paf->size &&\n n1->u.reg.file_id == paf->file_id) {\n fs_open_wget(fs1, n1, FS_OPEN_WGET_ARCHIVE_FILE);\n list_add_tail(&n1->u.reg.open_info->archive_link,\n &n->u.reg.open_info->archive_file_list);\n n1->u.reg.open_info->archive_offset = offset;\n } else {\n#if defined(DEBUG_CACHE)\n printf(\" inconsistent archive file: %s\\n\", paf->name);\n#endif\n /* fallback to file preload */\n fs_preload_file(fs1, paf->name);\n }\n }\n offset += paf->size;\n }\n } else {\n load_fallback:\n /* if the archive is already loaded or not loaded, we load the\n files separately (XXX: not optimal if the archive is\n already loaded, but it should not happen often) */\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n fs_preload_file(fs1, paf->name);\n }\n }\n}\n\nstatic void fs_preload_files(FSDevice *fs1, FSFileID file_id)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el;\n PreloadEntry *pe;\n PreloadFile *pf;\n \n list_for_each(el, &fs->preload_list) {\n pe = list_entry(el, PreloadEntry, link);\n if (pe->file_id == file_id)\n goto found;\n }\n return;\n found:\n list_for_each(el, &pe->file_list) {\n pf = list_entry(el, PreloadFile, link);\n if (pf->is_archive)\n fs_preload_archive(fs1, pf->name);\n else\n fs_preload_file(fs1, pf->name);\n }\n}\n\n/* return < 0 if error, 0 if OK, 1 if asynchronous completion */\n/* XXX: we don't support several simultaneous asynchronous open on the\n same inode */\nstatic int fs_open(FSDevice *fs1, FSQID *qid, FSFile *f, uint32_t flags,\n FSOpenCompletionFunc *cb, void *opaque)\n{\n FSINode *n = f->inode;\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int ret;\n \n fs_close(fs1, f);\n\n if (flags & P9_O_DIRECTORY) {\n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n } else {\n if (n->type != FT_REG && n->type != FT_DIR)\n return -P9_EINVAL; /* XXX */\n }\n f->open_flags = flags;\n if (n->type == FT_REG) {\n if ((flags & P9_O_TRUNC) && (flags & P9_O_NOACCESS) != P9_O_RDONLY) {\n fs_truncate(fs1, n, 0);\n }\n\n switch(n->u.reg.state) {\n case REG_STATE_UNLOADED:\n {\n FSOpenInfo *oi;\n /* need to load the file */\n fs_preload_files(fs1, n->u.reg.file_id);\n /* The state can be modified by the fs_preload_files */\n if (n->u.reg.state == REG_STATE_LOADING)\n goto handle_loading;\n ret = fs_open_wget(fs1, n, FS_OPEN_WGET_REG);\n if (ret)\n return ret;\n oi = n->u.reg.open_info;\n oi->f = f;\n oi->cb = cb;\n oi->opaque = opaque;\n return 1; /* completion callback will be called later */\n }\n break;\n case REG_STATE_LOADING:\n handle_loading:\n {\n FSOpenInfo *oi;\n /* we only handle the case where the file is being preloaded */\n oi = n->u.reg.open_info;\n if (oi->cb)\n return -P9_EIO;\n oi = n->u.reg.open_info;\n oi->f = f;\n oi->cb = cb;\n oi->opaque = opaque;\n return 1; /* completion callback will be called later */\n }\n break;\n case REG_STATE_LOCAL:\n goto do_open;\n case REG_STATE_LOADED:\n /* move to front */\n list_del(&n->u.reg.link);\n list_add(&n->u.reg.link, &fs->inode_cache_list);\n goto do_open;\n default:\n abort();\n }\n } else {\n do_open:\n f->is_opened = TRUE;\n inode_to_qid(qid, n);\n return 0;\n }\n}\n\nstatic int fs_create(FSDevice *fs, FSQID *qid, FSFile *f, const char *name, \n uint32_t flags, uint32_t mode, uint32_t gid)\n{\n FSINode *n1, *n = f->inode;\n \n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n if (inode_search(n, name)) {\n /* XXX: support it, but Linux does not seem to use this case */\n return -P9_EEXIST;\n } else {\n fs_close(fs, f);\n \n n1 = inode_new(fs, FT_REG, mode, f->uid, gid);\n inode_dir_add(fs, n, name, n1);\n \n inode_dec_open(fs, f->inode);\n f->inode = inode_inc_open(fs, n1);\n f->is_opened = TRUE;\n f->open_flags = flags;\n inode_to_qid(qid, n1);\n return 0;\n }\n}\n\nstatic int fs_readdir(FSDevice *fs, FSFile *f, uint64_t offset1,\n uint8_t *buf, int count)\n{\n FSINode *n1, *n = f->inode;\n int len, pos, name_len, type;\n struct list_head *el;\n FSDirEntry *de;\n uint64_t offset;\n\n if (!f->is_opened || n->type != FT_DIR)\n return -P9_EPROTO;\n \n el = n->u.dir.de_list.next;\n offset = 0;\n while (offset < offset1) {\n if (el == &n->u.dir.de_list)\n return 0; /* no more entries */\n offset++;\n el = el->next;\n }\n \n pos = 0;\n for(;;) {\n if (el == &n->u.dir.de_list)\n break;\n de = list_entry(el, FSDirEntry, link);\n name_len = strlen(de->name);\n len = 13 + 8 + 1 + 2 + name_len;\n if ((pos + len) > count)\n break;\n offset++;\n n1 = de->inode;\n if (n1->type == FT_DIR)\n type = P9_QTDIR;\n else if (n1->type == FT_LNK)\n type = P9_QTSYMLINK;\n else\n type = P9_QTFILE;\n buf[pos++] = type;\n put_le32(buf + pos, 0); /* version */\n pos += 4;\n put_le64(buf + pos, n1->inode_num);\n pos += 8;\n put_le64(buf + pos, offset);\n pos += 8;\n buf[pos++] = n1->type;\n put_le16(buf + pos, name_len);\n pos += 2;\n memcpy(buf + pos, de->name, name_len);\n pos += name_len;\n el = el->next;\n }\n return pos;\n}\n\nstatic int fs_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n FSINode *n = f->inode;\n uint64_t count1;\n\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n if ((f->open_flags & P9_O_NOACCESS) == P9_O_WRONLY)\n return -P9_EIO;\n if (n->u.reg.is_fscmd)\n return fs_cmd_read(fs, f, offset, buf, count);\n if (offset >= n->u.reg.size)\n return 0;\n count1 = n->u.reg.size - offset;\n if (count1 < count)\n count = count1;\n file_buffer_read(&n->u.reg.fbuf, offset, buf, count);\n return count;\n}\n\nstatic int fs_truncate(FSDevice *fs1, FSINode *n, uint64_t size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n intptr_t diff, diff_blocks;\n size_t new_allocated_size;\n \n if (n->type != FT_REG)\n return -P9_EINVAL;\n if (size > UINTPTR_MAX)\n return -P9_ENOSPC;\n diff = size - n->u.reg.size;\n if (diff == 0)\n return 0;\n diff_blocks = to_blocks(fs, size) - to_blocks(fs, n->u.reg.size);\n /* currently cannot resize while loading */\n switch(n->u.reg.state) {\n case REG_STATE_LOADING:\n return -P9_EIO;\n case REG_STATE_UNLOADED:\n if (size == 0) {\n /* now local content */\n n->u.reg.state = REG_STATE_LOCAL;\n }\n break;\n case REG_STATE_LOADED:\n case REG_STATE_LOCAL:\n if (diff > 0) {\n if ((fs->fs_blocks + diff_blocks) > fs->fs_max_blocks)\n return -P9_ENOSPC;\n if (size > n->u.reg.fbuf.allocated_size) {\n new_allocated_size = n->u.reg.fbuf.allocated_size * 5 / 4;\n if (size > new_allocated_size)\n new_allocated_size = size;\n if (file_buffer_resize(&n->u.reg.fbuf, new_allocated_size) < 0)\n return -P9_ENOSPC;\n }\n file_buffer_set(&n->u.reg.fbuf, n->u.reg.size, 0, diff);\n } else {\n new_allocated_size = n->u.reg.fbuf.allocated_size * 4 / 5;\n if (size <= new_allocated_size) {\n if (file_buffer_resize(&n->u.reg.fbuf, new_allocated_size) < 0)\n return -P9_ENOSPC;\n }\n }\n /* file is modified, so it is now local */\n if (n->u.reg.state == REG_STATE_LOADED) {\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n n->u.reg.state = REG_STATE_LOCAL;\n }\n break;\n default:\n abort();\n }\n fs->fs_blocks += diff_blocks;\n assert(fs->fs_blocks >= 0);\n n->u.reg.size = size;\n return 0;\n}\n\nstatic int fs_write(FSDevice *fs1, FSFile *f, uint64_t offset,\n const uint8_t *buf, int count)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n = f->inode;\n uint64_t end;\n int err;\n \n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n if ((f->open_flags & P9_O_NOACCESS) == P9_O_RDONLY)\n return -P9_EIO;\n if (count == 0)\n return 0;\n if (n->u.reg.is_fscmd) {\n return fs_cmd_write(fs1, f, offset, buf, count);\n }\n end = offset + count;\n if (end > n->u.reg.size) {\n err = fs_truncate(fs1, n, end);\n if (err)\n return err;\n }\n inode_update_mtime(fs1, n);\n /* file is modified, so it is now local */\n if (n->u.reg.state == REG_STATE_LOADED) {\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n n->u.reg.state = REG_STATE_LOCAL;\n }\n file_buffer_write(&n->u.reg.fbuf, offset, buf, count);\n return count;\n}\n\nstatic void fs_close(FSDevice *fs, FSFile *f)\n{\n if (f->is_opened) {\n f->is_opened = FALSE;\n }\n if (f->req)\n fs_cmd_close(fs, f);\n}\n\nstatic int fs_stat(FSDevice *fs1, FSFile *f, FSStat *st)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n = f->inode;\n\n inode_to_qid(&st->qid, n);\n st->st_mode = n->mode | (n->type << 12);\n st->st_uid = n->uid;\n st->st_gid = n->gid;\n st->st_nlink = n->refcount;\n if (n->type == FT_BLK || n->type == FT_CHR) {\n /* XXX: check */\n st->st_rdev = (n->u.dev.major << 8) | n->u.dev.minor;\n } else {\n st->st_rdev = 0;\n }\n st->st_blksize = fs->block_size;\n if (n->type == FT_REG) {\n st->st_size = n->u.reg.size;\n } else if (n->type == FT_LNK) {\n st->st_size = strlen(n->u.symlink.name);\n } else if (n->type == FT_DIR) {\n st->st_size = n->u.dir.size;\n } else {\n st->st_size = 0;\n }\n /* in 512 byte blocks */\n st->st_blocks = to_blocks(fs, st->st_size) << (fs->block_size_log2 - 9);\n \n /* Note: atime is not supported */\n st->st_atime_sec = n->mtime_sec;\n st->st_atime_nsec = n->mtime_nsec;\n st->st_mtime_sec = n->mtime_sec;\n st->st_mtime_nsec = n->mtime_nsec;\n st->st_ctime_sec = n->ctime_sec;\n st->st_ctime_nsec = n->ctime_nsec;\n return 0;\n}\n\nstatic int fs_setattr(FSDevice *fs1, FSFile *f, uint32_t mask,\n uint32_t mode, uint32_t uid, uint32_t gid,\n uint64_t size, uint64_t atime_sec, uint64_t atime_nsec,\n uint64_t mtime_sec, uint64_t mtime_nsec)\n{\n FSINode *n = f->inode;\n int ret;\n \n if (mask & P9_SETATTR_MODE) {\n n->mode = mode;\n }\n if (mask & P9_SETATTR_UID) {\n n->uid = uid;\n }\n if (mask & P9_SETATTR_GID) {\n n->gid = gid;\n }\n if (mask & P9_SETATTR_SIZE) {\n ret = fs_truncate(fs1, n, size);\n if (ret)\n return ret;\n }\n if (mask & P9_SETATTR_MTIME) {\n if (mask & P9_SETATTR_MTIME_SET) {\n n->mtime_sec = mtime_sec;\n n->mtime_nsec = mtime_nsec;\n } else {\n inode_update_mtime(fs1, n);\n }\n }\n if (mask & P9_SETATTR_CTIME) {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n n->ctime_sec = tv.tv_sec;\n n->ctime_nsec = tv.tv_usec * 1000;\n }\n return 0;\n}\n\nstatic int fs_link(FSDevice *fs, FSFile *df, FSFile *f, const char *name)\n{\n FSINode *n = df->inode;\n \n if (f->inode->type == FT_DIR)\n return -P9_EPERM;\n if (inode_search(n, name))\n return -P9_EEXIST;\n inode_dir_add(fs, n, name, inode_incref(fs, f->inode));\n return 0;\n}\n\nstatic int fs_symlink(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, const char *symgt, uint32_t gid)\n{\n FSINode *n1, *n = f->inode;\n \n if (inode_search(n, name))\n return -P9_EEXIST;\n\n n1 = inode_new(fs, FT_LNK, 0777, f->uid, gid);\n n1->u.symlink.name = strdup(symgt);\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\nstatic int fs_mknod(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, uint32_t mode, uint32_t major,\n uint32_t minor, uint32_t gid)\n{\n int type;\n FSINode *n1, *n = f->inode;\n\n type = (mode & P9_S_IFMT) >> 12;\n /* XXX: add FT_DIR support */\n if (type != FT_FIFO && type != FT_CHR && type != FT_BLK &&\n type != FT_REG && type != FT_SOCK)\n return -P9_EINVAL;\n if (inode_search(n, name))\n return -P9_EEXIST;\n n1 = inode_new(fs, type, mode, f->uid, gid);\n if (type == FT_CHR || type == FT_BLK) {\n n1->u.dev.major = major;\n n1->u.dev.minor = minor;\n }\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\nstatic int fs_readlink(FSDevice *fs, char *buf, int buf_size, FSFile *f)\n{\n FSINode *n = f->inode;\n int len;\n if (n->type != FT_LNK)\n return -P9_EIO;\n len = min_int(strlen(n->u.symlink.name), buf_size - 1);\n memcpy(buf, n->u.symlink.name, len);\n buf[len] = '\\0';\n return 0;\n}\n\nstatic int fs_renameat(FSDevice *fs, FSFile *f, const char *name, \n FSFile *new_f, const char *new_name)\n{\n FSDirEntry *de, *de1;\n FSINode *n1;\n \n de = inode_search(f->inode, name);\n if (!de)\n return -P9_ENOENT;\n de1 = inode_search(new_f->inode, new_name);\n n1 = NULL;\n if (de1) {\n n1 = de1->inode;\n if (n1->type == FT_DIR)\n return -P9_EEXIST; /* XXX: handle the case */\n inode_dirent_delete_no_decref(fs, new_f->inode, de1);\n }\n inode_dir_add(fs, new_f->inode, new_name, inode_incref(fs, de->inode));\n inode_dirent_delete(fs, f->inode, de);\n if (n1)\n inode_decref(fs, n1);\n return 0;\n}\n\nstatic int fs_unlinkat(FSDevice *fs, FSFile *f, const char *name)\n{\n FSDirEntry *de;\n FSINode *n;\n\n if (!strcmp(name, \".\") || !strcmp(name, \"..\"))\n return -P9_ENOENT;\n de = inode_search(f->inode, name);\n if (!de)\n return -P9_ENOENT;\n n = de->inode;\n if (n->type == FT_DIR) {\n if (!is_empty_dir(fs, n))\n return -P9_ENOTEMPTY;\n flush_dir(fs, n);\n }\n inode_dirent_delete(fs, f->inode, de);\n return 0;\n}\n\nstatic int fs_lock(FSDevice *fs, FSFile *f, const FSLock *lock)\n{\n FSINode *n = f->inode;\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n /* XXX: implement it */\n return P9_LOCK_SUCCESS;\n}\n\nstatic int fs_getlock(FSDevice *fs, FSFile *f, FSLock *lock)\n{\n FSINode *n = f->inode;\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n /* XXX: implement it */\n return 0;\n}\n\n/* XXX: only used with file lists, so not all the data is released */\nstatic void fs_mem_end(FSDevice *fs1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el, *el1, *el2, *el3;\n FSINode *n;\n FSDirEntry *de;\n\n list_for_each_safe(el, el1, &fs->inode_list) {\n n = list_entry(el, FSINode, link);\n n->refcount = 0;\n if (n->type == FT_DIR) {\n list_for_each_safe(el2, el3, &n->u.dir.de_list) {\n de = list_entry(el2, FSDirEntry, link);\n list_del(&de->link);\n free(de);\n }\n init_list_head(&n->u.dir.de_list);\n }\n inode_free(fs1, n);\n }\n assert(list_empty(&fs->inode_cache_list));\n free(fs->import_dir);\n}\n\nFSDevice *fs_mem_init(void)\n{\n FSDeviceMem *fs;\n FSDevice *fs1;\n FSINode *n;\n\n fs = mallocz(sizeof(*fs));\n fs1 = &fs->common;\n\n fs->common.fs_end = fs_mem_end;\n fs->common.fs_delete = fs_delete;\n fs->common.fs_statfs = fs_statfs;\n fs->common.fs_attach = fs_attach;\n fs->common.fs_walk = fs_walk;\n fs->common.fs_mkdir = fs_mkdir;\n fs->common.fs_open = fs_open;\n fs->common.fs_create = fs_create;\n fs->common.fs_stat = fs_stat;\n fs->common.fs_setattr = fs_setattr;\n fs->common.fs_close = fs_close;\n fs->common.fs_readdir = fs_readdir;\n fs->common.fs_read = fs_read;\n fs->common.fs_write = fs_write;\n fs->common.fs_link = fs_link;\n fs->common.fs_symlink = fs_symlink;\n fs->common.fs_mknod = fs_mknod;\n fs->common.fs_readlink = fs_readlink;\n fs->common.fs_renameat = fs_renameat;\n fs->common.fs_unlinkat = fs_unlinkat;\n fs->common.fs_lock = fs_lock;\n fs->common.fs_getlock = fs_getlock;\n\n init_list_head(&fs->inode_list);\n fs->inode_num_alloc = 1;\n fs->block_size_log2 = FS_BLOCK_SIZE_LOG2;\n fs->block_size = 1 << fs->block_size_log2;\n fs->inode_limit = 1 << 20; /* arbitrary */\n fs->fs_max_blocks = 1 << (30 - fs->block_size_log2); /* arbitrary */\n\n init_list_head(&fs->inode_cache_list);\n fs->inode_cache_size_limit = DEFAULT_INODE_CACHE_SIZE;\n\n init_list_head(&fs->preload_list);\n init_list_head(&fs->preload_archive_list);\n\n init_list_head(&fs->base_url_list);\n\n /* create the root inode */\n n = inode_new(fs1, FT_DIR, 0777, 0, 0);\n inode_dir_add(fs1, n, \".\", inode_incref(fs1, n));\n inode_dir_add(fs1, n, \"..\", inode_incref(fs1, n));\n fs->root_inode = n;\n\n return (FSDevice *)fs;\n}\n\nstatic BOOL fs_is_net(FSDevice *fs)\n{\n return (fs->fs_end == fs_mem_end);\n}\n\nstatic FSBaseURL *fs_find_base_url(FSDevice *fs1,\n const char *base_url_id)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el;\n FSBaseURL *bu;\n \n list_for_each(el, &fs->base_url_list) {\n bu = list_entry(el, FSBaseURL, link);\n if (!strcmp(bu->base_url_id, base_url_id))\n return bu;\n }\n return NULL;\n}\n\nstatic void fs_base_url_decref(FSDevice *fs, FSBaseURL *bu)\n{\n assert(bu->ref_count >= 1);\n if (--bu->ref_count == 0) {\n free(bu->base_url_id);\n free(bu->url);\n free(bu->user);\n free(bu->password);\n list_del(&bu->link);\n free(bu);\n }\n}\n\nstatic FSBaseURL *fs_net_set_base_url(FSDevice *fs1,\n const char *base_url_id,\n const char *url,\n const char *user, const char *password,\n AES_KEY *aes_state)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSBaseURL *bu;\n \n assert(fs_is_net(fs1));\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu) {\n bu = mallocz(sizeof(*bu));\n bu->base_url_id = strdup(base_url_id);\n bu->ref_count = 1;\n list_add_tail(&bu->link, &fs->base_url_list);\n } else {\n free(bu->url);\n free(bu->user);\n free(bu->password);\n }\n\n bu->url = strdup(url);\n if (user)\n bu->user = strdup(user);\n else\n bu->user = NULL;\n if (password)\n bu->password = strdup(password);\n else\n bu->password = NULL;\n if (aes_state) {\n bu->encrypted = TRUE;\n bu->aes_state = *aes_state;\n } else {\n bu->encrypted = FALSE;\n }\n return bu;\n}\n\nstatic int fs_net_reset_base_url(FSDevice *fs1,\n const char *base_url_id)\n{\n FSBaseURL *bu;\n \n assert(fs_is_net(fs1));\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu)\n return -P9_ENOENT;\n fs_base_url_decref(fs1, bu);\n return 0;\n}\n\nstatic void fs_net_set_fs_max_size(FSDevice *fs1, uint64_t fs_max_size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n assert(fs_is_net(fs1));\n fs->fs_max_blocks = to_blocks(fs, fs_max_size);\n}\n\nstatic int fs_net_set_url(FSDevice *fs1, FSINode *n,\n const char *base_url_id, FSFileID file_id, uint64_t size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSBaseURL *bu;\n\n assert(fs_is_net(fs1));\n\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu)\n return -P9_ENOENT;\n\n /* XXX: could accept more state */\n if (n->type != FT_REG ||\n n->u.reg.state != REG_STATE_LOCAL ||\n n->u.reg.fbuf.allocated_size != 0)\n return -P9_EIO;\n \n if (size > 0) {\n n->u.reg.state = REG_STATE_UNLOADED;\n n->u.reg.base_url = bu;\n bu->ref_count++;\n n->u.reg.size = size;\n fs->fs_blocks += to_blocks(fs, size);\n n->u.reg.file_id = file_id;\n }\n return 0;\n}\n\n#ifdef DUMP_CACHE_LOAD\n\n#include \"json.h\"\n\n#define ARCHIVE_SIZE_MAX (4 << 20)\n\nstatic void fs_dump_add_file(struct list_head *head, const char *name)\n{\n PreloadFile *pf;\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(name);\n list_add_tail(&pf->link, head);\n}\n\nstatic PreloadFile *fs_dump_find_file(struct list_head *head, const char *name)\n{\n PreloadFile *pf;\n struct list_head *el;\n list_for_each(el, head) {\n pf = list_entry(el, PreloadFile, link);\n if (!strcmp(pf->name, name))\n return pf;\n }\n return NULL;\n}\n\nstatic void dump_close_archive(FSDevice *fs1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (fs->dump_archive_file) {\n fclose(fs->dump_archive_file);\n }\n fs->dump_archive_file = NULL;\n fs->dump_archive_size = 0;\n}\n\nstatic void dump_loaded_file(FSDevice *fs1, FSINode *n)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char filename[1024];\n const char *fname, *p;\n \n if (!fs->dump_cache_load || !n->u.reg.filename)\n return;\n fname = n->u.reg.filename;\n \n if (fs_dump_find_file(&fs->dump_preload_list, fname)) {\n dump_close_archive(fs1);\n p = strrchr(fname, '/');\n if (!p)\n p = fname;\n else\n p++;\n free(fs->dump_archive_name);\n fs->dump_archive_name = strdup(p);\n fs->dump_started = TRUE;\n fs->dump_archive_num = 0;\n\n fprintf(fs->dump_preload_file, \"\\n%s :\\n\", fname);\n }\n if (!fs->dump_started)\n return;\n \n if (!fs->dump_archive_file) {\n snprintf(filename, sizeof(filename), \"%s/%s%d\",\n fs->dump_preload_dir, fs->dump_archive_name,\n fs->dump_archive_num);\n fs->dump_archive_file = fopen(filename, \"wb\");\n if (!fs->dump_archive_file) {\n perror(filename);\n exit(1);\n }\n fprintf(fs->dump_preload_archive_file, \"\\n@.preload2/%s%d :\\n\",\n fs->dump_archive_name, fs->dump_archive_num);\n fprintf(fs->dump_preload_file, \" @.preload2/%s%d\\n\",\n fs->dump_archive_name, fs->dump_archive_num);\n fflush(fs->dump_preload_file);\n fs->dump_archive_num++;\n }\n\n if (n->u.reg.size >= ARCHIVE_SIZE_MAX) {\n /* exclude large files from archive */\n /* add indicative size */\n fprintf(fs->dump_preload_file, \" %s %\" PRId64 \"\\n\",\n fname, n->u.reg.size);\n fflush(fs->dump_preload_file);\n } else {\n fprintf(fs->dump_preload_archive_file, \" %s %\" PRId64 \" %\" PRIx64 \"\\n\",\n n->u.reg.filename, n->u.reg.size, n->u.reg.file_id);\n fflush(fs->dump_preload_archive_file);\n fwrite(n->u.reg.fbuf.data, 1, n->u.reg.size, fs->dump_archive_file);\n fflush(fs->dump_archive_file);\n fs->dump_archive_size += n->u.reg.size;\n if (fs->dump_archive_size >= ARCHIVE_SIZE_MAX) {\n dump_close_archive(fs1);\n }\n }\n}\n\nstatic JSONValue json_load(const char *filename)\n{\n FILE *f;\n JSONValue val;\n size_t size;\n char *buf;\n \n f = fopen(filename, \"rb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n size = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = malloc(size + 1);\n fread(buf, 1, size, f);\n fclose(f);\n val = json_parse_value_len(buf, size);\n free(buf);\n return val;\n}\n\nvoid fs_dump_cache_load(FSDevice *fs1, const char *cfg_filename)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n JSONValue cfg, val, array;\n char *fname;\n const char *preload_dir, *name;\n int i;\n \n if (!fs_is_net(fs1))\n return;\n cfg = json_load(cfg_filename);\n if (json_is_error(cfg)) {\n fprintf(stderr, \"%s\\n\", json_get_error(cfg));\n exit(1);\n }\n\n val = json_object_get(cfg, \"preload_dir\");\n if (json_is_undefined(cfg)) {\n config_error:\n exit(1);\n }\n preload_dir = json_get_str(val);\n if (!preload_dir) {\n fprintf(stderr, \"expecting preload_filename\\n\");\n goto config_error;\n }\n fs->dump_preload_dir = strdup(preload_dir);\n \n init_list_head(&fs->dump_preload_list);\n init_list_head(&fs->dump_exclude_list);\n\n array = json_object_get(cfg, \"preload\");\n if (array.type != JSON_ARRAY) {\n fprintf(stderr, \"expecting preload array\\n\");\n goto config_error;\n }\n for(i = 0; i < array.u.array->len; i++) {\n val = json_array_get(array, i);\n name = json_get_str(val);\n if (!name) {\n fprintf(stderr, \"expecting a string\\n\");\n goto config_error;\n }\n fs_dump_add_file(&fs->dump_preload_list, name);\n }\n json_free(cfg);\n\n fname = compose_path(fs->dump_preload_dir, \"preload.txt\");\n fs->dump_preload_file = fopen(fname, \"w\");\n if (!fs->dump_preload_file) {\n perror(fname);\n exit(1);\n }\n free(fname);\n\n fname = compose_path(fs->dump_preload_dir, \"preload_archive.txt\");\n fs->dump_preload_archive_file = fopen(fname, \"w\");\n if (!fs->dump_preload_archive_file) {\n perror(fname);\n exit(1);\n }\n free(fname);\n\n fs->dump_cache_load = TRUE;\n}\n#else\nvoid fs_dump_cache_load(FSDevice *fs1, const char *cfg_filename)\n{\n}\n#endif\n\n/***********************************************/\n/* file list processing */\n\nstatic int filelist_load_rec(FSDevice *fs1, const char **pp, FSINode *dir,\n const char *path)\n{\n // FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char fname[1024], lname[1024];\n int ret;\n const char *p;\n FSINodeTypeEnum type;\n uint32_t mode, uid, gid;\n uint64_t size;\n FSINode *n;\n\n p = *pp;\n for(;;) {\n /* skip comments or empty lines */\n if (*p == '\\0')\n break;\n if (*p == '#') {\n skip_line(&p);\n continue;\n }\n /* end of directory */\n if (*p == '.') {\n p++;\n skip_line(&p);\n break;\n }\n if (parse_uint32_base(&mode, &p, 8) < 0) {\n fprintf(stderr, \"invalid mode\\n\");\n return -1;\n }\n type = mode >> 12;\n mode &= 0xfff;\n \n if (parse_uint32(&uid, &p) < 0) {\n fprintf(stderr, \"invalid uid\\n\");\n return -1;\n }\n\n if (parse_uint32(&gid, &p) < 0) {\n fprintf(stderr, \"invalid gid\\n\");\n return -1;\n }\n\n n = inode_new(fs1, type, mode, uid, gid);\n \n size = 0;\n switch(type) {\n case FT_CHR:\n case FT_BLK:\n if (parse_uint32(&n->u.dev.major, &p) < 0) {\n fprintf(stderr, \"invalid major\\n\");\n return -1;\n }\n if (parse_uint32(&n->u.dev.minor, &p) < 0) {\n fprintf(stderr, \"invalid minor\\n\");\n return -1;\n }\n break;\n case FT_REG:\n if (parse_uint64(&size, &p) < 0) {\n fprintf(stderr, \"invalid size\\n\");\n return -1;\n }\n break;\n case FT_DIR:\n inode_dir_add(fs1, n, \".\", inode_incref(fs1, n));\n inode_dir_add(fs1, n, \"..\", inode_incref(fs1, dir));\n break;\n default:\n break;\n }\n \n /* modification time */\n if (parse_time(&n->mtime_sec, &n->mtime_nsec, &p) < 0) {\n fprintf(stderr, \"invalid mtime\\n\");\n return -1;\n }\n\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return -1;\n }\n inode_dir_add(fs1, dir, fname, n);\n \n if (type == FT_LNK) {\n if (parse_fname(lname, sizeof(lname), &p) < 0) {\n fprintf(stderr, \"invalid symlink name\\n\");\n return -1;\n }\n n->u.symlink.name = strdup(lname);\n } else if (type == FT_REG && size > 0) {\n FSFileID file_id;\n if (parse_file_id(&file_id, &p) < 0) {\n fprintf(stderr, \"invalid file id\\n\");\n return -1;\n }\n fs_net_set_url(fs1, n, \"/\", file_id, size);\n#ifdef DUMP_CACHE_LOAD\n {\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (fs->dump_cache_load\n#ifdef DEBUG_CACHE\n || 1\n#endif\n ) {\n n->u.reg.filename = compose_path(path, fname);\n } else {\n n->u.reg.filename = NULL;\n }\n }\n#endif\n }\n\n skip_line(&p);\n \n if (type == FT_DIR) {\n char *path1;\n path1 = compose_path(path, fname);\n ret = filelist_load_rec(fs1, &p, n, path1);\n free(path1);\n if (ret)\n return ret;\n }\n }\n *pp = p;\n return 0;\n}\n\nstatic int filelist_load(FSDevice *fs1, const char *str)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int ret;\n const char *p;\n \n if (parse_tag_version(str) != 1)\n return -1;\n p = skip_header(str);\n if (!p)\n return -1;\n ret = filelist_load_rec(fs1, &p, fs->root_inode, \"\");\n return ret;\n}\n\n/************************************************************/\n/* FS init from network */\n\nstatic void __attribute__((format(printf, 1, 2))) fatal_error(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n fprintf(stderr, \"Error: \");\n vfprintf(stderr, fmt, ap);\n fprintf(stderr, \"\\n\");\n va_end(ap);\n exit(1);\n}\n\nstatic void fs_create_cmd(FSDevice *fs)\n{\n FSFile *root_fd;\n FSQID qid;\n FSINode *n;\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\"));\n assert(!fs->fs_create(fs, &qid, root_fd, FSCMD_NAME, P9_O_RDWR | P9_O_TRUNC,\n 0666, 0));\n n = root_fd->inode;\n n->u.reg.is_fscmd = TRUE;\n fs->fs_delete(fs, root_fd);\n}\n\ntypedef struct {\n FSDevice *fs;\n char *url;\n void (*start_cb)(void *opaque);\n void *start_opaque;\n \n FSFile *root_fd;\n FSFile *fd;\n int file_index;\n \n} FSNetInitState;\n\nstatic void fs_initial_sync(FSDevice *fs,\n const char *url, void (*start_cb)(void *opaque),\n void *start_opaque);\nstatic void head_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque);\nstatic void filelist_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque);\nstatic void kernel_load_cb(FSDevice *fs, FSQID *qid, int err,\n void *opaque);\nstatic int preload_parse(FSDevice *fs, const char *fname, BOOL is_new);\n\n#ifdef EMSCRIPTEN\nstatic FSDevice *fs_import_fs;\n#endif\n\n#define DEFAULT_IMPORT_FILE_PATH \"/tmp\"\n\nFSDevice *fs_net_init(const char *url, void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n FSDevice *fs;\n FSDeviceMem *fs1;\n \n fs_wget_init();\n \n fs = fs_mem_init();\n#ifdef EMSCRIPTEN\n if (!fs_import_fs)\n fs_import_fs = fs;\n#endif\n fs1 = (FSDeviceMem *)fs;\n fs1->import_dir = strdup(DEFAULT_IMPORT_FILE_PATH);\n \n fs_create_cmd(fs);\n\n if (url) {\n fs_initial_sync(fs, url, start_cb, start_opaque);\n }\n return fs;\n}\n\nstatic void fs_initial_sync(FSDevice *fs,\n const char *url, void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n FSNetInitState *s;\n FSFile *head_fd;\n FSQID qid;\n char *head_url;\n char buf[128];\n struct timeval tv;\n \n s = mallocz(sizeof(*s));\n s->fs = fs;\n s->url = strdup(url);\n s->start_cb = start_cb;\n s->start_opaque = start_opaque;\n assert(!fs->fs_attach(fs, &s->root_fd, &qid, 0, \"\", \"\"));\n \n /* avoid using cached version */\n gettimeofday(&tv, NULL);\n snprintf(buf, sizeof(buf), HEAD_FILENAME \"?nocache=%\" PRId64,\n (int64_t)tv.tv_sec * 1000000 + tv.tv_usec);\n head_url = compose_url(s->url, buf);\n head_fd = fs_dup(fs, s->root_fd);\n assert(!fs->fs_create(fs, &qid, head_fd, \".head\",\n P9_O_RDWR | P9_O_TRUNC, 0644, 0));\n fs_wget_file2(fs, head_fd, head_url, NULL, NULL, NULL, 0,\n head_loaded, s, NULL);\n free(head_url);\n}\n\nstatic void head_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque)\n{\n FSNetInitState *s = opaque;\n char *buf, *root_url, *url;\n char fname[FILEID_SIZE_MAX];\n FSFileID root_id;\n FSFile *new_filelist_fd;\n FSQID qid;\n uint64_t fs_max_size;\n \n if (size < 0)\n fatal_error(\"could not load 'head' file (HTTP error=%d)\", -(int)size);\n \n buf = malloc(size + 1);\n fs->fs_read(fs, f, 0, (uint8_t *)buf, size);\n buf[size] = '\\0';\n fs->fs_delete(fs, f);\n fs->fs_unlinkat(fs, s->root_fd, \".head\");\n\n if (parse_tag_version(buf) != 1)\n fatal_error(\"invalid head version\");\n\n if (parse_tag_file_id(&root_id, buf, \"RootID\") < 0)\n fatal_error(\"expected RootID tag\");\n\n if (parse_tag_uint64(&fs_max_size, buf, \"FSMaxSize\") == 0 &&\n fs_max_size >= ((uint64_t)1 << 20)) {\n fs_net_set_fs_max_size(fs, fs_max_size);\n }\n \n /* set the Root URL in the filesystem */\n root_url = compose_url(s->url, ROOT_FILENAME);\n fs_net_set_base_url(fs, \"/\", root_url, NULL, NULL, NULL);\n \n new_filelist_fd = fs_dup(fs, s->root_fd);\n assert(!fs->fs_create(fs, &qid, new_filelist_fd, \".filelist.txt\",\n P9_O_RDWR | P9_O_TRUNC, 0644, 0));\n\n file_id_to_filename(fname, root_id);\n url = compose_url(root_url, fname);\n fs_wget_file2(fs, new_filelist_fd, url, NULL, NULL, NULL, 0,\n filelist_loaded, s, NULL);\n free(root_url);\n free(url);\n}\n\nstatic void filelist_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque)\n{\n FSNetInitState *s = opaque;\n uint8_t *buf;\n\n if (size < 0)\n fatal_error(\"could not load file list (HTTP error=%d)\", -(int)size);\n \n buf = malloc(size + 1);\n fs->fs_read(fs, f, 0, buf, size);\n buf[size] = '\\0';\n fs->fs_delete(fs, f);\n fs->fs_unlinkat(fs, s->root_fd, \".filelist.txt\");\n \n if (filelist_load(fs, (char *)buf) != 0)\n fatal_error(\"error while parsing file list\");\n\n /* try to load the kernel and the preload file */\n s->file_index = 0;\n kernel_load_cb(fs, NULL, 0, s);\n}\n\n\n#define FILE_LOAD_COUNT 2\n\nstatic const char *kernel_file_list[FILE_LOAD_COUNT] = {\n \".preload\",\n \".preload2/preload.txt\",\n};\n\nstatic void kernel_load_cb(FSDevice *fs, FSQID *qid1, int err,\n void *opaque)\n{\n FSNetInitState *s = opaque;\n FSQID qid;\n\n#ifdef DUMP_CACHE_LOAD\n /* disable preloading if dumping cache load */\n if (((FSDeviceMem *)fs)->dump_cache_load)\n return;\n#endif\n\n if (s->fd) {\n fs->fs_delete(fs, s->fd);\n s->fd = NULL;\n }\n \n if (s->file_index >= FILE_LOAD_COUNT) {\n /* all files are loaded */\n if (preload_parse(fs, \".preload2/preload.txt\", TRUE) < 0) { \n preload_parse(fs, \".preload\", FALSE);\n }\n fs->fs_delete(fs, s->root_fd);\n if (s->start_cb)\n s->start_cb(s->start_opaque);\n free(s);\n } else {\n s->fd = fs_walk_path(fs, s->root_fd, kernel_file_list[s->file_index++]);\n if (!s->fd)\n goto done;\n err = fs->fs_open(fs, &qid, s->fd, P9_O_RDONLY, kernel_load_cb, s);\n if (err <= 0) {\n done:\n kernel_load_cb(fs, NULL, 0, s);\n }\n }\n}\n\nstatic void preload_parse_str_old(FSDevice *fs1, const char *p)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char fname[1024];\n PreloadEntry *pe;\n PreloadFile *pf;\n FSINode *n;\n\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\n') {\n p++;\n continue;\n }\n if (*p == '\\0')\n break;\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n // printf(\"preload file='%s\\n\", fname);\n n = inode_search_path(fs1, fname);\n if (!n || n->type != FT_REG || n->u.reg.state == REG_STATE_LOCAL) {\n fprintf(stderr, \"invalid preload file: '%s'\\n\", fname);\n while (*p != '\\n' && *p != '\\0')\n p++;\n } else {\n pe = mallocz(sizeof(*pe));\n pe->file_id = n->u.reg.file_id;\n init_list_head(&pe->file_list);\n list_add_tail(&pe->link, &fs->preload_list);\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\0' || *p == '\\n')\n break;\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n // printf(\" adding '%s'\\n\", fname);\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(fname);\n list_add_tail(&pf->link, &pe->file_list); \n }\n }\n }\n}\n\nstatic void preload_parse_str(FSDevice *fs1, const char *p)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n PreloadEntry *pe;\n PreloadArchive *pa;\n FSINode *n;\n BOOL is_archive;\n char fname[1024];\n \n pe = NULL;\n pa = NULL;\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\n') {\n pe = NULL;\n p++;\n continue;\n }\n if (*p == '#')\n continue; /* comment */\n if (*p == '\\0')\n break;\n\n is_archive = FALSE;\n if (*p == '@') {\n is_archive = TRUE;\n p++;\n }\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n while (isspace_nolf(*p))\n p++;\n if (*p == ':') {\n p++;\n // printf(\"preload file='%s' archive=%d\\n\", fname, is_archive);\n n = inode_search_path(fs1, fname);\n pe = NULL;\n pa = NULL;\n if (!n || n->type != FT_REG || n->u.reg.state == REG_STATE_LOCAL) {\n fprintf(stderr, \"invalid preload file: '%s'\\n\", fname);\n while (*p != '\\n' && *p != '\\0')\n p++;\n } else if (is_archive) {\n pa = mallocz(sizeof(*pa));\n pa->name = strdup(fname);\n init_list_head(&pa->file_list);\n list_add_tail(&pa->link, &fs->preload_archive_list);\n } else {\n pe = mallocz(sizeof(*pe));\n pe->file_id = n->u.reg.file_id;\n init_list_head(&pe->file_list);\n list_add_tail(&pe->link, &fs->preload_list);\n }\n } else {\n if (!pe && !pa) {\n fprintf(stderr, \"filename without target: %s\\n\", fname);\n return;\n }\n if (pa) {\n PreloadArchiveFile *paf;\n FSFileID file_id;\n uint64_t size;\n\n if (parse_uint64(&size, &p) < 0) {\n fprintf(stderr, \"invalid size\\n\");\n return;\n }\n\n if (parse_file_id(&file_id, &p) < 0) {\n fprintf(stderr, \"invalid file id\\n\");\n return;\n }\n\n paf = mallocz(sizeof(*paf));\n paf->name = strdup(fname);\n paf->file_id = file_id;\n paf->size = size;\n list_add_tail(&paf->link, &pa->file_list);\n } else {\n PreloadFile *pf;\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(fname);\n pf->is_archive = is_archive;\n list_add_tail(&pf->link, &pe->file_list);\n }\n }\n /* skip the rest of the line */\n while (*p != '\\n' && *p != '\\0')\n p++;\n if (*p == '\\n')\n p++;\n }\n}\n\nstatic int preload_parse(FSDevice *fs, const char *fname, BOOL is_new)\n{\n FSINode *n;\n char *buf;\n size_t size;\n \n n = inode_search_path(fs, fname);\n if (!n || n->type != FT_REG || n->u.reg.state != REG_STATE_LOADED)\n return -1;\n /* transform to zero terminated string */\n size = n->u.reg.size;\n buf = malloc(size + 1);\n file_buffer_read(&n->u.reg.fbuf, 0, (uint8_t *)buf, size);\n buf[size] = '\\0';\n if (is_new)\n preload_parse_str(fs, buf);\n else\n preload_parse_str_old(fs, buf);\n free(buf);\n return 0;\n}\n\n\n\n/************************************************************/\n/* FS user interface */\n\ntypedef struct CmdXHRState {\n FSFile *req_fd;\n FSFile *root_fd;\n FSFile *fd;\n FSFile *post_fd;\n AES_KEY aes_state;\n} CmdXHRState;\n\nstatic void fs_cmd_xhr_on_load(FSDevice *fs, FSFile *f, int64_t size,\n void *opaque);\n\nstatic int parse_hex_buf(uint8_t *buf, int buf_size, const char **pp)\n{\n char buf1[1024];\n int len;\n \n if (parse_fname(buf1, sizeof(buf1), pp) < 0)\n return -1;\n len = strlen(buf1);\n if ((len & 1) != 0)\n return -1;\n len >>= 1;\n if (len > buf_size)\n return -1;\n if (decode_hex(buf, buf1, len) < 0)\n return -1;\n return len;\n}\n\nstatic int fs_cmd_xhr(FSDevice *fs, FSFile *f,\n const char *p, uint32_t uid, uint32_t gid)\n{\n char url[1024], post_filename[1024], filename[1024];\n char user_buf[128], *user;\n char password_buf[128], *password;\n FSQID qid;\n FSFile *fd, *root_fd, *post_fd;\n uint64_t post_data_len;\n int err, aes_key_len;\n CmdXHRState *s;\n char *name;\n AES_KEY *paes_state;\n uint8_t aes_key[FS_KEY_LEN];\n uint32_t flags;\n FSCMDRequest *req;\n\n /* a request is already done or in progress */\n if (f->req != NULL)\n return -P9_EIO;\n\n if (parse_fname(url, sizeof(url), &p) < 0)\n goto fail;\n if (parse_fname(user_buf, sizeof(user_buf), &p) < 0)\n goto fail;\n if (parse_fname(password_buf, sizeof(password_buf), &p) < 0)\n goto fail;\n if (parse_fname(post_filename, sizeof(post_filename), &p) < 0)\n goto fail;\n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n aes_key_len = parse_hex_buf(aes_key, FS_KEY_LEN, &p);\n if (aes_key_len < 0)\n goto fail;\n if (parse_uint32(&flags, &p) < 0)\n goto fail;\n if (aes_key_len != 0 && aes_key_len != FS_KEY_LEN)\n goto fail;\n\n if (user_buf[0] != '\\0')\n user = user_buf;\n else\n user = NULL;\n if (password_buf[0] != '\\0')\n password = password_buf;\n else\n password = NULL;\n\n // printf(\"url='%s' '%s' '%s' filename='%s'\\n\", url, user, password, filename);\n assert(!fs->fs_attach(fs, &root_fd, &qid, uid, \"\", \"\"));\n post_fd = NULL;\n\n fd = fs_walk_path1(fs, root_fd, filename, &name);\n if (!fd) {\n err = -P9_ENOENT;\n goto fail1;\n }\n /* XXX: until fs_create is fixed */\n fs->fs_unlinkat(fs, fd, name);\n\n err = fs->fs_create(fs, &qid, fd, name,\n P9_O_RDWR | P9_O_TRUNC, 0600, gid);\n if (err < 0) {\n goto fail1;\n }\n\n if (post_filename[0] != '\\0') {\n FSINode *n;\n \n post_fd = fs_walk_path(fs, root_fd, post_filename);\n if (!post_fd) {\n err = -P9_ENOENT;\n goto fail1;\n }\n err = fs->fs_open(fs, &qid, post_fd, P9_O_RDONLY, NULL, NULL);\n if (err < 0)\n goto fail1;\n n = post_fd->inode;\n assert(n->type == FT_REG && n->u.reg.state == REG_STATE_LOCAL);\n post_data_len = n->u.reg.size;\n } else {\n post_data_len = 0;\n }\n\n s = mallocz(sizeof(*s));\n s->root_fd = root_fd;\n s->fd = fd;\n s->post_fd = post_fd;\n if (aes_key_len != 0) {\n AES_set_decrypt_key(aes_key, FS_KEY_LEN * 8, &s->aes_state);\n paes_state = &s->aes_state;\n } else {\n paes_state = NULL;\n }\n\n req = mallocz(sizeof(*req));\n req->type = FS_CMD_XHR;\n req->reply_len = 0;\n req->xhr_state = s;\n s->req_fd = f;\n f->req = req;\n \n fs_wget_file2(fs, fd, url, user, password, post_fd, post_data_len,\n fs_cmd_xhr_on_load, s, paes_state);\n return 0;\n fail1:\n if (fd)\n fs->fs_delete(fs, fd);\n if (post_fd)\n fs->fs_delete(fs, post_fd);\n fs->fs_delete(fs, root_fd);\n return err;\n fail:\n return -P9_EIO;\n}\n\nstatic void fs_cmd_xhr_on_load(FSDevice *fs, FSFile *f, int64_t size,\n void *opaque)\n{\n CmdXHRState *s = opaque;\n FSCMDRequest *req;\n int ret;\n \n // printf(\"fs_cmd_xhr_on_load: size=%d\\n\", (int)size);\n\n if (s->fd)\n fs->fs_delete(fs, s->fd);\n if (s->post_fd)\n fs->fs_delete(fs, s->post_fd);\n fs->fs_delete(fs, s->root_fd);\n \n if (s->req_fd) {\n req = s->req_fd->req;\n if (size < 0) {\n ret = size;\n } else {\n ret = 0;\n }\n put_le32(req->reply_buf, ret);\n req->reply_len = sizeof(ret);\n req->xhr_state = NULL;\n }\n free(s);\n}\n\nstatic int fs_cmd_set_base_url(FSDevice *fs, const char *p)\n{\n // FSDeviceMem *fs1 = (FSDeviceMem *)fs;\n char url[1024], base_url_id[1024];\n char user_buf[128], *user;\n char password_buf[128], *password;\n AES_KEY aes_state, *paes_state;\n uint8_t aes_key[FS_KEY_LEN];\n int aes_key_len;\n \n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n if (parse_fname(url, sizeof(url), &p) < 0)\n goto fail;\n if (parse_fname(user_buf, sizeof(user_buf), &p) < 0)\n goto fail;\n if (parse_fname(password_buf, sizeof(password_buf), &p) < 0)\n goto fail;\n aes_key_len = parse_hex_buf(aes_key, FS_KEY_LEN, &p);\n if (aes_key_len < 0)\n goto fail;\n\n if (user_buf[0] != '\\0')\n user = user_buf;\n else\n user = NULL;\n if (password_buf[0] != '\\0')\n password = password_buf;\n else\n password = NULL;\n\n if (aes_key_len != 0) {\n if (aes_key_len != FS_KEY_LEN)\n goto fail;\n AES_set_decrypt_key(aes_key, FS_KEY_LEN * 8, &aes_state);\n paes_state = &aes_state;\n } else {\n paes_state = NULL;\n }\n\n fs_net_set_base_url(fs, base_url_id, url, user, password,\n paes_state);\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_reset_base_url(FSDevice *fs, const char *p)\n{\n char base_url_id[1024];\n \n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n fs_net_reset_base_url(fs, base_url_id);\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_set_url(FSDevice *fs, const char *p)\n{\n char base_url_id[1024];\n char filename[1024];\n FSFileID file_id;\n uint64_t size;\n FSINode *n;\n \n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n if (parse_file_id(&file_id, &p) < 0)\n goto fail;\n if (parse_uint64(&size, &p) < 0)\n goto fail;\n \n n = inode_search_path(fs, filename);\n if (!n) {\n return -P9_ENOENT;\n }\n return fs_net_set_url(fs, n, base_url_id, file_id, size);\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_export_file(FSDevice *fs, const char *p)\n{\n char filename[1024];\n FSINode *n;\n const char *name;\n uint8_t *buf;\n \n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n n = inode_search_path(fs, filename);\n if (!n)\n return -P9_ENOENT;\n if (n->type != FT_REG ||\n (n->u.reg.state != REG_STATE_LOCAL &&\n n->u.reg.state != REG_STATE_LOADED))\n goto fail;\n name = strrchr(filename, '/');\n if (name)\n name++;\n else\n name = filename;\n /* XXX: pass the buffer to JS to avoid the allocation */\n buf = malloc(n->u.reg.size);\n file_buffer_read(&n->u.reg.fbuf, 0, buf, n->u.reg.size);\n fs_export_file(name, buf, n->u.reg.size);\n free(buf);\n return 0;\n fail:\n return -P9_EIO;\n}\n\n/* PBKDF2 crypto acceleration */\nstatic int fs_cmd_pbkdf2(FSDevice *fs, FSFile *f, const char *p)\n{\n uint8_t pwd[1024];\n uint8_t salt[128];\n uint32_t iter, key_len;\n int pwd_len, salt_len;\n FSCMDRequest *req;\n \n /* a request is already done or in progress */\n if (f->req != NULL)\n return -P9_EIO;\n\n pwd_len = parse_hex_buf(pwd, sizeof(pwd), &p);\n if (pwd_len < 0)\n goto fail;\n salt_len = parse_hex_buf(salt, sizeof(salt), &p);\n if (pwd_len < 0)\n goto fail;\n if (parse_uint32(&iter, &p) < 0)\n goto fail;\n if (parse_uint32(&key_len, &p) < 0)\n goto fail;\n if (key_len > FS_CMD_REPLY_LEN_MAX ||\n key_len == 0)\n goto fail;\n req = mallocz(sizeof(*req));\n req->type = FS_CMD_PBKDF2;\n req->reply_len = key_len;\n pbkdf2_hmac_sha256(pwd, pwd_len, salt, salt_len, iter, key_len,\n req->reply_buf);\n f->req = req;\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_set_import_dir(FSDevice *fs, FSFile *f, const char *p)\n{\n FSDeviceMem *fs1 = (FSDeviceMem *)fs;\n char filename[1024];\n\n if (parse_fname(filename, sizeof(filename), &p) < 0)\n return -P9_EINVAL;\n free(fs1->import_dir);\n fs1->import_dir = strdup(filename);\n return 0;\n}\n\nstatic int fs_cmd_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int buf_len)\n{\n char *buf1;\n const char *p;\n char cmd[64];\n int err;\n \n /* transform into a string */\n buf1 = malloc(buf_len + 1);\n memcpy(buf1, buf, buf_len);\n buf1[buf_len] = '\\0';\n \n err = 0;\n p = buf1;\n if (parse_fname(cmd, sizeof(cmd), &p) < 0)\n goto fail;\n if (!strcmp(cmd, \"xhr\")) {\n err = fs_cmd_xhr(fs, f, p, f->uid, 0);\n } else if (!strcmp(cmd, \"set_base_url\")) {\n err = fs_cmd_set_base_url(fs, p);\n } else if (!strcmp(cmd, \"reset_base_url\")) {\n err = fs_cmd_reset_base_url(fs, p);\n } else if (!strcmp(cmd, \"set_url\")) {\n err = fs_cmd_set_url(fs, p);\n } else if (!strcmp(cmd, \"export_file\")) {\n err = fs_cmd_export_file(fs, p);\n } else if (!strcmp(cmd, \"pbkdf2\")) {\n err = fs_cmd_pbkdf2(fs, f, p);\n } else if (!strcmp(cmd, \"set_import_dir\")) {\n err = fs_cmd_set_import_dir(fs, f, p);\n } else {\n printf(\"unknown command: '%s'\\n\", cmd);\n fail:\n err = -P9_EIO;\n }\n free(buf1);\n if (err == 0)\n return buf_len;\n else\n return err;\n}\n\nstatic int fs_cmd_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int buf_len)\n{\n FSCMDRequest *req;\n int l;\n \n req = f->req;\n if (!req)\n return -P9_EIO;\n l = min_int(req->reply_len, buf_len);\n memcpy(buf, req->reply_buf, l);\n return l;\n}\n\nstatic void fs_cmd_close(FSDevice *fs, FSFile *f)\n{\n FSCMDRequest *req;\n req = f->req;\n\n if (req) {\n if (req->xhr_state) {\n req->xhr_state->req_fd = NULL;\n }\n free(req);\n f->req = NULL;\n }\n}\n\n/* Create a .fscmd_pwd file to avoid passing the password thru the\n Linux command line */\nvoid fs_net_set_pwd(FSDevice *fs, const char *pwd)\n{\n FSFile *root_fd;\n FSQID qid;\n \n assert(fs_is_net(fs));\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\"));\n assert(!fs->fs_create(fs, &qid, root_fd, \".fscmd_pwd\", P9_O_RDWR | P9_O_TRUNC,\n 0600, 0));\n fs->fs_write(fs, root_fd, 0, (uint8_t *)pwd, strlen(pwd));\n fs->fs_delete(fs, root_fd);\n}\n\n/* external file import */\n\n#ifdef EMSCRIPTEN\n\nvoid fs_import_file(const char *filename, uint8_t *buf, int buf_len)\n{\n FSDevice *fs;\n FSDeviceMem *fs1;\n FSFile *fd, *root_fd;\n FSQID qid;\n \n // printf(\"importing file: %s len=%d\\n\", filename, buf_len);\n fs = fs_import_fs;\n if (!fs) {\n free(buf);\n return;\n }\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 1000, \"\", \"\"));\n fs1 = (FSDeviceMem *)fs;\n fd = fs_walk_path(fs, root_fd, fs1->import_dir);\n if (!fd)\n goto fail;\n fs_unlinkat(fs, root_fd, filename);\n if (fs->fs_create(fs, &qid, fd, filename, P9_O_RDWR | P9_O_TRUNC,\n 0600, 0) < 0)\n goto fail;\n fs->fs_write(fs, fd, 0, buf, buf_len);\n fail:\n if (fd)\n fs->fs_delete(fs, fd);\n if (root_fd)\n fs->fs_delete(fs, root_fd);\n free(buf);\n}\n\n#else\n\nvoid fs_export_file(const char *filename,\n const uint8_t *buf, int buf_len)\n{\n}\n\n#endif\n"], ["/linuxpdf/tinyemu/pckbd.c", "/*\n * QEMU PC keyboard emulation\n *\n * Copyright (c) 2003 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n/* debug PC keyboard */\n//#define DEBUG_KBD\n\n/* debug PC keyboard : only mouse */\n//#define DEBUG_MOUSE\n\n/*\tKeyboard Controller Commands */\n#define KBD_CCMD_READ_MODE\t0x20\t/* Read mode bits */\n#define KBD_CCMD_WRITE_MODE\t0x60\t/* Write mode bits */\n#define KBD_CCMD_GET_VERSION\t0xA1\t/* Get controller version */\n#define KBD_CCMD_MOUSE_DISABLE\t0xA7\t/* Disable mouse interface */\n#define KBD_CCMD_MOUSE_ENABLE\t0xA8\t/* Enable mouse interface */\n#define KBD_CCMD_TEST_MOUSE\t0xA9\t/* Mouse interface test */\n#define KBD_CCMD_SELF_TEST\t0xAA\t/* Controller self test */\n#define KBD_CCMD_KBD_TEST\t0xAB\t/* Keyboard interface test */\n#define KBD_CCMD_KBD_DISABLE\t0xAD\t/* Keyboard interface disable */\n#define KBD_CCMD_KBD_ENABLE\t0xAE\t/* Keyboard interface enable */\n#define KBD_CCMD_READ_INPORT 0xC0 /* read input port */\n#define KBD_CCMD_READ_OUTPORT\t0xD0 /* read output port */\n#define KBD_CCMD_WRITE_OUTPORT\t0xD1 /* write output port */\n#define KBD_CCMD_WRITE_OBUF\t0xD2\n#define KBD_CCMD_WRITE_AUX_OBUF\t0xD3 /* Write to output buffer as if\n\t\t\t\t\t initiated by the auxiliary device */\n#define KBD_CCMD_WRITE_MOUSE\t0xD4\t/* Write the following byte to the mouse */\n#define KBD_CCMD_DISABLE_A20 0xDD /* HP vectra only ? */\n#define KBD_CCMD_ENABLE_A20 0xDF /* HP vectra only ? */\n#define KBD_CCMD_RESET\t 0xFE\n\n/* Status Register Bits */\n#define KBD_STAT_OBF \t\t0x01\t/* Keyboard output buffer full */\n#define KBD_STAT_IBF \t\t0x02\t/* Keyboard input buffer full */\n#define KBD_STAT_SELFTEST\t0x04\t/* Self test successful */\n#define KBD_STAT_CMD\t\t0x08\t/* Last write was a command write (0=data) */\n#define KBD_STAT_UNLOCKED\t0x10\t/* Zero if keyboard locked */\n#define KBD_STAT_MOUSE_OBF\t0x20\t/* Mouse output buffer full */\n#define KBD_STAT_GTO \t\t0x40\t/* General receive/xmit timeout */\n#define KBD_STAT_PERR \t\t0x80\t/* Parity error */\n\n/* Controller Mode Register Bits */\n#define KBD_MODE_KBD_INT\t0x01\t/* Keyboard data generate IRQ1 */\n#define KBD_MODE_MOUSE_INT\t0x02\t/* Mouse data generate IRQ12 */\n#define KBD_MODE_SYS \t\t0x04\t/* The system flag (?) */\n#define KBD_MODE_NO_KEYLOCK\t0x08\t/* The keylock doesn't affect the keyboard if set */\n#define KBD_MODE_DISABLE_KBD\t0x10\t/* Disable keyboard interface */\n#define KBD_MODE_DISABLE_MOUSE\t0x20\t/* Disable mouse interface */\n#define KBD_MODE_KCC \t\t0x40\t/* Scan code conversion to PC format */\n#define KBD_MODE_RFU\t\t0x80\n\n#define KBD_PENDING_KBD 1\n#define KBD_PENDING_AUX 2\n\nstruct KBDState {\n uint8_t write_cmd; /* if non zero, write data to port 60 is expected */\n uint8_t status;\n uint8_t mode;\n /* Bitmask of devices with data available. */\n uint8_t pending;\n PS2KbdState *kbd;\n PS2MouseState *mouse;\n\n IRQSignal *irq_kbd;\n IRQSignal *irq_mouse;\n};\n\nstatic void qemu_system_reset_request(void)\n{\n printf(\"system_reset_request\\n\");\n exit(1);\n /* XXX */\n}\n\nstatic void ioport_set_a20(int val)\n{\n}\n\nstatic int ioport_get_a20(void)\n{\n return 1;\n}\n\n/* update irq and KBD_STAT_[MOUSE_]OBF */\n/* XXX: not generating the irqs if KBD_MODE_DISABLE_KBD is set may be\n incorrect, but it avoids having to simulate exact delays */\nstatic void kbd_update_irq(KBDState *s)\n{\n int irq_kbd_level, irq_mouse_level;\n\n irq_kbd_level = 0;\n irq_mouse_level = 0;\n s->status &= ~(KBD_STAT_OBF | KBD_STAT_MOUSE_OBF);\n if (s->pending) {\n s->status |= KBD_STAT_OBF;\n /* kbd data takes priority over aux data. */\n if (s->pending == KBD_PENDING_AUX) {\n s->status |= KBD_STAT_MOUSE_OBF;\n if (s->mode & KBD_MODE_MOUSE_INT)\n irq_mouse_level = 1;\n } else {\n if ((s->mode & KBD_MODE_KBD_INT) &&\n !(s->mode & KBD_MODE_DISABLE_KBD))\n irq_kbd_level = 1;\n }\n }\n set_irq(s->irq_kbd, irq_kbd_level);\n set_irq(s->irq_mouse, irq_mouse_level);\n}\n\nstatic void kbd_update_kbd_irq(void *opaque, int level)\n{\n KBDState *s = (KBDState *)opaque;\n\n if (level)\n s->pending |= KBD_PENDING_KBD;\n else\n s->pending &= ~KBD_PENDING_KBD;\n kbd_update_irq(s);\n}\n\nstatic void kbd_update_aux_irq(void *opaque, int level)\n{\n KBDState *s = (KBDState *)opaque;\n\n if (level)\n s->pending |= KBD_PENDING_AUX;\n else\n s->pending &= ~KBD_PENDING_AUX;\n kbd_update_irq(s);\n}\n\nstatic uint32_t kbd_read_status(void *opaque, uint32_t addr, int size_log2)\n{\n KBDState *s = opaque;\n int val;\n val = s->status;\n#if defined(DEBUG_KBD)\n printf(\"kbd: read status=0x%02x\\n\", val);\n#endif\n return val;\n}\n\nstatic void kbd_queue(KBDState *s, int b, int aux)\n{\n if (aux)\n ps2_queue(s->mouse, b);\n else\n ps2_queue(s->kbd, b);\n}\n\nstatic void kbd_write_command(void *opaque, uint32_t addr, uint32_t val,\n int size_log2)\n{\n KBDState *s = opaque;\n\n#if defined(DEBUG_KBD)\n printf(\"kbd: write cmd=0x%02x\\n\", val);\n#endif\n switch(val) {\n case KBD_CCMD_READ_MODE:\n kbd_queue(s, s->mode, 1);\n break;\n case KBD_CCMD_WRITE_MODE:\n case KBD_CCMD_WRITE_OBUF:\n case KBD_CCMD_WRITE_AUX_OBUF:\n case KBD_CCMD_WRITE_MOUSE:\n case KBD_CCMD_WRITE_OUTPORT:\n s->write_cmd = val;\n break;\n case KBD_CCMD_MOUSE_DISABLE:\n s->mode |= KBD_MODE_DISABLE_MOUSE;\n break;\n case KBD_CCMD_MOUSE_ENABLE:\n s->mode &= ~KBD_MODE_DISABLE_MOUSE;\n break;\n case KBD_CCMD_TEST_MOUSE:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_SELF_TEST:\n s->status |= KBD_STAT_SELFTEST;\n kbd_queue(s, 0x55, 0);\n break;\n case KBD_CCMD_KBD_TEST:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_KBD_DISABLE:\n s->mode |= KBD_MODE_DISABLE_KBD;\n kbd_update_irq(s);\n break;\n case KBD_CCMD_KBD_ENABLE:\n s->mode &= ~KBD_MODE_DISABLE_KBD;\n kbd_update_irq(s);\n break;\n case KBD_CCMD_READ_INPORT:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_READ_OUTPORT:\n /* XXX: check that */\n val = 0x01 | (ioport_get_a20() << 1);\n if (s->status & KBD_STAT_OBF)\n val |= 0x10;\n if (s->status & KBD_STAT_MOUSE_OBF)\n val |= 0x20;\n kbd_queue(s, val, 0);\n break;\n case KBD_CCMD_ENABLE_A20:\n ioport_set_a20(1);\n break;\n case KBD_CCMD_DISABLE_A20:\n ioport_set_a20(0);\n break;\n case KBD_CCMD_RESET:\n qemu_system_reset_request();\n break;\n case 0xff:\n /* ignore that - I don't know what is its use */\n break;\n default:\n fprintf(stderr, \"qemu: unsupported keyboard cmd=0x%02x\\n\", val);\n break;\n }\n}\n\nstatic uint32_t kbd_read_data(void *opaque, uint32_t addr, int size_log2)\n{\n KBDState *s = opaque;\n uint32_t val;\n if (s->pending == KBD_PENDING_AUX)\n val = ps2_read_data(s->mouse);\n else\n val = ps2_read_data(s->kbd);\n#ifdef DEBUG_KBD\n printf(\"kbd: read data=0x%02x\\n\", val);\n#endif\n return val;\n}\n\nstatic void kbd_write_data(void *opaque, uint32_t addr, uint32_t val, int size_log2)\n{\n KBDState *s = opaque;\n\n#ifdef DEBUG_KBD\n printf(\"kbd: write data=0x%02x\\n\", val);\n#endif\n\n switch(s->write_cmd) {\n case 0:\n ps2_write_keyboard(s->kbd, val);\n break;\n case KBD_CCMD_WRITE_MODE:\n s->mode = val;\n ps2_keyboard_set_translation(s->kbd, (s->mode & KBD_MODE_KCC) != 0);\n /* ??? */\n kbd_update_irq(s);\n break;\n case KBD_CCMD_WRITE_OBUF:\n kbd_queue(s, val, 0);\n break;\n case KBD_CCMD_WRITE_AUX_OBUF:\n kbd_queue(s, val, 1);\n break;\n case KBD_CCMD_WRITE_OUTPORT:\n ioport_set_a20((val >> 1) & 1);\n if (!(val & 1)) {\n qemu_system_reset_request();\n }\n break;\n case KBD_CCMD_WRITE_MOUSE:\n ps2_write_mouse(s->mouse, val);\n break;\n default:\n break;\n }\n s->write_cmd = 0;\n}\n\nstatic void kbd_reset(void *opaque)\n{\n KBDState *s = opaque;\n\n s->mode = KBD_MODE_KBD_INT | KBD_MODE_MOUSE_INT;\n s->status = KBD_STAT_CMD | KBD_STAT_UNLOCKED;\n}\n\nKBDState *i8042_init(PS2KbdState **pkbd,\n PS2MouseState **pmouse,\n PhysMemoryMap *port_map,\n IRQSignal *kbd_irq, IRQSignal *mouse_irq, uint32_t io_base)\n{\n KBDState *s;\n \n s = mallocz(sizeof(*s));\n \n s->irq_kbd = kbd_irq;\n s->irq_mouse = mouse_irq;\n\n kbd_reset(s);\n cpu_register_device(port_map, io_base, 1, s, kbd_read_data, kbd_write_data, \n DEVIO_SIZE8);\n cpu_register_device(port_map, io_base + 4, 1, s, kbd_read_status, kbd_write_command, \n DEVIO_SIZE8);\n\n s->kbd = ps2_kbd_init(kbd_update_kbd_irq, s);\n s->mouse = ps2_mouse_init(kbd_update_aux_irq, s);\n\n *pkbd = s->kbd;\n *pmouse = s->mouse;\n return s;\n}\n"], ["/linuxpdf/tinyemu/iomem.c", "/*\n * IO memory handling\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n\nstatic PhysMemoryRange *default_register_ram(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags);\nstatic void default_free_ram(PhysMemoryMap *s, PhysMemoryRange *pr);\nstatic const uint32_t *default_get_dirty_bits(PhysMemoryMap *map, PhysMemoryRange *pr);\nstatic void default_set_addr(PhysMemoryMap *map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled);\n\nPhysMemoryMap *phys_mem_map_init(void)\n{\n PhysMemoryMap *s;\n s = mallocz(sizeof(*s));\n s->register_ram = default_register_ram;\n s->free_ram = default_free_ram;\n s->get_dirty_bits = default_get_dirty_bits;\n s->set_ram_addr = default_set_addr;\n return s;\n}\n\nvoid phys_mem_map_end(PhysMemoryMap *s)\n{\n int i;\n PhysMemoryRange *pr;\n\n for(i = 0; i < s->n_phys_mem_range; i++) {\n pr = &s->phys_mem_range[i];\n if (pr->is_ram) {\n s->free_ram(s, pr);\n }\n }\n free(s);\n}\n\n/* return NULL if not found */\n/* XXX: optimize */\nPhysMemoryRange *get_phys_mem_range(PhysMemoryMap *s, uint64_t paddr)\n{\n PhysMemoryRange *pr;\n int i;\n for(i = 0; i < s->n_phys_mem_range; i++) {\n pr = &s->phys_mem_range[i];\n if (paddr >= pr->addr && paddr < pr->addr + pr->size)\n return pr;\n }\n return NULL;\n}\n\nPhysMemoryRange *register_ram_entry(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n\n assert(s->n_phys_mem_range < PHYS_MEM_RANGE_MAX);\n assert((size & (DEVRAM_PAGE_SIZE - 1)) == 0 && size != 0);\n pr = &s->phys_mem_range[s->n_phys_mem_range++];\n pr->map = s;\n pr->is_ram = TRUE;\n pr->devram_flags = devram_flags & ~DEVRAM_FLAG_DISABLED;\n pr->addr = addr;\n pr->org_size = size;\n if (devram_flags & DEVRAM_FLAG_DISABLED)\n pr->size = 0;\n else\n pr->size = pr->org_size;\n pr->phys_mem = NULL;\n pr->dirty_bits = NULL;\n return pr;\n}\n\nstatic PhysMemoryRange *default_register_ram(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n\n pr = register_ram_entry(s, addr, size, devram_flags);\n\n pr->phys_mem = mallocz(size);\n if (!pr->phys_mem) {\n fprintf(stderr, \"Could not allocate VM memory\\n\");\n exit(1);\n }\n\n if (devram_flags & DEVRAM_FLAG_DIRTY_BITS) {\n size_t nb_pages;\n int i;\n nb_pages = size >> DEVRAM_PAGE_SIZE_LOG2;\n pr->dirty_bits_size = ((nb_pages + 31) / 32) * sizeof(uint32_t);\n pr->dirty_bits_index = 0;\n for(i = 0; i < 2; i++) {\n pr->dirty_bits_tab[i] = mallocz(pr->dirty_bits_size);\n }\n pr->dirty_bits = pr->dirty_bits_tab[pr->dirty_bits_index];\n }\n return pr;\n}\n\n/* return a pointer to the bitmap of dirty bits and reset them */\nstatic const uint32_t *default_get_dirty_bits(PhysMemoryMap *map,\n PhysMemoryRange *pr)\n{\n uint32_t *dirty_bits;\n BOOL has_dirty_bits;\n size_t n, i;\n \n dirty_bits = pr->dirty_bits;\n\n has_dirty_bits = FALSE;\n n = pr->dirty_bits_size / sizeof(uint32_t);\n for(i = 0; i < n; i++) {\n if (dirty_bits[i] != 0) {\n has_dirty_bits = TRUE;\n break;\n }\n }\n if (has_dirty_bits && pr->size != 0) {\n /* invalidate the corresponding CPU write TLBs */\n map->flush_tlb_write_range(map->opaque, pr->phys_mem, pr->org_size);\n }\n \n pr->dirty_bits_index ^= 1;\n pr->dirty_bits = pr->dirty_bits_tab[pr->dirty_bits_index];\n memset(pr->dirty_bits, 0, pr->dirty_bits_size);\n return dirty_bits;\n}\n\n/* reset the dirty bit of one page at 'offset' inside 'pr' */\nvoid phys_mem_reset_dirty_bit(PhysMemoryRange *pr, size_t offset)\n{\n size_t page_index;\n uint32_t mask, *dirty_bits_ptr;\n PhysMemoryMap *map;\n if (pr->dirty_bits) {\n page_index = offset >> DEVRAM_PAGE_SIZE_LOG2;\n mask = 1 << (page_index & 0x1f);\n dirty_bits_ptr = pr->dirty_bits + (page_index >> 5);\n if (*dirty_bits_ptr & mask) {\n *dirty_bits_ptr &= ~mask;\n /* invalidate the corresponding CPU write TLBs */\n map = pr->map;\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem + (offset & ~(DEVRAM_PAGE_SIZE - 1)),\n DEVRAM_PAGE_SIZE);\n }\n }\n}\n\nstatic void default_free_ram(PhysMemoryMap *s, PhysMemoryRange *pr)\n{\n free(pr->phys_mem);\n}\n\nPhysMemoryRange *cpu_register_device(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, void *opaque,\n DeviceReadFunc *read_func, DeviceWriteFunc *write_func,\n int devio_flags)\n{\n PhysMemoryRange *pr;\n assert(s->n_phys_mem_range < PHYS_MEM_RANGE_MAX);\n assert(size <= 0xffffffff);\n pr = &s->phys_mem_range[s->n_phys_mem_range++];\n pr->map = s;\n pr->addr = addr;\n pr->org_size = size;\n if (devio_flags & DEVIO_DISABLED)\n pr->size = 0;\n else\n pr->size = pr->org_size;\n pr->is_ram = FALSE;\n pr->opaque = opaque;\n pr->read_func = read_func;\n pr->write_func = write_func;\n pr->devio_flags = devio_flags;\n return pr;\n}\n\nstatic void default_set_addr(PhysMemoryMap *map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n if (enabled) {\n if (pr->size == 0 || pr->addr != addr) {\n /* enable or move mapping */\n if (pr->is_ram) {\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem, pr->org_size);\n }\n pr->addr = addr;\n pr->size = pr->org_size;\n }\n } else {\n if (pr->size != 0) {\n /* disable mapping */\n if (pr->is_ram) {\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem, pr->org_size);\n }\n pr->addr = 0;\n pr->size = 0;\n }\n }\n}\n\nvoid phys_mem_set_addr(PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n PhysMemoryMap *map = pr->map;\n if (!pr->is_ram) {\n default_set_addr(map, pr, addr, enabled);\n } else {\n return map->set_ram_addr(map, pr, addr, enabled);\n }\n}\n\n/* return NULL if no valid RAM page. The access can only be done in the page */\nuint8_t *phys_mem_get_ram_ptr(PhysMemoryMap *map, uint64_t paddr, BOOL is_rw)\n{\n PhysMemoryRange *pr = get_phys_mem_range(map, paddr);\n uintptr_t offset;\n if (!pr || !pr->is_ram)\n return NULL;\n offset = paddr - pr->addr;\n if (is_rw)\n phys_mem_set_dirty_bit(pr, offset);\n return pr->phys_mem + (uintptr_t)offset;\n}\n\n/* IRQ support */\n\nvoid irq_init(IRQSignal *irq, SetIRQFunc *set_irq, void *opaque, int irq_num)\n{\n irq->set_irq = set_irq;\n irq->opaque = opaque;\n irq->irq_num = irq_num;\n}\n"], ["/linuxpdf/tinyemu/machine.c", "/*\n * VM utilities\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#include \"fs_utils.h\"\n#ifdef CONFIG_FS_NET\n#include \"fs_wget.h\"\n#endif\n\nvoid __attribute__((format(printf, 1, 2))) vm_error(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n#ifdef EMSCRIPTEN\n vprintf(fmt, ap);\n#else\n vfprintf(stderr, fmt, ap);\n#endif\n va_end(ap);\n}\n\nint vm_get_int(JSONValue obj, const char *name, int *pval)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n vm_error(\"expecting '%s' property\\n\", name);\n return -1;\n }\n if (val.type != JSON_INT) {\n vm_error(\"%s: integer expected\\n\", name);\n return -1;\n }\n *pval = val.u.int32;\n return 0;\n}\n\nint vm_get_int_opt(JSONValue obj, const char *name, int *pval, int def_val)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n *pval = def_val;\n return 0;\n }\n if (val.type != JSON_INT) {\n vm_error(\"%s: integer expected\\n\", name);\n return -1;\n }\n *pval = val.u.int32;\n return 0;\n}\n\nstatic int vm_get_str2(JSONValue obj, const char *name, const char **pstr,\n BOOL is_opt)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n if (is_opt) {\n *pstr = NULL;\n return 0;\n } else {\n vm_error(\"expecting '%s' property\\n\", name);\n return -1;\n }\n }\n if (val.type != JSON_STR) {\n vm_error(\"%s: string expected\\n\", name);\n return -1;\n }\n *pstr = val.u.str->data;\n return 0;\n}\n\nstatic int vm_get_str(JSONValue obj, const char *name, const char **pstr)\n{ \n return vm_get_str2(obj, name, pstr, FALSE);\n}\n\nstatic int vm_get_str_opt(JSONValue obj, const char *name, const char **pstr)\n{ \n return vm_get_str2(obj, name, pstr, TRUE);\n}\n\nstatic char *strdup_null(const char *str)\n{\n if (!str)\n return NULL;\n else\n return strdup(str);\n}\n\n/* currently only for \"TZ\" */\nstatic char *cmdline_subst(const char *cmdline)\n{\n DynBuf dbuf;\n const char *p;\n char var_name[32], *q, buf[32];\n \n dbuf_init(&dbuf);\n p = cmdline;\n while (*p != '\\0') {\n if (p[0] == '$' && p[1] == '{') {\n p += 2;\n q = var_name;\n while (*p != '\\0' && *p != '}') {\n if ((q - var_name) < sizeof(var_name) - 1)\n *q++ = *p;\n p++;\n }\n *q = '\\0';\n if (*p == '}')\n p++;\n if (!strcmp(var_name, \"TZ\")) {\n time_t ti;\n struct tm tm;\n int n, sg;\n /* get the offset to UTC */\n time(&ti);\n localtime_r(&ti, &tm);\n n = tm.tm_gmtoff / 60;\n sg = '-';\n if (n < 0) {\n sg = '+';\n n = -n;\n }\n snprintf(buf, sizeof(buf), \"UTC%c%02d:%02d\",\n sg, n / 60, n % 60);\n dbuf_putstr(&dbuf, buf);\n }\n } else {\n dbuf_putc(&dbuf, *p++);\n }\n }\n dbuf_putc(&dbuf, 0);\n return (char *)dbuf.buf;\n}\n\nstatic BOOL find_name(const char *name, const char *name_list)\n{\n size_t len;\n const char *p, *r;\n \n p = name_list;\n for(;;) {\n r = strchr(p, ',');\n if (!r) {\n if (!strcmp(name, p))\n return TRUE;\n break;\n } else {\n len = r - p;\n if (len == strlen(name) && !memcmp(name, p, len))\n return TRUE;\n p = r + 1;\n }\n }\n return FALSE;\n}\n\nstatic const VirtMachineClass *virt_machine_list[] = {\n#if defined(EMSCRIPTEN)\n /* only a single machine in the EMSCRIPTEN target */\n#ifndef CONFIG_X86EMU\n &riscv_machine_class,\n#endif \n#else\n &riscv_machine_class,\n#endif /* !EMSCRIPTEN */\n#ifdef CONFIG_X86EMU\n &pc_machine_class,\n#endif\n NULL,\n};\n\nstatic const VirtMachineClass *virt_machine_find_class(const char *machine_name)\n{\n const VirtMachineClass *vmc, **pvmc;\n \n for(pvmc = virt_machine_list; *pvmc != NULL; pvmc++) {\n vmc = *pvmc;\n if (find_name(machine_name, vmc->machine_names))\n return vmc;\n }\n return NULL;\n}\n\nstatic int virt_machine_parse_config(VirtMachineParams *p,\n char *config_file_str, int len)\n{\n int version, val;\n const char *tag_name, *str;\n char buf1[256];\n JSONValue cfg, obj, el;\n \n cfg = json_parse_value_len(config_file_str, len);\n if (json_is_error(cfg)) {\n vm_error(\"error: %s\\n\", json_get_error(cfg));\n json_free(cfg);\n return -1;\n }\n\n if (vm_get_int(cfg, \"version\", &version) < 0)\n goto tag_fail;\n if (version != VM_CONFIG_VERSION) {\n if (version > VM_CONFIG_VERSION) {\n vm_error(\"The emulator is too old to run this VM: please upgrade\\n\");\n return -1;\n } else {\n vm_error(\"The VM configuration file is too old for this emulator version: please upgrade the VM configuration file\\n\");\n return -1;\n }\n }\n \n if (vm_get_str(cfg, \"machine\", &str) < 0)\n goto tag_fail;\n p->machine_name = strdup(str);\n p->vmc = virt_machine_find_class(p->machine_name);\n if (!p->vmc) {\n vm_error(\"Unknown machine name: %s\\n\", p->machine_name);\n goto tag_fail;\n }\n p->vmc->virt_machine_set_defaults(p);\n\n tag_name = \"memory_size\";\n if (vm_get_int(cfg, tag_name, &val) < 0)\n goto tag_fail;\n p->ram_size = (uint64_t)val << 20;\n \n tag_name = \"bios\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_BIOS].filename = strdup(str);\n }\n\n tag_name = \"kernel\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_KERNEL].filename = strdup(str);\n }\n\n tag_name = \"initrd\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_INITRD].filename = strdup(str);\n }\n\n if (vm_get_str_opt(cfg, \"cmdline\", &str) < 0)\n goto tag_fail;\n if (str) {\n p->cmdline = cmdline_subst(str);\n }\n \n for(;;) {\n snprintf(buf1, sizeof(buf1), \"drive%d\", p->drive_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->drive_count >= MAX_DRIVE_DEVICE) {\n vm_error(\"Too many drives\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"file\", &str) < 0)\n goto tag_fail;\n p->tab_drive[p->drive_count].filename = strdup(str);\n if (vm_get_str_opt(obj, \"device\", &str) < 0)\n goto tag_fail;\n p->tab_drive[p->drive_count].device = strdup_null(str);\n p->drive_count++;\n }\n\n for(;;) {\n snprintf(buf1, sizeof(buf1), \"fs%d\", p->fs_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->fs_count >= MAX_DRIVE_DEVICE) {\n vm_error(\"Too many filesystems\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"file\", &str) < 0)\n goto tag_fail;\n p->tab_fs[p->fs_count].filename = strdup(str);\n if (vm_get_str_opt(obj, \"tag\", &str) < 0)\n goto tag_fail;\n if (!str) {\n if (p->fs_count == 0)\n strcpy(buf1, \"/dev/root\");\n else\n snprintf(buf1, sizeof(buf1), \"/dev/root%d\", p->fs_count);\n str = buf1;\n }\n p->tab_fs[p->fs_count].tag = strdup(str);\n p->fs_count++;\n }\n\n for(;;) {\n snprintf(buf1, sizeof(buf1), \"eth%d\", p->eth_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->eth_count >= MAX_ETH_DEVICE) {\n vm_error(\"Too many ethernet interfaces\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"driver\", &str) < 0)\n goto tag_fail;\n p->tab_eth[p->eth_count].driver = strdup(str);\n if (!strcmp(str, \"tap\")) {\n if (vm_get_str(obj, \"ifname\", &str) < 0)\n goto tag_fail;\n p->tab_eth[p->eth_count].ifname = strdup(str);\n }\n p->eth_count++;\n }\n\n p->display_device = NULL;\n obj = json_object_get(cfg, \"display0\");\n if (!json_is_undefined(obj)) {\n if (vm_get_str(obj, \"device\", &str) < 0)\n goto tag_fail;\n p->display_device = strdup(str);\n if (vm_get_int(obj, \"width\", &p->width) < 0)\n goto tag_fail;\n if (vm_get_int(obj, \"height\", &p->height) < 0)\n goto tag_fail;\n if (vm_get_str_opt(obj, \"vga_bios\", &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_VGA_BIOS].filename = strdup(str);\n }\n }\n\n if (vm_get_str_opt(cfg, \"input_device\", &str) < 0)\n goto tag_fail;\n p->input_device = strdup_null(str);\n\n if (vm_get_str_opt(cfg, \"accel\", &str) < 0)\n goto tag_fail;\n if (str) {\n if (!strcmp(str, \"none\")) {\n p->accel_enable = FALSE;\n } else if (!strcmp(str, \"auto\")) {\n p->accel_enable = TRUE;\n } else {\n vm_error(\"unsupported 'accel' config: %s\\n\", str);\n return -1;\n }\n }\n\n tag_name = \"rtc_local_time\";\n el = json_object_get(cfg, tag_name);\n if (!json_is_undefined(el)) {\n if (el.type != JSON_BOOL) {\n vm_error(\"%s: boolean expected\\n\", tag_name);\n goto tag_fail;\n }\n p->rtc_local_time = el.u.b;\n }\n \n json_free(cfg);\n return 0;\n tag_fail:\n json_free(cfg);\n return -1;\n}\n\ntypedef void FSLoadFileCB(void *opaque, uint8_t *buf, int buf_len);\n\ntypedef struct {\n VirtMachineParams *vm_params;\n void (*start_cb)(void *opaque);\n void *opaque;\n \n FSLoadFileCB *file_load_cb;\n void *file_load_opaque;\n int file_index;\n} VMConfigLoadState;\n\nstatic void config_file_loaded(void *opaque, uint8_t *buf, int buf_len);\nstatic void config_additional_file_load(VMConfigLoadState *s);\nstatic void config_additional_file_load_cb(void *opaque,\n uint8_t *buf, int buf_len);\n\n/* XXX: win32, URL */\nchar *get_file_path(const char *base_filename, const char *filename)\n{\n int len, len1;\n char *fname, *p;\n \n if (!base_filename)\n goto done;\n if (strchr(filename, ':'))\n goto done; /* full URL */\n if (filename[0] == '/')\n goto done;\n p = strrchr(base_filename, '/');\n if (!p) {\n done:\n return strdup(filename);\n }\n len = p + 1 - base_filename;\n len1 = strlen(filename);\n fname = malloc(len + len1 + 1);\n memcpy(fname, base_filename, len);\n memcpy(fname + len, filename, len1 + 1);\n return fname;\n}\n\n\n#ifdef EMSCRIPTEN\nstatic int load_file(uint8_t **pbuf, const char *filename)\n{\n abort();\n}\n#else\n/* return -1 if error. */\nstatic int load_file(uint8_t **pbuf, const char *filename)\n{\n FILE *f;\n int size;\n uint8_t *buf;\n \n f = fopen(filename, \"rb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n size = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = malloc(size);\n if (fread(buf, 1, size, f) != size) {\n fprintf(stderr, \"%s: read error\\n\", filename);\n exit(1);\n }\n fclose(f);\n *pbuf = buf;\n return size;\n}\n#endif\n\n#ifdef CONFIG_FS_NET\nstatic void config_load_file_cb(void *opaque, int err, void *data, size_t size)\n{\n VMConfigLoadState *s = opaque;\n \n // printf(\"err=%d data=%p size=%ld\\n\", err, data, size);\n if (err < 0) {\n vm_error(\"Error %d while loading file\\n\", -err);\n exit(1);\n }\n s->file_load_cb(s->file_load_opaque, data, size);\n}\n#endif\n\nstatic void config_load_file(VMConfigLoadState *s, const char *filename,\n FSLoadFileCB *cb, void *opaque)\n{\n // printf(\"loading %s\\n\", filename);\n#ifdef CONFIG_FS_NET\n if (is_url(filename)) {\n s->file_load_cb = cb;\n s->file_load_opaque = opaque;\n fs_wget(filename, NULL, NULL, s, config_load_file_cb, TRUE);\n } else\n#endif\n {\n uint8_t *buf;\n int size;\n size = load_file(&buf, filename);\n cb(opaque, buf, size);\n free(buf);\n }\n}\n\nvoid virt_machine_load_config_file(VirtMachineParams *p,\n const char *filename,\n void (*start_cb)(void *opaque),\n void *opaque)\n{\n VMConfigLoadState *s;\n \n s = mallocz(sizeof(*s));\n s->vm_params = p;\n s->start_cb = start_cb;\n s->opaque = opaque;\n p->cfg_filename = strdup(filename);\n\n config_load_file(s, filename, config_file_loaded, s);\n}\n\nstatic void config_file_loaded(void *opaque, uint8_t *buf, int buf_len)\n{\n VMConfigLoadState *s = opaque;\n VirtMachineParams *p = s->vm_params;\n\n if (virt_machine_parse_config(p, (char *)buf, buf_len) < 0)\n exit(1);\n \n /* load the additional files */\n s->file_index = 0;\n config_additional_file_load(s);\n}\n\nstatic void config_additional_file_load(VMConfigLoadState *s)\n{\n VirtMachineParams *p = s->vm_params;\n while (s->file_index < VM_FILE_COUNT &&\n p->files[s->file_index].filename == NULL) {\n s->file_index++;\n }\n if (s->file_index == VM_FILE_COUNT) {\n if (s->start_cb)\n s->start_cb(s->opaque);\n free(s);\n } else {\n char *fname;\n \n fname = get_file_path(p->cfg_filename,\n p->files[s->file_index].filename);\n config_load_file(s, fname,\n config_additional_file_load_cb, s);\n free(fname);\n }\n}\n\nstatic void config_additional_file_load_cb(void *opaque,\n uint8_t *buf, int buf_len)\n{\n VMConfigLoadState *s = opaque;\n VirtMachineParams *p = s->vm_params;\n\n p->files[s->file_index].buf = malloc(buf_len);\n memcpy(p->files[s->file_index].buf, buf, buf_len);\n p->files[s->file_index].len = buf_len;\n\n /* load the next files */\n s->file_index++;\n config_additional_file_load(s);\n}\n\nvoid vm_add_cmdline(VirtMachineParams *p, const char *cmdline)\n{\n char *new_cmdline, *old_cmdline;\n if (cmdline[0] == '!') {\n new_cmdline = strdup(cmdline + 1);\n } else {\n old_cmdline = p->cmdline;\n if (!old_cmdline)\n old_cmdline = \"\";\n new_cmdline = malloc(strlen(old_cmdline) + 1 + strlen(cmdline) + 1);\n strcpy(new_cmdline, old_cmdline);\n strcat(new_cmdline, \" \");\n strcat(new_cmdline, cmdline);\n }\n free(p->cmdline);\n p->cmdline = new_cmdline;\n}\n\nvoid virt_machine_free_config(VirtMachineParams *p)\n{\n int i;\n \n free(p->machine_name);\n free(p->cmdline);\n for(i = 0; i < VM_FILE_COUNT; i++) {\n free(p->files[i].filename);\n free(p->files[i].buf);\n }\n for(i = 0; i < p->drive_count; i++) {\n free(p->tab_drive[i].filename);\n free(p->tab_drive[i].device);\n }\n for(i = 0; i < p->fs_count; i++) {\n free(p->tab_fs[i].filename);\n free(p->tab_fs[i].tag);\n }\n for(i = 0; i < p->eth_count; i++) {\n free(p->tab_eth[i].driver);\n free(p->tab_eth[i].ifname);\n }\n free(p->input_device);\n free(p->display_device);\n free(p->cfg_filename);\n}\n\nVirtMachine *virt_machine_init(const VirtMachineParams *p)\n{\n const VirtMachineClass *vmc = p->vmc;\n return vmc->virt_machine_init(p);\n}\n\nvoid virt_machine_set_defaults(VirtMachineParams *p)\n{\n memset(p, 0, sizeof(*p));\n}\n\nvoid virt_machine_end(VirtMachine *s)\n{\n s->vmc->virt_machine_end(s);\n}\n"], ["/linuxpdf/tinyemu/jsemu.c", "/*\n * JS emulator main\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#include \"list.h\"\n#include \"fbuf.h\"\n\nint virt_machine_run(void *opaque);\n\n/* provided in lib.js */\nextern void console_write(void *opaque, const uint8_t *buf, int len);\nextern void console_get_size(int *pw, int *ph);\nextern void fb_refresh(void *opaque, void *data,\n int x, int y, int w, int h, int stride);\nextern void net_recv_packet(EthernetDevice *bs,\n const uint8_t *buf, int len);\n\nstatic uint8_t console_fifo[1024];\nstatic int console_fifo_windex;\nstatic int console_fifo_rindex;\nstatic int console_fifo_count;\nstatic BOOL console_resize_pending;\n\nstatic int global_width;\nstatic int global_height;\nstatic VirtMachine *global_vm;\nstatic BOOL global_carrier_state;\n\nstatic int console_read(void *opaque, uint8_t *buf, int len)\n{\n int out_len, l;\n len = min_int(len, console_fifo_count);\n console_fifo_count -= len;\n out_len = 0;\n while (len != 0) {\n l = min_int(len, sizeof(console_fifo) - console_fifo_rindex);\n memcpy(buf + out_len, console_fifo + console_fifo_rindex, l);\n len -= l;\n out_len += l;\n console_fifo_rindex += l;\n if (console_fifo_rindex == sizeof(console_fifo))\n console_fifo_rindex = 0;\n }\n return out_len;\n}\n\n/* called from JS */\nvoid console_queue_char(int c)\n{\n if (console_fifo_count < sizeof(console_fifo)) {\n console_fifo[console_fifo_windex] = c;\n if (++console_fifo_windex == sizeof(console_fifo))\n console_fifo_windex = 0;\n console_fifo_count++;\n }\n}\n\n/* called from JS */\nvoid display_key_event(int is_down, int key_code)\n{\n if (global_vm) {\n vm_send_key_event(global_vm, is_down, key_code);\n }\n}\n\n/* called from JS */\nstatic int mouse_last_x, mouse_last_y, mouse_last_buttons;\n\nvoid display_mouse_event(int dx, int dy, int buttons)\n{\n if (global_vm) {\n if (vm_mouse_is_absolute(global_vm) || 1) {\n dx = min_int(dx, global_width - 1);\n dy = min_int(dy, global_height - 1);\n dx = (dx * VIRTIO_INPUT_ABS_SCALE) / global_width;\n dy = (dy * VIRTIO_INPUT_ABS_SCALE) / global_height;\n } else {\n /* relative mouse is not supported */\n dx = 0;\n dy = 0;\n }\n mouse_last_x = dx;\n mouse_last_y = dy;\n mouse_last_buttons = buttons;\n vm_send_mouse_event(global_vm, dx, dy, 0, buttons);\n }\n}\n\n/* called from JS */\nvoid display_wheel_event(int dz)\n{\n if (global_vm) {\n vm_send_mouse_event(global_vm, mouse_last_x, mouse_last_y, dz,\n mouse_last_buttons);\n }\n}\n\n/* called from JS */\nvoid net_write_packet(const uint8_t *buf, int buf_len)\n{\n EthernetDevice *net = global_vm->net;\n if (net) {\n net->device_write_packet(net, buf, buf_len);\n }\n}\n\n/* called from JS */\nvoid net_set_carrier(BOOL carrier_state)\n{\n EthernetDevice *net;\n global_carrier_state = carrier_state;\n if (global_vm && global_vm->net) {\n net = global_vm->net;\n net->device_set_carrier(net, carrier_state);\n }\n}\n\nstatic void fb_refresh1(FBDevice *fb_dev, void *opaque,\n int x, int y, int w, int h)\n{\n int stride = fb_dev->stride;\n fb_refresh(opaque, fb_dev->fb_data + y * stride + x * 4, x, y, w, h,\n stride);\n}\n\nstatic CharacterDevice *console_init(void)\n{\n CharacterDevice *dev;\n console_resize_pending = TRUE;\n dev = mallocz(sizeof(*dev));\n dev->write_data = console_write;\n dev->read_data = console_read;\n return dev;\n}\n\ntypedef struct {\n VirtMachineParams *p;\n int ram_size;\n char *cmdline;\n BOOL has_network;\n char *pwd;\n} VMStartState;\n\nstatic void init_vm(void *arg);\nstatic void init_vm_fs(void *arg);\nstatic void init_vm_drive(void *arg);\n\nvoid vm_start(const char *url, int ram_size, const char *cmdline,\n const char *pwd, int width, int height, BOOL has_network)\n{\n VMStartState *s;\n\n s = mallocz(sizeof(*s));\n s->ram_size = ram_size;\n s->cmdline = strdup(cmdline);\n if (pwd)\n s->pwd = strdup(pwd);\n global_width = width;\n global_height = height;\n s->has_network = has_network;\n s->p = mallocz(sizeof(VirtMachineParams));\n virt_machine_set_defaults(s->p);\n virt_machine_load_config_file(s->p, url, init_vm_fs, s);\n}\n\nstatic void init_vm_fs(void *arg)\n{\n VMStartState *s = arg;\n VirtMachineParams *p = s->p;\n\n if (p->fs_count > 0) {\n assert(p->fs_count == 1);\n p->tab_fs[0].fs_dev = fs_net_init(p->tab_fs[0].filename,\n init_vm_drive, s);\n if (s->pwd) {\n fs_net_set_pwd(p->tab_fs[0].fs_dev, s->pwd);\n }\n } else {\n init_vm_drive(s);\n }\n}\n\nstatic void init_vm_drive(void *arg)\n{\n VMStartState *s = arg;\n VirtMachineParams *p = s->p;\n\n if (p->drive_count > 0) {\n assert(p->drive_count == 1);\n p->tab_drive[0].block_dev =\n block_device_init_http(p->tab_drive[0].filename,\n 131072,\n init_vm, s);\n } else {\n init_vm(s);\n }\n}\n\nstatic void init_vm(void *arg)\n{\n VMStartState *s = arg;\n VirtMachine *m;\n VirtMachineParams *p = s->p;\n int i;\n \n p->rtc_real_time = TRUE;\n p->ram_size = s->ram_size << 20;\n if (s->cmdline && s->cmdline[0] != '\\0') {\n vm_add_cmdline(s->p, s->cmdline);\n }\n\n if (global_width > 0 && global_height > 0) {\n /* enable graphic output if needed */\n if (!p->display_device)\n p->display_device = strdup(\"simplefb\");\n p->width = global_width;\n p->height = global_height;\n } else {\n p->console = console_init();\n }\n \n if (p->eth_count > 0 && !s->has_network) {\n /* remove the interfaces */\n for(i = 0; i < p->eth_count; i++) {\n free(p->tab_eth[i].ifname);\n free(p->tab_eth[i].driver);\n }\n p->eth_count = 0;\n }\n\n if (p->eth_count > 0) {\n EthernetDevice *net;\n int i;\n assert(p->eth_count == 1);\n net = mallocz(sizeof(EthernetDevice));\n net->mac_addr[0] = 0x02;\n for(i = 1; i < 6; i++)\n net->mac_addr[i] = (int)(emscripten_random() * 256);\n net->write_packet = net_recv_packet;\n net->opaque = NULL;\n p->tab_eth[0].net = net;\n }\n\n m = virt_machine_init(p);\n global_vm = m;\n\n virt_machine_free_config(s->p);\n\n if (m->net) {\n m->net->device_set_carrier(m->net, global_carrier_state);\n }\n \n free(s->p);\n free(s->cmdline);\n if (s->pwd) {\n memset(s->pwd, 0, strlen(s->pwd));\n free(s->pwd);\n }\n free(s);\n \n EM_ASM({\n start_machine_interval($0);\n }, m);\n}\n\n/* need to be long enough to hide the non zero delay of setTimeout(_, 0) */\n#define MAX_EXEC_TOTAL_CYCLE 100000\n#define MAX_EXEC_CYCLE 1000\n\n#define MAX_SLEEP_TIME 10 /* in ms */\n\nint virt_machine_run(void *opaque)\n{\n VirtMachine *m = opaque;\n int delay, i;\n FBDevice *fb_dev;\n \n if (m->console_dev && virtio_console_can_write_data(m->console_dev)) {\n uint8_t buf[128];\n int ret, len;\n len = virtio_console_get_write_len(m->console_dev);\n len = min_int(len, sizeof(buf));\n ret = m->console->read_data(m->console->opaque, buf, len);\n if (ret > 0)\n virtio_console_write_data(m->console_dev, buf, ret);\n if (console_resize_pending) {\n int w, h;\n console_get_size(&w, &h);\n virtio_console_resize_event(m->console_dev, w, h);\n console_resize_pending = FALSE;\n }\n }\n\n fb_dev = m->fb_dev;\n if (fb_dev) {\n /* refresh the display */\n fb_dev->refresh(fb_dev, fb_refresh1, NULL);\n }\n \n i = 0;\n for(;;) {\n /* wait for an event: the only asynchronous event is the RTC timer */\n delay = virt_machine_get_sleep_duration(m, MAX_SLEEP_TIME);\n if (delay != 0 || i >= MAX_EXEC_TOTAL_CYCLE / MAX_EXEC_CYCLE)\n break;\n virt_machine_interp(m, MAX_EXEC_CYCLE);\n i++;\n }\n return i * MAX_EXEC_CYCLE;\n \n /*\n if (delay == 0) {\n emscripten_async_call(virt_machine_run, m, 0);\n } else {\n emscripten_async_call(virt_machine_run, m, MAX_SLEEP_TIME);\n }\n */\n}\n\n"], ["/linuxpdf/tinyemu/ps2.c", "/*\n * QEMU PS/2 keyboard/mouse emulation\n *\n * Copyright (c) 2003 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n\n/* debug PC keyboard */\n//#define DEBUG_KBD\n\n/* debug PC keyboard : only mouse */\n//#define DEBUG_MOUSE\n\n/* Keyboard Commands */\n#define KBD_CMD_SET_LEDS\t0xED\t/* Set keyboard leds */\n#define KBD_CMD_ECHO \t0xEE\n#define KBD_CMD_GET_ID \t 0xF2\t/* get keyboard ID */\n#define KBD_CMD_SET_RATE\t0xF3\t/* Set typematic rate */\n#define KBD_CMD_ENABLE\t\t0xF4\t/* Enable scanning */\n#define KBD_CMD_RESET_DISABLE\t0xF5\t/* reset and disable scanning */\n#define KBD_CMD_RESET_ENABLE \t0xF6 /* reset and enable scanning */\n#define KBD_CMD_RESET\t\t0xFF\t/* Reset */\n\n/* Keyboard Replies */\n#define KBD_REPLY_POR\t\t0xAA\t/* Power on reset */\n#define KBD_REPLY_ACK\t\t0xFA\t/* Command ACK */\n#define KBD_REPLY_RESEND\t0xFE\t/* Command NACK, send the cmd again */\n\n/* Mouse Commands */\n#define AUX_SET_SCALE11\t\t0xE6\t/* Set 1:1 scaling */\n#define AUX_SET_SCALE21\t\t0xE7\t/* Set 2:1 scaling */\n#define AUX_SET_RES\t\t0xE8\t/* Set resolution */\n#define AUX_GET_SCALE\t\t0xE9\t/* Get scaling factor */\n#define AUX_SET_STREAM\t\t0xEA\t/* Set stream mode */\n#define AUX_POLL\t\t0xEB\t/* Poll */\n#define AUX_RESET_WRAP\t\t0xEC\t/* Reset wrap mode */\n#define AUX_SET_WRAP\t\t0xEE\t/* Set wrap mode */\n#define AUX_SET_REMOTE\t\t0xF0\t/* Set remote mode */\n#define AUX_GET_TYPE\t\t0xF2\t/* Get type */\n#define AUX_SET_SAMPLE\t\t0xF3\t/* Set sample rate */\n#define AUX_ENABLE_DEV\t\t0xF4\t/* Enable aux device */\n#define AUX_DISABLE_DEV\t\t0xF5\t/* Disable aux device */\n#define AUX_SET_DEFAULT\t\t0xF6\n#define AUX_RESET\t\t0xFF\t/* Reset aux device */\n#define AUX_ACK\t\t\t0xFA\t/* Command byte ACK. */\n\n#define MOUSE_STATUS_REMOTE 0x40\n#define MOUSE_STATUS_ENABLED 0x20\n#define MOUSE_STATUS_SCALE21 0x10\n\n#define PS2_QUEUE_SIZE 256\n\ntypedef struct {\n uint8_t data[PS2_QUEUE_SIZE];\n int rptr, wptr, count;\n} PS2Queue;\n\ntypedef struct {\n PS2Queue queue;\n int32_t write_cmd;\n void (*update_irq)(void *, int);\n void *update_arg;\n} PS2State;\n\nstruct PS2KbdState {\n PS2State common;\n int scan_enabled;\n /* Qemu uses translated PC scancodes internally. To avoid multiple\n conversions we do the translation (if any) in the PS/2 emulation\n not the keyboard controller. */\n int translate;\n};\n\nstruct PS2MouseState {\n PS2State common;\n uint8_t mouse_status;\n uint8_t mouse_resolution;\n uint8_t mouse_sample_rate;\n uint8_t mouse_wrap;\n uint8_t mouse_type; /* 0 = PS2, 3 = IMPS/2, 4 = IMEX */\n uint8_t mouse_detect_state;\n int mouse_dx; /* current values, needed for 'poll' mode */\n int mouse_dy;\n int mouse_dz;\n uint8_t mouse_buttons;\n};\n\nvoid ps2_queue(void *opaque, int b)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q = &s->queue;\n\n if (q->count >= PS2_QUEUE_SIZE)\n return;\n q->data[q->wptr] = b;\n if (++q->wptr == PS2_QUEUE_SIZE)\n q->wptr = 0;\n q->count++;\n s->update_irq(s->update_arg, 1);\n}\n\n#define INPUT_MAKE_KEY_MIN 96\n#define INPUT_MAKE_KEY_MAX 127\n\nstatic const uint8_t linux_input_to_keycode_set1[INPUT_MAKE_KEY_MAX - INPUT_MAKE_KEY_MIN + 1] = {\n 0x1c, 0x1d, 0x35, 0x00, 0x38, 0x00, 0x47, 0x48, \n 0x49, 0x4b, 0x4d, 0x4f, 0x50, 0x51, 0x52, 0x53, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x5b, 0x5c, 0x5d, \n};\n\n/* keycode is a Linux input layer keycode. We only support the PS/2\n keycode set 1 */\nvoid ps2_put_keycode(PS2KbdState *s, BOOL is_down, int keycode)\n{\n if (keycode >= INPUT_MAKE_KEY_MIN) {\n if (keycode > INPUT_MAKE_KEY_MAX)\n return;\n keycode = linux_input_to_keycode_set1[keycode - INPUT_MAKE_KEY_MIN];\n if (keycode == 0)\n return;\n ps2_queue(&s->common, 0xe0);\n }\n ps2_queue(&s->common, keycode | ((!is_down) << 7));\n}\n\nuint32_t ps2_read_data(void *opaque)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q;\n int val, index;\n\n q = &s->queue;\n if (q->count == 0) {\n /* NOTE: if no data left, we return the last keyboard one\n (needed for EMM386) */\n /* XXX: need a timer to do things correctly */\n index = q->rptr - 1;\n if (index < 0)\n index = PS2_QUEUE_SIZE - 1;\n val = q->data[index];\n } else {\n val = q->data[q->rptr];\n if (++q->rptr == PS2_QUEUE_SIZE)\n q->rptr = 0;\n q->count--;\n /* reading deasserts IRQ */\n s->update_irq(s->update_arg, 0);\n /* reassert IRQs if data left */\n s->update_irq(s->update_arg, q->count != 0);\n }\n return val;\n}\n\nstatic void ps2_reset_keyboard(PS2KbdState *s)\n{\n s->scan_enabled = 1;\n}\n\nvoid ps2_write_keyboard(void *opaque, int val)\n{\n PS2KbdState *s = (PS2KbdState *)opaque;\n\n switch(s->common.write_cmd) {\n default:\n case -1:\n switch(val) {\n case 0x00:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case 0x05:\n ps2_queue(&s->common, KBD_REPLY_RESEND);\n break;\n case KBD_CMD_GET_ID:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n ps2_queue(&s->common, 0xab);\n ps2_queue(&s->common, 0x83);\n break;\n case KBD_CMD_ECHO:\n ps2_queue(&s->common, KBD_CMD_ECHO);\n break;\n case KBD_CMD_ENABLE:\n s->scan_enabled = 1;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_SET_LEDS:\n case KBD_CMD_SET_RATE:\n s->common.write_cmd = val;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET_DISABLE:\n ps2_reset_keyboard(s);\n s->scan_enabled = 0;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET_ENABLE:\n ps2_reset_keyboard(s);\n s->scan_enabled = 1;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET:\n ps2_reset_keyboard(s);\n ps2_queue(&s->common, KBD_REPLY_ACK);\n ps2_queue(&s->common, KBD_REPLY_POR);\n break;\n default:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n }\n break;\n case KBD_CMD_SET_LEDS:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n s->common.write_cmd = -1;\n break;\n case KBD_CMD_SET_RATE:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n s->common.write_cmd = -1;\n break;\n }\n}\n\n/* Set the scancode translation mode.\n 0 = raw scancodes.\n 1 = translated scancodes (used by qemu internally). */\n\nvoid ps2_keyboard_set_translation(void *opaque, int mode)\n{\n PS2KbdState *s = (PS2KbdState *)opaque;\n s->translate = mode;\n}\n\nstatic void ps2_mouse_send_packet(PS2MouseState *s)\n{\n unsigned int b;\n int dx1, dy1, dz1;\n\n dx1 = s->mouse_dx;\n dy1 = s->mouse_dy;\n dz1 = s->mouse_dz;\n /* XXX: increase range to 8 bits ? */\n if (dx1 > 127)\n dx1 = 127;\n else if (dx1 < -127)\n dx1 = -127;\n if (dy1 > 127)\n dy1 = 127;\n else if (dy1 < -127)\n dy1 = -127;\n b = 0x08 | ((dx1 < 0) << 4) | ((dy1 < 0) << 5) | (s->mouse_buttons & 0x07);\n ps2_queue(&s->common, b);\n ps2_queue(&s->common, dx1 & 0xff);\n ps2_queue(&s->common, dy1 & 0xff);\n /* extra byte for IMPS/2 or IMEX */\n switch(s->mouse_type) {\n default:\n break;\n case 3:\n if (dz1 > 127)\n dz1 = 127;\n else if (dz1 < -127)\n dz1 = -127;\n ps2_queue(&s->common, dz1 & 0xff);\n break;\n case 4:\n if (dz1 > 7)\n dz1 = 7;\n else if (dz1 < -7)\n dz1 = -7;\n b = (dz1 & 0x0f) | ((s->mouse_buttons & 0x18) << 1);\n ps2_queue(&s->common, b);\n break;\n }\n\n /* update deltas */\n s->mouse_dx -= dx1;\n s->mouse_dy -= dy1;\n s->mouse_dz -= dz1;\n}\n\nvoid ps2_mouse_event(PS2MouseState *s,\n int dx, int dy, int dz, int buttons_state)\n{\n /* check if deltas are recorded when disabled */\n if (!(s->mouse_status & MOUSE_STATUS_ENABLED))\n return;\n\n s->mouse_dx += dx;\n s->mouse_dy -= dy;\n s->mouse_dz += dz;\n /* XXX: SDL sometimes generates nul events: we delete them */\n if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0 &&\n s->mouse_buttons == buttons_state)\n\treturn;\n s->mouse_buttons = buttons_state;\n\n if (!(s->mouse_status & MOUSE_STATUS_REMOTE) &&\n (s->common.queue.count < (PS2_QUEUE_SIZE - 16))) {\n for(;;) {\n /* if not remote, send event. Multiple events are sent if\n too big deltas */\n ps2_mouse_send_packet(s);\n if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0)\n break;\n }\n }\n}\n\nvoid ps2_write_mouse(void *opaque, int val)\n{\n PS2MouseState *s = (PS2MouseState *)opaque;\n#ifdef DEBUG_MOUSE\n printf(\"kbd: write mouse 0x%02x\\n\", val);\n#endif\n switch(s->common.write_cmd) {\n default:\n case -1:\n /* mouse command */\n if (s->mouse_wrap) {\n if (val == AUX_RESET_WRAP) {\n s->mouse_wrap = 0;\n ps2_queue(&s->common, AUX_ACK);\n return;\n } else if (val != AUX_RESET) {\n ps2_queue(&s->common, val);\n return;\n }\n }\n switch(val) {\n case AUX_SET_SCALE11:\n s->mouse_status &= ~MOUSE_STATUS_SCALE21;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_SCALE21:\n s->mouse_status |= MOUSE_STATUS_SCALE21;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_STREAM:\n s->mouse_status &= ~MOUSE_STATUS_REMOTE;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_WRAP:\n s->mouse_wrap = 1;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_REMOTE:\n s->mouse_status |= MOUSE_STATUS_REMOTE;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_GET_TYPE:\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, s->mouse_type);\n break;\n case AUX_SET_RES:\n case AUX_SET_SAMPLE:\n s->common.write_cmd = val;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_GET_SCALE:\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, s->mouse_status);\n ps2_queue(&s->common, s->mouse_resolution);\n ps2_queue(&s->common, s->mouse_sample_rate);\n break;\n case AUX_POLL:\n ps2_queue(&s->common, AUX_ACK);\n ps2_mouse_send_packet(s);\n break;\n case AUX_ENABLE_DEV:\n s->mouse_status |= MOUSE_STATUS_ENABLED;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_DISABLE_DEV:\n s->mouse_status &= ~MOUSE_STATUS_ENABLED;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_DEFAULT:\n s->mouse_sample_rate = 100;\n s->mouse_resolution = 2;\n s->mouse_status = 0;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_RESET:\n s->mouse_sample_rate = 100;\n s->mouse_resolution = 2;\n s->mouse_status = 0;\n s->mouse_type = 0;\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, 0xaa);\n ps2_queue(&s->common, s->mouse_type);\n break;\n default:\n break;\n }\n break;\n case AUX_SET_SAMPLE:\n s->mouse_sample_rate = val;\n /* detect IMPS/2 or IMEX */\n switch(s->mouse_detect_state) {\n default:\n case 0:\n if (val == 200)\n s->mouse_detect_state = 1;\n break;\n case 1:\n if (val == 100)\n s->mouse_detect_state = 2;\n else if (val == 200)\n s->mouse_detect_state = 3;\n else\n s->mouse_detect_state = 0;\n break;\n case 2:\n if (val == 80)\n s->mouse_type = 3; /* IMPS/2 */\n s->mouse_detect_state = 0;\n break;\n case 3:\n if (val == 80)\n s->mouse_type = 4; /* IMEX */\n s->mouse_detect_state = 0;\n break;\n }\n ps2_queue(&s->common, AUX_ACK);\n s->common.write_cmd = -1;\n break;\n case AUX_SET_RES:\n s->mouse_resolution = val;\n ps2_queue(&s->common, AUX_ACK);\n s->common.write_cmd = -1;\n break;\n }\n}\n\nstatic void ps2_reset(void *opaque)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q;\n s->write_cmd = -1;\n q = &s->queue;\n q->rptr = 0;\n q->wptr = 0;\n q->count = 0;\n}\n\nPS2KbdState *ps2_kbd_init(void (*update_irq)(void *, int), void *update_arg)\n{\n PS2KbdState *s = (PS2KbdState *)mallocz(sizeof(PS2KbdState));\n\n s->common.update_irq = update_irq;\n s->common.update_arg = update_arg;\n ps2_reset(&s->common);\n return s;\n}\n\nPS2MouseState *ps2_mouse_init(void (*update_irq)(void *, int), void *update_arg)\n{\n PS2MouseState *s = (PS2MouseState *)mallocz(sizeof(PS2MouseState));\n\n s->common.update_irq = update_irq;\n s->common.update_arg = update_arg;\n ps2_reset(&s->common);\n return s;\n}\n"], ["/linuxpdf/tinyemu/fs_wget.c", "/*\n * HTTP file download\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n\n#if defined(EMSCRIPTEN)\n#include \n#else\n#include \n#endif\n\n/***********************************************/\n/* HTTP get */\n\n#ifdef EMSCRIPTEN\n\nstruct XHRState {\n void *opaque;\n WGetWriteCallback *cb;\n};\n\nstatic int downloading_count;\n\nvoid fs_wget_init(void)\n{\n}\n\nextern void fs_wget_update_downloading(int flag);\n\nstatic void fs_wget_update_downloading_count(int incr)\n{\n int prev_state, state;\n prev_state = (downloading_count > 0);\n downloading_count += incr;\n state = (downloading_count > 0);\n if (prev_state != state)\n fs_wget_update_downloading(state);\n}\n\nstatic void fs_wget_onerror(unsigned int handle, void *opaque, int status,\n const char *status_text)\n{\n XHRState *s = opaque;\n if (status <= 0)\n status = -404; /* HTTP not found error */\n else\n status = -status;\n fs_wget_update_downloading_count(-1);\n if (s->cb)\n s->cb(s->opaque, status, NULL, 0);\n}\n\nstatic void fs_wget_onload(unsigned int handle,\n void *opaque, void *data, unsigned int size)\n{\n XHRState *s = opaque;\n fs_wget_update_downloading_count(-1);\n if (s->cb)\n s->cb(s->opaque, 0, data, size);\n}\n\nextern int emscripten_async_wget3_data(const char* url, const char* requesttype, const char *user, const char *password, const uint8_t *post_data, int post_data_len, void *arg, int free, em_async_wget2_data_onload_func onload, em_async_wget2_data_onerror_func onerror, em_async_wget2_data_onprogress_func onprogress);\n\nXHRState *fs_wget2(const char *url, const char *user, const char *password,\n WGetReadCallback *read_cb, uint64_t post_data_len,\n void *opaque, WGetWriteCallback *cb, BOOL single_write)\n{\n XHRState *s;\n const char *request;\n uint8_t *post_data;\n \n s = mallocz(sizeof(*s));\n s->opaque = opaque;\n s->cb = cb;\n\n if (post_data_len != 0) {\n request = \"POST\";\n post_data = malloc(post_data_len);\n read_cb(opaque, post_data, post_data_len);\n } else {\n request = \"GET\";\n post_data = NULL;\n }\n fs_wget_update_downloading_count(1);\n\n emscripten_async_wget3_data(url, request, user, password,\n post_data, post_data_len, s, 1, fs_wget_onload,\n fs_wget_onerror, NULL);\n if (post_data_len != 0)\n free(post_data);\n return s;\n}\n\nvoid fs_wget_free(XHRState *s)\n{\n s->cb = NULL;\n s->opaque = NULL;\n}\n\n#else\n\nstruct XHRState {\n struct list_head link;\n CURL *eh;\n void *opaque;\n WGetWriteCallback *write_cb;\n WGetReadCallback *read_cb;\n\n BOOL single_write;\n DynBuf dbuf; /* used if single_write */\n};\n\ntypedef struct {\n struct list_head link;\n int64_t timeout;\n void (*cb)(void *opaque);\n void *opaque;\n} AsyncCallState;\n\nstatic CURLM *curl_multi_ctx;\nstatic struct list_head xhr_list; /* list of XHRState.link */\n\nvoid fs_wget_init(void)\n{\n if (curl_multi_ctx)\n return;\n curl_global_init(CURL_GLOBAL_ALL);\n curl_multi_ctx = curl_multi_init();\n init_list_head(&xhr_list);\n}\n\nvoid fs_wget_end(void)\n{\n curl_multi_cleanup(curl_multi_ctx);\n curl_global_cleanup();\n}\n\nstatic size_t fs_wget_write_cb(char *ptr, size_t size, size_t nmemb,\n void *userdata)\n{\n XHRState *s = userdata;\n size *= nmemb;\n\n if (s->single_write) {\n dbuf_write(&s->dbuf, s->dbuf.size, (void *)ptr, size);\n } else {\n s->write_cb(s->opaque, 1, ptr, size);\n }\n return size;\n}\n\nstatic size_t fs_wget_read_cb(char *ptr, size_t size, size_t nmemb,\n void *userdata)\n{\n XHRState *s = userdata;\n size *= nmemb;\n return s->read_cb(s->opaque, ptr, size);\n}\n\nXHRState *fs_wget2(const char *url, const char *user, const char *password,\n WGetReadCallback *read_cb, uint64_t post_data_len,\n void *opaque, WGetWriteCallback *write_cb, BOOL single_write)\n{\n XHRState *s;\n s = mallocz(sizeof(*s));\n s->eh = curl_easy_init();\n s->opaque = opaque;\n s->write_cb = write_cb;\n s->read_cb = read_cb;\n s->single_write = single_write;\n dbuf_init(&s->dbuf);\n \n curl_easy_setopt(s->eh, CURLOPT_PRIVATE, s);\n curl_easy_setopt(s->eh, CURLOPT_WRITEDATA, s);\n curl_easy_setopt(s->eh, CURLOPT_WRITEFUNCTION, fs_wget_write_cb);\n curl_easy_setopt(s->eh, CURLOPT_HEADER, 0);\n curl_easy_setopt(s->eh, CURLOPT_URL, url);\n curl_easy_setopt(s->eh, CURLOPT_VERBOSE, 0L);\n curl_easy_setopt(s->eh, CURLOPT_ACCEPT_ENCODING, \"\");\n if (user) {\n curl_easy_setopt(s->eh, CURLOPT_USERNAME, user);\n curl_easy_setopt(s->eh, CURLOPT_PASSWORD, password);\n }\n if (post_data_len != 0) {\n struct curl_slist *headers = NULL;\n headers = curl_slist_append(headers,\n \"Content-Type: application/octet-stream\");\n curl_easy_setopt(s->eh, CURLOPT_HTTPHEADER, headers);\n curl_easy_setopt(s->eh, CURLOPT_POST, 1L);\n curl_easy_setopt(s->eh, CURLOPT_POSTFIELDSIZE_LARGE,\n (curl_off_t)post_data_len);\n curl_easy_setopt(s->eh, CURLOPT_READDATA, s);\n curl_easy_setopt(s->eh, CURLOPT_READFUNCTION, fs_wget_read_cb);\n }\n curl_multi_add_handle(curl_multi_ctx, s->eh);\n list_add_tail(&s->link, &xhr_list);\n return s;\n}\n\nvoid fs_wget_free(XHRState *s)\n{\n dbuf_free(&s->dbuf);\n curl_easy_cleanup(s->eh);\n list_del(&s->link);\n free(s);\n}\n\n/* timeout is in ms */\nvoid fs_net_set_fdset(int *pfd_max, fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *ptimeout)\n{\n long timeout;\n int n, fd_max;\n CURLMsg *msg;\n \n if (!curl_multi_ctx)\n return;\n \n curl_multi_perform(curl_multi_ctx, &n);\n\n for(;;) {\n msg = curl_multi_info_read(curl_multi_ctx, &n);\n if (!msg)\n break;\n if (msg->msg == CURLMSG_DONE) {\n XHRState *s;\n long http_code;\n\n curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char **)&s);\n curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE,\n &http_code);\n /* signal the end of the transfer or error */\n if (http_code == 200) {\n if (s->single_write) {\n s->write_cb(s->opaque, 0, s->dbuf.buf, s->dbuf.size);\n } else {\n s->write_cb(s->opaque, 0, NULL, 0);\n }\n } else {\n s->write_cb(s->opaque, -http_code, NULL, 0);\n }\n curl_multi_remove_handle(curl_multi_ctx, s->eh);\n curl_easy_cleanup(s->eh);\n dbuf_free(&s->dbuf);\n list_del(&s->link);\n free(s);\n }\n }\n\n curl_multi_fdset(curl_multi_ctx, rfds, wfds, efds, &fd_max);\n *pfd_max = max_int(*pfd_max, fd_max);\n curl_multi_timeout(curl_multi_ctx, &timeout);\n if (timeout >= 0)\n *ptimeout = min_int(*ptimeout, timeout);\n}\n\nvoid fs_net_event_loop(FSNetEventLoopCompletionFunc *cb, void *opaque)\n{\n fd_set rfds, wfds, efds;\n int timeout, fd_max;\n struct timeval tv;\n \n if (!curl_multi_ctx)\n return;\n\n for(;;) {\n fd_max = -1;\n FD_ZERO(&rfds);\n FD_ZERO(&wfds);\n FD_ZERO(&efds);\n timeout = 10000;\n fs_net_set_fdset(&fd_max, &rfds, &wfds, &efds, &timeout);\n if (cb) {\n if (cb(opaque))\n break;\n } else {\n if (list_empty(&xhr_list))\n break;\n }\n tv.tv_sec = timeout / 1000;\n tv.tv_usec = (timeout % 1000) * 1000;\n select(fd_max + 1, &rfds, &wfds, &efds, &tv);\n }\n}\n\n#endif /* !EMSCRIPTEN */\n\nXHRState *fs_wget(const char *url, const char *user, const char *password,\n void *opaque, WGetWriteCallback *cb, BOOL single_write)\n{\n return fs_wget2(url, user, password, NULL, 0, opaque, cb, single_write);\n}\n\n/***********************************************/\n/* file decryption */\n\n#define ENCRYPTED_FILE_HEADER_SIZE (4 + AES_BLOCK_SIZE)\n\n#define DEC_BUF_SIZE (256 * AES_BLOCK_SIZE)\n\nstruct DecryptFileState {\n DecryptFileCB *write_cb;\n void *opaque;\n int dec_state;\n int dec_buf_pos;\n AES_KEY *aes_state;\n uint8_t iv[AES_BLOCK_SIZE];\n uint8_t dec_buf[DEC_BUF_SIZE];\n};\n\nDecryptFileState *decrypt_file_init(AES_KEY *aes_state,\n DecryptFileCB *write_cb,\n void *opaque)\n{\n DecryptFileState *s;\n s = mallocz(sizeof(*s));\n s->write_cb = write_cb;\n s->opaque = opaque;\n s->aes_state = aes_state;\n return s;\n}\n \nint decrypt_file(DecryptFileState *s, const uint8_t *data,\n size_t size)\n{\n int l, len, ret;\n\n while (size != 0) {\n switch(s->dec_state) {\n case 0:\n l = min_int(size, ENCRYPTED_FILE_HEADER_SIZE - s->dec_buf_pos);\n memcpy(s->dec_buf + s->dec_buf_pos, data, l);\n s->dec_buf_pos += l;\n if (s->dec_buf_pos >= ENCRYPTED_FILE_HEADER_SIZE) {\n if (memcmp(s->dec_buf, encrypted_file_magic, 4) != 0)\n return -1;\n memcpy(s->iv, s->dec_buf + 4, AES_BLOCK_SIZE);\n s->dec_state = 1;\n s->dec_buf_pos = 0;\n }\n break;\n case 1:\n l = min_int(size, DEC_BUF_SIZE - s->dec_buf_pos);\n memcpy(s->dec_buf + s->dec_buf_pos, data, l);\n s->dec_buf_pos += l;\n if (s->dec_buf_pos >= DEC_BUF_SIZE) {\n /* keep one block in case it is the padding */\n len = s->dec_buf_pos - AES_BLOCK_SIZE;\n AES_cbc_encrypt(s->dec_buf, s->dec_buf, len,\n s->aes_state, s->iv, FALSE);\n ret = s->write_cb(s->opaque, s->dec_buf, len);\n if (ret < 0)\n return ret;\n memcpy(s->dec_buf, s->dec_buf + s->dec_buf_pos - AES_BLOCK_SIZE,\n AES_BLOCK_SIZE);\n s->dec_buf_pos = AES_BLOCK_SIZE;\n }\n break;\n default:\n abort();\n }\n data += l;\n size -= l;\n }\n return 0;\n}\n\n/* write last blocks */\nint decrypt_file_flush(DecryptFileState *s)\n{\n int len, pad_len, ret;\n\n if (s->dec_state != 1)\n return -1;\n len = s->dec_buf_pos;\n if (len == 0 || \n (len % AES_BLOCK_SIZE) != 0)\n return -1;\n AES_cbc_encrypt(s->dec_buf, s->dec_buf, len,\n s->aes_state, s->iv, FALSE);\n pad_len = s->dec_buf[s->dec_buf_pos - 1];\n if (pad_len < 1 || pad_len > AES_BLOCK_SIZE)\n return -1;\n len -= pad_len;\n if (len != 0) {\n ret = s->write_cb(s->opaque, s->dec_buf, len);\n if (ret < 0)\n return ret;\n }\n return 0;\n}\n\nvoid decrypt_file_end(DecryptFileState *s)\n{\n free(s);\n}\n\n/* XHR file */\n\ntypedef struct {\n FSDevice *fs;\n FSFile *f;\n int64_t pos;\n FSWGetFileCB *cb;\n void *opaque;\n FSFile *posted_file;\n int64_t read_pos;\n DecryptFileState *dec_state;\n} FSWGetFileState;\n\nstatic int fs_wget_file_write_cb(void *opaque, const uint8_t *data,\n size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n\n ret = fs->fs_write(fs, s->f, s->pos, data, size);\n if (ret < 0)\n return ret;\n s->pos += ret;\n return ret;\n}\n\nstatic void fs_wget_file_on_load(void *opaque, int err, void *data, size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n int64_t ret_size;\n \n // printf(\"err=%d size=%ld\\n\", err, size);\n if (err < 0) {\n ret_size = err;\n goto done;\n } else {\n if (s->dec_state) {\n ret = decrypt_file(s->dec_state, data, size);\n if (ret >= 0 && err == 0) {\n /* handle the end of file */\n decrypt_file_flush(s->dec_state);\n }\n } else {\n ret = fs_wget_file_write_cb(s, data, size);\n }\n if (ret < 0) {\n ret_size = ret;\n goto done;\n } else if (err == 0) {\n /* end of transfer */\n ret_size = s->pos;\n done:\n s->cb(fs, s->f, ret_size, s->opaque);\n if (s->dec_state)\n decrypt_file_end(s->dec_state);\n free(s);\n }\n }\n}\n\nstatic size_t fs_wget_file_read_cb(void *opaque, void *data, size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n \n if (!s->posted_file)\n return 0;\n ret = fs->fs_read(fs, s->posted_file, s->read_pos, data, size);\n if (ret < 0)\n return 0;\n s->read_pos += ret;\n return ret;\n}\n\nvoid fs_wget_file2(FSDevice *fs, FSFile *f, const char *url,\n const char *user, const char *password,\n FSFile *posted_file, uint64_t post_data_len,\n FSWGetFileCB *cb, void *opaque,\n AES_KEY *aes_state)\n{\n FSWGetFileState *s;\n s = mallocz(sizeof(*s));\n s->fs = fs;\n s->f = f;\n s->pos = 0;\n s->cb = cb;\n s->opaque = opaque;\n s->posted_file = posted_file;\n s->read_pos = 0;\n if (aes_state) {\n s->dec_state = decrypt_file_init(aes_state, fs_wget_file_write_cb, s);\n }\n \n fs_wget2(url, user, password, fs_wget_file_read_cb, post_data_len,\n s, fs_wget_file_on_load, FALSE);\n}\n\n/***********************************************/\n/* PBKDF2 */\n\n#ifdef USE_BUILTIN_CRYPTO\n\n#define HMAC_BLOCK_SIZE 64\n\ntypedef struct {\n SHA256_CTX ctx;\n uint8_t K[HMAC_BLOCK_SIZE + SHA256_DIGEST_LENGTH];\n} HMAC_SHA256_CTX;\n\nvoid hmac_sha256_init(HMAC_SHA256_CTX *s, const uint8_t *key, int key_len)\n{\n int i, l;\n \n if (key_len > HMAC_BLOCK_SIZE) {\n SHA256(key, key_len, s->K);\n l = SHA256_DIGEST_LENGTH;\n } else {\n memcpy(s->K, key, key_len);\n l = key_len;\n }\n memset(s->K + l, 0, HMAC_BLOCK_SIZE - l);\n for(i = 0; i < HMAC_BLOCK_SIZE; i++)\n s->K[i] ^= 0x36;\n SHA256_Init(&s->ctx);\n SHA256_Update(&s->ctx, s->K, HMAC_BLOCK_SIZE);\n}\n\nvoid hmac_sha256_update(HMAC_SHA256_CTX *s, const uint8_t *buf, int len)\n{\n SHA256_Update(&s->ctx, buf, len);\n}\n\n/* out has a length of SHA256_DIGEST_LENGTH */\nvoid hmac_sha256_final(HMAC_SHA256_CTX *s, uint8_t *out)\n{\n int i;\n \n SHA256_Final(s->K + HMAC_BLOCK_SIZE, &s->ctx);\n for(i = 0; i < HMAC_BLOCK_SIZE; i++)\n s->K[i] ^= (0x36 ^ 0x5c);\n SHA256(s->K, HMAC_BLOCK_SIZE + SHA256_DIGEST_LENGTH, out);\n}\n\n#define SALT_LEN_MAX 32\n\nvoid pbkdf2_hmac_sha256(const uint8_t *pwd, int pwd_len,\n const uint8_t *salt, int salt_len,\n int iter, int key_len, uint8_t *out)\n{\n uint8_t F[SHA256_DIGEST_LENGTH], U[SALT_LEN_MAX + 4];\n HMAC_SHA256_CTX ctx;\n int it, U_len, j, l;\n uint32_t i;\n \n assert(salt_len <= SALT_LEN_MAX);\n i = 1;\n while (key_len > 0) {\n memset(F, 0, SHA256_DIGEST_LENGTH);\n memcpy(U, salt, salt_len);\n U[salt_len] = i >> 24;\n U[salt_len + 1] = i >> 16;\n U[salt_len + 2] = i >> 8;\n U[salt_len + 3] = i;\n U_len = salt_len + 4;\n for(it = 0; it < iter; it++) {\n hmac_sha256_init(&ctx, pwd, pwd_len);\n hmac_sha256_update(&ctx, U, U_len);\n hmac_sha256_final(&ctx, U);\n for(j = 0; j < SHA256_DIGEST_LENGTH; j++)\n F[j] ^= U[j];\n U_len = SHA256_DIGEST_LENGTH;\n }\n l = min_int(key_len, SHA256_DIGEST_LENGTH);\n memcpy(out, F, l);\n out += l;\n key_len -= l;\n i++;\n }\n}\n\n#else\n\nvoid pbkdf2_hmac_sha256(const uint8_t *pwd, int pwd_len,\n const uint8_t *salt, int salt_len,\n int iter, int key_len, uint8_t *out)\n{\n PKCS5_PBKDF2_HMAC((const char *)pwd, pwd_len, salt, salt_len,\n iter, EVP_sha256(), key_len, out);\n}\n\n#endif /* !USE_BUILTIN_CRYPTO */\n"], ["/linuxpdf/tinyemu/slirp/tcp_subr.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_subr.c\t8.1 (Berkeley) 6/10/93\n * tcp_subr.c,v 1.5 1994/10/08 22:39:58 phk Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n/* patchable/settable parameters for tcp */\n/* Don't do rfc1323 performance enhancements */\n#define TCP_DO_RFC1323 0\n\n/*\n * Tcp initialization\n */\nvoid\ntcp_init(Slirp *slirp)\n{\n slirp->tcp_iss = 1;\t\t/* wrong */\n slirp->tcb.so_next = slirp->tcb.so_prev = &slirp->tcb;\n slirp->tcp_last_so = &slirp->tcb;\n}\n\n/*\n * Create template to be used to send tcp packets on a connection.\n * Call after host entry created, fills\n * in a skeletal tcp/ip header, minimizing the amount of work\n * necessary when the connection is used.\n */\nvoid\ntcp_template(struct tcpcb *tp)\n{\n\tstruct socket *so = tp->t_socket;\n\tregister struct tcpiphdr *n = &tp->t_template;\n\n\tn->ti_mbuf = NULL;\n\tn->ti_x1 = 0;\n\tn->ti_pr = IPPROTO_TCP;\n\tn->ti_len = htons(sizeof (struct tcpiphdr) - sizeof (struct ip));\n\tn->ti_src = so->so_faddr;\n\tn->ti_dst = so->so_laddr;\n\tn->ti_sport = so->so_fport;\n\tn->ti_dport = so->so_lport;\n\n\tn->ti_seq = 0;\n\tn->ti_ack = 0;\n\tn->ti_x2 = 0;\n\tn->ti_off = 5;\n\tn->ti_flags = 0;\n\tn->ti_win = 0;\n\tn->ti_sum = 0;\n\tn->ti_urp = 0;\n}\n\n/*\n * Send a single message to the TCP at address specified by\n * the given TCP/IP header. If m == 0, then we make a copy\n * of the tcpiphdr at ti and send directly to the addressed host.\n * This is used to force keep alive messages out using the TCP\n * template for a connection tp->t_template. If flags are given\n * then we send a message back to the TCP which originated the\n * segment ti, and discard the mbuf containing it and any other\n * attached mbufs.\n *\n * In any case the ack and sequence number of the transmitted\n * segment are as specified by the parameters.\n */\nvoid\ntcp_respond(struct tcpcb *tp, struct tcpiphdr *ti, struct mbuf *m,\n tcp_seq ack, tcp_seq seq, int flags)\n{\n\tregister int tlen;\n\tint win = 0;\n\n\tDEBUG_CALL(\"tcp_respond\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"ti = %lx\", (long)ti);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"ack = %u\", ack);\n\tDEBUG_ARG(\"seq = %u\", seq);\n\tDEBUG_ARG(\"flags = %x\", flags);\n\n\tif (tp)\n\t\twin = sbspace(&tp->t_socket->so_rcv);\n if (m == NULL) {\n\t\tif ((m = m_get(tp->t_socket->slirp)) == NULL)\n\t\t\treturn;\n\t\ttlen = 0;\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\t*mtod(m, struct tcpiphdr *) = *ti;\n\t\tti = mtod(m, struct tcpiphdr *);\n\t\tflags = TH_ACK;\n\t} else {\n\t\t/*\n\t\t * ti points into m so the next line is just making\n\t\t * the mbuf point to ti\n\t\t */\n\t\tm->m_data = (caddr_t)ti;\n\n\t\tm->m_len = sizeof (struct tcpiphdr);\n\t\ttlen = 0;\n#define xchg(a,b,type) { type t; t=a; a=b; b=t; }\n\t\txchg(ti->ti_dst.s_addr, ti->ti_src.s_addr, uint32_t);\n\t\txchg(ti->ti_dport, ti->ti_sport, uint16_t);\n#undef xchg\n\t}\n\tti->ti_len = htons((u_short)(sizeof (struct tcphdr) + tlen));\n\ttlen += sizeof (struct tcpiphdr);\n\tm->m_len = tlen;\n\n ti->ti_mbuf = NULL;\n\tti->ti_x1 = 0;\n\tti->ti_seq = htonl(seq);\n\tti->ti_ack = htonl(ack);\n\tti->ti_x2 = 0;\n\tti->ti_off = sizeof (struct tcphdr) >> 2;\n\tti->ti_flags = flags;\n\tif (tp)\n\t\tti->ti_win = htons((uint16_t) (win >> tp->rcv_scale));\n\telse\n\t\tti->ti_win = htons((uint16_t)win);\n\tti->ti_urp = 0;\n\tti->ti_sum = 0;\n\tti->ti_sum = cksum(m, tlen);\n\t((struct ip *)ti)->ip_len = tlen;\n\n\tif(flags & TH_RST)\n\t ((struct ip *)ti)->ip_ttl = MAXTTL;\n\telse\n\t ((struct ip *)ti)->ip_ttl = IPDEFTTL;\n\n\t(void) ip_output((struct socket *)0, m);\n}\n\n/*\n * Create a new TCP control block, making an\n * empty reassembly queue and hooking it to the argument\n * protocol control block.\n */\nstruct tcpcb *\ntcp_newtcpcb(struct socket *so)\n{\n\tregister struct tcpcb *tp;\n\n\ttp = (struct tcpcb *)malloc(sizeof(*tp));\n\tif (tp == NULL)\n\t\treturn ((struct tcpcb *)0);\n\n\tmemset((char *) tp, 0, sizeof(struct tcpcb));\n\ttp->seg_next = tp->seg_prev = (struct tcpiphdr*)tp;\n\ttp->t_maxseg = TCP_MSS;\n\n\ttp->t_flags = TCP_DO_RFC1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;\n\ttp->t_socket = so;\n\n\t/*\n\t * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no\n\t * rtt estimate. Set rttvar so that srtt + 2 * rttvar gives\n\t * reasonable initial retransmit time.\n\t */\n\ttp->t_srtt = TCPTV_SRTTBASE;\n\ttp->t_rttvar = TCPTV_SRTTDFLT << 2;\n\ttp->t_rttmin = TCPTV_MIN;\n\n\tTCPT_RANGESET(tp->t_rxtcur,\n\t ((TCPTV_SRTTBASE >> 2) + (TCPTV_SRTTDFLT << 2)) >> 1,\n\t TCPTV_MIN, TCPTV_REXMTMAX);\n\n\ttp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;\n\ttp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;\n\ttp->t_state = TCPS_CLOSED;\n\n\tso->so_tcpcb = tp;\n\n\treturn (tp);\n}\n\n/*\n * Drop a TCP connection, reporting\n * the specified error. If connection is synchronized,\n * then send a RST to peer.\n */\nstruct tcpcb *tcp_drop(struct tcpcb *tp, int err)\n{\n\tDEBUG_CALL(\"tcp_drop\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"errno = %d\", errno);\n\n\tif (TCPS_HAVERCVDSYN(tp->t_state)) {\n\t\ttp->t_state = TCPS_CLOSED;\n\t\t(void) tcp_output(tp);\n\t}\n\treturn (tcp_close(tp));\n}\n\n/*\n * Close a TCP control block:\n *\tdiscard all space held by the tcp\n *\tdiscard internet protocol block\n *\twake up any sleepers\n */\nstruct tcpcb *\ntcp_close(struct tcpcb *tp)\n{\n\tregister struct tcpiphdr *t;\n\tstruct socket *so = tp->t_socket;\n\tSlirp *slirp = so->slirp;\n\tregister struct mbuf *m;\n\n\tDEBUG_CALL(\"tcp_close\");\n\tDEBUG_ARG(\"tp = %lx\", (long )tp);\n\n\t/* free the reassembly queue, if any */\n\tt = tcpfrag_list_first(tp);\n\twhile (!tcpfrag_list_end(t, tp)) {\n\t\tt = tcpiphdr_next(t);\n\t\tm = tcpiphdr_prev(t)->ti_mbuf;\n\t\tremque(tcpiphdr2qlink(tcpiphdr_prev(t)));\n\t\tm_freem(m);\n\t}\n\tfree(tp);\n so->so_tcpcb = NULL;\n\t/* clobber input socket cache if we're closing the cached connection */\n\tif (so == slirp->tcp_last_so)\n\t\tslirp->tcp_last_so = &slirp->tcb;\n\tclosesocket(so->s);\n\tsbfree(&so->so_rcv);\n\tsbfree(&so->so_snd);\n\tsofree(so);\n\treturn ((struct tcpcb *)0);\n}\n\n/*\n * TCP protocol interface to socket abstraction.\n */\n\n/*\n * User issued close, and wish to trail through shutdown states:\n * if never received SYN, just forget it. If got a SYN from peer,\n * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.\n * If already got a FIN from peer, then almost done; go to LAST_ACK\n * state. In all other cases, have already sent FIN to peer (e.g.\n * after PRU_SHUTDOWN), and just have to play tedious game waiting\n * for peer to send FIN or not respond to keep-alives, etc.\n * We can let the user exit from the close as soon as the FIN is acked.\n */\nvoid\ntcp_sockclosed(struct tcpcb *tp)\n{\n\n\tDEBUG_CALL(\"tcp_sockclosed\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\n\tswitch (tp->t_state) {\n\n\tcase TCPS_CLOSED:\n\tcase TCPS_LISTEN:\n\tcase TCPS_SYN_SENT:\n\t\ttp->t_state = TCPS_CLOSED;\n\t\ttp = tcp_close(tp);\n\t\tbreak;\n\n\tcase TCPS_SYN_RECEIVED:\n\tcase TCPS_ESTABLISHED:\n\t\ttp->t_state = TCPS_FIN_WAIT_1;\n\t\tbreak;\n\n\tcase TCPS_CLOSE_WAIT:\n\t\ttp->t_state = TCPS_LAST_ACK;\n\t\tbreak;\n\t}\n\tif (tp)\n\t\ttcp_output(tp);\n}\n\n/*\n * Connect to a host on the Internet\n * Called by tcp_input\n * Only do a connect, the tcp fields will be set in tcp_input\n * return 0 if there's a result of the connect,\n * else return -1 means we're still connecting\n * The return value is almost always -1 since the socket is\n * nonblocking. Connect returns after the SYN is sent, and does\n * not wait for ACK+SYN.\n */\nint tcp_fconnect(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n int ret=0;\n\n DEBUG_CALL(\"tcp_fconnect\");\n DEBUG_ARG(\"so = %lx\", (long )so);\n\n if( (ret = so->s = os_socket(AF_INET,SOCK_STREAM,0)) >= 0) {\n int opt, s=so->s;\n struct sockaddr_in addr;\n\n fd_nonblock(s);\n opt = 1;\n setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(opt ));\n opt = 1;\n setsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(opt ));\n\n addr.sin_family = AF_INET;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n /* It's an alias */\n if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\tif (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n } else {\n\taddr.sin_addr = loopback_addr;\n }\n } else\n addr.sin_addr = so->so_faddr;\n addr.sin_port = so->so_fport;\n\n DEBUG_MISC((dfd, \" connect()ing, addr.sin_port=%d, \"\n\t\t\"addr.sin_addr.s_addr=%.16s\\n\",\n\t\tntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));\n /* We don't care what port we get */\n ret = connect(s,(struct sockaddr *)&addr,sizeof (addr));\n\n /*\n * If it's not in progress, it failed, so we just return 0,\n * without clearing SS_NOFDREF\n */\n soisfconnecting(so);\n }\n\n return(ret);\n}\n\n/*\n * Accept the socket and connect to the local-host\n *\n * We have a problem. The correct thing to do would be\n * to first connect to the local-host, and only if the\n * connection is accepted, then do an accept() here.\n * But, a) we need to know who's trying to connect\n * to the socket to be able to SYN the local-host, and\n * b) we are already connected to the foreign host by\n * the time it gets to accept(), so... We simply accept\n * here and SYN the local-host.\n */\nvoid\ntcp_connect(struct socket *inso)\n{\n\tSlirp *slirp = inso->slirp;\n\tstruct socket *so;\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\tstruct tcpcb *tp;\n\tint s, opt;\n\n\tDEBUG_CALL(\"tcp_connect\");\n\tDEBUG_ARG(\"inso = %lx\", (long)inso);\n\n\t/*\n\t * If it's an SS_ACCEPTONCE socket, no need to socreate()\n\t * another socket, just use the accept() socket.\n\t */\n\tif (inso->so_state & SS_FACCEPTONCE) {\n\t\t/* FACCEPTONCE already have a tcpcb */\n\t\tso = inso;\n\t} else {\n\t\tif ((so = socreate(slirp)) == NULL) {\n\t\t\t/* If it failed, get rid of the pending connection */\n\t\t\tclosesocket(accept(inso->s,(struct sockaddr *)&addr,&addrlen));\n\t\t\treturn;\n\t\t}\n\t\tif (tcp_attach(so) < 0) {\n\t\t\tfree(so); /* NOT sofree */\n\t\t\treturn;\n\t\t}\n\t\tso->so_laddr = inso->so_laddr;\n\t\tso->so_lport = inso->so_lport;\n\t}\n\n\t(void) tcp_mss(sototcpcb(so), 0);\n\n\tif ((s = accept(inso->s,(struct sockaddr *)&addr,&addrlen)) < 0) {\n\t\ttcp_close(sototcpcb(so)); /* This will sofree() as well */\n\t\treturn;\n\t}\n\tfd_nonblock(s);\n\topt = 1;\n\tsetsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\topt = 1;\n\tsetsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\topt = 1;\n\tsetsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&opt,sizeof(int));\n\n\tso->so_fport = addr.sin_port;\n\tso->so_faddr = addr.sin_addr;\n\t/* Translate connections from localhost to the real hostname */\n\tif (so->so_faddr.s_addr == 0 || so->so_faddr.s_addr == loopback_addr.s_addr)\n\t so->so_faddr = slirp->vhost_addr;\n\n\t/* Close the accept() socket, set right state */\n\tif (inso->so_state & SS_FACCEPTONCE) {\n\t\tclosesocket(so->s); /* If we only accept once, close the accept() socket */\n\t\tso->so_state = SS_NOFDREF; /* Don't select it yet, even though we have an FD */\n\t\t\t\t\t /* if it's not FACCEPTONCE, it's already NOFDREF */\n\t}\n\tso->s = s;\n\tso->so_state |= SS_INCOMING;\n\n\tso->so_iptos = tcp_tos(so);\n\ttp = sototcpcb(so);\n\n\ttcp_template(tp);\n\n\ttp->t_state = TCPS_SYN_SENT;\n\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\ttp->iss = slirp->tcp_iss;\n\tslirp->tcp_iss += TCP_ISSINCR/2;\n\ttcp_sendseqinit(tp);\n\ttcp_output(tp);\n}\n\n/*\n * Attach a TCPCB to a socket.\n */\nint\ntcp_attach(struct socket *so)\n{\n\tif ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL)\n\t return -1;\n\n\tinsque(so, &so->slirp->tcb);\n\n\treturn 0;\n}\n\n/*\n * Set the socket's type of service field\n */\nstatic const struct tos_t tcptos[] = {\n\t {0, 20, IPTOS_THROUGHPUT, 0},\t/* ftp data */\n\t {21, 21, IPTOS_LOWDELAY, EMU_FTP},\t/* ftp control */\n\t {0, 23, IPTOS_LOWDELAY, 0},\t/* telnet */\n\t {0, 80, IPTOS_THROUGHPUT, 0},\t/* WWW */\n\t {0, 513, IPTOS_LOWDELAY, EMU_RLOGIN|EMU_NOCONNECT},\t/* rlogin */\n\t {0, 514, IPTOS_LOWDELAY, EMU_RSH|EMU_NOCONNECT},\t/* shell */\n\t {0, 544, IPTOS_LOWDELAY, EMU_KSH},\t\t/* kshell */\n\t {0, 543, IPTOS_LOWDELAY, 0},\t/* klogin */\n\t {0, 6667, IPTOS_THROUGHPUT, EMU_IRC},\t/* IRC */\n\t {0, 6668, IPTOS_THROUGHPUT, EMU_IRC},\t/* IRC undernet */\n\t {0, 7070, IPTOS_LOWDELAY, EMU_REALAUDIO }, /* RealAudio control */\n\t {0, 113, IPTOS_LOWDELAY, EMU_IDENT }, /* identd protocol */\n\t {0, 0, 0, 0}\n};\n\nstatic struct emu_t *tcpemu = NULL;\n\n/*\n * Return TOS according to the above table\n */\nuint8_t\ntcp_tos(struct socket *so)\n{\n\tint i = 0;\n\tstruct emu_t *emup;\n\n\twhile(tcptos[i].tos) {\n\t\tif ((tcptos[i].fport && (ntohs(so->so_fport) == tcptos[i].fport)) ||\n\t\t (tcptos[i].lport && (ntohs(so->so_lport) == tcptos[i].lport))) {\n\t\t\tso->so_emu = tcptos[i].emu;\n\t\t\treturn tcptos[i].tos;\n\t\t}\n\t\ti++;\n\t}\n\n\t/* Nope, lets see if there's a user-added one */\n\tfor (emup = tcpemu; emup; emup = emup->next) {\n\t\tif ((emup->fport && (ntohs(so->so_fport) == emup->fport)) ||\n\t\t (emup->lport && (ntohs(so->so_lport) == emup->lport))) {\n\t\t\tso->so_emu = emup->emu;\n\t\t\treturn emup->tos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/*\n * Emulate programs that try and connect to us\n * This includes ftp (the data connection is\n * initiated by the server) and IRC (DCC CHAT and\n * DCC SEND) for now\n *\n * NOTE: It's possible to crash SLiRP by sending it\n * unstandard strings to emulate... if this is a problem,\n * more checks are needed here\n *\n * XXX Assumes the whole command came in one packet\n *\n * XXX Some ftp clients will have their TOS set to\n * LOWDELAY and so Nagel will kick in. Because of this,\n * we'll get the first letter, followed by the rest, so\n * we simply scan for ORT instead of PORT...\n * DCC doesn't have this problem because there's other stuff\n * in the packet before the DCC command.\n *\n * Return 1 if the mbuf m is still valid and should be\n * sbappend()ed\n *\n * NOTE: if you return 0 you MUST m_free() the mbuf!\n */\nint\ntcp_emu(struct socket *so, struct mbuf *m)\n{\n\tSlirp *slirp = so->slirp;\n\tu_int n1, n2, n3, n4, n5, n6;\n char buff[257];\n\tuint32_t laddr;\n\tu_int lport;\n\tchar *bptr;\n\n\tDEBUG_CALL(\"tcp_emu\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n\tswitch(so->so_emu) {\n\t\tint x, i;\n\n\t case EMU_IDENT:\n\t\t/*\n\t\t * Identification protocol as per rfc-1413\n\t\t */\n\n\t\t{\n\t\t\tstruct socket *tmpso;\n\t\t\tstruct sockaddr_in addr;\n\t\t\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\t\t\tstruct sbuf *so_rcv = &so->so_rcv;\n\n\t\t\tmemcpy(so_rcv->sb_wptr, m->m_data, m->m_len);\n\t\t\tso_rcv->sb_wptr += m->m_len;\n\t\t\tso_rcv->sb_rptr += m->m_len;\n\t\t\tm->m_data[m->m_len] = 0; /* NULL terminate */\n\t\t\tif (strchr(m->m_data, '\\r') || strchr(m->m_data, '\\n')) {\n\t\t\t\tif (sscanf(so_rcv->sb_data, \"%u%*[ ,]%u\", &n1, &n2) == 2) {\n\t\t\t\t\tHTONS(n1);\n\t\t\t\t\tHTONS(n2);\n\t\t\t\t\t/* n2 is the one on our host */\n\t\t\t\t\tfor (tmpso = slirp->tcb.so_next;\n\t\t\t\t\t tmpso != &slirp->tcb;\n\t\t\t\t\t tmpso = tmpso->so_next) {\n\t\t\t\t\t\tif (tmpso->so_laddr.s_addr == so->so_laddr.s_addr &&\n\t\t\t\t\t\t tmpso->so_lport == n2 &&\n\t\t\t\t\t\t tmpso->so_faddr.s_addr == so->so_faddr.s_addr &&\n\t\t\t\t\t\t tmpso->so_fport == n1) {\n\t\t\t\t\t\t\tif (getsockname(tmpso->s,\n\t\t\t\t\t\t\t\t(struct sockaddr *)&addr, &addrlen) == 0)\n\t\t\t\t\t\t\t n2 = ntohs(addr.sin_port);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n so_rcv->sb_cc = snprintf(so_rcv->sb_data,\n so_rcv->sb_datalen,\n \"%d,%d\\r\\n\", n1, n2);\n\t\t\t\tso_rcv->sb_rptr = so_rcv->sb_data;\n\t\t\t\tso_rcv->sb_wptr = so_rcv->sb_data + so_rcv->sb_cc;\n\t\t\t}\n\t\t\tm_free(m);\n\t\t\treturn 0;\n\t\t}\n\n case EMU_FTP: /* ftp */\n *(m->m_data+m->m_len) = 0; /* NUL terminate for strstr */\n\t\tif ((bptr = (char *)strstr(m->m_data, \"ORT\")) != NULL) {\n\t\t\t/*\n\t\t\t * Need to emulate the PORT command\n\t\t\t */\n\t\t\tx = sscanf(bptr, \"ORT %u,%u,%u,%u,%u,%u\\r\\n%256[^\\177]\",\n\t\t\t\t &n1, &n2, &n3, &n4, &n5, &n6, buff);\n\t\t\tif (x < 6)\n\t\t\t return 1;\n\n\t\t\tladdr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));\n\t\t\tlport = htons((n5 << 8) | (n6));\n\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr,\n\t\t\t lport, SS_FACCEPTONCE)) == NULL) {\n\t\t\t return 1;\n\t\t\t}\n\t\t\tn6 = ntohs(so->so_fport);\n\n\t\t\tn5 = (n6 >> 8) & 0xff;\n\t\t\tn6 &= 0xff;\n\n\t\t\tladdr = ntohl(so->so_faddr.s_addr);\n\n\t\t\tn1 = ((laddr >> 24) & 0xff);\n\t\t\tn2 = ((laddr >> 16) & 0xff);\n\t\t\tn3 = ((laddr >> 8) & 0xff);\n\t\t\tn4 = (laddr & 0xff);\n\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size - m->m_len,\n \"ORT %d,%d,%d,%d,%d,%d\\r\\n%s\",\n n1, n2, n3, n4, n5, n6, x==7?buff:\"\");\n\t\t\treturn 1;\n\t\t} else if ((bptr = (char *)strstr(m->m_data, \"27 Entering\")) != NULL) {\n\t\t\t/*\n\t\t\t * Need to emulate the PASV response\n\t\t\t */\n\t\t\tx = sscanf(bptr, \"27 Entering Passive Mode (%u,%u,%u,%u,%u,%u)\\r\\n%256[^\\177]\",\n\t\t\t\t &n1, &n2, &n3, &n4, &n5, &n6, buff);\n\t\t\tif (x < 6)\n\t\t\t return 1;\n\n\t\t\tladdr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));\n\t\t\tlport = htons((n5 << 8) | (n6));\n\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr,\n\t\t\t lport, SS_FACCEPTONCE)) == NULL) {\n\t\t\t return 1;\n\t\t\t}\n\t\t\tn6 = ntohs(so->so_fport);\n\n\t\t\tn5 = (n6 >> 8) & 0xff;\n\t\t\tn6 &= 0xff;\n\n\t\t\tladdr = ntohl(so->so_faddr.s_addr);\n\n\t\t\tn1 = ((laddr >> 24) & 0xff);\n\t\t\tn2 = ((laddr >> 16) & 0xff);\n\t\t\tn3 = ((laddr >> 8) & 0xff);\n\t\t\tn4 = (laddr & 0xff);\n\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n\t\t\tm->m_len += snprintf(bptr, m->m_hdr.mh_size - m->m_len,\n \"27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\\r\\n%s\",\n n1, n2, n3, n4, n5, n6, x==7?buff:\"\");\n\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn 1;\n\n\t case EMU_KSH:\n\t\t/*\n\t\t * The kshell (Kerberos rsh) and shell services both pass\n\t\t * a local port port number to carry signals to the server\n\t\t * and stderr to the client. It is passed at the beginning\n\t\t * of the connection as a NUL-terminated decimal ASCII string.\n\t\t */\n\t\tso->so_emu = 0;\n\t\tfor (lport = 0, i = 0; i < m->m_len-1; ++i) {\n\t\t\tif (m->m_data[i] < '0' || m->m_data[i] > '9')\n\t\t\t\treturn 1; /* invalid number */\n\t\t\tlport *= 10;\n\t\t\tlport += m->m_data[i] - '0';\n\t\t}\n\t\tif (m->m_data[m->m_len-1] == '\\0' && lport != 0 &&\n\t\t (so = tcp_listen(slirp, INADDR_ANY, 0, so->so_laddr.s_addr,\n\t\t htons(lport), SS_FACCEPTONCE)) != NULL)\n m->m_len = snprintf(m->m_data, m->m_hdr.mh_size, \"%d\",\n ntohs(so->so_fport)) + 1;\n\t\treturn 1;\n\n\t case EMU_IRC:\n\t\t/*\n\t\t * Need to emulate DCC CHAT, DCC SEND and DCC MOVE\n\t\t */\n\t\t*(m->m_data+m->m_len) = 0; /* NULL terminate the string for strstr */\n\t\tif ((bptr = (char *)strstr(m->m_data, \"DCC\")) == NULL)\n\t\t\t return 1;\n\n\t\t/* The %256s is for the broken mIRC */\n\t\tif (sscanf(bptr, \"DCC CHAT %256s %u %u\", buff, &laddr, &lport) == 3) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC CHAT chat %lu %u%c\\n\",\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), 1);\n\t\t} else if (sscanf(bptr, \"DCC SEND %256s %u %u %u\", buff, &laddr, &lport, &n1) == 4) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC SEND %s %lu %u %u%c\\n\", buff,\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), n1, 1);\n\t\t} else if (sscanf(bptr, \"DCC MOVE %256s %u %u %u\", buff, &laddr, &lport, &n1) == 4) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC MOVE %s %lu %u %u%c\\n\", buff,\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), n1, 1);\n\t\t}\n\t\treturn 1;\n\n\t case EMU_REALAUDIO:\n /*\n\t\t * RealAudio emulation - JP. We must try to parse the incoming\n\t\t * data and try to find the two characters that contain the\n\t\t * port number. Then we redirect an udp port and replace the\n\t\t * number with the real port we got.\n\t\t *\n\t\t * The 1.0 beta versions of the player are not supported\n\t\t * any more.\n\t\t *\n\t\t * A typical packet for player version 1.0 (release version):\n\t\t *\n\t\t * 0000:50 4E 41 00 05\n\t\t * 0000:00 01 00 02 1B D7 00 00 67 E6 6C DC 63 00 12 50 ........g.l.c..P\n\t\t * 0010:4E 43 4C 49 45 4E 54 20 31 30 31 20 41 4C 50 48 NCLIENT 101 ALPH\n\t\t * 0020:41 6C 00 00 52 00 17 72 61 66 69 6C 65 73 2F 76 Al..R..rafiles/v\n\t\t * 0030:6F 61 2F 65 6E 67 6C 69 73 68 5F 2E 72 61 79 42 oa/english_.rayB\n\t\t *\n\t\t * Now the port number 0x1BD7 is found at offset 0x04 of the\n\t\t * Now the port number 0x1BD7 is found at offset 0x04 of the\n\t\t * second packet. This time we received five bytes first and\n\t\t * then the rest. You never know how many bytes you get.\n\t\t *\n\t\t * A typical packet for player version 2.0 (beta):\n\t\t *\n\t\t * 0000:50 4E 41 00 06 00 02 00 00 00 01 00 02 1B C1 00 PNA.............\n\t\t * 0010:00 67 75 78 F5 63 00 0A 57 69 6E 32 2E 30 2E 30 .gux.c..Win2.0.0\n\t\t * 0020:2E 35 6C 00 00 52 00 1C 72 61 66 69 6C 65 73 2F .5l..R..rafiles/\n\t\t * 0030:77 65 62 73 69 74 65 2F 32 30 72 65 6C 65 61 73 website/20releas\n\t\t * 0040:65 2E 72 61 79 53 00 00 06 36 42 e.rayS...6B\n\t\t *\n\t\t * Port number 0x1BC1 is found at offset 0x0d.\n\t\t *\n\t\t * This is just a horrible switch statement. Variable ra tells\n\t\t * us where we're going.\n\t\t */\n\n\t\tbptr = m->m_data;\n\t\twhile (bptr < m->m_data + m->m_len) {\n\t\t\tu_short p;\n\t\t\tstatic int ra = 0;\n\t\t\tchar ra_tbl[4];\n\n\t\t\tra_tbl[0] = 0x50;\n\t\t\tra_tbl[1] = 0x4e;\n\t\t\tra_tbl[2] = 0x41;\n\t\t\tra_tbl[3] = 0;\n\n\t\t\tswitch (ra) {\n\t\t\t case 0:\n\t\t\t case 2:\n\t\t\t case 3:\n\t\t\t\tif (*bptr++ != ra_tbl[ra]) {\n\t\t\t\t\tra = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t case 1:\n\t\t\t\t/*\n\t\t\t\t * We may get 0x50 several times, ignore them\n\t\t\t\t */\n\t\t\t\tif (*bptr == 0x50) {\n\t\t\t\t\tra = 1;\n\t\t\t\t\tbptr++;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (*bptr++ != ra_tbl[ra]) {\n\t\t\t\t\tra = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t case 4:\n\t\t\t\t/*\n\t\t\t\t * skip version number\n\t\t\t\t */\n\t\t\t\tbptr++;\n\t\t\t\tbreak;\n\n\t\t\t case 5:\n\t\t\t\t/*\n\t\t\t\t * The difference between versions 1.0 and\n\t\t\t\t * 2.0 is here. For future versions of\n\t\t\t\t * the player this may need to be modified.\n\t\t\t\t */\n\t\t\t\tif (*(bptr + 1) == 0x02)\n\t\t\t\t bptr += 8;\n\t\t\t\telse\n\t\t\t\t bptr += 4;\n\t\t\t\tbreak;\n\n\t\t\t case 6:\n\t\t\t\t/* This is the field containing the port\n\t\t\t\t * number that RA-player is listening to.\n\t\t\t\t */\n\t\t\t\tlport = (((u_char*)bptr)[0] << 8)\n\t\t\t\t+ ((u_char *)bptr)[1];\n\t\t\t\tif (lport < 6970)\n\t\t\t\t lport += 256; /* don't know why */\n\t\t\t\tif (lport < 6970 || lport > 7170)\n\t\t\t\t return 1; /* failed */\n\n\t\t\t\t/* try to get udp port between 6970 - 7170 */\n\t\t\t\tfor (p = 6970; p < 7071; p++) {\n\t\t\t\t\tif (udp_listen(slirp, INADDR_ANY,\n\t\t\t\t\t\t htons(p),\n\t\t\t\t\t\t so->so_laddr.s_addr,\n\t\t\t\t\t\t htons(lport),\n\t\t\t\t\t\t SS_FACCEPTONCE)) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (p == 7071)\n\t\t\t\t p = 0;\n\t\t\t\t*(u_char *)bptr++ = (p >> 8) & 0xff;\n *(u_char *)bptr = p & 0xff;\n\t\t\t\tra = 0;\n\t\t\t\treturn 1; /* port redirected, we're done */\n\t\t\t\tbreak;\n\n\t\t\t default:\n\t\t\t\tra = 0;\n\t\t\t}\n\t\t\tra++;\n\t\t}\n\t\treturn 1;\n\n\t default:\n\t\t/* Ooops, not emulated, won't call tcp_emu again */\n\t\tso->so_emu = 0;\n\t\treturn 1;\n\t}\n}\n\n/*\n * Do misc. config of SLiRP while its running.\n * Return 0 if this connections is to be closed, 1 otherwise,\n * return 2 if this is a command-line connection\n */\nint tcp_ctl(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n struct sbuf *sb = &so->so_snd;\n struct ex_list *ex_ptr;\n int do_pty;\n\n DEBUG_CALL(\"tcp_ctl\");\n DEBUG_ARG(\"so = %lx\", (long )so);\n\n if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {\n /* Check if it's pty_exec */\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_fport == so->so_fport &&\n so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {\n if (ex_ptr->ex_pty == 3) {\n so->s = -1;\n so->extra = (void *)ex_ptr->ex_exec;\n return 1;\n }\n do_pty = ex_ptr->ex_pty;\n DEBUG_MISC((dfd, \" executing %s \\n\",ex_ptr->ex_exec));\n return fork_exec(so, ex_ptr->ex_exec, do_pty);\n }\n }\n }\n sb->sb_cc =\n snprintf(sb->sb_wptr, sb->sb_datalen - (sb->sb_wptr - sb->sb_data),\n \"Error: No application configured.\\r\\n\");\n sb->sb_wptr += sb->sb_cc;\n return 0;\n}\n"], ["/linuxpdf/tinyemu/slirp/slirp.c", "/*\n * libslirp glue\n *\n * Copyright (c) 2004-2008 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"slirp.h\"\n\n/* host loopback address */\nstruct in_addr loopback_addr;\n\n/* emulated hosts use the MAC addr 52:55:IP:IP:IP:IP */\nstatic const uint8_t special_ethaddr[6] = {\n 0x52, 0x55, 0x00, 0x00, 0x00, 0x00\n};\n\nstatic const uint8_t zero_ethaddr[6] = { 0, 0, 0, 0, 0, 0 };\n\n/* XXX: suppress those select globals */\nfd_set *global_readfds, *global_writefds, *global_xfds;\n\nu_int curtime;\nstatic u_int time_fasttimo, last_slowtimo;\nstatic int do_slowtimo;\n\nstatic struct in_addr dns_addr;\nstatic u_int dns_addr_time;\n\n#ifdef _WIN32\n\nint get_dns_addr(struct in_addr *pdns_addr)\n{\n FIXED_INFO *FixedInfo=NULL;\n ULONG BufLen;\n DWORD ret;\n IP_ADDR_STRING *pIPAddr;\n struct in_addr tmp_addr;\n\n if (dns_addr.s_addr != 0 && (curtime - dns_addr_time) < 1000) {\n *pdns_addr = dns_addr;\n return 0;\n }\n\n FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));\n BufLen = sizeof(FIXED_INFO);\n\n if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen)) {\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n FixedInfo = GlobalAlloc(GPTR, BufLen);\n }\n\n if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS) {\n printf(\"GetNetworkParams failed. ret = %08x\\n\", (u_int)ret );\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n return -1;\n }\n\n pIPAddr = &(FixedInfo->DnsServerList);\n inet_aton(pIPAddr->IpAddress.String, &tmp_addr);\n *pdns_addr = tmp_addr;\n dns_addr = tmp_addr;\n dns_addr_time = curtime;\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n return 0;\n}\n\nstatic void winsock_cleanup(void)\n{\n WSACleanup();\n}\n\n#else\n\nstatic struct stat dns_addr_stat;\n\nint get_dns_addr(struct in_addr *pdns_addr)\n{\n char buff[512];\n char buff2[257];\n FILE *f;\n int found = 0;\n struct in_addr tmp_addr;\n\n if (dns_addr.s_addr != 0) {\n struct stat old_stat;\n if ((curtime - dns_addr_time) < 1000) {\n *pdns_addr = dns_addr;\n return 0;\n }\n old_stat = dns_addr_stat;\n if (stat(\"/etc/resolv.conf\", &dns_addr_stat) != 0)\n return -1;\n if ((dns_addr_stat.st_dev == old_stat.st_dev)\n && (dns_addr_stat.st_ino == old_stat.st_ino)\n && (dns_addr_stat.st_size == old_stat.st_size)\n && (dns_addr_stat.st_mtime == old_stat.st_mtime)) {\n *pdns_addr = dns_addr;\n return 0;\n }\n }\n\n f = fopen(\"/etc/resolv.conf\", \"r\");\n if (!f)\n return -1;\n\n#ifdef DEBUG\n lprint(\"IP address of your DNS(s): \");\n#endif\n while (fgets(buff, 512, f) != NULL) {\n if (sscanf(buff, \"nameserver%*[ \\t]%256s\", buff2) == 1) {\n if (!inet_aton(buff2, &tmp_addr))\n continue;\n /* If it's the first one, set it to dns_addr */\n if (!found) {\n *pdns_addr = tmp_addr;\n dns_addr = tmp_addr;\n dns_addr_time = curtime;\n }\n#ifdef DEBUG\n else\n lprint(\", \");\n#endif\n if (++found > 3) {\n#ifdef DEBUG\n lprint(\"(more)\");\n#endif\n break;\n }\n#ifdef DEBUG\n else\n lprint(\"%s\", inet_ntoa(tmp_addr));\n#endif\n }\n }\n fclose(f);\n if (!found)\n return -1;\n return 0;\n}\n\n#endif\n\nstatic void slirp_init_once(void)\n{\n static int initialized;\n#ifdef _WIN32\n WSADATA Data;\n#endif\n\n if (initialized) {\n return;\n }\n initialized = 1;\n\n#ifdef _WIN32\n WSAStartup(MAKEWORD(2,0), &Data);\n atexit(winsock_cleanup);\n#endif\n\n loopback_addr.s_addr = htonl(INADDR_LOOPBACK);\n}\n\nSlirp *slirp_init(int restricted, struct in_addr vnetwork,\n struct in_addr vnetmask, struct in_addr vhost,\n const char *vhostname, const char *tftp_path,\n const char *bootfile, struct in_addr vdhcp_start,\n struct in_addr vnameserver, void *opaque)\n{\n Slirp *slirp = mallocz(sizeof(Slirp));\n\n slirp_init_once();\n\n slirp->restricted = restricted;\n\n if_init(slirp);\n ip_init(slirp);\n\n /* Initialise mbufs *after* setting the MTU */\n m_init(slirp);\n\n slirp->vnetwork_addr = vnetwork;\n slirp->vnetwork_mask = vnetmask;\n slirp->vhost_addr = vhost;\n if (vhostname) {\n pstrcpy(slirp->client_hostname, sizeof(slirp->client_hostname),\n vhostname);\n }\n if (tftp_path) {\n slirp->tftp_prefix = strdup(tftp_path);\n }\n if (bootfile) {\n slirp->bootp_filename = strdup(bootfile);\n }\n slirp->vdhcp_startaddr = vdhcp_start;\n slirp->vnameserver_addr = vnameserver;\n\n slirp->opaque = opaque;\n\n return slirp;\n}\n\nvoid slirp_cleanup(Slirp *slirp)\n{\n free(slirp->tftp_prefix);\n free(slirp->bootp_filename);\n free(slirp);\n}\n\n#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)\n#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)\n#define UPD_NFDS(x) if (nfds < (x)) nfds = (x)\n\nvoid slirp_select_fill(Slirp *slirp, int *pnfds,\n fd_set *readfds, fd_set *writefds, fd_set *xfds)\n{\n struct socket *so, *so_next;\n int nfds;\n\n /* fail safe */\n global_readfds = NULL;\n global_writefds = NULL;\n global_xfds = NULL;\n\n nfds = *pnfds;\n\t/*\n\t * First, TCP sockets\n\t */\n\tdo_slowtimo = 0;\n\n\t{\n\t\t/*\n\t\t * *_slowtimo needs calling if there are IP fragments\n\t\t * in the fragment queue, or there are TCP connections active\n\t\t */\n\t\tdo_slowtimo |= ((slirp->tcb.so_next != &slirp->tcb) ||\n\t\t (&slirp->ipq.ip_link != slirp->ipq.ip_link.next));\n\n\t\tfor (so = slirp->tcb.so_next; so != &slirp->tcb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * See if we need a tcp_fasttimo\n\t\t\t */\n\t\t\tif (time_fasttimo == 0 && so->so_tcpcb->t_flags & TF_DELACK)\n\t\t\t time_fasttimo = curtime; /* Flag when we want a fasttimo */\n\n\t\t\t/*\n\t\t\t * NOFDREF can include still connecting to local-host,\n\t\t\t * newly socreated() sockets etc. Don't want to select these.\n\t \t\t */\n\t\t\tif (so->so_state & SS_NOFDREF || so->s == -1)\n\t\t\t continue;\n\n\t\t\t/*\n\t\t\t * Set for reading sockets which are accepting\n\t\t\t */\n\t\t\tif (so->so_state & SS_FACCEPTCONN) {\n FD_SET(so->s, readfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for writing sockets which are connecting\n\t\t\t */\n\t\t\tif (so->so_state & SS_ISFCONNECTING) {\n\t\t\t\tFD_SET(so->s, writefds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for writing if we are connected, can send more, and\n\t\t\t * we have something to send\n\t\t\t */\n\t\t\tif (CONN_CANFSEND(so) && so->so_rcv.sb_cc) {\n\t\t\t\tFD_SET(so->s, writefds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for reading (and urgent data) if we are connected, can\n\t\t\t * receive more, and we have room for it XXX /2 ?\n\t\t\t */\n\t\t\tif (CONN_CANFRCV(so) && (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2))) {\n\t\t\t\tFD_SET(so->s, readfds);\n\t\t\t\tFD_SET(so->s, xfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * UDP sockets\n\t\t */\n\t\tfor (so = slirp->udb.so_next; so != &slirp->udb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * See if it's timed out\n\t\t\t */\n\t\t\tif (so->so_expire) {\n\t\t\t\tif (so->so_expire <= curtime) {\n\t\t\t\t\tudp_detach(so);\n\t\t\t\t\tcontinue;\n\t\t\t\t} else\n\t\t\t\t\tdo_slowtimo = 1; /* Let socket expire */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * When UDP packets are received from over the\n\t\t\t * link, they're sendto()'d straight away, so\n\t\t\t * no need for setting for writing\n\t\t\t * Limit the number of packets queued by this session\n\t\t\t * to 4. Note that even though we try and limit this\n\t\t\t * to 4 packets, the session could have more queued\n\t\t\t * if the packets needed to be fragmented\n\t\t\t * (XXX <= 4 ?)\n\t\t\t */\n\t\t\tif ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4) {\n\t\t\t\tFD_SET(so->s, readfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\t\t}\n\t}\n\n *pnfds = nfds;\n}\n\nvoid slirp_select_poll(Slirp *slirp,\n fd_set *readfds, fd_set *writefds, fd_set *xfds,\n int select_error)\n{\n struct socket *so, *so_next;\n int ret;\n\n global_readfds = readfds;\n global_writefds = writefds;\n global_xfds = xfds;\n\n curtime = os_get_time_ms();\n\n {\n\t/*\n\t * See if anything has timed out\n\t */\n\t\tif (time_fasttimo && ((curtime - time_fasttimo) >= 2)) {\n\t\t\ttcp_fasttimo(slirp);\n\t\t\ttime_fasttimo = 0;\n\t\t}\n\t\tif (do_slowtimo && ((curtime - last_slowtimo) >= 499)) {\n\t\t\tip_slowtimo(slirp);\n\t\t\ttcp_slowtimo(slirp);\n\t\t\tlast_slowtimo = curtime;\n\t\t}\n\n\t/*\n\t * Check sockets\n\t */\n\tif (!select_error) {\n\t\t/*\n\t\t * Check TCP sockets\n\t\t */\n\t\tfor (so = slirp->tcb.so_next; so != &slirp->tcb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * FD_ISSET is meaningless on these sockets\n\t\t\t * (and they can crash the program)\n\t\t\t */\n\t\t\tif (so->so_state & SS_NOFDREF || so->s == -1)\n\t\t\t continue;\n\n\t\t\t/*\n\t\t\t * Check for URG data\n\t\t\t * This will soread as well, so no need to\n\t\t\t * test for readfds below if this succeeds\n\t\t\t */\n\t\t\tif (FD_ISSET(so->s, xfds))\n\t\t\t sorecvoob(so);\n\t\t\t/*\n\t\t\t * Check sockets for reading\n\t\t\t */\n\t\t\telse if (FD_ISSET(so->s, readfds)) {\n\t\t\t\t/*\n\t\t\t\t * Check for incoming connections\n\t\t\t\t */\n\t\t\t\tif (so->so_state & SS_FACCEPTCONN) {\n\t\t\t\t\ttcp_connect(so);\n\t\t\t\t\tcontinue;\n\t\t\t\t} /* else */\n\t\t\t\tret = soread(so);\n\n\t\t\t\t/* Output it if we read something */\n\t\t\t\tif (ret > 0)\n\t\t\t\t tcp_output(sototcpcb(so));\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Check sockets for writing\n\t\t\t */\n\t\t\tif (FD_ISSET(so->s, writefds)) {\n\t\t\t /*\n\t\t\t * Check for non-blocking, still-connecting sockets\n\t\t\t */\n\t\t\t if (so->so_state & SS_ISFCONNECTING) {\n\t\t\t /* Connected */\n\t\t\t so->so_state &= ~SS_ISFCONNECTING;\n\n\t\t\t ret = send(so->s, (const void *) &ret, 0, 0);\n\t\t\t if (ret < 0) {\n\t\t\t /* XXXXX Must fix, zero bytes is a NOP */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\t errno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t\tcontinue;\n\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\t\t\t }\n\t\t\t /* else so->so_state &= ~SS_ISFCONNECTING; */\n\n\t\t\t /*\n\t\t\t * Continue tcp_input\n\t\t\t */\n\t\t\t tcp_input((struct mbuf *)NULL, sizeof(struct ip), so);\n\t\t\t /* continue; */\n\t\t\t } else\n\t\t\t ret = sowrite(so);\n\t\t\t /*\n\t\t\t * XXXXX If we wrote something (a lot), there\n\t\t\t * could be a need for a window update.\n\t\t\t * In the worst case, the remote will send\n\t\t\t * a window probe to get things going again\n\t\t\t */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Probe a still-connecting, non-blocking socket\n\t\t\t * to check if it's still alive\n\t \t \t */\n#ifdef PROBE_CONN\n\t\t\tif (so->so_state & SS_ISFCONNECTING) {\n\t\t\t ret = recv(so->s, (char *)&ret, 0,0);\n\n\t\t\t if (ret < 0) {\n\t\t\t /* XXX */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\terrno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t continue; /* Still connecting, continue */\n\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\n\t\t\t /* tcp_input will take care of it */\n\t\t\t } else {\n\t\t\t ret = send(so->s, &ret, 0,0);\n\t\t\t if (ret < 0) {\n\t\t\t /* XXX */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\t errno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t\tcontinue;\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\t\t\t } else\n\t\t\t so->so_state &= ~SS_ISFCONNECTING;\n\n\t\t\t }\n\t\t\t tcp_input((struct mbuf *)NULL, sizeof(struct ip),so);\n\t\t\t} /* SS_ISFCONNECTING */\n#endif\n\t\t}\n\n\t\t/*\n\t\t * Now UDP sockets.\n\t\t * Incoming packets are sent straight away, they're not buffered.\n\t\t * Incoming UDP data isn't buffered either.\n\t\t */\n\t\tfor (so = slirp->udb.so_next; so != &slirp->udb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\tif (so->s != -1 && FD_ISSET(so->s, readfds)) {\n sorecvfrom(so);\n }\n\t\t}\n\t}\n\n\t/*\n\t * See if we can start outputting\n\t */\n\tif (slirp->if_queued) {\n\t if_start(slirp);\n\t}\n }\n\n\t/* clear global file descriptor sets.\n\t * these reside on the stack in vl.c\n\t * so they're unusable if we're not in\n\t * slirp_select_fill or slirp_select_poll.\n\t */\n\t global_readfds = NULL;\n\t global_writefds = NULL;\n\t global_xfds = NULL;\n}\n\n#define ETH_ALEN 6\n#define ETH_HLEN 14\n\n#define ETH_P_IP\t0x0800\t\t/* Internet Protocol packet\t*/\n#define ETH_P_ARP\t0x0806\t\t/* Address Resolution packet\t*/\n\n#define\tARPOP_REQUEST\t1\t\t/* ARP request\t\t\t*/\n#define\tARPOP_REPLY\t2\t\t/* ARP reply\t\t\t*/\n\nstruct ethhdr\n{\n\tunsigned char\th_dest[ETH_ALEN];\t/* destination eth addr\t*/\n\tunsigned char\th_source[ETH_ALEN];\t/* source ether addr\t*/\n\tunsigned short\th_proto;\t\t/* packet type ID field\t*/\n};\n\nstruct arphdr\n{\n\tunsigned short\tar_hrd;\t\t/* format of hardware address\t*/\n\tunsigned short\tar_pro;\t\t/* format of protocol address\t*/\n\tunsigned char\tar_hln;\t\t/* length of hardware address\t*/\n\tunsigned char\tar_pln;\t\t/* length of protocol address\t*/\n\tunsigned short\tar_op;\t\t/* ARP opcode (command)\t\t*/\n\n\t /*\n\t *\t Ethernet looks like this : This bit is variable sized however...\n\t */\n\tunsigned char\t\tar_sha[ETH_ALEN];\t/* sender hardware address\t*/\n\tuint32_t\t\tar_sip;\t\t\t/* sender IP address\t\t*/\n\tunsigned char\t\tar_tha[ETH_ALEN];\t/* target hardware address\t*/\n\tuint32_t\t\tar_tip\t;\t\t/* target IP address\t\t*/\n} __attribute__((packed));\n\nstatic void arp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)\n{\n struct ethhdr *eh = (struct ethhdr *)pkt;\n struct arphdr *ah = (struct arphdr *)(pkt + ETH_HLEN);\n uint8_t arp_reply[max(ETH_HLEN + sizeof(struct arphdr), 64)];\n struct ethhdr *reh = (struct ethhdr *)arp_reply;\n struct arphdr *rah = (struct arphdr *)(arp_reply + ETH_HLEN);\n int ar_op;\n struct ex_list *ex_ptr;\n\n ar_op = ntohs(ah->ar_op);\n switch(ar_op) {\n case ARPOP_REQUEST:\n if ((ah->ar_tip & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n if (ah->ar_tip == slirp->vnameserver_addr.s_addr ||\n ah->ar_tip == slirp->vhost_addr.s_addr)\n goto arp_ok;\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_addr.s_addr == ah->ar_tip)\n goto arp_ok;\n }\n return;\n arp_ok:\n memset(arp_reply, 0, sizeof(arp_reply));\n /* XXX: make an ARP request to have the client address */\n memcpy(slirp->client_ethaddr, eh->h_source, ETH_ALEN);\n\n /* ARP request for alias/dns mac address */\n memcpy(reh->h_dest, pkt + ETH_ALEN, ETH_ALEN);\n memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);\n memcpy(&reh->h_source[2], &ah->ar_tip, 4);\n reh->h_proto = htons(ETH_P_ARP);\n\n rah->ar_hrd = htons(1);\n rah->ar_pro = htons(ETH_P_IP);\n rah->ar_hln = ETH_ALEN;\n rah->ar_pln = 4;\n rah->ar_op = htons(ARPOP_REPLY);\n memcpy(rah->ar_sha, reh->h_source, ETH_ALEN);\n rah->ar_sip = ah->ar_tip;\n memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);\n rah->ar_tip = ah->ar_sip;\n slirp_output(slirp->opaque, arp_reply, sizeof(arp_reply));\n }\n break;\n case ARPOP_REPLY:\n /* reply to request of client mac address ? */\n if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN) &&\n ah->ar_sip == slirp->client_ipaddr.s_addr) {\n memcpy(slirp->client_ethaddr, ah->ar_sha, ETH_ALEN);\n }\n break;\n default:\n break;\n }\n}\n\nvoid slirp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)\n{\n struct mbuf *m;\n int proto;\n\n if (pkt_len < ETH_HLEN)\n return;\n\n proto = ntohs(*(uint16_t *)(pkt + 12));\n switch(proto) {\n case ETH_P_ARP:\n arp_input(slirp, pkt, pkt_len);\n break;\n case ETH_P_IP:\n m = m_get(slirp);\n if (!m)\n return;\n /* Note: we add to align the IP header */\n if (M_FREEROOM(m) < pkt_len + 2) {\n m_inc(m, pkt_len + 2);\n }\n m->m_len = pkt_len + 2;\n memcpy(m->m_data + 2, pkt, pkt_len);\n\n m->m_data += 2 + ETH_HLEN;\n m->m_len -= 2 + ETH_HLEN;\n\n ip_input(m);\n break;\n default:\n break;\n }\n}\n\n/* output the IP packet to the ethernet device */\nvoid if_encap(Slirp *slirp, const uint8_t *ip_data, int ip_data_len)\n{\n uint8_t buf[1600];\n struct ethhdr *eh = (struct ethhdr *)buf;\n\n if (ip_data_len + ETH_HLEN > sizeof(buf))\n return;\n \n if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN)) {\n uint8_t arp_req[ETH_HLEN + sizeof(struct arphdr)];\n struct ethhdr *reh = (struct ethhdr *)arp_req;\n struct arphdr *rah = (struct arphdr *)(arp_req + ETH_HLEN);\n const struct ip *iph = (const struct ip *)ip_data;\n\n /* If the client addr is not known, there is no point in\n sending the packet to it. Normally the sender should have\n done an ARP request to get its MAC address. Here we do it\n in place of sending the packet and we hope that the sender\n will retry sending its packet. */\n memset(reh->h_dest, 0xff, ETH_ALEN);\n memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);\n memcpy(&reh->h_source[2], &slirp->vhost_addr, 4);\n reh->h_proto = htons(ETH_P_ARP);\n rah->ar_hrd = htons(1);\n rah->ar_pro = htons(ETH_P_IP);\n rah->ar_hln = ETH_ALEN;\n rah->ar_pln = 4;\n rah->ar_op = htons(ARPOP_REQUEST);\n /* source hw addr */\n memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN - 4);\n memcpy(&rah->ar_sha[2], &slirp->vhost_addr, 4);\n /* source IP */\n rah->ar_sip = slirp->vhost_addr.s_addr;\n /* target hw addr (none) */\n memset(rah->ar_tha, 0, ETH_ALEN);\n /* target IP */\n rah->ar_tip = iph->ip_dst.s_addr;\n slirp->client_ipaddr = iph->ip_dst;\n slirp_output(slirp->opaque, arp_req, sizeof(arp_req));\n } else {\n memcpy(eh->h_dest, slirp->client_ethaddr, ETH_ALEN);\n memcpy(eh->h_source, special_ethaddr, ETH_ALEN - 4);\n /* XXX: not correct */\n memcpy(&eh->h_source[2], &slirp->vhost_addr, 4);\n eh->h_proto = htons(ETH_P_IP);\n memcpy(buf + sizeof(struct ethhdr), ip_data, ip_data_len);\n slirp_output(slirp->opaque, buf, ip_data_len + ETH_HLEN);\n }\n}\n\n/* Drop host forwarding rule, return 0 if found. */\nint slirp_remove_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,\n int host_port)\n{\n struct socket *so;\n struct socket *head = (is_udp ? &slirp->udb : &slirp->tcb);\n struct sockaddr_in addr;\n int port = htons(host_port);\n socklen_t addr_len;\n\n for (so = head->so_next; so != head; so = so->so_next) {\n addr_len = sizeof(addr);\n if ((so->so_state & SS_HOSTFWD) &&\n getsockname(so->s, (struct sockaddr *)&addr, &addr_len) == 0 &&\n addr.sin_addr.s_addr == host_addr.s_addr &&\n addr.sin_port == port) {\n close(so->s);\n sofree(so);\n return 0;\n }\n }\n\n return -1;\n}\n\nint slirp_add_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,\n int host_port, struct in_addr guest_addr, int guest_port)\n{\n if (!guest_addr.s_addr) {\n guest_addr = slirp->vdhcp_startaddr;\n }\n if (is_udp) {\n if (!udp_listen(slirp, host_addr.s_addr, htons(host_port),\n guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))\n return -1;\n } else {\n if (!tcp_listen(slirp, host_addr.s_addr, htons(host_port),\n guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))\n return -1;\n }\n return 0;\n}\n\nint slirp_add_exec(Slirp *slirp, int do_pty, const void *args,\n struct in_addr *guest_addr, int guest_port)\n{\n if (!guest_addr->s_addr) {\n guest_addr->s_addr = slirp->vnetwork_addr.s_addr |\n (htonl(0x0204) & ~slirp->vnetwork_mask.s_addr);\n }\n if ((guest_addr->s_addr & slirp->vnetwork_mask.s_addr) !=\n slirp->vnetwork_addr.s_addr ||\n guest_addr->s_addr == slirp->vhost_addr.s_addr ||\n guest_addr->s_addr == slirp->vnameserver_addr.s_addr) {\n return -1;\n }\n return add_exec(&slirp->exec_list, do_pty, (char *)args, *guest_addr,\n htons(guest_port));\n}\n\nssize_t slirp_send(struct socket *so, const void *buf, size_t len, int flags)\n{\n#if 0\n if (so->s == -1 && so->extra) {\n\t\tqemu_chr_write(so->extra, buf, len);\n\t\treturn len;\n\t}\n#endif\n\treturn send(so->s, buf, len, flags);\n}\n\nstatic struct socket *\nslirp_find_ctl_socket(Slirp *slirp, struct in_addr guest_addr, int guest_port)\n{\n struct socket *so;\n\n for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {\n if (so->so_faddr.s_addr == guest_addr.s_addr &&\n htons(so->so_fport) == guest_port) {\n return so;\n }\n }\n return NULL;\n}\n\nsize_t slirp_socket_can_recv(Slirp *slirp, struct in_addr guest_addr,\n int guest_port)\n{\n\tstruct iovec iov[2];\n\tstruct socket *so;\n\n\tso = slirp_find_ctl_socket(slirp, guest_addr, guest_port);\n\n\tif (!so || so->so_state & SS_NOFDREF)\n\t\treturn 0;\n\n\tif (!CONN_CANFRCV(so) || so->so_snd.sb_cc >= (so->so_snd.sb_datalen/2))\n\t\treturn 0;\n\n\treturn sopreprbuf(so, iov, NULL);\n}\n\nvoid slirp_socket_recv(Slirp *slirp, struct in_addr guest_addr, int guest_port,\n const uint8_t *buf, int size)\n{\n int ret;\n struct socket *so = slirp_find_ctl_socket(slirp, guest_addr, guest_port);\n\n if (!so)\n return;\n\n ret = soreadbuf(so, (const char *)buf, size);\n\n if (ret > 0)\n tcp_output(sototcpcb(so));\n}\n"], ["/linuxpdf/tinyemu/slirp/socket.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\nstatic void sofcantrcvmore(struct socket *so);\nstatic void sofcantsendmore(struct socket *so);\n\nstruct socket *\nsolookup(struct socket *head, struct in_addr laddr, u_int lport,\n struct in_addr faddr, u_int fport)\n{\n\tstruct socket *so;\n\n\tfor (so = head->so_next; so != head; so = so->so_next) {\n\t\tif (so->so_lport == lport &&\n\t\t so->so_laddr.s_addr == laddr.s_addr &&\n\t\t so->so_faddr.s_addr == faddr.s_addr &&\n\t\t so->so_fport == fport)\n\t\t break;\n\t}\n\n\tif (so == head)\n\t return (struct socket *)NULL;\n\treturn so;\n\n}\n\n/*\n * Create a new socket, initialise the fields\n * It is the responsibility of the caller to\n * insque() it into the correct linked-list\n */\nstruct socket *\nsocreate(Slirp *slirp)\n{\n struct socket *so;\n\n so = (struct socket *)malloc(sizeof(struct socket));\n if(so) {\n memset(so, 0, sizeof(struct socket));\n so->so_state = SS_NOFDREF;\n so->s = -1;\n so->slirp = slirp;\n }\n return(so);\n}\n\n/*\n * remque and free a socket, clobber cache\n */\nvoid\nsofree(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n\n if (so->so_emu==EMU_RSH && so->extra) {\n\tsofree(so->extra);\n\tso->extra=NULL;\n }\n if (so == slirp->tcp_last_so) {\n slirp->tcp_last_so = &slirp->tcb;\n } else if (so == slirp->udp_last_so) {\n slirp->udp_last_so = &slirp->udb;\n }\n m_free(so->so_m);\n\n if(so->so_next && so->so_prev)\n remque(so); /* crashes if so is not in a queue */\n\n free(so);\n}\n\nsize_t sopreprbuf(struct socket *so, struct iovec *iov, int *np)\n{\n\tint n, lss, total;\n\tstruct sbuf *sb = &so->so_snd;\n\tint len = sb->sb_datalen - sb->sb_cc;\n\tint mss = so->so_tcpcb->t_maxseg;\n\n\tDEBUG_CALL(\"sopreprbuf\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\tif (len <= 0)\n\t\treturn 0;\n\n\tiov[0].iov_base = sb->sb_wptr;\n iov[1].iov_base = NULL;\n iov[1].iov_len = 0;\n\tif (sb->sb_wptr < sb->sb_rptr) {\n\t\tiov[0].iov_len = sb->sb_rptr - sb->sb_wptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len)\n\t\t iov[0].iov_len = len;\n\t\tif (iov[0].iov_len > mss)\n\t\t iov[0].iov_len -= iov[0].iov_len%mss;\n\t\tn = 1;\n\t} else {\n\t\tiov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_wptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tlen -= iov[0].iov_len;\n\t\tif (len) {\n\t\t\tiov[1].iov_base = sb->sb_data;\n\t\t\tiov[1].iov_len = sb->sb_rptr - sb->sb_data;\n\t\t\tif(iov[1].iov_len > len)\n\t\t\t iov[1].iov_len = len;\n\t\t\ttotal = iov[0].iov_len + iov[1].iov_len;\n\t\t\tif (total > mss) {\n\t\t\t\tlss = total%mss;\n\t\t\t\tif (iov[1].iov_len > lss) {\n\t\t\t\t\tiov[1].iov_len -= lss;\n\t\t\t\t\tn = 2;\n\t\t\t\t} else {\n\t\t\t\t\tlss -= iov[1].iov_len;\n\t\t\t\t\tiov[0].iov_len -= lss;\n\t\t\t\t\tn = 1;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tn = 2;\n\t\t} else {\n\t\t\tif (iov[0].iov_len > mss)\n\t\t\t iov[0].iov_len -= iov[0].iov_len%mss;\n\t\t\tn = 1;\n\t\t}\n\t}\n\tif (np)\n\t\t*np = n;\n\n\treturn iov[0].iov_len + (n - 1) * iov[1].iov_len;\n}\n\n/*\n * Read from so's socket into sb_snd, updating all relevant sbuf fields\n * NOTE: This will only be called if it is select()ed for reading, so\n * a read() of 0 (or less) means it's disconnected\n */\nint\nsoread(struct socket *so)\n{\n\tint n, nn;\n\tstruct sbuf *sb = &so->so_snd;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"soread\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\t/*\n\t * No need to check if there's enough room to read.\n\t * soread wouldn't have been called if there weren't\n\t */\n\tsopreprbuf(so, iov, &n);\n\n#ifdef HAVE_READV\n\tnn = readv(so->s, (struct iovec *)iov, n);\n\tDEBUG_MISC((dfd, \" ... read nn = %d bytes\\n\", nn));\n#else\n\tnn = recv(so->s, iov[0].iov_base, iov[0].iov_len,0);\n#endif\n\tif (nn <= 0) {\n\t\tif (nn < 0 && (errno == EINTR || errno == EAGAIN))\n\t\t\treturn 0;\n\t\telse {\n\t\t\tDEBUG_MISC((dfd, \" --- soread() disconnected, nn = %d, errno = %d-%s\\n\", nn, errno,strerror(errno)));\n\t\t\tsofcantrcvmore(so);\n\t\t\ttcp_sockclosed(sototcpcb(so));\n\t\t\treturn -1;\n\t\t}\n\t}\n\n#ifndef HAVE_READV\n\t/*\n\t * If there was no error, try and read the second time round\n\t * We read again if n = 2 (ie, there's another part of the buffer)\n\t * and we read as much as we could in the first read\n\t * We don't test for <= 0 this time, because there legitimately\n\t * might not be any more data (since the socket is non-blocking),\n\t * a close will be detected on next iteration.\n\t * A return of -1 wont (shouldn't) happen, since it didn't happen above\n\t */\n\tif (n == 2 && nn == iov[0].iov_len) {\n int ret;\n ret = recv(so->s, iov[1].iov_base, iov[1].iov_len,0);\n if (ret > 0)\n nn += ret;\n }\n\n\tDEBUG_MISC((dfd, \" ... read nn = %d bytes\\n\", nn));\n#endif\n\n\t/* Update fields */\n\tsb->sb_cc += nn;\n\tsb->sb_wptr += nn;\n\tif (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_wptr -= sb->sb_datalen;\n\treturn nn;\n}\n\nint soreadbuf(struct socket *so, const char *buf, int size)\n{\n int n, nn, copy = size;\n\tstruct sbuf *sb = &so->so_snd;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"soreadbuf\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\t/*\n\t * No need to check if there's enough room to read.\n\t * soread wouldn't have been called if there weren't\n\t */\n\tif (sopreprbuf(so, iov, &n) < size)\n goto err;\n\n nn = min(iov[0].iov_len, copy);\n memcpy(iov[0].iov_base, buf, nn);\n\n copy -= nn;\n buf += nn;\n\n if (copy == 0)\n goto done;\n\n memcpy(iov[1].iov_base, buf, copy);\n\ndone:\n /* Update fields */\n\tsb->sb_cc += size;\n\tsb->sb_wptr += size;\n\tif (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_wptr -= sb->sb_datalen;\n return size;\nerr:\n\n sofcantrcvmore(so);\n tcp_sockclosed(sototcpcb(so));\n fprintf(stderr, \"soreadbuf buffer to small\");\n return -1;\n}\n\n/*\n * Get urgent data\n *\n * When the socket is created, we set it SO_OOBINLINE,\n * so when OOB data arrives, we soread() it and everything\n * in the send buffer is sent as urgent data\n */\nvoid\nsorecvoob(struct socket *so)\n{\n\tstruct tcpcb *tp = sototcpcb(so);\n\n\tDEBUG_CALL(\"sorecvoob\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\t/*\n\t * We take a guess at how much urgent data has arrived.\n\t * In most situations, when urgent data arrives, the next\n\t * read() should get all the urgent data. This guess will\n\t * be wrong however if more data arrives just after the\n\t * urgent data, or the read() doesn't return all the\n\t * urgent data.\n\t */\n\tsoread(so);\n\ttp->snd_up = tp->snd_una + so->so_snd.sb_cc;\n\ttp->t_force = 1;\n\ttcp_output(tp);\n\ttp->t_force = 0;\n}\n\n/*\n * Send urgent data\n * There's a lot duplicated code here, but...\n */\nint\nsosendoob(struct socket *so)\n{\n\tstruct sbuf *sb = &so->so_rcv;\n\tchar buff[2048]; /* XXX Shouldn't be sending more oob data than this */\n\n\tint n, len;\n\n\tDEBUG_CALL(\"sosendoob\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"sb->sb_cc = %d\", sb->sb_cc);\n\n\tif (so->so_urgc > 2048)\n\t so->so_urgc = 2048; /* XXXX */\n\n\tif (sb->sb_rptr < sb->sb_wptr) {\n\t\t/* We can send it directly */\n\t\tn = slirp_send(so, sb->sb_rptr, so->so_urgc, (MSG_OOB)); /* |MSG_DONTWAIT)); */\n\t\tso->so_urgc -= n;\n\n\t\tDEBUG_MISC((dfd, \" --- sent %d bytes urgent data, %d urgent bytes left\\n\", n, so->so_urgc));\n\t} else {\n\t\t/*\n\t\t * Since there's no sendv or sendtov like writev,\n\t\t * we must copy all data to a linear buffer then\n\t\t * send it all\n\t\t */\n\t\tlen = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;\n\t\tif (len > so->so_urgc) len = so->so_urgc;\n\t\tmemcpy(buff, sb->sb_rptr, len);\n\t\tso->so_urgc -= len;\n\t\tif (so->so_urgc) {\n\t\t\tn = sb->sb_wptr - sb->sb_data;\n\t\t\tif (n > so->so_urgc) n = so->so_urgc;\n\t\t\tmemcpy((buff + len), sb->sb_data, n);\n\t\t\tso->so_urgc -= n;\n\t\t\tlen += n;\n\t\t}\n\t\tn = slirp_send(so, buff, len, (MSG_OOB)); /* |MSG_DONTWAIT)); */\n#ifdef DEBUG\n\t\tif (n != len)\n\t\t DEBUG_ERROR((dfd, \"Didn't send all data urgently XXXXX\\n\"));\n#endif\n\t\tDEBUG_MISC((dfd, \" ---2 sent %d bytes urgent data, %d urgent bytes left\\n\", n, so->so_urgc));\n\t}\n\n\tsb->sb_cc -= n;\n\tsb->sb_rptr += n;\n\tif (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n\treturn n;\n}\n\n/*\n * Write data from so_rcv to so's socket,\n * updating all sbuf field as necessary\n */\nint\nsowrite(struct socket *so)\n{\n\tint n,nn;\n\tstruct sbuf *sb = &so->so_rcv;\n\tint len = sb->sb_cc;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"sowrite\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\tif (so->so_urgc) {\n\t\tsosendoob(so);\n\t\tif (sb->sb_cc == 0)\n\t\t\treturn 0;\n\t}\n\n\t/*\n\t * No need to check if there's something to write,\n\t * sowrite wouldn't have been called otherwise\n\t */\n\n\tiov[0].iov_base = sb->sb_rptr;\n iov[1].iov_base = NULL;\n iov[1].iov_len = 0;\n\tif (sb->sb_rptr < sb->sb_wptr) {\n\t\tiov[0].iov_len = sb->sb_wptr - sb->sb_rptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tn = 1;\n\t} else {\n\t\tiov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tlen -= iov[0].iov_len;\n\t\tif (len) {\n\t\t\tiov[1].iov_base = sb->sb_data;\n\t\t\tiov[1].iov_len = sb->sb_wptr - sb->sb_data;\n\t\t\tif (iov[1].iov_len > len) iov[1].iov_len = len;\n\t\t\tn = 2;\n\t\t} else\n\t\t\tn = 1;\n\t}\n\t/* Check if there's urgent data to send, and if so, send it */\n\n#ifdef HAVE_READV\n\tnn = writev(so->s, (const struct iovec *)iov, n);\n\n\tDEBUG_MISC((dfd, \" ... wrote nn = %d bytes\\n\", nn));\n#else\n\tnn = slirp_send(so, iov[0].iov_base, iov[0].iov_len,0);\n#endif\n\t/* This should never happen, but people tell me it does *shrug* */\n\tif (nn < 0 && (errno == EAGAIN || errno == EINTR))\n\t\treturn 0;\n\n\tif (nn <= 0) {\n\t\tDEBUG_MISC((dfd, \" --- sowrite disconnected, so->so_state = %x, errno = %d\\n\",\n\t\t\tso->so_state, errno));\n\t\tsofcantsendmore(so);\n\t\ttcp_sockclosed(sototcpcb(so));\n\t\treturn -1;\n\t}\n\n#ifndef HAVE_READV\n\tif (n == 2 && nn == iov[0].iov_len) {\n int ret;\n ret = slirp_send(so, iov[1].iov_base, iov[1].iov_len,0);\n if (ret > 0)\n nn += ret;\n }\n DEBUG_MISC((dfd, \" ... wrote nn = %d bytes\\n\", nn));\n#endif\n\n\t/* Update sbuf */\n\tsb->sb_cc -= nn;\n\tsb->sb_rptr += nn;\n\tif (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n\t/*\n\t * If in DRAIN mode, and there's no more data, set\n\t * it CANTSENDMORE\n\t */\n\tif ((so->so_state & SS_FWDRAIN) && sb->sb_cc == 0)\n\t\tsofcantsendmore(so);\n\n\treturn nn;\n}\n\n/*\n * recvfrom() a UDP socket\n */\nvoid\nsorecvfrom(struct socket *so)\n{\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\n\tDEBUG_CALL(\"sorecvfrom\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\tif (so->so_type == IPPROTO_ICMP) { /* This is a \"ping\" reply */\n\t char buff[256];\n\t int len;\n\n\t len = recvfrom(so->s, buff, 256, 0,\n\t\t\t (struct sockaddr *)&addr, &addrlen);\n\t /* XXX Check if reply is \"correct\"? */\n\n\t if(len == -1 || len == 0) {\n\t u_char code=ICMP_UNREACH_PORT;\n\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;\n\n\t DEBUG_MISC((dfd,\" udp icmp rx errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));\n\t } else {\n\t icmp_reflect(so->so_m);\n so->so_m = NULL; /* Don't m_free() it again! */\n\t }\n\t /* No need for this socket anymore, udp_detach it */\n\t udp_detach(so);\n\t} else { \t/* A \"normal\" UDP packet */\n\t struct mbuf *m;\n int len;\n#ifdef _WIN32\n unsigned long n;\n#else\n int n;\n#endif\n\n\t m = m_get(so->slirp);\n\t if (!m) {\n\t return;\n\t }\n\t m->m_data += IF_MAXLINKHDR;\n\n\t /*\n\t * XXX Shouldn't FIONREAD packets destined for port 53,\n\t * but I don't know the max packet size for DNS lookups\n\t */\n\t len = M_FREEROOM(m);\n\t /* if (so->so_fport != htons(53)) { */\n\t ioctlsocket(so->s, FIONREAD, &n);\n\n\t if (n > len) {\n\t n = (m->m_data - m->m_dat) + m->m_len + n + 1;\n\t m_inc(m, n);\n\t len = M_FREEROOM(m);\n\t }\n\t /* } */\n\n\t m->m_len = recvfrom(so->s, m->m_data, len, 0,\n\t\t\t (struct sockaddr *)&addr, &addrlen);\n\t DEBUG_MISC((dfd, \" did recvfrom %d, errno = %d-%s\\n\",\n\t\t m->m_len, errno,strerror(errno)));\n\t if(m->m_len<0) {\n\t u_char code=ICMP_UNREACH_PORT;\n\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;\n\n\t DEBUG_MISC((dfd,\" rx error, tx icmp ICMP_UNREACH:%i\\n\", code));\n\t icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));\n\t m_free(m);\n\t } else {\n\t /*\n\t * Hack: domain name lookup will be used the most for UDP,\n\t * and since they'll only be used once there's no need\n\t * for the 4 minute (or whatever) timeout... So we time them\n\t * out much quicker (10 seconds for now...)\n\t */\n\t if (so->so_expire) {\n\t if (so->so_fport == htons(53))\n\t\tso->so_expire = curtime + SO_EXPIREFAST;\n\t else\n\t\tso->so_expire = curtime + SO_EXPIRE;\n\t }\n\n\t /*\n\t * If this packet was destined for CTL_ADDR,\n\t * make it look like that's where it came from, done by udp_output\n\t */\n\t udp_output(so, m, &addr);\n\t } /* rx error */\n\t} /* if ping packet */\n}\n\n/*\n * sendto() a socket\n */\nint\nsosendto(struct socket *so, struct mbuf *m)\n{\n\tSlirp *slirp = so->slirp;\n\tint ret;\n\tstruct sockaddr_in addr;\n\n\tDEBUG_CALL(\"sosendto\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n addr.sin_family = AF_INET;\n\tif ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n\t slirp->vnetwork_addr.s_addr) {\n\t /* It's an alias */\n\t if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\t if (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n\t } else {\n\t addr.sin_addr = loopback_addr;\n\t }\n\t} else\n\t addr.sin_addr = so->so_faddr;\n\taddr.sin_port = so->so_fport;\n\n\tDEBUG_MISC((dfd, \" sendto()ing, addr.sin_port=%d, addr.sin_addr.s_addr=%.16s\\n\", ntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));\n\n\t/* Don't care what port we get */\n\tret = sendto(so->s, m->m_data, m->m_len, 0,\n\t\t (struct sockaddr *)&addr, sizeof (struct sockaddr));\n\tif (ret < 0)\n\t\treturn -1;\n\n\t/*\n\t * Kill the socket if there's no reply in 4 minutes,\n\t * but only if it's an expirable socket\n\t */\n\tif (so->so_expire)\n\t\tso->so_expire = curtime + SO_EXPIRE;\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= SS_ISFCONNECTED; /* So that it gets select()ed */\n\treturn 0;\n}\n\n/*\n * Listen for incoming TCP connections\n */\nstruct socket *\ntcp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,\n u_int lport, int flags)\n{\n\tstruct sockaddr_in addr;\n\tstruct socket *so;\n\tint s, opt = 1;\n\tsocklen_t addrlen = sizeof(addr);\n\tmemset(&addr, 0, addrlen);\n\n\tDEBUG_CALL(\"tcp_listen\");\n\tDEBUG_ARG(\"haddr = %x\", haddr);\n\tDEBUG_ARG(\"hport = %d\", hport);\n\tDEBUG_ARG(\"laddr = %x\", laddr);\n\tDEBUG_ARG(\"lport = %d\", lport);\n\tDEBUG_ARG(\"flags = %x\", flags);\n\n\tso = socreate(slirp);\n\tif (!so) {\n\t return NULL;\n\t}\n\n\t/* Don't tcp_attach... we don't need so_snd nor so_rcv */\n\tif ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL) {\n\t\tfree(so);\n\t\treturn NULL;\n\t}\n\tinsque(so, &slirp->tcb);\n\n\t/*\n\t * SS_FACCEPTONCE sockets must time out.\n\t */\n\tif (flags & SS_FACCEPTONCE)\n\t so->so_tcpcb->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT*2;\n\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= (SS_FACCEPTCONN | flags);\n\tso->so_lport = lport; /* Kept in network format */\n\tso->so_laddr.s_addr = laddr; /* Ditto */\n\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = haddr;\n\taddr.sin_port = hport;\n\n\tif (((s = os_socket(AF_INET,SOCK_STREAM,0)) < 0) ||\n\t (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int)) < 0) ||\n\t (bind(s,(struct sockaddr *)&addr, sizeof(addr)) < 0) ||\n\t (listen(s,1) < 0)) {\n\t\tint tmperrno = errno; /* Don't clobber the real reason we failed */\n\n\t\tclose(s);\n\t\tsofree(so);\n\t\t/* Restore the real errno */\n#ifdef _WIN32\n\t\tWSASetLastError(tmperrno);\n#else\n\t\terrno = tmperrno;\n#endif\n\t\treturn NULL;\n\t}\n\tsetsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\n\tgetsockname(s,(struct sockaddr *)&addr,&addrlen);\n\tso->so_fport = addr.sin_port;\n\tif (addr.sin_addr.s_addr == 0 || addr.sin_addr.s_addr == loopback_addr.s_addr)\n\t so->so_faddr = slirp->vhost_addr;\n\telse\n\t so->so_faddr = addr.sin_addr;\n\n\tso->s = s;\n\treturn so;\n}\n\n/*\n * Various session state calls\n * XXX Should be #define's\n * The socket state stuff needs work, these often get call 2 or 3\n * times each when only 1 was needed\n */\nvoid\nsoisfconnecting(struct socket *so)\n{\n\tso->so_state &= ~(SS_NOFDREF|SS_ISFCONNECTED|SS_FCANTRCVMORE|\n\t\t\t SS_FCANTSENDMORE|SS_FWDRAIN);\n\tso->so_state |= SS_ISFCONNECTING; /* Clobber other states */\n}\n\nvoid\nsoisfconnected(struct socket *so)\n{\n\tso->so_state &= ~(SS_ISFCONNECTING|SS_FWDRAIN|SS_NOFDREF);\n\tso->so_state |= SS_ISFCONNECTED; /* Clobber other states */\n}\n\nstatic void\nsofcantrcvmore(struct socket *so)\n{\n\tif ((so->so_state & SS_NOFDREF) == 0) {\n\t\tshutdown(so->s,0);\n\t\tif(global_writefds) {\n\t\t FD_CLR(so->s,global_writefds);\n\t\t}\n\t}\n\tso->so_state &= ~(SS_ISFCONNECTING);\n\tif (so->so_state & SS_FCANTSENDMORE) {\n\t so->so_state &= SS_PERSISTENT_MASK;\n\t so->so_state |= SS_NOFDREF; /* Don't select it */\n\t} else {\n\t so->so_state |= SS_FCANTRCVMORE;\n\t}\n}\n\nstatic void\nsofcantsendmore(struct socket *so)\n{\n\tif ((so->so_state & SS_NOFDREF) == 0) {\n shutdown(so->s,1); /* send FIN to fhost */\n if (global_readfds) {\n FD_CLR(so->s,global_readfds);\n }\n if (global_xfds) {\n FD_CLR(so->s,global_xfds);\n }\n\t}\n\tso->so_state &= ~(SS_ISFCONNECTING);\n\tif (so->so_state & SS_FCANTRCVMORE) {\n\t so->so_state &= SS_PERSISTENT_MASK;\n\t so->so_state |= SS_NOFDREF; /* as above */\n\t} else {\n\t so->so_state |= SS_FCANTSENDMORE;\n\t}\n}\n\n/*\n * Set write drain mode\n * Set CANTSENDMORE once all data has been write()n\n */\nvoid\nsofwdrain(struct socket *so)\n{\n\tif (so->so_rcv.sb_cc)\n\t\tso->so_state |= SS_FWDRAIN;\n\telse\n\t\tsofcantsendmore(so);\n}\n"], ["/linuxpdf/tinyemu/block_net.c", "/*\n * HTTP block device\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"virtio.h\"\n#include \"fs_wget.h\"\n#include \"list.h\"\n#include \"fbuf.h\"\n#include \"machine.h\"\n\ntypedef enum {\n CBLOCK_LOADING,\n CBLOCK_LOADED,\n} CachedBlockStateEnum;\n\ntypedef struct CachedBlock {\n struct list_head link;\n struct BlockDeviceHTTP *bf;\n unsigned int block_num;\n CachedBlockStateEnum state;\n FileBuffer fbuf;\n} CachedBlock;\n\n#define BLK_FMT \"%sblk%09u.bin\"\n#define GROUP_FMT \"%sgrp%09u.bin\"\n#define PREFETCH_GROUP_LEN_MAX 32\n\ntypedef struct {\n struct BlockDeviceHTTP *bf;\n int group_num;\n int n_block_num;\n CachedBlock *tab_block[PREFETCH_GROUP_LEN_MAX];\n} PrefetchGroupRequest;\n\n/* modified data is stored per cluster (smaller than cached blocks to\n avoid losing space) */\ntypedef struct Cluster {\n FileBuffer fbuf;\n} Cluster;\n\ntypedef struct BlockDeviceHTTP {\n BlockDevice *bs;\n int max_cache_size_kb;\n char url[1024];\n int prefetch_count;\n void (*start_cb)(void *opaque);\n void *start_opaque;\n \n int64_t nb_sectors;\n int block_size; /* in sectors, power of two */\n int nb_blocks;\n struct list_head cached_blocks; /* list of CachedBlock */\n int n_cached_blocks;\n int n_cached_blocks_max;\n\n /* write support */\n int sectors_per_cluster; /* power of two */\n Cluster **clusters; /* NULL if no written data */\n int n_clusters;\n int n_allocated_clusters;\n \n /* statistics */\n int64_t n_read_sectors;\n int64_t n_read_blocks;\n int64_t n_write_sectors;\n\n /* current read request */\n BOOL is_write;\n uint64_t sector_num;\n int cur_block_num;\n int sector_index, sector_count;\n BlockDeviceCompletionFunc *cb;\n void *opaque;\n uint8_t *io_buf;\n\n /* prefetch */\n int prefetch_group_len;\n} BlockDeviceHTTP;\n\nstatic void bf_update_block(CachedBlock *b, const uint8_t *data);\nstatic void bf_read_onload(void *opaque, int err, void *data, size_t size);\nstatic void bf_init_onload(void *opaque, int err, void *data, size_t size);\nstatic void bf_prefetch_group_onload(void *opaque, int err, void *data,\n size_t size);\n\nstatic CachedBlock *bf_find_block(BlockDeviceHTTP *bf, unsigned int block_num)\n{\n CachedBlock *b;\n struct list_head *el;\n \n list_for_each(el, &bf->cached_blocks) {\n b = list_entry(el, CachedBlock, link);\n if (b->block_num == block_num) {\n /* move to front */\n if (bf->cached_blocks.next != el) {\n list_del(&b->link);\n list_add(&b->link, &bf->cached_blocks);\n }\n return b;\n }\n }\n return NULL;\n}\n\nstatic void bf_free_block(BlockDeviceHTTP *bf, CachedBlock *b)\n{\n bf->n_cached_blocks--;\n file_buffer_reset(&b->fbuf);\n list_del(&b->link);\n free(b);\n}\n\nstatic CachedBlock *bf_add_block(BlockDeviceHTTP *bf, unsigned int block_num)\n{\n CachedBlock *b;\n if (bf->n_cached_blocks >= bf->n_cached_blocks_max) {\n struct list_head *el, *el1;\n /* start by looking at the least unused blocks */\n list_for_each_prev_safe(el, el1, &bf->cached_blocks) {\n b = list_entry(el, CachedBlock, link);\n if (b->state == CBLOCK_LOADED) {\n bf_free_block(bf, b);\n if (bf->n_cached_blocks < bf->n_cached_blocks_max)\n break;\n }\n }\n }\n b = mallocz(sizeof(CachedBlock));\n b->bf = bf;\n b->block_num = block_num;\n b->state = CBLOCK_LOADING;\n file_buffer_init(&b->fbuf);\n file_buffer_resize(&b->fbuf, bf->block_size * 512);\n list_add(&b->link, &bf->cached_blocks);\n bf->n_cached_blocks++;\n return b;\n}\n\nstatic int64_t bf_get_sector_count(BlockDevice *bs)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n return bf->nb_sectors;\n}\n\nstatic void bf_start_load_block(BlockDevice *bs, int block_num)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n char filename[1024];\n CachedBlock *b;\n b = bf_add_block(bf, block_num);\n bf->n_read_blocks++;\n /* make a XHR to read the block */\n#if 0\n printf(\"%u,\\n\", block_num);\n#endif\n#if 0\n printf(\"load_blk=%d cached=%d read=%d KB (%d KB) write=%d KB (%d KB)\\n\",\n block_num, bf->n_cached_blocks,\n (int)(bf->n_read_sectors / 2),\n (int)(bf->n_read_blocks * bf->block_size / 2),\n (int)(bf->n_write_sectors / 2),\n (int)(bf->n_allocated_clusters * bf->sectors_per_cluster / 2));\n#endif\n snprintf(filename, sizeof(filename), BLK_FMT, bf->url, block_num);\n // printf(\"wget %s\\n\", filename);\n fs_wget(filename, NULL, NULL, b, bf_read_onload, TRUE);\n}\n\nstatic void bf_start_load_prefetch_group(BlockDevice *bs, int group_num,\n const int *tab_block_num,\n int n_block_num)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n CachedBlock *b;\n PrefetchGroupRequest *req;\n char filename[1024];\n BOOL req_flag;\n int i;\n \n req_flag = FALSE;\n req = malloc(sizeof(*req));\n req->bf = bf;\n req->group_num = group_num;\n req->n_block_num = n_block_num;\n for(i = 0; i < n_block_num; i++) {\n b = bf_find_block(bf, tab_block_num[i]);\n if (!b) {\n b = bf_add_block(bf, tab_block_num[i]);\n req_flag = TRUE;\n } else {\n /* no need to read the block if it is already loading or\n loaded */\n b = NULL;\n }\n req->tab_block[i] = b;\n }\n\n if (req_flag) {\n snprintf(filename, sizeof(filename), GROUP_FMT, bf->url, group_num);\n // printf(\"wget %s\\n\", filename);\n fs_wget(filename, NULL, NULL, req, bf_prefetch_group_onload, TRUE);\n /* XXX: should add request in a list to free it for clean exit */\n } else {\n free(req);\n }\n}\n\nstatic void bf_prefetch_group_onload(void *opaque, int err, void *data,\n size_t size)\n{\n PrefetchGroupRequest *req = opaque;\n BlockDeviceHTTP *bf = req->bf;\n CachedBlock *b;\n int block_bytes, i;\n \n if (err < 0) {\n fprintf(stderr, \"Could not load group %u\\n\", req->group_num);\n exit(1);\n }\n block_bytes = bf->block_size * 512;\n assert(size == block_bytes * req->n_block_num);\n for(i = 0; i < req->n_block_num; i++) {\n b = req->tab_block[i];\n if (b) {\n bf_update_block(b, (const uint8_t *)data + block_bytes * i);\n }\n }\n free(req);\n}\n\nstatic int bf_rw_async1(BlockDevice *bs, BOOL is_sync)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n int offset, block_num, n, cluster_num;\n CachedBlock *b;\n Cluster *c;\n \n for(;;) {\n n = bf->sector_count - bf->sector_index;\n if (n == 0)\n break;\n cluster_num = bf->sector_num / bf->sectors_per_cluster;\n c = bf->clusters[cluster_num];\n if (c) {\n offset = bf->sector_num % bf->sectors_per_cluster;\n n = min_int(n, bf->sectors_per_cluster - offset);\n if (bf->is_write) {\n file_buffer_write(&c->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n } else {\n file_buffer_read(&c->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n }\n bf->sector_index += n;\n bf->sector_num += n;\n } else {\n block_num = bf->sector_num / bf->block_size;\n offset = bf->sector_num % bf->block_size;\n n = min_int(n, bf->block_size - offset);\n bf->cur_block_num = block_num;\n \n b = bf_find_block(bf, block_num);\n if (b) {\n if (b->state == CBLOCK_LOADING) {\n /* wait until the block is loaded */\n return 1;\n } else {\n if (bf->is_write) {\n int cluster_size, cluster_offset;\n uint8_t *buf;\n /* allocate a new cluster */\n c = mallocz(sizeof(Cluster));\n cluster_size = bf->sectors_per_cluster * 512;\n buf = malloc(cluster_size);\n file_buffer_init(&c->fbuf);\n file_buffer_resize(&c->fbuf, cluster_size);\n bf->clusters[cluster_num] = c;\n /* copy the cached block data to the cluster */\n cluster_offset = (cluster_num * bf->sectors_per_cluster) &\n (bf->block_size - 1);\n file_buffer_read(&b->fbuf, cluster_offset * 512,\n buf, cluster_size);\n file_buffer_write(&c->fbuf, 0, buf, cluster_size);\n free(buf);\n bf->n_allocated_clusters++;\n continue; /* write to the allocated cluster */\n } else {\n file_buffer_read(&b->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n }\n bf->sector_index += n;\n bf->sector_num += n;\n }\n } else {\n bf_start_load_block(bs, block_num);\n return 1;\n }\n bf->cur_block_num = -1;\n }\n }\n\n if (!is_sync) {\n // printf(\"end of request\\n\");\n /* end of request */\n bf->cb(bf->opaque, 0);\n } \n return 0;\n}\n\nstatic void bf_update_block(CachedBlock *b, const uint8_t *data)\n{\n BlockDeviceHTTP *bf = b->bf;\n BlockDevice *bs = bf->bs;\n\n assert(b->state == CBLOCK_LOADING);\n file_buffer_write(&b->fbuf, 0, data, bf->block_size * 512);\n b->state = CBLOCK_LOADED;\n \n /* continue I/O read/write if necessary */\n if (b->block_num == bf->cur_block_num) {\n bf_rw_async1(bs, FALSE);\n }\n}\n\nstatic void bf_read_onload(void *opaque, int err, void *data, size_t size)\n{\n CachedBlock *b = opaque;\n BlockDeviceHTTP *bf = b->bf;\n\n if (err < 0) {\n fprintf(stderr, \"Could not load block %u\\n\", b->block_num);\n exit(1);\n }\n \n assert(size == bf->block_size * 512);\n bf_update_block(b, data);\n}\n\nstatic int bf_read_async(BlockDevice *bs,\n uint64_t sector_num, uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n // printf(\"bf_read_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n bf->is_write = FALSE;\n bf->sector_num = sector_num;\n bf->io_buf = buf;\n bf->sector_count = n;\n bf->sector_index = 0;\n bf->cb = cb;\n bf->opaque = opaque;\n bf->n_read_sectors += n;\n return bf_rw_async1(bs, TRUE);\n}\n\nstatic int bf_write_async(BlockDevice *bs,\n uint64_t sector_num, const uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n // printf(\"bf_write_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n bf->is_write = TRUE;\n bf->sector_num = sector_num;\n bf->io_buf = (uint8_t *)buf;\n bf->sector_count = n;\n bf->sector_index = 0;\n bf->cb = cb;\n bf->opaque = opaque;\n bf->n_write_sectors += n;\n return bf_rw_async1(bs, TRUE);\n}\n\nBlockDevice *block_device_init_http(const char *url,\n int max_cache_size_kb,\n void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n BlockDevice *bs;\n BlockDeviceHTTP *bf;\n char *p;\n\n bs = mallocz(sizeof(*bs));\n bf = mallocz(sizeof(*bf));\n strcpy(bf->url, url);\n /* get the path with the trailing '/' */\n p = strrchr(bf->url, '/');\n if (!p)\n p = bf->url;\n else\n p++;\n *p = '\\0';\n\n init_list_head(&bf->cached_blocks);\n bf->max_cache_size_kb = max_cache_size_kb;\n bf->start_cb = start_cb;\n bf->start_opaque = start_opaque;\n bf->bs = bs;\n \n bs->opaque = bf;\n bs->get_sector_count = bf_get_sector_count;\n bs->read_async = bf_read_async;\n bs->write_async = bf_write_async;\n \n fs_wget(url, NULL, NULL, bs, bf_init_onload, TRUE);\n return bs;\n}\n\nstatic void bf_init_onload(void *opaque, int err, void *data, size_t size)\n{\n BlockDevice *bs = opaque;\n BlockDeviceHTTP *bf = bs->opaque;\n int block_size_kb, block_num;\n JSONValue cfg, array;\n \n if (err < 0) {\n fprintf(stderr, \"Could not load block device file (err=%d)\\n\", -err);\n exit(1);\n }\n\n /* parse the disk image info */\n cfg = json_parse_value_len(data, size);\n if (json_is_error(cfg)) {\n vm_error(\"error: %s\\n\", json_get_error(cfg));\n config_error:\n json_free(cfg);\n exit(1);\n }\n\n if (vm_get_int(cfg, \"block_size\", &block_size_kb) < 0)\n goto config_error;\n bf->block_size = block_size_kb * 2;\n if (bf->block_size <= 0 ||\n (bf->block_size & (bf->block_size - 1)) != 0) {\n vm_error(\"invalid block_size\\n\");\n goto config_error;\n }\n if (vm_get_int(cfg, \"n_block\", &bf->nb_blocks) < 0)\n goto config_error;\n if (bf->nb_blocks <= 0) {\n vm_error(\"invalid n_block\\n\");\n goto config_error;\n }\n\n bf->nb_sectors = bf->block_size * (uint64_t)bf->nb_blocks;\n bf->n_cached_blocks = 0;\n bf->n_cached_blocks_max = max_int(1, bf->max_cache_size_kb / block_size_kb);\n bf->cur_block_num = -1; /* no request in progress */\n \n bf->sectors_per_cluster = 8; /* 4 KB */\n bf->n_clusters = (bf->nb_sectors + bf->sectors_per_cluster - 1) / bf->sectors_per_cluster;\n bf->clusters = mallocz(sizeof(bf->clusters[0]) * bf->n_clusters);\n\n if (vm_get_int_opt(cfg, \"prefetch_group_len\",\n &bf->prefetch_group_len, 1) < 0)\n goto config_error;\n if (bf->prefetch_group_len > PREFETCH_GROUP_LEN_MAX) {\n vm_error(\"prefetch_group_len is too large\");\n goto config_error;\n }\n \n array = json_object_get(cfg, \"prefetch\");\n if (!json_is_undefined(array)) {\n int idx, prefetch_len, l, i;\n JSONValue el;\n int tab_block_num[PREFETCH_GROUP_LEN_MAX];\n \n if (array.type != JSON_ARRAY) {\n vm_error(\"expecting an array\\n\");\n goto config_error;\n }\n prefetch_len = array.u.array->len;\n idx = 0;\n while (idx < prefetch_len) {\n l = min_int(prefetch_len - idx, bf->prefetch_group_len);\n for(i = 0; i < l; i++) {\n el = json_array_get(array, idx + i);\n if (el.type != JSON_INT) {\n vm_error(\"expecting an integer\\n\");\n goto config_error;\n }\n tab_block_num[i] = el.u.int32;\n }\n if (l == 1) {\n block_num = tab_block_num[0];\n if (!bf_find_block(bf, block_num)) {\n bf_start_load_block(bs, block_num);\n }\n } else {\n bf_start_load_prefetch_group(bs, idx / bf->prefetch_group_len,\n tab_block_num, l);\n }\n idx += l;\n }\n }\n json_free(cfg);\n \n if (bf->start_cb) {\n bf->start_cb(bf->start_opaque);\n }\n}\n"], ["/linuxpdf/tinyemu/vmmouse.c", "/*\n * VM mouse emulation\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n\n#define VMPORT_MAGIC 0x564D5868\n\n#define REG_EAX 0\n#define REG_EBX 1\n#define REG_ECX 2\n#define REG_EDX 3\n#define REG_ESI 4\n#define REG_EDI 5\n\n#define FIFO_SIZE (4 * 16)\n\nstruct VMMouseState {\n PS2MouseState *ps2_mouse;\n int fifo_count, fifo_rindex, fifo_windex;\n BOOL enabled;\n BOOL absolute;\n uint32_t fifo_buf[FIFO_SIZE];\n};\n\nstatic void put_queue(VMMouseState *s, uint32_t val)\n{\n if (s->fifo_count >= FIFO_SIZE)\n return;\n s->fifo_buf[s->fifo_windex] = val;\n if (++s->fifo_windex == FIFO_SIZE)\n s->fifo_windex = 0;\n s->fifo_count++;\n}\n\nstatic void read_data(VMMouseState *s, uint32_t *regs, int size)\n{\n int i;\n if (size > 6 || size > s->fifo_count) {\n // printf(\"vmmouse: read error req=%d count=%d\\n\", size, s->fifo_count);\n s->enabled = FALSE;\n return;\n }\n for(i = 0; i < size; i++) {\n regs[i] = s->fifo_buf[s->fifo_rindex];\n if (++s->fifo_rindex == FIFO_SIZE)\n s->fifo_rindex = 0;\n }\n s->fifo_count -= size;\n}\n\nvoid vmmouse_send_mouse_event(VMMouseState *s, int x, int y, int dz,\n int buttons)\n{\n int state;\n\n if (!s->enabled) {\n ps2_mouse_event(s->ps2_mouse, x, y, dz, buttons);\n return;\n }\n\n if ((s->fifo_count + 4) > FIFO_SIZE)\n return;\n\n state = 0;\n if (buttons & 1)\n state |= 0x20;\n if (buttons & 2)\n state |= 0x10;\n if (buttons & 4)\n state |= 0x08;\n if (s->absolute) {\n /* range = 0 ... 65535 */\n x *= 2; \n y *= 2;\n }\n\n put_queue(s, state);\n put_queue(s, x);\n put_queue(s, y);\n put_queue(s, -dz);\n\n /* send PS/2 mouse event */\n ps2_mouse_event(s->ps2_mouse, 1, 0, 0, 0);\n}\n\nvoid vmmouse_handler(VMMouseState *s, uint32_t *regs)\n{\n uint32_t cmd;\n \n cmd = regs[REG_ECX] & 0xff;\n switch(cmd) {\n case 10: /* get version */\n regs[REG_EBX] = VMPORT_MAGIC;\n break;\n case 39: /* VMMOUSE_DATA */\n read_data(s, regs, regs[REG_EBX]);\n break;\n case 40: /* VMMOUSE_STATUS */\n regs[REG_EAX] = ((s->enabled ? 0 : 0xffff) << 16) | s->fifo_count;\n break;\n case 41: /* VMMOUSE_COMMAND */\n switch(regs[REG_EBX]) {\n case 0x45414552: /* read id */\n if (s->fifo_count < FIFO_SIZE) {\n put_queue(s, 0x3442554a);\n s->enabled = TRUE;\n }\n break;\n case 0x000000f5: /* disable */\n s->enabled = FALSE;\n break;\n case 0x4c455252: /* set relative */\n s->absolute = 0;\n break;\n case 0x53424152: /* set absolute */\n s->absolute = 1;\n break;\n }\n break;\n }\n}\n\nBOOL vmmouse_is_absolute(VMMouseState *s)\n{\n return s->absolute;\n}\n\nVMMouseState *vmmouse_init(PS2MouseState *ps2_mouse)\n{\n VMMouseState *s;\n s = mallocz(sizeof(*s));\n s->ps2_mouse = ps2_mouse;\n return s;\n}\n"], ["/linuxpdf/tinyemu/slirp/misc.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n#ifdef DEBUG\nint slirp_debug = DBG_CALL|DBG_MISC|DBG_ERROR;\n#endif\n\nstruct quehead {\n\tstruct quehead *qh_link;\n\tstruct quehead *qh_rlink;\n};\n\ninline void\ninsque(void *a, void *b)\n{\n\tregister struct quehead *element = (struct quehead *) a;\n\tregister struct quehead *head = (struct quehead *) b;\n\telement->qh_link = head->qh_link;\n\thead->qh_link = (struct quehead *)element;\n\telement->qh_rlink = (struct quehead *)head;\n\t((struct quehead *)(element->qh_link))->qh_rlink\n\t= (struct quehead *)element;\n}\n\ninline void\nremque(void *a)\n{\n register struct quehead *element = (struct quehead *) a;\n ((struct quehead *)(element->qh_link))->qh_rlink = element->qh_rlink;\n ((struct quehead *)(element->qh_rlink))->qh_link = element->qh_link;\n element->qh_rlink = NULL;\n}\n\nint add_exec(struct ex_list **ex_ptr, int do_pty, char *exec,\n struct in_addr addr, int port)\n{\n\tstruct ex_list *tmp_ptr;\n\n\t/* First, check if the port is \"bound\" */\n\tfor (tmp_ptr = *ex_ptr; tmp_ptr; tmp_ptr = tmp_ptr->ex_next) {\n\t\tif (port == tmp_ptr->ex_fport &&\n\t\t addr.s_addr == tmp_ptr->ex_addr.s_addr)\n\t\t\treturn -1;\n\t}\n\n\ttmp_ptr = *ex_ptr;\n\t*ex_ptr = (struct ex_list *)malloc(sizeof(struct ex_list));\n\t(*ex_ptr)->ex_fport = port;\n\t(*ex_ptr)->ex_addr = addr;\n\t(*ex_ptr)->ex_pty = do_pty;\n\t(*ex_ptr)->ex_exec = (do_pty == 3) ? exec : strdup(exec);\n\t(*ex_ptr)->ex_next = tmp_ptr;\n\treturn 0;\n}\n\n#ifndef HAVE_STRERROR\n\n/*\n * For systems with no strerror\n */\n\nextern int sys_nerr;\nextern char *sys_errlist[];\n\nchar *\nstrerror(error)\n\tint error;\n{\n\tif (error < sys_nerr)\n\t return sys_errlist[error];\n\telse\n\t return \"Unknown error.\";\n}\n\n#endif\n\nint os_socket(int domain, int type, int protocol)\n{\n return socket(domain, type, protocol);\n}\n\nuint32_t os_get_time_ms(void)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return ts.tv_sec * 1000 +\n (ts.tv_nsec / 1000000);\n}\n\n\n#if 1\n\nint\nfork_exec(struct socket *so, const char *ex, int do_pty)\n{\n /* not implemented */\n return 0;\n}\n\n#else\n\n/*\n * XXX This is ugly\n * We create and bind a socket, then fork off to another\n * process, which connects to this socket, after which we\n * exec the wanted program. If something (strange) happens,\n * the accept() call could block us forever.\n *\n * do_pty = 0 Fork/exec inetd style\n * do_pty = 1 Fork/exec using slirp.telnetd\n * do_ptr = 2 Fork/exec using pty\n */\nint\nfork_exec(struct socket *so, const char *ex, int do_pty)\n{\n\tint s;\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(addr);\n\tint opt;\n int master = -1;\n\tconst char *argv[256];\n\t/* don't want to clobber the original */\n\tchar *bptr;\n\tconst char *curarg;\n\tint c, i, ret;\n\n\tDEBUG_CALL(\"fork_exec\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"ex = %lx\", (long)ex);\n\tDEBUG_ARG(\"do_pty = %lx\", (long)do_pty);\n\n\tif (do_pty == 2) {\n return 0;\n\t} else {\n\t\taddr.sin_family = AF_INET;\n\t\taddr.sin_port = 0;\n\t\taddr.sin_addr.s_addr = INADDR_ANY;\n\n\t\tif ((s = os_socket(AF_INET, SOCK_STREAM, 0)) < 0 ||\n\t\t bind(s, (struct sockaddr *)&addr, addrlen) < 0 ||\n\t\t listen(s, 1) < 0) {\n\t\t\tlprint(\"Error: inet socket: %s\\n\", strerror(errno));\n\t\t\tclosesocket(s);\n\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tswitch(fork()) {\n\t case -1:\n\t\tlprint(\"Error: fork failed: %s\\n\", strerror(errno));\n\t\tclose(s);\n\t\tif (do_pty == 2)\n\t\t close(master);\n\t\treturn 0;\n\n\t case 0:\n\t\t/* Set the DISPLAY */\n\t\tif (do_pty == 2) {\n\t\t\t(void) close(master);\n#ifdef TIOCSCTTY /* XXXXX */\n\t\t\t(void) setsid();\n\t\t\tioctl(s, TIOCSCTTY, (char *)NULL);\n#endif\n\t\t} else {\n\t\t\tgetsockname(s, (struct sockaddr *)&addr, &addrlen);\n\t\t\tclose(s);\n\t\t\t/*\n\t\t\t * Connect to the socket\n\t\t\t * XXX If any of these fail, we're in trouble!\n\t \t\t */\n\t\t\ts = os_socket(AF_INET, SOCK_STREAM, 0);\n\t\t\taddr.sin_addr = loopback_addr;\n do {\n ret = connect(s, (struct sockaddr *)&addr, addrlen);\n } while (ret < 0 && errno == EINTR);\n\t\t}\n\n\t\tdup2(s, 0);\n\t\tdup2(s, 1);\n\t\tdup2(s, 2);\n\t\tfor (s = getdtablesize() - 1; s >= 3; s--)\n\t\t close(s);\n\n\t\ti = 0;\n\t\tbptr = qemu_strdup(ex); /* No need to free() this */\n\t\tif (do_pty == 1) {\n\t\t\t/* Setup \"slirp.telnetd -x\" */\n\t\t\targv[i++] = \"slirp.telnetd\";\n\t\t\targv[i++] = \"-x\";\n\t\t\targv[i++] = bptr;\n\t\t} else\n\t\t do {\n\t\t\t/* Change the string into argv[] */\n\t\t\tcurarg = bptr;\n\t\t\twhile (*bptr != ' ' && *bptr != (char)0)\n\t\t\t bptr++;\n\t\t\tc = *bptr;\n\t\t\t*bptr++ = (char)0;\n\t\t\targv[i++] = strdup(curarg);\n\t\t } while (c);\n\n argv[i] = NULL;\n\t\texecvp(argv[0], (char **)argv);\n\n\t\t/* Ooops, failed, let's tell the user why */\n fprintf(stderr, \"Error: execvp of %s failed: %s\\n\",\n argv[0], strerror(errno));\n\t\tclose(0); close(1); close(2); /* XXX */\n\t\texit(1);\n\n\t default:\n\t\tif (do_pty == 2) {\n\t\t\tclose(s);\n\t\t\tso->s = master;\n\t\t} else {\n\t\t\t/*\n\t\t\t * XXX this could block us...\n\t\t\t * XXX Should set a timer here, and if accept() doesn't\n\t\t \t * return after X seconds, declare it a failure\n\t\t \t * The only reason this will block forever is if socket()\n\t\t \t * of connect() fail in the child process\n\t\t \t */\n do {\n so->s = accept(s, (struct sockaddr *)&addr, &addrlen);\n } while (so->s < 0 && errno == EINTR);\n closesocket(s);\n\t\t\topt = 1;\n\t\t\tsetsockopt(so->s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\t\t\topt = 1;\n\t\t\tsetsockopt(so->s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\t\t}\n\t\tfd_nonblock(so->s);\n\n\t\t/* Append the telnet options now */\n if (so->so_m != NULL && do_pty == 1) {\n\t\t\tsbappend(so, so->so_m);\n so->so_m = NULL;\n\t\t}\n\n\t\treturn 1;\n\t}\n}\n#endif\n\n#ifndef HAVE_STRDUP\nchar *\nstrdup(str)\n\tconst char *str;\n{\n\tchar *bptr;\n\n\tbptr = (char *)malloc(strlen(str)+1);\n\tstrcpy(bptr, str);\n\n\treturn bptr;\n}\n#endif\n\nvoid lprint(const char *format, ...)\n{\n va_list args;\n\n va_start(args, format);\n vprintf(format, args);\n va_end(args);\n}\n\n/*\n * Set fd blocking and non-blocking\n */\n\nvoid\nfd_nonblock(int fd)\n{\n#ifdef FIONBIO\n#ifdef _WIN32\n unsigned long opt = 1;\n#else\n int opt = 1;\n#endif\n\n\tioctlsocket(fd, FIONBIO, &opt);\n#else\n\tint opt;\n\n\topt = fcntl(fd, F_GETFL, 0);\n\topt |= O_NONBLOCK;\n\tfcntl(fd, F_SETFL, opt);\n#endif\n}\n\nvoid\nfd_block(int fd)\n{\n#ifdef FIONBIO\n#ifdef _WIN32\n unsigned long opt = 0;\n#else\n\tint opt = 0;\n#endif\n\n\tioctlsocket(fd, FIONBIO, &opt);\n#else\n\tint opt;\n\n\topt = fcntl(fd, F_GETFL, 0);\n\topt &= ~O_NONBLOCK;\n\tfcntl(fd, F_SETFL, opt);\n#endif\n}\n\n#if 0\nvoid slirp_connection_info(Slirp *slirp, Monitor *mon)\n{\n const char * const tcpstates[] = {\n [TCPS_CLOSED] = \"CLOSED\",\n [TCPS_LISTEN] = \"LISTEN\",\n [TCPS_SYN_SENT] = \"SYN_SENT\",\n [TCPS_SYN_RECEIVED] = \"SYN_RCVD\",\n [TCPS_ESTABLISHED] = \"ESTABLISHED\",\n [TCPS_CLOSE_WAIT] = \"CLOSE_WAIT\",\n [TCPS_FIN_WAIT_1] = \"FIN_WAIT_1\",\n [TCPS_CLOSING] = \"CLOSING\",\n [TCPS_LAST_ACK] = \"LAST_ACK\",\n [TCPS_FIN_WAIT_2] = \"FIN_WAIT_2\",\n [TCPS_TIME_WAIT] = \"TIME_WAIT\",\n };\n struct in_addr dst_addr;\n struct sockaddr_in src;\n socklen_t src_len;\n uint16_t dst_port;\n struct socket *so;\n const char *state;\n char buf[20];\n int n;\n\n monitor_printf(mon, \" Protocol[State] FD Source Address Port \"\n \"Dest. Address Port RecvQ SendQ\\n\");\n\n for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {\n if (so->so_state & SS_HOSTFWD) {\n state = \"HOST_FORWARD\";\n } else if (so->so_tcpcb) {\n state = tcpstates[so->so_tcpcb->t_state];\n } else {\n state = \"NONE\";\n }\n if (so->so_state & (SS_HOSTFWD | SS_INCOMING)) {\n src_len = sizeof(src);\n getsockname(so->s, (struct sockaddr *)&src, &src_len);\n dst_addr = so->so_laddr;\n dst_port = so->so_lport;\n } else {\n src.sin_addr = so->so_laddr;\n src.sin_port = so->so_lport;\n dst_addr = so->so_faddr;\n dst_port = so->so_fport;\n }\n n = snprintf(buf, sizeof(buf), \" TCP[%s]\", state);\n memset(&buf[n], ' ', 19 - n);\n buf[19] = 0;\n monitor_printf(mon, \"%s %3d %15s %5d \", buf, so->s,\n src.sin_addr.s_addr ? inet_ntoa(src.sin_addr) : \"*\",\n ntohs(src.sin_port));\n monitor_printf(mon, \"%15s %5d %5d %5d\\n\",\n inet_ntoa(dst_addr), ntohs(dst_port),\n so->so_rcv.sb_cc, so->so_snd.sb_cc);\n }\n\n for (so = slirp->udb.so_next; so != &slirp->udb; so = so->so_next) {\n if (so->so_state & SS_HOSTFWD) {\n n = snprintf(buf, sizeof(buf), \" UDP[HOST_FORWARD]\");\n src_len = sizeof(src);\n getsockname(so->s, (struct sockaddr *)&src, &src_len);\n dst_addr = so->so_laddr;\n dst_port = so->so_lport;\n } else {\n n = snprintf(buf, sizeof(buf), \" UDP[%d sec]\",\n (so->so_expire - curtime) / 1000);\n src.sin_addr = so->so_laddr;\n src.sin_port = so->so_lport;\n dst_addr = so->so_faddr;\n dst_port = so->so_fport;\n }\n memset(&buf[n], ' ', 19 - n);\n buf[19] = 0;\n monitor_printf(mon, \"%s %3d %15s %5d \", buf, so->s,\n src.sin_addr.s_addr ? inet_ntoa(src.sin_addr) : \"*\",\n ntohs(src.sin_port));\n monitor_printf(mon, \"%15s %5d %5d %5d\\n\",\n inet_ntoa(dst_addr), ntohs(dst_port),\n so->so_rcv.sb_cc, so->so_snd.sb_cc);\n }\n}\n#endif\n"], ["/linuxpdf/tinyemu/slirp/tcp_input.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_input.c\t8.5 (Berkeley) 4/10/94\n * tcp_input.c,v 1.10 1994/10/13 18:36:32 wollman Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n#define\tTCPREXMTTHRESH 3\n\n#define TCP_PAWS_IDLE\t(24 * 24 * 60 * 60 * PR_SLOWHZ)\n\n/* for modulo comparisons of timestamps */\n#define TSTMP_LT(a,b)\t((int)((a)-(b)) < 0)\n#define TSTMP_GEQ(a,b)\t((int)((a)-(b)) >= 0)\n\n/*\n * Insert segment ti into reassembly queue of tcp with\n * control block tp. Return TH_FIN if reassembly now includes\n * a segment with FIN. The macro form does the common case inline\n * (segment is the next to be received on an established connection,\n * and the queue is empty), avoiding linkage into and removal\n * from the queue and repetition of various conversions.\n * Set DELACK for segments received in order, but ack immediately\n * when segments are out of order (so fast retransmit can work).\n */\n#ifdef TCP_ACK_HACK\n#define TCP_REASS(tp, ti, m, so, flags) {\\\n if ((ti)->ti_seq == (tp)->rcv_nxt && \\\n tcpfrag_list_empty(tp) && \\\n (tp)->t_state == TCPS_ESTABLISHED) {\\\n if (ti->ti_flags & TH_PUSH) \\\n tp->t_flags |= TF_ACKNOW; \\\n else \\\n tp->t_flags |= TF_DELACK; \\\n (tp)->rcv_nxt += (ti)->ti_len; \\\n flags = (ti)->ti_flags & TH_FIN; \\\n if (so->so_emu) { \\\n\t\t if (tcp_emu((so),(m))) sbappend((so), (m)); \\\n\t } else \\\n\t \t sbappend((so), (m)); \\\n\t} else {\\\n (flags) = tcp_reass((tp), (ti), (m)); \\\n tp->t_flags |= TF_ACKNOW; \\\n } \\\n}\n#else\n#define\tTCP_REASS(tp, ti, m, so, flags) { \\\n\tif ((ti)->ti_seq == (tp)->rcv_nxt && \\\n tcpfrag_list_empty(tp) && \\\n\t (tp)->t_state == TCPS_ESTABLISHED) { \\\n\t\ttp->t_flags |= TF_DELACK; \\\n\t\t(tp)->rcv_nxt += (ti)->ti_len; \\\n\t\tflags = (ti)->ti_flags & TH_FIN; \\\n\t\tif (so->so_emu) { \\\n\t\t\tif (tcp_emu((so),(m))) sbappend(so, (m)); \\\n\t\t} else \\\n\t\t\tsbappend((so), (m)); \\\n\t} else { \\\n\t\t(flags) = tcp_reass((tp), (ti), (m)); \\\n\t\ttp->t_flags |= TF_ACKNOW; \\\n\t} \\\n}\n#endif\nstatic void tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt,\n struct tcpiphdr *ti);\nstatic void tcp_xmit_timer(register struct tcpcb *tp, int rtt);\n\nstatic int\ntcp_reass(register struct tcpcb *tp, register struct tcpiphdr *ti,\n struct mbuf *m)\n{\n\tregister struct tcpiphdr *q;\n\tstruct socket *so = tp->t_socket;\n\tint flags;\n\n\t/*\n\t * Call with ti==NULL after become established to\n\t * force pre-ESTABLISHED data up to user socket.\n\t */\n if (ti == NULL)\n\t\tgoto present;\n\n\t/*\n\t * Find a segment which begins after this one does.\n\t */\n\tfor (q = tcpfrag_list_first(tp); !tcpfrag_list_end(q, tp);\n q = tcpiphdr_next(q))\n\t\tif (SEQ_GT(q->ti_seq, ti->ti_seq))\n\t\t\tbreak;\n\n\t/*\n\t * If there is a preceding segment, it may provide some of\n\t * our data already. If so, drop the data from the incoming\n\t * segment. If it provides all of our data, drop us.\n\t */\n\tif (!tcpfrag_list_end(tcpiphdr_prev(q), tp)) {\n\t\tregister int i;\n\t\tq = tcpiphdr_prev(q);\n\t\t/* conversion to int (in i) handles seq wraparound */\n\t\ti = q->ti_seq + q->ti_len - ti->ti_seq;\n\t\tif (i > 0) {\n\t\t\tif (i >= ti->ti_len) {\n\t\t\t\tm_freem(m);\n\t\t\t\t/*\n\t\t\t\t * Try to present any queued data\n\t\t\t\t * at the left window edge to the user.\n\t\t\t\t * This is needed after the 3-WHS\n\t\t\t\t * completes.\n\t\t\t\t */\n\t\t\t\tgoto present; /* ??? */\n\t\t\t}\n\t\t\tm_adj(m, i);\n\t\t\tti->ti_len -= i;\n\t\t\tti->ti_seq += i;\n\t\t}\n\t\tq = tcpiphdr_next(q);\n\t}\n\tti->ti_mbuf = m;\n\n\t/*\n\t * While we overlap succeeding segments trim them or,\n\t * if they are completely covered, dequeue them.\n\t */\n\twhile (!tcpfrag_list_end(q, tp)) {\n\t\tregister int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;\n\t\tif (i <= 0)\n\t\t\tbreak;\n\t\tif (i < q->ti_len) {\n\t\t\tq->ti_seq += i;\n\t\t\tq->ti_len -= i;\n\t\t\tm_adj(q->ti_mbuf, i);\n\t\t\tbreak;\n\t\t}\n\t\tq = tcpiphdr_next(q);\n\t\tm = tcpiphdr_prev(q)->ti_mbuf;\n\t\tremque(tcpiphdr2qlink(tcpiphdr_prev(q)));\n\t\tm_freem(m);\n\t}\n\n\t/*\n\t * Stick new segment in its place.\n\t */\n\tinsque(tcpiphdr2qlink(ti), tcpiphdr2qlink(tcpiphdr_prev(q)));\n\npresent:\n\t/*\n\t * Present data to user, advancing rcv_nxt through\n\t * completed sequence space.\n\t */\n\tif (!TCPS_HAVEESTABLISHED(tp->t_state))\n\t\treturn (0);\n\tti = tcpfrag_list_first(tp);\n\tif (tcpfrag_list_end(ti, tp) || ti->ti_seq != tp->rcv_nxt)\n\t\treturn (0);\n\tif (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)\n\t\treturn (0);\n\tdo {\n\t\ttp->rcv_nxt += ti->ti_len;\n\t\tflags = ti->ti_flags & TH_FIN;\n\t\tremque(tcpiphdr2qlink(ti));\n\t\tm = ti->ti_mbuf;\n\t\tti = tcpiphdr_next(ti);\n\t\tif (so->so_state & SS_FCANTSENDMORE)\n\t\t\tm_freem(m);\n\t\telse {\n\t\t\tif (so->so_emu) {\n\t\t\t\tif (tcp_emu(so,m)) sbappend(so, m);\n\t\t\t} else\n\t\t\t\tsbappend(so, m);\n\t\t}\n\t} while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);\n\treturn (flags);\n}\n\n/*\n * TCP input routine, follows pages 65-76 of the\n * protocol specification dated September, 1981 very closely.\n */\nvoid\ntcp_input(struct mbuf *m, int iphlen, struct socket *inso)\n{\n \tstruct ip save_ip, *ip;\n\tregister struct tcpiphdr *ti;\n\tcaddr_t optp = NULL;\n\tint optlen = 0;\n\tint len, tlen, off;\n register struct tcpcb *tp = NULL;\n\tregister int tiflags;\n struct socket *so = NULL;\n\tint todrop, acked, ourfinisacked, needoutput = 0;\n\tint iss = 0;\n\tu_long tiwin;\n\tint ret;\n struct ex_list *ex_ptr;\n Slirp *slirp;\n\n\tDEBUG_CALL(\"tcp_input\");\n\tDEBUG_ARGS((dfd,\" m = %8lx iphlen = %2d inso = %lx\\n\",\n\t\t (long )m, iphlen, (long )inso ));\n\n\t/*\n\t * If called with m == 0, then we're continuing the connect\n\t */\n\tif (m == NULL) {\n\t\tso = inso;\n\t\tslirp = so->slirp;\n\n\t\t/* Re-set a few variables */\n\t\ttp = sototcpcb(so);\n\t\tm = so->so_m;\n so->so_m = NULL;\n\t\tti = so->so_ti;\n\t\ttiwin = ti->ti_win;\n\t\ttiflags = ti->ti_flags;\n\n\t\tgoto cont_conn;\n\t}\n\tslirp = m->slirp;\n\n\t/*\n\t * Get IP and TCP header together in first mbuf.\n\t * Note: IP leaves IP header in first mbuf.\n\t */\n\tti = mtod(m, struct tcpiphdr *);\n\tif (iphlen > sizeof(struct ip )) {\n\t ip_stripoptions(m, (struct mbuf *)0);\n\t iphlen=sizeof(struct ip );\n\t}\n\t/* XXX Check if too short */\n\n\n\t/*\n\t * Save a copy of the IP header in case we want restore it\n\t * for sending an ICMP error message in response.\n\t */\n\tip=mtod(m, struct ip *);\n\tsave_ip = *ip;\n\tsave_ip.ip_len+= iphlen;\n\n\t/*\n\t * Checksum extended TCP header and data.\n\t */\n\ttlen = ((struct ip *)ti)->ip_len;\n tcpiphdr2qlink(ti)->next = tcpiphdr2qlink(ti)->prev = NULL;\n memset(&ti->ti_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));\n\tti->ti_x1 = 0;\n\tti->ti_len = htons((uint16_t)tlen);\n\tlen = sizeof(struct ip ) + tlen;\n\tif(cksum(m, len)) {\n\t goto drop;\n\t}\n\n\t/*\n\t * Check that TCP offset makes sense,\n\t * pull out TCP options and adjust length.\t\tXXX\n\t */\n\toff = ti->ti_off << 2;\n\tif (off < sizeof (struct tcphdr) || off > tlen) {\n\t goto drop;\n\t}\n\ttlen -= off;\n\tti->ti_len = tlen;\n\tif (off > sizeof (struct tcphdr)) {\n\t optlen = off - sizeof (struct tcphdr);\n\t optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);\n\t}\n\ttiflags = ti->ti_flags;\n\n\t/*\n\t * Convert TCP protocol specific fields to host format.\n\t */\n\tNTOHL(ti->ti_seq);\n\tNTOHL(ti->ti_ack);\n\tNTOHS(ti->ti_win);\n\tNTOHS(ti->ti_urp);\n\n\t/*\n\t * Drop TCP, IP headers and TCP options.\n\t */\n\tm->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\tm->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\n if (slirp->restricted) {\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_fport == ti->ti_dport &&\n ti->ti_dst.s_addr == ex_ptr->ex_addr.s_addr) {\n break;\n }\n }\n if (!ex_ptr)\n goto drop;\n }\n\t/*\n\t * Locate pcb for segment.\n\t */\nfindso:\n\tso = slirp->tcp_last_so;\n\tif (so->so_fport != ti->ti_dport ||\n\t so->so_lport != ti->ti_sport ||\n\t so->so_laddr.s_addr != ti->ti_src.s_addr ||\n\t so->so_faddr.s_addr != ti->ti_dst.s_addr) {\n\t\tso = solookup(&slirp->tcb, ti->ti_src, ti->ti_sport,\n\t\t\t ti->ti_dst, ti->ti_dport);\n\t\tif (so)\n\t\t\tslirp->tcp_last_so = so;\n\t}\n\n\t/*\n\t * If the state is CLOSED (i.e., TCB does not exist) then\n\t * all data in the incoming segment is discarded.\n\t * If the TCB exists but is in CLOSED state, it is embryonic,\n\t * but should either do a listen or a connect soon.\n\t *\n\t * state == CLOSED means we've done socreate() but haven't\n\t * attached it to a protocol yet...\n\t *\n\t * XXX If a TCB does not exist, and the TH_SYN flag is\n\t * the only flag set, then create a session, mark it\n\t * as if it was LISTENING, and continue...\n\t */\n if (so == NULL) {\n\t if ((tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) != TH_SYN)\n\t goto dropwithreset;\n\n\t if ((so = socreate(slirp)) == NULL)\n\t goto dropwithreset;\n\t if (tcp_attach(so) < 0) {\n\t free(so); /* Not sofree (if it failed, it's not insqued) */\n\t goto dropwithreset;\n\t }\n\n\t sbreserve(&so->so_snd, TCP_SNDSPACE);\n\t sbreserve(&so->so_rcv, TCP_RCVSPACE);\n\n\t so->so_laddr = ti->ti_src;\n\t so->so_lport = ti->ti_sport;\n\t so->so_faddr = ti->ti_dst;\n\t so->so_fport = ti->ti_dport;\n\n\t if ((so->so_iptos = tcp_tos(so)) == 0)\n\t so->so_iptos = ((struct ip *)ti)->ip_tos;\n\n\t tp = sototcpcb(so);\n\t tp->t_state = TCPS_LISTEN;\n\t}\n\n /*\n * If this is a still-connecting socket, this probably\n * a retransmit of the SYN. Whether it's a retransmit SYN\n\t * or something else, we nuke it.\n */\n if (so->so_state & SS_ISFCONNECTING)\n goto drop;\n\n\ttp = sototcpcb(so);\n\n\t/* XXX Should never fail */\n if (tp == NULL)\n\t\tgoto dropwithreset;\n\tif (tp->t_state == TCPS_CLOSED)\n\t\tgoto drop;\n\n\ttiwin = ti->ti_win;\n\n\t/*\n\t * Segment received on connection.\n\t * Reset idle time and keep-alive timer.\n\t */\n\ttp->t_idle = 0;\n\tif (SO_OPTIONS)\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;\n\telse\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;\n\n\t/*\n\t * Process options if not in LISTEN state,\n\t * else do it below (after getting remote address).\n\t */\n\tif (optp && tp->t_state != TCPS_LISTEN)\n\t\ttcp_dooptions(tp, (u_char *)optp, optlen, ti);\n\n\t/*\n\t * Header prediction: check for the two common cases\n\t * of a uni-directional data xfer. If the packet has\n\t * no control flags, is in-sequence, the window didn't\n\t * change and we're not retransmitting, it's a\n\t * candidate. If the length is zero and the ack moved\n\t * forward, we're the sender side of the xfer. Just\n\t * free the data acked & wake any higher level process\n\t * that was blocked waiting for space. If the length\n\t * is non-zero and the ack didn't move, we're the\n\t * receiver side. If we're getting packets in-order\n\t * (the reassembly queue is empty), add the data to\n\t * the socket buffer and note that we need a delayed ack.\n\t *\n\t * XXX Some of these tests are not needed\n\t * eg: the tiwin == tp->snd_wnd prevents many more\n\t * predictions.. with no *real* advantage..\n\t */\n\tif (tp->t_state == TCPS_ESTABLISHED &&\n\t (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&\n\t ti->ti_seq == tp->rcv_nxt &&\n\t tiwin && tiwin == tp->snd_wnd &&\n\t tp->snd_nxt == tp->snd_max) {\n\t\tif (ti->ti_len == 0) {\n\t\t\tif (SEQ_GT(ti->ti_ack, tp->snd_una) &&\n\t\t\t SEQ_LEQ(ti->ti_ack, tp->snd_max) &&\n\t\t\t tp->snd_cwnd >= tp->snd_wnd) {\n\t\t\t\t/*\n\t\t\t\t * this is a pure ack for outstanding data.\n\t\t\t\t */\n\t\t\t\tif (tp->t_rtt &&\n\t\t\t\t SEQ_GT(ti->ti_ack, tp->t_rtseq))\n\t\t\t\t\ttcp_xmit_timer(tp, tp->t_rtt);\n\t\t\t\tacked = ti->ti_ack - tp->snd_una;\n\t\t\t\tsbdrop(&so->so_snd, acked);\n\t\t\t\ttp->snd_una = ti->ti_ack;\n\t\t\t\tm_freem(m);\n\n\t\t\t\t/*\n\t\t\t\t * If all outstanding data are acked, stop\n\t\t\t\t * retransmit timer, otherwise restart timer\n\t\t\t\t * using current (possibly backed-off) value.\n\t\t\t\t * If process is waiting for space,\n\t\t\t\t * wakeup/selwakeup/signal. If data\n\t\t\t\t * are ready to send, let tcp_output\n\t\t\t\t * decide between more output or persist.\n\t\t\t\t */\n\t\t\t\tif (tp->snd_una == tp->snd_max)\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\t\telse if (tp->t_timer[TCPT_PERSIST] == 0)\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\n\t\t\t\t/*\n\t\t\t\t * This is called because sowwakeup might have\n\t\t\t\t * put data into so_snd. Since we don't so sowwakeup,\n\t\t\t\t * we don't need this.. XXX???\n\t\t\t\t */\n\t\t\t\tif (so->so_snd.sb_cc)\n\t\t\t\t\t(void) tcp_output(tp);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (ti->ti_ack == tp->snd_una &&\n\t\t tcpfrag_list_empty(tp) &&\n\t\t ti->ti_len <= sbspace(&so->so_rcv)) {\n\t\t\t/*\n\t\t\t * this is a pure, in-sequence data packet\n\t\t\t * with nothing on the reassembly queue and\n\t\t\t * we have enough buffer space to take it.\n\t\t\t */\n\t\t\ttp->rcv_nxt += ti->ti_len;\n\t\t\t/*\n\t\t\t * Add data to socket buffer.\n\t\t\t */\n\t\t\tif (so->so_emu) {\n\t\t\t\tif (tcp_emu(so,m)) sbappend(so, m);\n\t\t\t} else\n\t\t\t\tsbappend(so, m);\n\n\t\t\t/*\n\t\t\t * If this is a short packet, then ACK now - with Nagel\n\t\t\t *\tcongestion avoidance sender won't send more until\n\t\t\t *\the gets an ACK.\n\t\t\t *\n\t\t\t * It is better to not delay acks at all to maximize\n\t\t\t * TCP throughput. See RFC 2581.\n\t\t\t */\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttcp_output(tp);\n\t\t\treturn;\n\t\t}\n\t} /* header prediction */\n\t/*\n\t * Calculate amount of space in receive window,\n\t * and then do TCP input processing.\n\t * Receive window is amount of space in rcv queue,\n\t * but not less than advertised window.\n\t */\n\t{ int win;\n win = sbspace(&so->so_rcv);\n\t if (win < 0)\n\t win = 0;\n\t tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));\n\t}\n\n\tswitch (tp->t_state) {\n\n\t/*\n\t * If the state is LISTEN then ignore segment if it contains an RST.\n\t * If the segment contains an ACK then it is bad and send a RST.\n\t * If it does not contain a SYN then it is not interesting; drop it.\n\t * Don't bother responding if the destination was a broadcast.\n\t * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial\n\t * tp->iss, and send a segment:\n\t * \n\t * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.\n\t * Fill in remote peer address fields if not previously specified.\n\t * Enter SYN_RECEIVED state, and process any other fields of this\n\t * segment in this state.\n\t */\n\tcase TCPS_LISTEN: {\n\n\t if (tiflags & TH_RST)\n\t goto drop;\n\t if (tiflags & TH_ACK)\n\t goto dropwithreset;\n\t if ((tiflags & TH_SYN) == 0)\n\t goto drop;\n\n\t /*\n\t * This has way too many gotos...\n\t * But a bit of spaghetti code never hurt anybody :)\n\t */\n\n\t /*\n\t * If this is destined for the control address, then flag to\n\t * tcp_ctl once connected, otherwise connect\n\t */\n\t if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n\t slirp->vnetwork_addr.s_addr) {\n\t if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr &&\n\t\tso->so_faddr.s_addr != slirp->vnameserver_addr.s_addr) {\n\t\t/* May be an add exec */\n\t\tfor (ex_ptr = slirp->exec_list; ex_ptr;\n\t\t ex_ptr = ex_ptr->ex_next) {\n\t\t if(ex_ptr->ex_fport == so->so_fport &&\n\t\t so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {\n\t\t so->so_state |= SS_CTL;\n\t\t break;\n\t\t }\n\t\t}\n\t\tif (so->so_state & SS_CTL) {\n\t\t goto cont_input;\n\t\t}\n\t }\n\t /* CTL_ALIAS: Do nothing, tcp_fconnect will be called on it */\n\t }\n\n\t if (so->so_emu & EMU_NOCONNECT) {\n\t so->so_emu &= ~EMU_NOCONNECT;\n\t goto cont_input;\n\t }\n\n\t if((tcp_fconnect(so) == -1) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK)) {\n\t u_char code=ICMP_UNREACH_NET;\n\t DEBUG_MISC((dfd,\" tcp fconnect errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t if(errno == ECONNREFUSED) {\n\t /* ACK the SYN, send RST to refuse the connection */\n\t tcp_respond(tp, ti, m, ti->ti_seq+1, (tcp_seq)0,\n\t\t\t TH_RST|TH_ACK);\n\t } else {\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t HTONL(ti->ti_seq); /* restore tcp header */\n\t HTONL(ti->ti_ack);\n\t HTONS(ti->ti_win);\n\t HTONS(ti->ti_urp);\n\t m->m_data -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\t m->m_len += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\t *ip=save_ip;\n\t icmp_error(m, ICMP_UNREACH,code, 0,strerror(errno));\n\t }\n tcp_close(tp);\n\t m_free(m);\n\t } else {\n\t /*\n\t * Haven't connected yet, save the current mbuf\n\t * and ti, and return\n\t * XXX Some OS's don't tell us whether the connect()\n\t * succeeded or not. So we must time it out.\n\t */\n\t so->so_m = m;\n\t so->so_ti = ti;\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\t tp->t_state = TCPS_SYN_RECEIVED;\n\t }\n\t return;\n\n\tcont_conn:\n\t /* m==NULL\n\t * Check if the connect succeeded\n\t */\n\t if (so->so_state & SS_NOFDREF) {\n\t tp = tcp_close(tp);\n\t goto dropwithreset;\n\t }\n\tcont_input:\n\t tcp_template(tp);\n\n\t if (optp)\n\t tcp_dooptions(tp, (u_char *)optp, optlen, ti);\n\n\t if (iss)\n\t tp->iss = iss;\n\t else\n\t tp->iss = slirp->tcp_iss;\n\t slirp->tcp_iss += TCP_ISSINCR/2;\n\t tp->irs = ti->ti_seq;\n\t tcp_sendseqinit(tp);\n\t tcp_rcvseqinit(tp);\n\t tp->t_flags |= TF_ACKNOW;\n\t tp->t_state = TCPS_SYN_RECEIVED;\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\t goto trimthenstep6;\n\t} /* case TCPS_LISTEN */\n\n\t/*\n\t * If the state is SYN_SENT:\n\t *\tif seg contains an ACK, but not for our SYN, drop the input.\n\t *\tif seg contains a RST, then drop the connection.\n\t *\tif seg does not contain SYN, then drop it.\n\t * Otherwise this is an acceptable SYN segment\n\t *\tinitialize tp->rcv_nxt and tp->irs\n\t *\tif seg contains ack then advance tp->snd_una\n\t *\tif SYN has been acked change to ESTABLISHED else SYN_RCVD state\n\t *\tarrange for segment to be acked (eventually)\n\t *\tcontinue processing rest of data/controls, beginning with URG\n\t */\n\tcase TCPS_SYN_SENT:\n\t\tif ((tiflags & TH_ACK) &&\n\t\t (SEQ_LEQ(ti->ti_ack, tp->iss) ||\n\t\t SEQ_GT(ti->ti_ack, tp->snd_max)))\n\t\t\tgoto dropwithreset;\n\n\t\tif (tiflags & TH_RST) {\n if (tiflags & TH_ACK) {\n tcp_drop(tp, 0); /* XXX Check t_softerror! */\n }\n\t\t\tgoto drop;\n\t\t}\n\n\t\tif ((tiflags & TH_SYN) == 0)\n\t\t\tgoto drop;\n\t\tif (tiflags & TH_ACK) {\n\t\t\ttp->snd_una = ti->ti_ack;\n\t\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_una))\n\t\t\t\ttp->snd_nxt = tp->snd_una;\n\t\t}\n\n\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\ttp->irs = ti->ti_seq;\n\t\ttcp_rcvseqinit(tp);\n\t\ttp->t_flags |= TF_ACKNOW;\n\t\tif (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {\n\t\t\tsoisfconnected(so);\n\t\t\ttp->t_state = TCPS_ESTABLISHED;\n\n\t\t\t(void) tcp_reass(tp, (struct tcpiphdr *)0,\n\t\t\t\t(struct mbuf *)0);\n\t\t\t/*\n\t\t\t * if we didn't have to retransmit the SYN,\n\t\t\t * use its rtt as our initial srtt & rtt var.\n\t\t\t */\n\t\t\tif (tp->t_rtt)\n\t\t\t\ttcp_xmit_timer(tp, tp->t_rtt);\n\t\t} else\n\t\t\ttp->t_state = TCPS_SYN_RECEIVED;\n\ntrimthenstep6:\n\t\t/*\n\t\t * Advance ti->ti_seq to correspond to first data byte.\n\t\t * If data, trim to stay within window,\n\t\t * dropping FIN if necessary.\n\t\t */\n\t\tti->ti_seq++;\n\t\tif (ti->ti_len > tp->rcv_wnd) {\n\t\t\ttodrop = ti->ti_len - tp->rcv_wnd;\n\t\t\tm_adj(m, -todrop);\n\t\t\tti->ti_len = tp->rcv_wnd;\n\t\t\ttiflags &= ~TH_FIN;\n\t\t}\n\t\ttp->snd_wl1 = ti->ti_seq - 1;\n\t\ttp->rcv_up = ti->ti_seq;\n\t\tgoto step6;\n\t} /* switch tp->t_state */\n\t/*\n\t * States other than LISTEN or SYN_SENT.\n\t * Check that at least some bytes of segment are within\n\t * receive window. If segment begins before rcv_nxt,\n\t * drop leading data (and SYN); if nothing left, just ack.\n\t */\n\ttodrop = tp->rcv_nxt - ti->ti_seq;\n\tif (todrop > 0) {\n\t\tif (tiflags & TH_SYN) {\n\t\t\ttiflags &= ~TH_SYN;\n\t\t\tti->ti_seq++;\n\t\t\tif (ti->ti_urp > 1)\n\t\t\t\tti->ti_urp--;\n\t\t\telse\n\t\t\t\ttiflags &= ~TH_URG;\n\t\t\ttodrop--;\n\t\t}\n\t\t/*\n\t\t * Following if statement from Stevens, vol. 2, p. 960.\n\t\t */\n\t\tif (todrop > ti->ti_len\n\t\t || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {\n\t\t\t/*\n\t\t\t * Any valid FIN must be to the left of the window.\n\t\t\t * At this point the FIN must be a duplicate or out\n\t\t\t * of sequence; drop it.\n\t\t\t */\n\t\t\ttiflags &= ~TH_FIN;\n\n\t\t\t/*\n\t\t\t * Send an ACK to resynchronize and drop any data.\n\t\t\t * But keep on processing for RST or ACK.\n\t\t\t */\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttodrop = ti->ti_len;\n\t\t}\n\t\tm_adj(m, todrop);\n\t\tti->ti_seq += todrop;\n\t\tti->ti_len -= todrop;\n\t\tif (ti->ti_urp > todrop)\n\t\t\tti->ti_urp -= todrop;\n\t\telse {\n\t\t\ttiflags &= ~TH_URG;\n\t\t\tti->ti_urp = 0;\n\t\t}\n\t}\n\t/*\n\t * If new data are received on a connection after the\n\t * user processes are gone, then RST the other end.\n\t */\n\tif ((so->so_state & SS_NOFDREF) &&\n\t tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {\n\t\ttp = tcp_close(tp);\n\t\tgoto dropwithreset;\n\t}\n\n\t/*\n\t * If segment ends after window, drop trailing data\n\t * (and PUSH and FIN); if nothing left, just ACK.\n\t */\n\ttodrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);\n\tif (todrop > 0) {\n\t\tif (todrop >= ti->ti_len) {\n\t\t\t/*\n\t\t\t * If a new connection request is received\n\t\t\t * while in TIME_WAIT, drop the old connection\n\t\t\t * and start over if the sequence numbers\n\t\t\t * are above the previous ones.\n\t\t\t */\n\t\t\tif (tiflags & TH_SYN &&\n\t\t\t tp->t_state == TCPS_TIME_WAIT &&\n\t\t\t SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {\n\t\t\t\tiss = tp->rcv_nxt + TCP_ISSINCR;\n\t\t\t\ttp = tcp_close(tp);\n\t\t\t\tgoto findso;\n\t\t\t}\n\t\t\t/*\n\t\t\t * If window is closed can only take segments at\n\t\t\t * window edge, and have to drop data and PUSH from\n\t\t\t * incoming segments. Continue processing, but\n\t\t\t * remember to ack. Otherwise, drop segment\n\t\t\t * and ack.\n\t\t\t */\n\t\t\tif (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {\n\t\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\t} else {\n\t\t\t\tgoto dropafterack;\n\t\t\t}\n\t\t}\n\t\tm_adj(m, -todrop);\n\t\tti->ti_len -= todrop;\n\t\ttiflags &= ~(TH_PUSH|TH_FIN);\n\t}\n\n\t/*\n\t * If the RST bit is set examine the state:\n\t * SYN_RECEIVED STATE:\n\t *\tIf passive open, return to LISTEN state.\n\t *\tIf active open, inform user that connection was refused.\n\t * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:\n\t *\tInform user that connection was reset, and close tcb.\n\t * CLOSING, LAST_ACK, TIME_WAIT STATES\n\t *\tClose the tcb.\n\t */\n\tif (tiflags&TH_RST) switch (tp->t_state) {\n\n\tcase TCPS_SYN_RECEIVED:\n\tcase TCPS_ESTABLISHED:\n\tcase TCPS_FIN_WAIT_1:\n\tcase TCPS_FIN_WAIT_2:\n\tcase TCPS_CLOSE_WAIT:\n\t\ttp->t_state = TCPS_CLOSED;\n tcp_close(tp);\n\t\tgoto drop;\n\n\tcase TCPS_CLOSING:\n\tcase TCPS_LAST_ACK:\n\tcase TCPS_TIME_WAIT:\n tcp_close(tp);\n\t\tgoto drop;\n\t}\n\n\t/*\n\t * If a SYN is in the window, then this is an\n\t * error and we send an RST and drop the connection.\n\t */\n\tif (tiflags & TH_SYN) {\n\t\ttp = tcp_drop(tp,0);\n\t\tgoto dropwithreset;\n\t}\n\n\t/*\n\t * If the ACK bit is off we drop the segment and return.\n\t */\n\tif ((tiflags & TH_ACK) == 0) goto drop;\n\n\t/*\n\t * Ack processing.\n\t */\n\tswitch (tp->t_state) {\n\t/*\n\t * In SYN_RECEIVED state if the ack ACKs our SYN then enter\n\t * ESTABLISHED state and continue processing, otherwise\n\t * send an RST. una<=ack<=max\n\t */\n\tcase TCPS_SYN_RECEIVED:\n\n\t\tif (SEQ_GT(tp->snd_una, ti->ti_ack) ||\n\t\t SEQ_GT(ti->ti_ack, tp->snd_max))\n\t\t\tgoto dropwithreset;\n\t\ttp->t_state = TCPS_ESTABLISHED;\n\t\t/*\n\t\t * The sent SYN is ack'ed with our sequence number +1\n\t\t * The first data byte already in the buffer will get\n\t\t * lost if no correction is made. This is only needed for\n\t\t * SS_CTL since the buffer is empty otherwise.\n\t\t * tp->snd_una++; or:\n\t\t */\n\t\ttp->snd_una=ti->ti_ack;\n\t\tif (so->so_state & SS_CTL) {\n\t\t /* So tcp_ctl reports the right state */\n\t\t ret = tcp_ctl(so);\n\t\t if (ret == 1) {\n\t\t soisfconnected(so);\n\t\t so->so_state &= ~SS_CTL; /* success XXX */\n\t\t } else if (ret == 2) {\n\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t so->so_state |= SS_NOFDREF; /* CTL_CMD */\n\t\t } else {\n\t\t needoutput = 1;\n\t\t tp->t_state = TCPS_FIN_WAIT_1;\n\t\t }\n\t\t} else {\n\t\t soisfconnected(so);\n\t\t}\n\n\t\t(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);\n\t\ttp->snd_wl1 = ti->ti_seq - 1;\n\t\t/* Avoid ack processing; snd_una==ti_ack => dup ack */\n\t\tgoto synrx_to_est;\n\t\t/* fall into ... */\n\n\t/*\n\t * In ESTABLISHED state: drop duplicate ACKs; ACK out of range\n\t * ACKs. If the ack is in the range\n\t *\ttp->snd_una < ti->ti_ack <= tp->snd_max\n\t * then advance tp->snd_una to ti->ti_ack and drop\n\t * data from the retransmission queue. If this ACK reflects\n\t * more up to date window information we update our window information.\n\t */\n\tcase TCPS_ESTABLISHED:\n\tcase TCPS_FIN_WAIT_1:\n\tcase TCPS_FIN_WAIT_2:\n\tcase TCPS_CLOSE_WAIT:\n\tcase TCPS_CLOSING:\n\tcase TCPS_LAST_ACK:\n\tcase TCPS_TIME_WAIT:\n\n\t\tif (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {\n\t\t\tif (ti->ti_len == 0 && tiwin == tp->snd_wnd) {\n\t\t\t DEBUG_MISC((dfd,\" dup ack m = %lx so = %lx \\n\",\n\t\t\t\t (long )m, (long )so));\n\t\t\t\t/*\n\t\t\t\t * If we have outstanding data (other than\n\t\t\t\t * a window probe), this is a completely\n\t\t\t\t * duplicate ack (ie, window info didn't\n\t\t\t\t * change), the ack is the biggest we've\n\t\t\t\t * seen and we've seen exactly our rexmt\n\t\t\t\t * threshold of them, assume a packet\n\t\t\t\t * has been dropped and retransmit it.\n\t\t\t\t * Kludge snd_nxt & the congestion\n\t\t\t\t * window so we send only this one\n\t\t\t\t * packet.\n\t\t\t\t *\n\t\t\t\t * We know we're losing at the current\n\t\t\t\t * window size so do congestion avoidance\n\t\t\t\t * (set ssthresh to half the current window\n\t\t\t\t * and pull our congestion window back to\n\t\t\t\t * the new ssthresh).\n\t\t\t\t *\n\t\t\t\t * Dup acks mean that packets have left the\n\t\t\t\t * network (they're now cached at the receiver)\n\t\t\t\t * so bump cwnd by the amount in the receiver\n\t\t\t\t * to keep a constant cwnd packets in the\n\t\t\t\t * network.\n\t\t\t\t */\n\t\t\t\tif (tp->t_timer[TCPT_REXMT] == 0 ||\n\t\t\t\t ti->ti_ack != tp->snd_una)\n\t\t\t\t\ttp->t_dupacks = 0;\n\t\t\t\telse if (++tp->t_dupacks == TCPREXMTTHRESH) {\n\t\t\t\t\ttcp_seq onxt = tp->snd_nxt;\n\t\t\t\t\tu_int win =\n\t\t\t\t\t min(tp->snd_wnd, tp->snd_cwnd) / 2 /\n\t\t\t\t\t\ttp->t_maxseg;\n\n\t\t\t\t\tif (win < 2)\n\t\t\t\t\t\twin = 2;\n\t\t\t\t\ttp->snd_ssthresh = win * tp->t_maxseg;\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\t\t\ttp->t_rtt = 0;\n\t\t\t\t\ttp->snd_nxt = ti->ti_ack;\n\t\t\t\t\ttp->snd_cwnd = tp->t_maxseg;\n\t\t\t\t\t(void) tcp_output(tp);\n\t\t\t\t\ttp->snd_cwnd = tp->snd_ssthresh +\n\t\t\t\t\t tp->t_maxseg * tp->t_dupacks;\n\t\t\t\t\tif (SEQ_GT(onxt, tp->snd_nxt))\n\t\t\t\t\t\ttp->snd_nxt = onxt;\n\t\t\t\t\tgoto drop;\n\t\t\t\t} else if (tp->t_dupacks > TCPREXMTTHRESH) {\n\t\t\t\t\ttp->snd_cwnd += tp->t_maxseg;\n\t\t\t\t\t(void) tcp_output(tp);\n\t\t\t\t\tgoto drop;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\ttp->t_dupacks = 0;\n\t\t\tbreak;\n\t\t}\n\tsynrx_to_est:\n\t\t/*\n\t\t * If the congestion window was inflated to account\n\t\t * for the other side's cached packets, retract it.\n\t\t */\n\t\tif (tp->t_dupacks > TCPREXMTTHRESH &&\n\t\t tp->snd_cwnd > tp->snd_ssthresh)\n\t\t\ttp->snd_cwnd = tp->snd_ssthresh;\n\t\ttp->t_dupacks = 0;\n\t\tif (SEQ_GT(ti->ti_ack, tp->snd_max)) {\n\t\t\tgoto dropafterack;\n\t\t}\n\t\tacked = ti->ti_ack - tp->snd_una;\n\n\t\t/*\n\t\t * If transmit timer is running and timed sequence\n\t\t * number was acked, update smoothed round trip time.\n\t\t * Since we now have an rtt measurement, cancel the\n\t\t * timer backoff (cf., Phil Karn's retransmit alg.).\n\t\t * Recompute the initial retransmit timer.\n\t\t */\n\t\tif (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))\n\t\t\ttcp_xmit_timer(tp,tp->t_rtt);\n\n\t\t/*\n\t\t * If all outstanding data is acked, stop retransmit\n\t\t * timer and remember to restart (more output or persist).\n\t\t * If there is more data to be acked, restart retransmit\n\t\t * timer, using current (possibly backed-off) value.\n\t\t */\n\t\tif (ti->ti_ack == tp->snd_max) {\n\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\tneedoutput = 1;\n\t\t} else if (tp->t_timer[TCPT_PERSIST] == 0)\n\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t/*\n\t\t * When new data is acked, open the congestion window.\n\t\t * If the window gives us less than ssthresh packets\n\t\t * in flight, open exponentially (maxseg per packet).\n\t\t * Otherwise open linearly: maxseg per window\n\t\t * (maxseg^2 / cwnd per packet).\n\t\t */\n\t\t{\n\t\t register u_int cw = tp->snd_cwnd;\n\t\t register u_int incr = tp->t_maxseg;\n\n\t\t if (cw > tp->snd_ssthresh)\n\t\t incr = incr * incr / cw;\n\t\t tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<snd_scale);\n\t\t}\n\t\tif (acked > so->so_snd.sb_cc) {\n\t\t\ttp->snd_wnd -= so->so_snd.sb_cc;\n\t\t\tsbdrop(&so->so_snd, (int )so->so_snd.sb_cc);\n\t\t\tourfinisacked = 1;\n\t\t} else {\n\t\t\tsbdrop(&so->so_snd, acked);\n\t\t\ttp->snd_wnd -= acked;\n\t\t\tourfinisacked = 0;\n\t\t}\n\t\ttp->snd_una = ti->ti_ack;\n\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_una))\n\t\t\ttp->snd_nxt = tp->snd_una;\n\n\t\tswitch (tp->t_state) {\n\n\t\t/*\n\t\t * In FIN_WAIT_1 STATE in addition to the processing\n\t\t * for the ESTABLISHED state if our FIN is now acknowledged\n\t\t * then enter FIN_WAIT_2.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_1:\n\t\t\tif (ourfinisacked) {\n\t\t\t\t/*\n\t\t\t\t * If we can't receive any more\n\t\t\t\t * data, then closing user can proceed.\n\t\t\t\t * Starting the timer is contrary to the\n\t\t\t\t * specification, but if we don't get a FIN\n\t\t\t\t * we'll hang forever.\n\t\t\t\t */\n\t\t\t\tif (so->so_state & SS_FCANTRCVMORE) {\n\t\t\t\t\ttp->t_timer[TCPT_2MSL] = TCP_MAXIDLE;\n\t\t\t\t}\n\t\t\t\ttp->t_state = TCPS_FIN_WAIT_2;\n\t\t\t}\n\t\t\tbreak;\n\n\t \t/*\n\t\t * In CLOSING STATE in addition to the processing for\n\t\t * the ESTABLISHED state if the ACK acknowledges our FIN\n\t\t * then enter the TIME-WAIT state, otherwise ignore\n\t\t * the segment.\n\t\t */\n\t\tcase TCPS_CLOSING:\n\t\t\tif (ourfinisacked) {\n\t\t\t\ttp->t_state = TCPS_TIME_WAIT;\n\t\t\t\ttcp_canceltimers(tp);\n\t\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In LAST_ACK, we may still be waiting for data to drain\n\t\t * and/or to be acked, as well as for the ack of our FIN.\n\t\t * If our FIN is now acknowledged, delete the TCB,\n\t\t * enter the closed state and return.\n\t\t */\n\t\tcase TCPS_LAST_ACK:\n\t\t\tif (ourfinisacked) {\n tcp_close(tp);\n\t\t\t\tgoto drop;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In TIME_WAIT state the only thing that should arrive\n\t\t * is a retransmission of the remote FIN. Acknowledge\n\t\t * it and restart the finack timer.\n\t\t */\n\t\tcase TCPS_TIME_WAIT:\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tgoto dropafterack;\n\t\t}\n\t} /* switch(tp->t_state) */\n\nstep6:\n\t/*\n\t * Update window information.\n\t * Don't look at window if no ACK: TAC's send garbage on first SYN.\n\t */\n\tif ((tiflags & TH_ACK) &&\n\t (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||\n\t (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||\n\t (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {\n\t\ttp->snd_wnd = tiwin;\n\t\ttp->snd_wl1 = ti->ti_seq;\n\t\ttp->snd_wl2 = ti->ti_ack;\n\t\tif (tp->snd_wnd > tp->max_sndwnd)\n\t\t\ttp->max_sndwnd = tp->snd_wnd;\n\t\tneedoutput = 1;\n\t}\n\n\t/*\n\t * Process segments with URG.\n\t */\n\tif ((tiflags & TH_URG) && ti->ti_urp &&\n\t TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\t/*\n\t\t * This is a kludge, but if we receive and accept\n\t\t * random urgent pointers, we'll crash in\n\t\t * soreceive. It's hard to imagine someone\n\t\t * actually wanting to send this much urgent data.\n\t\t */\n\t\tif (ti->ti_urp + so->so_rcv.sb_cc > so->so_rcv.sb_datalen) {\n\t\t\tti->ti_urp = 0;\n\t\t\ttiflags &= ~TH_URG;\n\t\t\tgoto dodata;\n\t\t}\n\t\t/*\n\t\t * If this segment advances the known urgent pointer,\n\t\t * then mark the data stream. This should not happen\n\t\t * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since\n\t\t * a FIN has been received from the remote side.\n\t\t * In these states we ignore the URG.\n\t\t *\n\t\t * According to RFC961 (Assigned Protocols),\n\t\t * the urgent pointer points to the last octet\n\t\t * of urgent data. We continue, however,\n\t\t * to consider it to indicate the first octet\n\t\t * of data past the urgent section as the original\n\t\t * spec states (in one of two places).\n\t\t */\n\t\tif (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {\n\t\t\ttp->rcv_up = ti->ti_seq + ti->ti_urp;\n\t\t\tso->so_urgc = so->so_rcv.sb_cc +\n\t\t\t\t(tp->rcv_up - tp->rcv_nxt); /* -1; */\n\t\t\ttp->rcv_up = ti->ti_seq + ti->ti_urp;\n\n\t\t}\n\t} else\n\t\t/*\n\t\t * If no out of band data is expected,\n\t\t * pull receive urgent pointer along\n\t\t * with the receive window.\n\t\t */\n\t\tif (SEQ_GT(tp->rcv_nxt, tp->rcv_up))\n\t\t\ttp->rcv_up = tp->rcv_nxt;\ndodata:\n\n\t/*\n\t * Process the segment text, merging it into the TCP sequencing queue,\n\t * and arranging for acknowledgment of receipt if necessary.\n\t * This process logically involves adjusting tp->rcv_wnd as data\n\t * is presented to the user (this happens in tcp_usrreq.c,\n\t * case PRU_RCVD). If a FIN has already been received on this\n\t * connection then we just ignore the text.\n\t */\n\tif ((ti->ti_len || (tiflags&TH_FIN)) &&\n\t TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\tTCP_REASS(tp, ti, m, so, tiflags);\n\t} else {\n\t\tm_free(m);\n\t\ttiflags &= ~TH_FIN;\n\t}\n\n\t/*\n\t * If FIN is received ACK the FIN and let the user know\n\t * that the connection is closing.\n\t */\n\tif (tiflags & TH_FIN) {\n\t\tif (TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\t\t/*\n\t\t\t * If we receive a FIN we can't send more data,\n\t\t\t * set it SS_FDRAIN\n * Shutdown the socket if there is no rx data in the\n\t\t\t * buffer.\n\t\t\t * soread() is called on completion of shutdown() and\n\t\t\t * will got to TCPS_LAST_ACK, and use tcp_output()\n\t\t\t * to send the FIN.\n\t\t\t */\n\t\t\tsofwdrain(so);\n\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttp->rcv_nxt++;\n\t\t}\n\t\tswitch (tp->t_state) {\n\n\t \t/*\n\t\t * In SYN_RECEIVED and ESTABLISHED STATES\n\t\t * enter the CLOSE_WAIT state.\n\t\t */\n\t\tcase TCPS_SYN_RECEIVED:\n\t\tcase TCPS_ESTABLISHED:\n\t\t if(so->so_emu == EMU_CTL) /* no shutdown on socket */\n\t\t tp->t_state = TCPS_LAST_ACK;\n\t\t else\n\t\t tp->t_state = TCPS_CLOSE_WAIT;\n\t\t break;\n\n\t \t/*\n\t\t * If still in FIN_WAIT_1 STATE FIN has not been acked so\n\t\t * enter the CLOSING state.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_1:\n\t\t\ttp->t_state = TCPS_CLOSING;\n\t\t\tbreak;\n\n\t \t/*\n\t\t * In FIN_WAIT_2 state enter the TIME_WAIT state,\n\t\t * starting the time-wait timer, turning off the other\n\t\t * standard timers.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_2:\n\t\t\ttp->t_state = TCPS_TIME_WAIT;\n\t\t\ttcp_canceltimers(tp);\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In TIME_WAIT state restart the 2 MSL time_wait timer.\n\t\t */\n\t\tcase TCPS_TIME_WAIT:\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/*\n\t * If this is a small packet, then ACK now - with Nagel\n\t * congestion avoidance sender won't send more until\n\t * he gets an ACK.\n\t *\n\t * See above.\n\t */\n\tif (ti->ti_len && (unsigned)ti->ti_len <= 5 &&\n\t ((struct tcpiphdr_2 *)ti)->first_char == (char)27) {\n\t\ttp->t_flags |= TF_ACKNOW;\n\t}\n\n\t/*\n\t * Return any desired output.\n\t */\n\tif (needoutput || (tp->t_flags & TF_ACKNOW)) {\n\t\t(void) tcp_output(tp);\n\t}\n\treturn;\n\ndropafterack:\n\t/*\n\t * Generate an ACK dropping incoming segment if it occupies\n\t * sequence space, where the ACK reflects our state.\n\t */\n\tif (tiflags & TH_RST)\n\t\tgoto drop;\n\tm_freem(m);\n\ttp->t_flags |= TF_ACKNOW;\n\t(void) tcp_output(tp);\n\treturn;\n\ndropwithreset:\n\t/* reuses m if m!=NULL, m_free() unnecessary */\n\tif (tiflags & TH_ACK)\n\t\ttcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);\n\telse {\n\t\tif (tiflags & TH_SYN) ti->ti_len++;\n\t\ttcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,\n\t\t TH_RST|TH_ACK);\n\t}\n\n\treturn;\n\ndrop:\n\t/*\n\t * Drop space held by incoming segment and return.\n\t */\n\tm_free(m);\n\n\treturn;\n}\n\nstatic void\ntcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcpiphdr *ti)\n{\n\tuint16_t mss;\n\tint opt, optlen;\n\n\tDEBUG_CALL(\"tcp_dooptions\");\n\tDEBUG_ARGS((dfd,\" tp = %lx cnt=%i \\n\", (long )tp, cnt));\n\n\tfor (; cnt > 0; cnt -= optlen, cp += optlen) {\n\t\topt = cp[0];\n\t\tif (opt == TCPOPT_EOL)\n\t\t\tbreak;\n\t\tif (opt == TCPOPT_NOP)\n\t\t\toptlen = 1;\n\t\telse {\n\t\t\toptlen = cp[1];\n\t\t\tif (optlen <= 0)\n\t\t\t\tbreak;\n\t\t}\n\t\tswitch (opt) {\n\n\t\tdefault:\n\t\t\tcontinue;\n\n\t\tcase TCPOPT_MAXSEG:\n\t\t\tif (optlen != TCPOLEN_MAXSEG)\n\t\t\t\tcontinue;\n\t\t\tif (!(ti->ti_flags & TH_SYN))\n\t\t\t\tcontinue;\n\t\t\tmemcpy((char *) &mss, (char *) cp + 2, sizeof(mss));\n\t\t\tNTOHS(mss);\n\t\t\t(void) tcp_mss(tp, mss);\t/* sets t_maxseg */\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n/*\n * Pull out of band byte out of a segment so\n * it doesn't appear in the user's data queue.\n * It is still reflected in the segment length for\n * sequencing purposes.\n */\n\n#ifdef notdef\n\nvoid\ntcp_pulloutofband(so, ti, m)\n\tstruct socket *so;\n\tstruct tcpiphdr *ti;\n\tregister struct mbuf *m;\n{\n\tint cnt = ti->ti_urp - 1;\n\n\twhile (cnt >= 0) {\n\t\tif (m->m_len > cnt) {\n\t\t\tchar *cp = mtod(m, caddr_t) + cnt;\n\t\t\tstruct tcpcb *tp = sototcpcb(so);\n\n\t\t\ttp->t_iobc = *cp;\n\t\t\ttp->t_oobflags |= TCPOOB_HAVEDATA;\n\t\t\tmemcpy(sp, cp+1, (unsigned)(m->m_len - cnt - 1));\n\t\t\tm->m_len--;\n\t\t\treturn;\n\t\t}\n\t\tcnt -= m->m_len;\n\t\tm = m->m_next; /* XXX WRONG! Fix it! */\n\t\tif (m == 0)\n\t\t\tbreak;\n\t}\n\tpanic(\"tcp_pulloutofband\");\n}\n\n#endif /* notdef */\n\n/*\n * Collect new round-trip time estimate\n * and update averages and current timeout.\n */\n\nstatic void\ntcp_xmit_timer(register struct tcpcb *tp, int rtt)\n{\n\tregister short delta;\n\n\tDEBUG_CALL(\"tcp_xmit_timer\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"rtt = %d\", rtt);\n\n\tif (tp->t_srtt != 0) {\n\t\t/*\n\t\t * srtt is stored as fixed point with 3 bits after the\n\t\t * binary point (i.e., scaled by 8). The following magic\n\t\t * is equivalent to the smoothing algorithm in rfc793 with\n\t\t * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed\n\t\t * point). Adjust rtt to origin 0.\n\t\t */\n\t\tdelta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);\n\t\tif ((tp->t_srtt += delta) <= 0)\n\t\t\ttp->t_srtt = 1;\n\t\t/*\n\t\t * We accumulate a smoothed rtt variance (actually, a\n\t\t * smoothed mean difference), then set the retransmit\n\t\t * timer to smoothed rtt + 4 times the smoothed variance.\n\t\t * rttvar is stored as fixed point with 2 bits after the\n\t\t * binary point (scaled by 4). The following is\n\t\t * equivalent to rfc793 smoothing with an alpha of .75\n\t\t * (rttvar = rttvar*3/4 + |delta| / 4). This replaces\n\t\t * rfc793's wired-in beta.\n\t\t */\n\t\tif (delta < 0)\n\t\t\tdelta = -delta;\n\t\tdelta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);\n\t\tif ((tp->t_rttvar += delta) <= 0)\n\t\t\ttp->t_rttvar = 1;\n\t} else {\n\t\t/*\n\t\t * No rtt measurement yet - use the unsmoothed rtt.\n\t\t * Set the variance to half the rtt (so our first\n\t\t * retransmit happens at 3*rtt).\n\t\t */\n\t\ttp->t_srtt = rtt << TCP_RTT_SHIFT;\n\t\ttp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);\n\t}\n\ttp->t_rtt = 0;\n\ttp->t_rxtshift = 0;\n\n\t/*\n\t * the retransmit should happen at rtt + 4 * rttvar.\n\t * Because of the way we do the smoothing, srtt and rttvar\n\t * will each average +1/2 tick of bias. When we compute\n\t * the retransmit timer, we want 1/2 tick of rounding and\n\t * 1 extra tick because of +-1/2 tick uncertainty in the\n\t * firing of the timer. The bias will give us exactly the\n\t * 1.5 tick we need. But, because the bias is\n\t * statistical, we have to test that we don't drop below\n\t * the minimum feasible timer (which is 2 ticks).\n\t */\n\tTCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),\n\t (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */\n\n\t/*\n\t * We received an ack for a packet that wasn't retransmitted;\n\t * it is probably safe to discard any error indications we've\n\t * received recently. This isn't quite right, but close enough\n\t * for now (a route might have failed after we sent a segment,\n\t * and the return path might not be symmetrical).\n\t */\n\ttp->t_softerror = 0;\n}\n\n/*\n * Determine a reasonable value for maxseg size.\n * If the route is known, check route for mtu.\n * If none, use an mss that can be handled on the outgoing\n * interface without forcing IP to fragment; if bigger than\n * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES\n * to utilize large mbufs. If no route is found, route has no mtu,\n * or the destination isn't local, use a default, hopefully conservative\n * size (usually 512 or the default IP max size, but no more than the mtu\n * of the interface), as we can't discover anything about intervening\n * gateways or networks. We also initialize the congestion/slow start\n * window to be a single segment if the destination isn't local.\n * While looking at the routing entry, we also initialize other path-dependent\n * parameters from pre-set or cached values in the routing entry.\n */\n\nint\ntcp_mss(struct tcpcb *tp, u_int offer)\n{\n\tstruct socket *so = tp->t_socket;\n\tint mss;\n\n\tDEBUG_CALL(\"tcp_mss\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"offer = %d\", offer);\n\n\tmss = min(IF_MTU, IF_MRU) - sizeof(struct tcpiphdr);\n\tif (offer)\n\t\tmss = min(mss, offer);\n\tmss = max(mss, 32);\n\tif (mss < tp->t_maxseg || offer != 0)\n\t tp->t_maxseg = mss;\n\n\ttp->snd_cwnd = mss;\n\n\tsbreserve(&so->so_snd, TCP_SNDSPACE + ((TCP_SNDSPACE % mss) ?\n (mss - (TCP_SNDSPACE % mss)) :\n 0));\n\tsbreserve(&so->so_rcv, TCP_RCVSPACE + ((TCP_RCVSPACE % mss) ?\n (mss - (TCP_RCVSPACE % mss)) :\n 0));\n\n\tDEBUG_MISC((dfd, \" returning mss = %d\\n\", mss));\n\n\treturn mss;\n}\n"], ["/linuxpdf/tinyemu/sdl.c", "/*\n * SDL display driver\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"cutils.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n#define KEYCODE_MAX 127\n\nstatic SDL_Surface *screen;\nstatic SDL_Surface *fb_surface;\nstatic int screen_width, screen_height, fb_width, fb_height, fb_stride;\nstatic SDL_Cursor *sdl_cursor_hidden;\nstatic uint8_t key_pressed[KEYCODE_MAX + 1];\n\nstatic void sdl_update_fb_surface(FBDevice *fb_dev)\n{\n if (!fb_surface)\n goto force_alloc;\n if (fb_width != fb_dev->width ||\n fb_height != fb_dev->height ||\n fb_stride != fb_dev->stride) {\n force_alloc:\n if (fb_surface != NULL)\n SDL_FreeSurface(fb_surface);\n fb_width = fb_dev->width;\n fb_height = fb_dev->height;\n fb_stride = fb_dev->stride;\n fb_surface = SDL_CreateRGBSurfaceFrom(fb_dev->fb_data,\n fb_dev->width, fb_dev->height,\n 32, fb_dev->stride,\n 0x00ff0000,\n 0x0000ff00,\n 0x000000ff,\n 0x00000000);\n if (!fb_surface) {\n fprintf(stderr, \"Could not create SDL framebuffer surface\\n\");\n exit(1);\n }\n }\n}\n\nstatic void sdl_update(FBDevice *fb_dev, void *opaque,\n int x, int y, int w, int h)\n{\n SDL_Rect r;\n // printf(\"sdl_update: %d %d %d %d\\n\", x, y, w, h);\n r.x = x;\n r.y = y;\n r.w = w;\n r.h = h;\n SDL_BlitSurface(fb_surface, &r, screen, &r);\n SDL_UpdateRect(screen, r.x, r.y, r.w, r.h);\n}\n\n#if defined(_WIN32)\n\nstatic int sdl_get_keycode(const SDL_KeyboardEvent *ev)\n{\n return ev->keysym.scancode;\n}\n\n#else\n\n/* we assume Xorg is used with a PC keyboard. Return 0 if no keycode found. */\nstatic int sdl_get_keycode(const SDL_KeyboardEvent *ev)\n{\n int keycode;\n keycode = ev->keysym.scancode;\n if (keycode < 9) {\n keycode = 0;\n } else if (keycode < 127 + 8) {\n keycode -= 8;\n } else {\n keycode = 0;\n }\n return keycode;\n}\n\n#endif\n\n/* release all pressed keys */\nstatic void sdl_reset_keys(VirtMachine *m)\n{\n int i;\n \n for(i = 1; i <= KEYCODE_MAX; i++) {\n if (key_pressed[i]) {\n vm_send_key_event(m, FALSE, i);\n key_pressed[i] = FALSE;\n }\n }\n}\n\nstatic void sdl_handle_key_event(const SDL_KeyboardEvent *ev, VirtMachine *m)\n{\n int keycode, keypress;\n\n keycode = sdl_get_keycode(ev);\n if (keycode) {\n if (keycode == 0x3a || keycode ==0x45) {\n /* SDL does not generate key up for numlock & caps lock */\n vm_send_key_event(m, TRUE, keycode);\n vm_send_key_event(m, FALSE, keycode);\n } else {\n keypress = (ev->type == SDL_KEYDOWN);\n if (keycode <= KEYCODE_MAX)\n key_pressed[keycode] = keypress;\n vm_send_key_event(m, keypress, keycode);\n }\n } else if (ev->type == SDL_KEYUP) {\n /* workaround to reset the keyboard state (used when changing\n desktop with ctrl-alt-x on Linux) */\n sdl_reset_keys(m);\n }\n}\n\nstatic void sdl_send_mouse_event(VirtMachine *m, int x1, int y1,\n int dz, int state, BOOL is_absolute)\n{\n int buttons, x, y;\n\n buttons = 0;\n if (state & SDL_BUTTON(SDL_BUTTON_LEFT))\n buttons |= (1 << 0);\n if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))\n buttons |= (1 << 1);\n if (state & SDL_BUTTON(SDL_BUTTON_MIDDLE))\n buttons |= (1 << 2);\n if (is_absolute) {\n x = (x1 * 32768) / screen_width;\n y = (y1 * 32768) / screen_height;\n } else {\n x = x1;\n y = y1;\n }\n vm_send_mouse_event(m, x, y, dz, buttons);\n}\n\nstatic void sdl_handle_mouse_motion_event(const SDL_Event *ev, VirtMachine *m)\n{\n BOOL is_absolute = vm_mouse_is_absolute(m);\n int x, y;\n if (is_absolute) {\n x = ev->motion.x;\n y = ev->motion.y;\n } else {\n x = ev->motion.xrel;\n y = ev->motion.yrel;\n }\n sdl_send_mouse_event(m, x, y, 0, ev->motion.state, is_absolute);\n}\n\nstatic void sdl_handle_mouse_button_event(const SDL_Event *ev, VirtMachine *m)\n{\n BOOL is_absolute = vm_mouse_is_absolute(m);\n int state, dz;\n\n dz = 0;\n if (ev->type == SDL_MOUSEBUTTONDOWN) {\n if (ev->button.button == SDL_BUTTON_WHEELUP) {\n dz = 1;\n } else if (ev->button.button == SDL_BUTTON_WHEELDOWN) {\n dz = -1;\n }\n }\n \n state = SDL_GetMouseState(NULL, NULL);\n /* just in case */\n if (ev->type == SDL_MOUSEBUTTONDOWN)\n state |= SDL_BUTTON(ev->button.button);\n else\n state &= ~SDL_BUTTON(ev->button.button);\n\n if (is_absolute) {\n sdl_send_mouse_event(m, ev->button.x, ev->button.y,\n dz, state, is_absolute);\n } else {\n sdl_send_mouse_event(m, 0, 0, dz, state, is_absolute);\n }\n}\n\nvoid sdl_refresh(VirtMachine *m)\n{\n SDL_Event ev_s, *ev = &ev_s;\n\n if (!m->fb_dev)\n return;\n \n sdl_update_fb_surface(m->fb_dev);\n\n m->fb_dev->refresh(m->fb_dev, sdl_update, NULL);\n \n while (SDL_PollEvent(ev)) {\n switch (ev->type) {\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n sdl_handle_key_event(&ev->key, m);\n break;\n case SDL_MOUSEMOTION:\n sdl_handle_mouse_motion_event(ev, m);\n break;\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n sdl_handle_mouse_button_event(ev, m);\n break;\n case SDL_QUIT:\n exit(0);\n }\n }\n}\n\nstatic void sdl_hide_cursor(void)\n{\n uint8_t data = 0;\n sdl_cursor_hidden = SDL_CreateCursor(&data, &data, 8, 1, 0, 0);\n SDL_ShowCursor(1);\n SDL_SetCursor(sdl_cursor_hidden);\n}\n\nvoid sdl_init(int width, int height)\n{\n int flags;\n \n screen_width = width;\n screen_height = height;\n\n if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE)) {\n fprintf(stderr, \"Could not initialize SDL - exiting\\n\");\n exit(1);\n }\n\n flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;\n screen = SDL_SetVideoMode(width, height, 0, flags);\n if (!screen || !screen->pixels) {\n fprintf(stderr, \"Could not open SDL display\\n\");\n exit(1);\n }\n\n SDL_WM_SetCaption(\"TinyEMU\", \"TinyEMU\");\n\n sdl_hide_cursor();\n}\n\n"], ["/linuxpdf/tinyemu/fs_disk.c", "/*\n * Filesystem on disk\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n\ntypedef struct {\n FSDevice common;\n char *root_path;\n} FSDeviceDisk;\n\nstatic void fs_close(FSDevice *fs, FSFile *f);\n\nstruct FSFile {\n uint32_t uid;\n char *path; /* complete path */\n BOOL is_opened;\n BOOL is_dir;\n union {\n int fd;\n DIR *dirp;\n } u;\n};\n\nstatic void fs_delete(FSDevice *fs, FSFile *f)\n{\n if (f->is_opened)\n fs_close(fs, f);\n free(f->path);\n free(f);\n}\n\n/* warning: path belong to fid_create() */\nstatic FSFile *fid_create(FSDevice *s1, char *path, uint32_t uid)\n{\n FSFile *f;\n f = mallocz(sizeof(*f));\n f->path = path;\n f->uid = uid;\n return f;\n}\n\n\nstatic int errno_table[][2] = {\n { P9_EPERM, EPERM },\n { P9_ENOENT, ENOENT },\n { P9_EIO, EIO },\n { P9_EEXIST, EEXIST },\n { P9_EINVAL, EINVAL },\n { P9_ENOSPC, ENOSPC },\n { P9_ENOTEMPTY, ENOTEMPTY },\n { P9_EPROTO, EPROTO },\n { P9_ENOTSUP, ENOTSUP },\n};\n\nstatic int errno_to_p9(int err)\n{\n int i;\n if (err == 0)\n return 0;\n for(i = 0; i < countof(errno_table); i++) {\n if (err == errno_table[i][1])\n return errno_table[i][0];\n }\n return P9_EINVAL;\n}\n\nstatic int open_flags[][2] = {\n { P9_O_CREAT, O_CREAT },\n { P9_O_EXCL, O_EXCL },\n // { P9_O_NOCTTY, O_NOCTTY },\n { P9_O_TRUNC, O_TRUNC },\n { P9_O_APPEND, O_APPEND },\n { P9_O_NONBLOCK, O_NONBLOCK },\n { P9_O_DSYNC, O_DSYNC },\n // { P9_O_FASYNC, O_FASYNC },\n // { P9_O_DIRECT, O_DIRECT },\n // { P9_O_LARGEFILE, O_LARGEFILE },\n // { P9_O_DIRECTORY, O_DIRECTORY },\n { P9_O_NOFOLLOW, O_NOFOLLOW },\n // { P9_O_NOATIME, O_NOATIME },\n // { P9_O_CLOEXEC, O_CLOEXEC },\n { P9_O_SYNC, O_SYNC },\n};\n\nstatic int p9_flags_to_host(int flags)\n{\n int ret, i;\n\n ret = (flags & P9_O_NOACCESS);\n for(i = 0; i < countof(open_flags); i++) {\n if (flags & open_flags[i][0])\n ret |= open_flags[i][1];\n }\n return ret;\n}\n\nstatic void stat_to_qid(FSQID *qid, const struct stat *st)\n{\n if (S_ISDIR(st->st_mode))\n qid->type = P9_QTDIR;\n else if (S_ISLNK(st->st_mode))\n qid->type = P9_QTSYMLINK;\n else\n qid->type = P9_QTFILE;\n qid->version = 0; /* no caching on client */\n qid->path = st->st_ino;\n}\n\nstatic void fs_statfs(FSDevice *fs1, FSStatFS *st)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n struct statfs st1;\n statfs(fs->root_path, &st1);\n st->f_bsize = st1.f_bsize;\n st->f_blocks = st1.f_blocks;\n st->f_bfree = st1.f_bfree;\n st->f_bavail = st1.f_bavail;\n st->f_files = st1.f_files;\n st->f_ffree = st1.f_ffree;\n}\n\nstatic char *compose_path(const char *path, const char *name)\n{\n int path_len, name_len;\n char *d;\n\n path_len = strlen(path);\n name_len = strlen(name);\n d = malloc(path_len + 1 + name_len + 1);\n memcpy(d, path, path_len);\n d[path_len] = '/';\n memcpy(d + path_len + 1, name, name_len + 1);\n return d;\n}\n\nstatic int fs_attach(FSDevice *fs1, FSFile **pf,\n FSQID *qid, uint32_t uid,\n const char *uname, const char *aname)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n struct stat st;\n FSFile *f;\n \n if (lstat(fs->root_path, &st) != 0) {\n *pf = NULL;\n return -errno_to_p9(errno);\n }\n f = fid_create(fs1, strdup(fs->root_path), uid);\n stat_to_qid(qid, &st);\n *pf = f;\n return 0;\n}\n\nstatic int fs_walk(FSDevice *fs, FSFile **pf, FSQID *qids,\n FSFile *f, int n, char **names)\n{\n char *path, *path1;\n struct stat st;\n int i;\n\n path = strdup(f->path);\n for(i = 0; i < n; i++) {\n path1 = compose_path(path, names[i]);\n if (lstat(path1, &st) != 0) {\n free(path1);\n break;\n }\n free(path);\n path = path1;\n stat_to_qid(&qids[i], &st);\n }\n *pf = fid_create(fs, path, f->uid);\n return i;\n}\n\n\nstatic int fs_mkdir(FSDevice *fs, FSQID *qid, FSFile *f,\n const char *name, uint32_t mode, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (mkdir(path, mode) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_open(FSDevice *fs, FSQID *qid, FSFile *f, uint32_t flags,\n FSOpenCompletionFunc *cb, void *opaque)\n{\n struct stat st;\n fs_close(fs, f);\n\n if (stat(f->path, &st) != 0) \n return -errno_to_p9(errno);\n stat_to_qid(qid, &st);\n \n if (flags & P9_O_DIRECTORY) {\n DIR *dirp;\n dirp = opendir(f->path);\n if (!dirp)\n return -errno_to_p9(errno);\n f->is_opened = TRUE;\n f->is_dir = TRUE;\n f->u.dirp = dirp;\n } else {\n int fd;\n fd = open(f->path, p9_flags_to_host(flags) & ~O_CREAT);\n if (fd < 0)\n return -errno_to_p9(errno);\n f->is_opened = TRUE;\n f->is_dir = FALSE;\n f->u.fd = fd;\n }\n return 0;\n}\n\nstatic int fs_create(FSDevice *fs, FSQID *qid, FSFile *f, const char *name, \n uint32_t flags, uint32_t mode, uint32_t gid)\n{\n struct stat st;\n char *path;\n int ret, fd;\n\n fs_close(fs, f);\n \n path = compose_path(f->path, name);\n fd = open(path, p9_flags_to_host(flags) | O_CREAT, mode);\n if (fd < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n ret = lstat(path, &st);\n if (ret != 0) {\n free(path);\n close(fd);\n return -errno_to_p9(errno);\n }\n free(f->path);\n f->path = path;\n f->is_opened = TRUE;\n f->is_dir = FALSE;\n f->u.fd = fd;\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_readdir(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n struct dirent *de;\n int len, pos, name_len, type, d_type;\n\n if (!f->is_opened || !f->is_dir)\n return -P9_EPROTO;\n if (offset == 0)\n rewinddir(f->u.dirp);\n else\n seekdir(f->u.dirp, offset);\n pos = 0;\n for(;;) {\n de = readdir(f->u.dirp);\n if (de == NULL)\n break;\n name_len = strlen(de->d_name);\n len = 13 + 8 + 1 + 2 + name_len;\n if ((pos + len) > count)\n break;\n offset = telldir(f->u.dirp);\n d_type = de->d_type;\n if (d_type == DT_UNKNOWN) {\n char *path;\n struct stat st;\n path = compose_path(f->path, de->d_name);\n if (lstat(path, &st) == 0) {\n d_type = st.st_mode >> 12;\n } else {\n d_type = DT_REG; /* default */\n }\n free(path);\n }\n if (d_type == DT_DIR)\n type = P9_QTDIR;\n else if (d_type == DT_LNK)\n type = P9_QTSYMLINK;\n else\n type = P9_QTFILE;\n buf[pos++] = type;\n put_le32(buf + pos, 0); /* version */\n pos += 4;\n put_le64(buf + pos, de->d_ino);\n pos += 8;\n put_le64(buf + pos, offset);\n pos += 8;\n buf[pos++] = d_type;\n put_le16(buf + pos, name_len);\n pos += 2;\n memcpy(buf + pos, de->d_name, name_len);\n pos += name_len;\n }\n return pos;\n}\n\nstatic int fs_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n int ret;\n\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n ret = pread(f->u.fd, buf, count, offset);\n if (ret < 0) \n return -errno_to_p9(errno);\n else\n return ret;\n}\n\nstatic int fs_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int count)\n{\n int ret;\n\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n ret = pwrite(f->u.fd, buf, count, offset);\n if (ret < 0) \n return -errno_to_p9(errno);\n else\n return ret;\n}\n\nstatic void fs_close(FSDevice *fs, FSFile *f)\n{\n if (!f->is_opened)\n return;\n if (f->is_dir)\n closedir(f->u.dirp);\n else\n close(f->u.fd);\n f->is_opened = FALSE;\n}\n\nstatic int fs_stat(FSDevice *fs, FSFile *f, FSStat *st)\n{\n struct stat st1;\n\n if (lstat(f->path, &st1) != 0)\n return -P9_ENOENT;\n stat_to_qid(&st->qid, &st1);\n st->st_mode = st1.st_mode;\n st->st_uid = st1.st_uid;\n st->st_gid = st1.st_gid;\n st->st_nlink = st1.st_nlink;\n st->st_rdev = st1.st_rdev;\n st->st_size = st1.st_size;\n st->st_blksize = st1.st_blksize;\n st->st_blocks = st1.st_blocks;\n st->st_atime_sec = st1.st_atim.tv_sec;\n st->st_atime_nsec = st1.st_atim.tv_nsec;\n st->st_mtime_sec = st1.st_mtim.tv_sec;\n st->st_mtime_nsec = st1.st_mtim.tv_nsec;\n st->st_ctime_sec = st1.st_ctim.tv_sec;\n st->st_ctime_nsec = st1.st_ctim.tv_nsec;\n return 0;\n}\n\nstatic int fs_setattr(FSDevice *fs, FSFile *f, uint32_t mask,\n uint32_t mode, uint32_t uid, uint32_t gid,\n uint64_t size, uint64_t atime_sec, uint64_t atime_nsec,\n uint64_t mtime_sec, uint64_t mtime_nsec)\n{\n BOOL ctime_updated = FALSE;\n\n if (mask & (P9_SETATTR_UID | P9_SETATTR_GID)) {\n if (lchown(f->path, (mask & P9_SETATTR_UID) ? uid : -1,\n (mask & P9_SETATTR_GID) ? gid : -1) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n /* must be done after uid change for suid */\n if (mask & P9_SETATTR_MODE) {\n if (chmod(f->path, mode) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if (mask & P9_SETATTR_SIZE) {\n if (truncate(f->path, size) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if (mask & (P9_SETATTR_ATIME | P9_SETATTR_MTIME)) {\n struct timespec ts[2];\n if (mask & P9_SETATTR_ATIME) {\n if (mask & P9_SETATTR_ATIME_SET) {\n ts[0].tv_sec = atime_sec;\n ts[0].tv_nsec = atime_nsec;\n } else {\n ts[0].tv_sec = 0;\n ts[0].tv_nsec = UTIME_NOW;\n }\n } else {\n ts[0].tv_sec = 0;\n ts[0].tv_nsec = UTIME_OMIT;\n }\n if (mask & P9_SETATTR_MTIME) {\n if (mask & P9_SETATTR_MTIME_SET) {\n ts[1].tv_sec = mtime_sec;\n ts[1].tv_nsec = mtime_nsec;\n } else {\n ts[1].tv_sec = 0;\n ts[1].tv_nsec = UTIME_NOW;\n }\n } else {\n ts[1].tv_sec = 0;\n ts[1].tv_nsec = UTIME_OMIT;\n }\n if (utimensat(AT_FDCWD, f->path, ts, AT_SYMLINK_NOFOLLOW) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if ((mask & P9_SETATTR_CTIME) && !ctime_updated) {\n if (lchown(f->path, -1, -1) < 0)\n return -errno_to_p9(errno);\n }\n return 0;\n}\n\nstatic int fs_link(FSDevice *fs, FSFile *df, FSFile *f, const char *name)\n{\n char *path;\n \n path = compose_path(df->path, name);\n if (link(f->path, path) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n return 0;\n}\n\nstatic int fs_symlink(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, const char *symgt, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (symlink(symgt, path) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_mknod(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, uint32_t mode, uint32_t major,\n uint32_t minor, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (mknod(path, mode, makedev(major, minor)) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_readlink(FSDevice *fs, char *buf, int buf_size, FSFile *f)\n{\n int ret;\n ret = readlink(f->path, buf, buf_size - 1);\n if (ret < 0)\n return -errno_to_p9(errno);\n buf[ret] = '\\0';\n return 0;\n}\n\nstatic int fs_renameat(FSDevice *fs, FSFile *f, const char *name, \n FSFile *new_f, const char *new_name)\n{\n char *path, *new_path;\n int ret;\n\n path = compose_path(f->path, name);\n new_path = compose_path(new_f->path, new_name);\n ret = rename(path, new_path);\n free(path);\n free(new_path);\n if (ret < 0)\n return -errno_to_p9(errno);\n return 0;\n}\n\nstatic int fs_unlinkat(FSDevice *fs, FSFile *f, const char *name)\n{\n char *path;\n int ret;\n\n path = compose_path(f->path, name);\n ret = remove(path);\n free(path);\n if (ret < 0)\n return -errno_to_p9(errno);\n return 0;\n \n}\n\nstatic int fs_lock(FSDevice *fs, FSFile *f, const FSLock *lock)\n{\n int ret;\n struct flock fl;\n \n /* XXX: lock directories too */\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n\n fl.l_type = lock->type;\n fl.l_whence = SEEK_SET;\n fl.l_start = lock->start;\n fl.l_len = lock->length;\n \n ret = fcntl(f->u.fd, F_SETLK, &fl);\n if (ret == 0) {\n ret = P9_LOCK_SUCCESS;\n } else if (errno == EAGAIN || errno == EACCES) {\n ret = P9_LOCK_BLOCKED;\n } else {\n ret = -errno_to_p9(errno);\n }\n return ret;\n}\n\nstatic int fs_getlock(FSDevice *fs, FSFile *f, FSLock *lock)\n{\n int ret;\n struct flock fl;\n \n /* XXX: lock directories too */\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n\n fl.l_type = lock->type;\n fl.l_whence = SEEK_SET;\n fl.l_start = lock->start;\n fl.l_len = lock->length;\n\n ret = fcntl(f->u.fd, F_GETLK, &fl);\n if (ret < 0) {\n ret = -errno_to_p9(errno);\n } else {\n lock->type = fl.l_type;\n lock->start = fl.l_start;\n lock->length = fl.l_len;\n }\n return ret;\n}\n\nstatic void fs_disk_end(FSDevice *fs1)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n free(fs->root_path);\n}\n\nFSDevice *fs_disk_init(const char *root_path)\n{\n FSDeviceDisk *fs;\n struct stat st;\n\n lstat(root_path, &st);\n if (!S_ISDIR(st.st_mode))\n return NULL;\n\n fs = mallocz(sizeof(*fs));\n\n fs->common.fs_end = fs_disk_end;\n fs->common.fs_delete = fs_delete;\n fs->common.fs_statfs = fs_statfs;\n fs->common.fs_attach = fs_attach;\n fs->common.fs_walk = fs_walk;\n fs->common.fs_mkdir = fs_mkdir;\n fs->common.fs_open = fs_open;\n fs->common.fs_create = fs_create;\n fs->common.fs_stat = fs_stat;\n fs->common.fs_setattr = fs_setattr;\n fs->common.fs_close = fs_close;\n fs->common.fs_readdir = fs_readdir;\n fs->common.fs_read = fs_read;\n fs->common.fs_write = fs_write;\n fs->common.fs_link = fs_link;\n fs->common.fs_symlink = fs_symlink;\n fs->common.fs_mknod = fs_mknod;\n fs->common.fs_readlink = fs_readlink;\n fs->common.fs_renameat = fs_renameat;\n fs->common.fs_unlinkat = fs_unlinkat;\n fs->common.fs_lock = fs_lock;\n fs->common.fs_getlock = fs_getlock;\n \n fs->root_path = strdup(root_path);\n return (FSDevice *)fs;\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_icmp.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_icmp.c\t8.2 (Berkeley) 1/4/94\n * ip_icmp.c,v 1.7 1995/05/30 08:09:42 rgrimes Exp\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n/* The message sent when emulating PING */\n/* Be nice and tell them it's just a pseudo-ping packet */\nstatic const char icmp_ping_msg[] = \"This is a pseudo-PING packet used by Slirp to emulate ICMP ECHO-REQUEST packets.\\n\";\n\n/* list of actions for icmp_error() on RX of an icmp message */\nstatic const int icmp_flush[19] = {\n/* ECHO REPLY (0) */ 0,\n\t\t 1,\n\t\t 1,\n/* DEST UNREACH (3) */ 1,\n/* SOURCE QUENCH (4)*/ 1,\n/* REDIRECT (5) */ 1,\n\t\t 1,\n\t\t 1,\n/* ECHO (8) */ 0,\n/* ROUTERADVERT (9) */ 1,\n/* ROUTERSOLICIT (10) */ 1,\n/* TIME EXCEEDED (11) */ 1,\n/* PARAMETER PROBLEM (12) */ 1,\n/* TIMESTAMP (13) */ 0,\n/* TIMESTAMP REPLY (14) */ 0,\n/* INFO (15) */ 0,\n/* INFO REPLY (16) */ 0,\n/* ADDR MASK (17) */ 0,\n/* ADDR MASK REPLY (18) */ 0\n};\n\n/*\n * Process a received ICMP message.\n */\nvoid\nicmp_input(struct mbuf *m, int hlen)\n{\n register struct icmp *icp;\n register struct ip *ip=mtod(m, struct ip *);\n int icmplen=ip->ip_len;\n Slirp *slirp = m->slirp;\n\n DEBUG_CALL(\"icmp_input\");\n DEBUG_ARG(\"m = %lx\", (long )m);\n DEBUG_ARG(\"m_len = %d\", m->m_len);\n\n /*\n * Locate icmp structure in mbuf, and check\n * that its not corrupted and of at least minimum length.\n */\n if (icmplen < ICMP_MINLEN) { /* min 8 bytes payload */\n freeit:\n m_freem(m);\n goto end_error;\n }\n\n m->m_len -= hlen;\n m->m_data += hlen;\n icp = mtod(m, struct icmp *);\n if (cksum(m, icmplen)) {\n goto freeit;\n }\n m->m_len += hlen;\n m->m_data -= hlen;\n\n DEBUG_ARG(\"icmp_type = %d\", icp->icmp_type);\n switch (icp->icmp_type) {\n case ICMP_ECHO:\n icp->icmp_type = ICMP_ECHOREPLY;\n ip->ip_len += hlen;\t /* since ip_input subtracts this */\n if (ip->ip_dst.s_addr == slirp->vhost_addr.s_addr) {\n icmp_reflect(m);\n } else {\n struct socket *so;\n struct sockaddr_in addr;\n if ((so = socreate(slirp)) == NULL) goto freeit;\n if(udp_attach(so) == -1) {\n\tDEBUG_MISC((dfd,\"icmp_input udp_attach errno = %d-%s\\n\",\n\t\t errno,strerror(errno)));\n\tsofree(so);\n\tm_free(m);\n\tgoto end_error;\n }\n so->so_m = m;\n so->so_faddr = ip->ip_dst;\n so->so_fport = htons(7);\n so->so_laddr = ip->ip_src;\n so->so_lport = htons(9);\n so->so_iptos = ip->ip_tos;\n so->so_type = IPPROTO_ICMP;\n so->so_state = SS_ISFCONNECTED;\n\n /* Send the packet */\n addr.sin_family = AF_INET;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n\t/* It's an alias */\n\tif (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\t if (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n\t} else {\n\t addr.sin_addr = loopback_addr;\n\t}\n } else {\n\taddr.sin_addr = so->so_faddr;\n }\n addr.sin_port = so->so_fport;\n if(sendto(so->s, icmp_ping_msg, strlen(icmp_ping_msg), 0,\n\t\t(struct sockaddr *)&addr, sizeof(addr)) == -1) {\n\tDEBUG_MISC((dfd,\"icmp_input udp sendto tx errno = %d-%s\\n\",\n\t\t errno,strerror(errno)));\n\ticmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));\n\tudp_detach(so);\n }\n } /* if ip->ip_dst.s_addr == alias_addr.s_addr */\n break;\n case ICMP_UNREACH:\n /* XXX? report error? close socket? */\n case ICMP_TIMXCEED:\n case ICMP_PARAMPROB:\n case ICMP_SOURCEQUENCH:\n case ICMP_TSTAMP:\n case ICMP_MASKREQ:\n case ICMP_REDIRECT:\n m_freem(m);\n break;\n\n default:\n m_freem(m);\n } /* swith */\n\nend_error:\n /* m is m_free()'d xor put in a socket xor or given to ip_send */\n return;\n}\n\n\n/*\n *\tSend an ICMP message in response to a situation\n *\n *\tRFC 1122: 3.2.2\tMUST send at least the IP header and 8 bytes of header. MAY send more (we do).\n *\t\t\tMUST NOT change this header information.\n *\t\t\tMUST NOT reply to a multicast/broadcast IP address.\n *\t\t\tMUST NOT reply to a multicast/broadcast MAC address.\n *\t\t\tMUST reply to only the first fragment.\n */\n/*\n * Send ICMP_UNREACH back to the source regarding msrc.\n * mbuf *msrc is used as a template, but is NOT m_free()'d.\n * It is reported as the bad ip packet. The header should\n * be fully correct and in host byte order.\n * ICMP fragmentation is illegal. All machines must accept 576 bytes in one\n * packet. The maximum payload is 576-20(ip hdr)-8(icmp hdr)=548\n */\n\n#define ICMP_MAXDATALEN (IP_MSS-28)\nvoid\nicmp_error(struct mbuf *msrc, u_char type, u_char code, int minsize,\n const char *message)\n{\n unsigned hlen, shlen, s_ip_len;\n register struct ip *ip;\n register struct icmp *icp;\n register struct mbuf *m;\n\n DEBUG_CALL(\"icmp_error\");\n DEBUG_ARG(\"msrc = %lx\", (long )msrc);\n DEBUG_ARG(\"msrc_len = %d\", msrc->m_len);\n\n if(type!=ICMP_UNREACH && type!=ICMP_TIMXCEED) goto end_error;\n\n /* check msrc */\n if(!msrc) goto end_error;\n ip = mtod(msrc, struct ip *);\n#ifdef DEBUG\n { char bufa[20], bufb[20];\n strcpy(bufa, inet_ntoa(ip->ip_src));\n strcpy(bufb, inet_ntoa(ip->ip_dst));\n DEBUG_MISC((dfd, \" %.16s to %.16s\\n\", bufa, bufb));\n }\n#endif\n if(ip->ip_off & IP_OFFMASK) goto end_error; /* Only reply to fragment 0 */\n\n shlen=ip->ip_hl << 2;\n s_ip_len=ip->ip_len;\n if(ip->ip_p == IPPROTO_ICMP) {\n icp = (struct icmp *)((char *)ip + shlen);\n /*\n *\tAssume any unknown ICMP type is an error. This isn't\n *\tspecified by the RFC, but think about it..\n */\n if(icp->icmp_type>18 || icmp_flush[icp->icmp_type]) goto end_error;\n }\n\n /* make a copy */\n m = m_get(msrc->slirp);\n if (!m) {\n goto end_error;\n }\n\n { int new_m_size;\n new_m_size=sizeof(struct ip )+ICMP_MINLEN+msrc->m_len+ICMP_MAXDATALEN;\n if(new_m_size>m->m_size) m_inc(m, new_m_size);\n }\n memcpy(m->m_data, msrc->m_data, msrc->m_len);\n m->m_len = msrc->m_len; /* copy msrc to m */\n\n /* make the header of the reply packet */\n ip = mtod(m, struct ip *);\n hlen= sizeof(struct ip ); /* no options in reply */\n\n /* fill in icmp */\n m->m_data += hlen;\n m->m_len -= hlen;\n\n icp = mtod(m, struct icmp *);\n\n if(minsize) s_ip_len=shlen+ICMP_MINLEN; /* return header+8b only */\n else if(s_ip_len>ICMP_MAXDATALEN) /* maximum size */\n s_ip_len=ICMP_MAXDATALEN;\n\n m->m_len=ICMP_MINLEN+s_ip_len; /* 8 bytes ICMP header */\n\n /* min. size = 8+sizeof(struct ip)+8 */\n\n icp->icmp_type = type;\n icp->icmp_code = code;\n icp->icmp_id = 0;\n icp->icmp_seq = 0;\n\n memcpy(&icp->icmp_ip, msrc->m_data, s_ip_len); /* report the ip packet */\n HTONS(icp->icmp_ip.ip_len);\n HTONS(icp->icmp_ip.ip_id);\n HTONS(icp->icmp_ip.ip_off);\n\n#ifdef DEBUG\n if(message) { /* DEBUG : append message to ICMP packet */\n int message_len;\n char *cpnt;\n message_len=strlen(message);\n if(message_len>ICMP_MAXDATALEN) message_len=ICMP_MAXDATALEN;\n cpnt=(char *)m->m_data+m->m_len;\n memcpy(cpnt, message, message_len);\n m->m_len+=message_len;\n }\n#endif\n\n icp->icmp_cksum = 0;\n icp->icmp_cksum = cksum(m, m->m_len);\n\n m->m_data -= hlen;\n m->m_len += hlen;\n\n /* fill in ip */\n ip->ip_hl = hlen >> 2;\n ip->ip_len = m->m_len;\n\n ip->ip_tos=((ip->ip_tos & 0x1E) | 0xC0); /* high priority for errors */\n\n ip->ip_ttl = MAXTTL;\n ip->ip_p = IPPROTO_ICMP;\n ip->ip_dst = ip->ip_src; /* ip adresses */\n ip->ip_src = m->slirp->vhost_addr;\n\n (void ) ip_output((struct socket *)NULL, m);\n\nend_error:\n return;\n}\n#undef ICMP_MAXDATALEN\n\n/*\n * Reflect the ip packet back to the source\n */\nvoid\nicmp_reflect(struct mbuf *m)\n{\n register struct ip *ip = mtod(m, struct ip *);\n int hlen = ip->ip_hl << 2;\n int optlen = hlen - sizeof(struct ip );\n register struct icmp *icp;\n\n /*\n * Send an icmp packet back to the ip level,\n * after supplying a checksum.\n */\n m->m_data += hlen;\n m->m_len -= hlen;\n icp = mtod(m, struct icmp *);\n\n icp->icmp_cksum = 0;\n icp->icmp_cksum = cksum(m, ip->ip_len - hlen);\n\n m->m_data -= hlen;\n m->m_len += hlen;\n\n /* fill in ip */\n if (optlen > 0) {\n /*\n * Strip out original options by copying rest of first\n * mbuf's data back, and adjust the IP length.\n */\n memmove((caddr_t)(ip + 1), (caddr_t)ip + hlen,\n\t (unsigned )(m->m_len - hlen));\n hlen -= optlen;\n ip->ip_hl = hlen >> 2;\n ip->ip_len -= optlen;\n m->m_len -= optlen;\n }\n\n ip->ip_ttl = MAXTTL;\n { /* swap */\n struct in_addr icmp_dst;\n icmp_dst = ip->ip_dst;\n ip->ip_dst = ip->ip_src;\n ip->ip_src = icmp_dst;\n }\n\n (void ) ip_output((struct socket *)NULL, m);\n}\n"], ["/linuxpdf/tinyemu/build_filelist.c", "/*\n * File list builder for RISCVEMU network filesystem\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"fs_utils.h\"\n\nvoid print_str(FILE *f, const char *str)\n{\n const char *s;\n int c;\n s = str;\n while (*s != '\\0') {\n if (*s <= ' ' || *s > '~')\n goto use_quote;\n s++;\n }\n fputs(str, f);\n return;\n use_quote:\n s = str;\n fputc('\"', f);\n while (*s != '\\0') {\n c = *(uint8_t *)s;\n if (c < ' ' || c == 127) {\n fprintf(f, \"\\\\x%02x\", c);\n } else if (c == '\\\\' || c == '\\\"') {\n fprintf(f, \"\\\\%c\", c);\n } else {\n fputc(c, f);\n }\n s++;\n }\n fputc('\"', f);\n}\n\n#define COPY_BUF_LEN (1024 * 1024)\n\nstatic void copy_file(const char *src_filename, const char *dst_filename)\n{\n uint8_t *buf;\n FILE *fi, *fo;\n int len;\n \n buf = malloc(COPY_BUF_LEN);\n fi = fopen(src_filename, \"rb\");\n if (!fi) {\n perror(src_filename);\n exit(1);\n }\n fo = fopen(dst_filename, \"wb\");\n if (!fo) {\n perror(dst_filename);\n exit(1);\n }\n for(;;) {\n len = fread(buf, 1, COPY_BUF_LEN, fi);\n if (len == 0)\n break;\n fwrite(buf, 1, len, fo);\n }\n fclose(fo);\n fclose(fi);\n}\n\ntypedef struct {\n char *files_path;\n uint64_t next_inode_num;\n uint64_t fs_size;\n uint64_t fs_max_size;\n FILE *f;\n} ScanState;\n\nstatic void add_file_size(ScanState *s, uint64_t size)\n{\n s->fs_size += block_align(size, FS_BLOCK_SIZE);\n if (s->fs_size > s->fs_max_size) {\n fprintf(stderr, \"Filesystem Quota exceeded (%\" PRId64 \" bytes)\\n\", s->fs_max_size);\n exit(1);\n }\n}\n\nvoid scan_dir(ScanState *s, const char *path)\n{\n FILE *f = s->f;\n DIR *dirp;\n struct dirent *de;\n const char *name;\n struct stat st;\n char *path1;\n uint32_t mode, v;\n\n dirp = opendir(path);\n if (!dirp) {\n perror(path);\n exit(1);\n }\n for(;;) {\n de = readdir(dirp);\n if (!de)\n break;\n name = de->d_name;\n if (!strcmp(name, \".\") || !strcmp(name, \"..\"))\n continue;\n path1 = compose_path(path, name);\n if (lstat(path1, &st) < 0) {\n perror(path1);\n exit(1);\n }\n\n mode = st.st_mode & 0xffff;\n fprintf(f, \"%06o %u %u\", \n mode, \n (int)st.st_uid,\n (int)st.st_gid);\n if (S_ISCHR(mode) || S_ISBLK(mode)) {\n fprintf(f, \" %u %u\",\n (int)major(st.st_rdev),\n (int)minor(st.st_rdev));\n }\n if (S_ISREG(mode)) {\n fprintf(f, \" %\" PRIu64, st.st_size);\n }\n /* modification time (at most ms resolution) */\n fprintf(f, \" %u\", (int)st.st_mtim.tv_sec);\n v = st.st_mtim.tv_nsec;\n if (v != 0) {\n fprintf(f, \".\");\n while (v != 0) {\n fprintf(f, \"%u\", v / 100000000);\n v = (v % 100000000) * 10;\n }\n }\n \n fprintf(f, \" \");\n print_str(f, name);\n if (S_ISLNK(mode)) {\n char buf[1024];\n int len;\n len = readlink(path1, buf, sizeof(buf) - 1);\n if (len < 0) {\n perror(\"readlink\");\n exit(1);\n }\n buf[len] = '\\0';\n fprintf(f, \" \");\n print_str(f, buf);\n } else if (S_ISREG(mode) && st.st_size > 0) {\n char buf1[FILEID_SIZE_MAX], *fname;\n FSFileID file_id;\n file_id = s->next_inode_num++;\n fprintf(f, \" %\" PRIx64, file_id);\n file_id_to_filename(buf1, file_id);\n fname = compose_path(s->files_path, buf1);\n copy_file(path1, fname);\n add_file_size(s, st.st_size);\n }\n\n fprintf(f, \"\\n\");\n if (S_ISDIR(mode)) {\n scan_dir(s, path1);\n }\n free(path1);\n }\n\n closedir(dirp);\n fprintf(f, \".\\n\"); /* end of directory */\n}\n\nvoid help(void)\n{\n printf(\"usage: build_filelist [options] source_path dest_path\\n\"\n \"\\n\"\n \"Options:\\n\"\n \"-m size_mb set the max filesystem size in MiB\\n\");\n exit(1);\n}\n\n#define LOCK_FILENAME \"lock\"\n\nint main(int argc, char **argv)\n{\n const char *dst_path, *src_path;\n ScanState s_s, *s = &s_s;\n FILE *f;\n char *filename;\n FSFileID root_id;\n char fname[FILEID_SIZE_MAX];\n struct stat st;\n uint64_t first_inode, fs_max_size;\n int c;\n \n first_inode = 1;\n fs_max_size = (uint64_t)1 << 30;\n for(;;) {\n c = getopt(argc, argv, \"hi:m:\");\n if (c == -1)\n break;\n switch(c) {\n case 'h':\n help();\n case 'i':\n first_inode = strtoul(optarg, NULL, 0);\n break;\n case 'm':\n fs_max_size = (uint64_t)strtoul(optarg, NULL, 0) << 20;\n break;\n default:\n exit(1);\n }\n }\n\n if (optind + 1 >= argc)\n help();\n src_path = argv[optind];\n dst_path = argv[optind + 1];\n \n mkdir(dst_path, 0755);\n\n s->files_path = compose_path(dst_path, ROOT_FILENAME);\n s->next_inode_num = first_inode;\n s->fs_size = 0;\n s->fs_max_size = fs_max_size;\n \n mkdir(s->files_path, 0755);\n\n root_id = s->next_inode_num++;\n file_id_to_filename(fname, root_id);\n filename = compose_path(s->files_path, fname);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fprintf(f, \"Version: 1\\n\");\n fprintf(f, \"Revision: 1\\n\");\n fprintf(f, \"\\n\");\n s->f = f;\n scan_dir(s, src_path);\n fclose(f);\n\n /* take into account the filelist size */\n if (stat(filename, &st) < 0) {\n perror(filename);\n exit(1);\n }\n add_file_size(s, st.st_size);\n \n free(filename);\n \n filename = compose_path(dst_path, HEAD_FILENAME);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fprintf(f, \"Version: 1\\n\");\n fprintf(f, \"Revision: 1\\n\");\n fprintf(f, \"NextFileID: %\" PRIx64 \"\\n\", s->next_inode_num);\n fprintf(f, \"FSFileCount: %\" PRIu64 \"\\n\", s->next_inode_num - 1);\n fprintf(f, \"FSSize: %\" PRIu64 \"\\n\", s->fs_size);\n fprintf(f, \"FSMaxSize: %\" PRIu64 \"\\n\", s->fs_max_size);\n fprintf(f, \"Key:\\n\"); /* not encrypted */\n fprintf(f, \"RootID: %\" PRIx64 \"\\n\", root_id);\n fclose(f);\n free(filename);\n \n filename = compose_path(dst_path, LOCK_FILENAME);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fclose(f);\n free(filename);\n\n return 0;\n}\n"], ["/linuxpdf/tinyemu/simplefb.c", "/*\n * Simple frame buffer\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n//#define DEBUG_VBE\n\n#define FB_ALLOC_ALIGN 65536\n\nstruct SimpleFBState {\n FBDevice *fb_dev;\n int fb_page_count;\n PhysMemoryRange *mem_range;\n};\n\n#define MAX_MERGE_DISTANCE 3\n\nvoid simplefb_refresh(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque,\n PhysMemoryRange *mem_range,\n int fb_page_count)\n{\n const uint32_t *dirty_bits;\n uint32_t dirty_val;\n int y0, y1, page_y0, page_y1, byte_pos, page_index, bit_pos;\n\n dirty_bits = phys_mem_get_dirty_bits(mem_range);\n \n page_index = 0;\n y0 = y1 = 0;\n while (page_index < fb_page_count) {\n dirty_val = dirty_bits[page_index >> 5];\n if (dirty_val != 0) {\n bit_pos = 0;\n while (dirty_val != 0) {\n while (((dirty_val >> bit_pos) & 1) == 0)\n bit_pos++;\n dirty_val &= ~(1 << bit_pos);\n\n byte_pos = (page_index + bit_pos) * DEVRAM_PAGE_SIZE;\n page_y0 = byte_pos / fb_dev->stride;\n page_y1 = ((byte_pos + DEVRAM_PAGE_SIZE - 1) / fb_dev->stride) + 1;\n page_y1 = min_int(page_y1, fb_dev->height);\n if (y0 == y1) {\n y0 = page_y0;\n y1 = page_y1;\n } else if (page_y0 <= (y1 + MAX_MERGE_DISTANCE)) {\n /* union with current region */\n y1 = page_y1;\n } else {\n /* flush */\n redraw_func(fb_dev, opaque,\n 0, y0, fb_dev->width, y1 - y0);\n y0 = page_y0;\n y1 = page_y1;\n }\n }\n }\n page_index += 32;\n }\n\n if (y0 != y1) {\n redraw_func(fb_dev, opaque,\n 0, y0, fb_dev->width, y1 - y0);\n }\n}\n\nstatic void simplefb_refresh1(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n SimpleFBState *s = fb_dev->device_opaque;\n simplefb_refresh(fb_dev, redraw_func, opaque, s->mem_range,\n s->fb_page_count);\n}\n\nSimpleFBState *simplefb_init(PhysMemoryMap *map, uint64_t phys_addr,\n FBDevice *fb_dev, int width, int height)\n{\n SimpleFBState *s;\n \n s = mallocz(sizeof(*s));\n s->fb_dev = fb_dev;\n\n fb_dev->width = width;\n fb_dev->height = height;\n fb_dev->stride = width * 4;\n fb_dev->fb_size = (height * fb_dev->stride + FB_ALLOC_ALIGN - 1) & ~(FB_ALLOC_ALIGN - 1);\n s->fb_page_count = fb_dev->fb_size >> DEVRAM_PAGE_SIZE_LOG2;\n\n s->mem_range = cpu_register_ram(map, phys_addr, fb_dev->fb_size,\n DEVRAM_FLAG_DIRTY_BITS);\n \n fb_dev->fb_data = s->mem_range->phys_mem;\n fb_dev->device_opaque = s;\n fb_dev->refresh = simplefb_refresh1;\n return s;\n}\n"], ["/linuxpdf/tinyemu/slirp/udp.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)udp_usrreq.c\t8.4 (Berkeley) 1/21/94\n * udp_usrreq.c,v 1.4 1994/10/02 17:48:45 phk Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\nstatic uint8_t udp_tos(struct socket *so);\n\nvoid\nudp_init(Slirp *slirp)\n{\n slirp->udb.so_next = slirp->udb.so_prev = &slirp->udb;\n slirp->udp_last_so = &slirp->udb;\n}\n/* m->m_data points at ip packet header\n * m->m_len length ip packet\n * ip->ip_len length data (IPDU)\n */\nvoid\nudp_input(register struct mbuf *m, int iphlen)\n{\n\tSlirp *slirp = m->slirp;\n\tregister struct ip *ip;\n\tregister struct udphdr *uh;\n\tint len;\n\tstruct ip save_ip;\n\tstruct socket *so;\n\n\tDEBUG_CALL(\"udp_input\");\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"iphlen = %d\", iphlen);\n\n\t/*\n\t * Strip IP options, if any; should skip this,\n\t * make available to user, and use on returned packets,\n\t * but we don't yet have a way to check the checksum\n\t * with options still present.\n\t */\n\tif(iphlen > sizeof(struct ip)) {\n\t\tip_stripoptions(m, (struct mbuf *)0);\n\t\tiphlen = sizeof(struct ip);\n\t}\n\n\t/*\n\t * Get IP and UDP header together in first mbuf.\n\t */\n\tip = mtod(m, struct ip *);\n\tuh = (struct udphdr *)((caddr_t)ip + iphlen);\n\n\t/*\n\t * Make mbuf data length reflect UDP length.\n\t * If not enough data to reflect UDP length, drop.\n\t */\n\tlen = ntohs((uint16_t)uh->uh_ulen);\n\n\tif (ip->ip_len != len) {\n\t\tif (len > ip->ip_len) {\n\t\t\tgoto bad;\n\t\t}\n\t\tm_adj(m, len - ip->ip_len);\n\t\tip->ip_len = len;\n\t}\n\n\t/*\n\t * Save a copy of the IP header in case we want restore it\n\t * for sending an ICMP error message in response.\n\t */\n\tsave_ip = *ip;\n\tsave_ip.ip_len+= iphlen; /* tcp_input subtracts this */\n\n\t/*\n\t * Checksum extended UDP header and data.\n\t */\n\tif (uh->uh_sum) {\n memset(&((struct ipovly *)ip)->ih_mbuf, 0, sizeof(struct mbuf_ptr));\n\t ((struct ipovly *)ip)->ih_x1 = 0;\n\t ((struct ipovly *)ip)->ih_len = uh->uh_ulen;\n\t if(cksum(m, len + sizeof(struct ip))) {\n\t goto bad;\n\t }\n\t}\n\n /*\n * handle DHCP/BOOTP\n */\n if (ntohs(uh->uh_dport) == BOOTP_SERVER) {\n bootp_input(m);\n goto bad;\n }\n\n if (slirp->restricted) {\n goto bad;\n }\n\n#if 0\n /*\n * handle TFTP\n */\n if (ntohs(uh->uh_dport) == TFTP_SERVER) {\n tftp_input(m);\n goto bad;\n }\n#endif\n \n\t/*\n\t * Locate pcb for datagram.\n\t */\n\tso = slirp->udp_last_so;\n\tif (so->so_lport != uh->uh_sport ||\n\t so->so_laddr.s_addr != ip->ip_src.s_addr) {\n\t\tstruct socket *tmp;\n\n\t\tfor (tmp = slirp->udb.so_next; tmp != &slirp->udb;\n\t\t tmp = tmp->so_next) {\n\t\t\tif (tmp->so_lport == uh->uh_sport &&\n\t\t\t tmp->so_laddr.s_addr == ip->ip_src.s_addr) {\n\t\t\t\tso = tmp;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (tmp == &slirp->udb) {\n\t\t so = NULL;\n\t\t} else {\n\t\t slirp->udp_last_so = so;\n\t\t}\n\t}\n\n\tif (so == NULL) {\n\t /*\n\t * If there's no socket for this packet,\n\t * create one\n\t */\n\t so = socreate(slirp);\n\t if (!so) {\n\t goto bad;\n\t }\n\t if(udp_attach(so) == -1) {\n\t DEBUG_MISC((dfd,\" udp_attach errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t sofree(so);\n\t goto bad;\n\t }\n\n\t /*\n\t * Setup fields\n\t */\n\t so->so_laddr = ip->ip_src;\n\t so->so_lport = uh->uh_sport;\n\n\t if ((so->so_iptos = udp_tos(so)) == 0)\n\t so->so_iptos = ip->ip_tos;\n\n\t /*\n\t * XXXXX Here, check if it's in udpexec_list,\n\t * and if it is, do the fork_exec() etc.\n\t */\n\t}\n\n so->so_faddr = ip->ip_dst; /* XXX */\n so->so_fport = uh->uh_dport; /* XXX */\n\n\tiphlen += sizeof(struct udphdr);\n\tm->m_len -= iphlen;\n\tm->m_data += iphlen;\n\n\t/*\n\t * Now we sendto() the packet.\n\t */\n\tif(sosendto(so,m) == -1) {\n\t m->m_len += iphlen;\n\t m->m_data -= iphlen;\n\t *ip=save_ip;\n\t DEBUG_MISC((dfd,\"udp tx errno = %d-%s\\n\",errno,strerror(errno)));\n\t icmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));\n\t}\n\n\tm_free(so->so_m); /* used for ICMP if error on sorecvfrom */\n\n\t/* restore the orig mbuf packet */\n\tm->m_len += iphlen;\n\tm->m_data -= iphlen;\n\t*ip=save_ip;\n\tso->so_m=m; /* ICMP backup */\n\n\treturn;\nbad:\n\tm_freem(m);\n\treturn;\n}\n\nint udp_output2(struct socket *so, struct mbuf *m,\n struct sockaddr_in *saddr, struct sockaddr_in *daddr,\n int iptos)\n{\n\tregister struct udpiphdr *ui;\n\tint error = 0;\n\n\tDEBUG_CALL(\"udp_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"saddr = %lx\", (long)saddr->sin_addr.s_addr);\n\tDEBUG_ARG(\"daddr = %lx\", (long)daddr->sin_addr.s_addr);\n\n\t/*\n\t * Adjust for header\n\t */\n\tm->m_data -= sizeof(struct udpiphdr);\n\tm->m_len += sizeof(struct udpiphdr);\n\n\t/*\n\t * Fill in mbuf with extended UDP header\n\t * and addresses and length put into network format.\n\t */\n\tui = mtod(m, struct udpiphdr *);\n memset(&ui->ui_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));\n\tui->ui_x1 = 0;\n\tui->ui_pr = IPPROTO_UDP;\n\tui->ui_len = htons(m->m_len - sizeof(struct ip));\n\t/* XXXXX Check for from-one-location sockets, or from-any-location sockets */\n ui->ui_src = saddr->sin_addr;\n\tui->ui_dst = daddr->sin_addr;\n\tui->ui_sport = saddr->sin_port;\n\tui->ui_dport = daddr->sin_port;\n\tui->ui_ulen = ui->ui_len;\n\n\t/*\n\t * Stuff checksum and output datagram.\n\t */\n\tui->ui_sum = 0;\n\tif ((ui->ui_sum = cksum(m, m->m_len)) == 0)\n\t\tui->ui_sum = 0xffff;\n\t((struct ip *)ui)->ip_len = m->m_len;\n\n\t((struct ip *)ui)->ip_ttl = IPDEFTTL;\n\t((struct ip *)ui)->ip_tos = iptos;\n\n\terror = ip_output(so, m);\n\n\treturn (error);\n}\n\nint udp_output(struct socket *so, struct mbuf *m,\n struct sockaddr_in *addr)\n\n{\n Slirp *slirp = so->slirp;\n struct sockaddr_in saddr, daddr;\n\n saddr = *addr;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n uint32_t inv_mask = ~slirp->vnetwork_mask.s_addr;\n\n if ((so->so_faddr.s_addr & inv_mask) == inv_mask) {\n saddr.sin_addr = slirp->vhost_addr;\n } else if (addr->sin_addr.s_addr == loopback_addr.s_addr ||\n so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {\n saddr.sin_addr = so->so_faddr;\n }\n }\n daddr.sin_addr = so->so_laddr;\n daddr.sin_port = so->so_lport;\n\n return udp_output2(so, m, &saddr, &daddr, so->so_iptos);\n}\n\nint\nudp_attach(struct socket *so)\n{\n if((so->s = os_socket(AF_INET,SOCK_DGRAM,0)) != -1) {\n so->so_expire = curtime + SO_EXPIRE;\n insque(so, &so->slirp->udb);\n }\n return(so->s);\n}\n\nvoid\nudp_detach(struct socket *so)\n{\n\tclosesocket(so->s);\n\tsofree(so);\n}\n\nstatic const struct tos_t udptos[] = {\n\t{0, 53, IPTOS_LOWDELAY, 0},\t\t\t/* DNS */\n\t{0, 0, 0, 0}\n};\n\nstatic uint8_t\nudp_tos(struct socket *so)\n{\n\tint i = 0;\n\n\twhile(udptos[i].tos) {\n\t\tif ((udptos[i].fport && ntohs(so->so_fport) == udptos[i].fport) ||\n\t\t (udptos[i].lport && ntohs(so->so_lport) == udptos[i].lport)) {\n\t\t \tso->so_emu = udptos[i].emu;\n\t\t\treturn udptos[i].tos;\n\t\t}\n\t\ti++;\n\t}\n\n\treturn 0;\n}\n\nstruct socket *\nudp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,\n u_int lport, int flags)\n{\n\tstruct sockaddr_in addr;\n\tstruct socket *so;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in), opt = 1;\n\n\tso = socreate(slirp);\n\tif (!so) {\n\t return NULL;\n\t}\n\tso->s = os_socket(AF_INET,SOCK_DGRAM,0);\n\tso->so_expire = curtime + SO_EXPIRE;\n\tinsque(so, &slirp->udb);\n\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = haddr;\n\taddr.sin_port = hport;\n\n\tif (bind(so->s,(struct sockaddr *)&addr, addrlen) < 0) {\n\t\tudp_detach(so);\n\t\treturn NULL;\n\t}\n\tsetsockopt(so->s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\n\tgetsockname(so->s,(struct sockaddr *)&addr,&addrlen);\n\tso->so_fport = addr.sin_port;\n\tif (addr.sin_addr.s_addr == 0 ||\n\t addr.sin_addr.s_addr == loopback_addr.s_addr) {\n\t so->so_faddr = slirp->vhost_addr;\n\t} else {\n\t so->so_faddr = addr.sin_addr;\n\t}\n\tso->so_lport = lport;\n\tso->so_laddr.s_addr = laddr;\n\tif (flags != SS_FACCEPTONCE)\n\t so->so_expire = 0;\n\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= SS_ISFCONNECTED | flags;\n\n\treturn so;\n}\n"], ["/linuxpdf/tinyemu/slirp/bootp.c", "/*\n * QEMU BOOTP/DHCP server\n *\n * Copyright (c) 2004 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"slirp.h\"\n\n/* XXX: only DHCP is supported */\n\n#define LEASE_TIME (24 * 3600)\n\nstatic const uint8_t rfc1533_cookie[] = { RFC1533_COOKIE };\n\n#ifdef DEBUG\n#define DPRINTF(fmt, ...) \\\ndo if (slirp_debug & DBG_CALL) { fprintf(dfd, fmt, ## __VA_ARGS__); fflush(dfd); } while (0)\n#else\n#define DPRINTF(fmt, ...) do{}while(0)\n#endif\n\nstatic BOOTPClient *get_new_addr(Slirp *slirp, struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n BOOTPClient *bc;\n int i;\n\n for(i = 0; i < NB_BOOTP_CLIENTS; i++) {\n bc = &slirp->bootp_clients[i];\n if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6))\n goto found;\n }\n return NULL;\n found:\n bc = &slirp->bootp_clients[i];\n bc->allocated = 1;\n paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i);\n return bc;\n}\n\nstatic BOOTPClient *request_addr(Slirp *slirp, const struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n uint32_t req_addr = ntohl(paddr->s_addr);\n uint32_t dhcp_addr = ntohl(slirp->vdhcp_startaddr.s_addr);\n BOOTPClient *bc;\n\n if (req_addr >= dhcp_addr &&\n req_addr < (dhcp_addr + NB_BOOTP_CLIENTS)) {\n bc = &slirp->bootp_clients[req_addr - dhcp_addr];\n if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6)) {\n bc->allocated = 1;\n return bc;\n }\n }\n return NULL;\n}\n\nstatic BOOTPClient *find_addr(Slirp *slirp, struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n BOOTPClient *bc;\n int i;\n\n for(i = 0; i < NB_BOOTP_CLIENTS; i++) {\n if (!memcmp(macaddr, slirp->bootp_clients[i].macaddr, 6))\n goto found;\n }\n return NULL;\n found:\n bc = &slirp->bootp_clients[i];\n bc->allocated = 1;\n paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i);\n return bc;\n}\n\nstatic void dhcp_decode(const struct bootp_t *bp, int *pmsg_type,\n struct in_addr *preq_addr)\n{\n const uint8_t *p, *p_end;\n int len, tag;\n\n *pmsg_type = 0;\n preq_addr->s_addr = htonl(0L);\n\n p = bp->bp_vend;\n p_end = p + DHCP_OPT_LEN;\n if (memcmp(p, rfc1533_cookie, 4) != 0)\n return;\n p += 4;\n while (p < p_end) {\n tag = p[0];\n if (tag == RFC1533_PAD) {\n p++;\n } else if (tag == RFC1533_END) {\n break;\n } else {\n p++;\n if (p >= p_end)\n break;\n len = *p++;\n DPRINTF(\"dhcp: tag=%d len=%d\\n\", tag, len);\n\n switch(tag) {\n case RFC2132_MSG_TYPE:\n if (len >= 1)\n *pmsg_type = p[0];\n break;\n case RFC2132_REQ_ADDR:\n if (len >= 4) {\n memcpy(&(preq_addr->s_addr), p, 4);\n }\n break;\n default:\n break;\n }\n p += len;\n }\n }\n if (*pmsg_type == DHCPREQUEST && preq_addr->s_addr == htonl(0L) &&\n bp->bp_ciaddr.s_addr) {\n memcpy(&(preq_addr->s_addr), &bp->bp_ciaddr, 4);\n }\n}\n\nstatic void bootp_reply(Slirp *slirp, const struct bootp_t *bp)\n{\n BOOTPClient *bc = NULL;\n struct mbuf *m;\n struct bootp_t *rbp;\n struct sockaddr_in saddr, daddr;\n struct in_addr preq_addr;\n int dhcp_msg_type, val;\n uint8_t *q;\n\n /* extract exact DHCP msg type */\n dhcp_decode(bp, &dhcp_msg_type, &preq_addr);\n DPRINTF(\"bootp packet op=%d msgtype=%d\", bp->bp_op, dhcp_msg_type);\n if (preq_addr.s_addr != htonl(0L))\n DPRINTF(\" req_addr=%08x\\n\", ntohl(preq_addr.s_addr));\n else\n DPRINTF(\"\\n\");\n\n if (dhcp_msg_type == 0)\n dhcp_msg_type = DHCPREQUEST; /* Force reply for old BOOTP clients */\n\n if (dhcp_msg_type != DHCPDISCOVER &&\n dhcp_msg_type != DHCPREQUEST)\n return;\n /* XXX: this is a hack to get the client mac address */\n memcpy(slirp->client_ethaddr, bp->bp_hwaddr, 6);\n\n m = m_get(slirp);\n if (!m) {\n return;\n }\n m->m_data += IF_MAXLINKHDR;\n rbp = (struct bootp_t *)m->m_data;\n m->m_data += sizeof(struct udpiphdr);\n memset(rbp, 0, sizeof(struct bootp_t));\n\n if (dhcp_msg_type == DHCPDISCOVER) {\n if (preq_addr.s_addr != htonl(0L)) {\n bc = request_addr(slirp, &preq_addr, slirp->client_ethaddr);\n if (bc) {\n daddr.sin_addr = preq_addr;\n }\n }\n if (!bc) {\n new_addr:\n bc = get_new_addr(slirp, &daddr.sin_addr, slirp->client_ethaddr);\n if (!bc) {\n DPRINTF(\"no address left\\n\");\n return;\n }\n }\n memcpy(bc->macaddr, slirp->client_ethaddr, 6);\n } else if (preq_addr.s_addr != htonl(0L)) {\n bc = request_addr(slirp, &preq_addr, slirp->client_ethaddr);\n if (bc) {\n daddr.sin_addr = preq_addr;\n memcpy(bc->macaddr, slirp->client_ethaddr, 6);\n } else {\n daddr.sin_addr.s_addr = 0;\n }\n } else {\n bc = find_addr(slirp, &daddr.sin_addr, bp->bp_hwaddr);\n if (!bc) {\n /* if never assigned, behaves as if it was already\n assigned (windows fix because it remembers its address) */\n goto new_addr;\n }\n }\n\n saddr.sin_addr = slirp->vhost_addr;\n saddr.sin_port = htons(BOOTP_SERVER);\n\n daddr.sin_port = htons(BOOTP_CLIENT);\n\n rbp->bp_op = BOOTP_REPLY;\n rbp->bp_xid = bp->bp_xid;\n rbp->bp_htype = 1;\n rbp->bp_hlen = 6;\n memcpy(rbp->bp_hwaddr, bp->bp_hwaddr, 6);\n\n rbp->bp_yiaddr = daddr.sin_addr; /* Client IP address */\n rbp->bp_siaddr = saddr.sin_addr; /* Server IP address */\n\n q = rbp->bp_vend;\n memcpy(q, rfc1533_cookie, 4);\n q += 4;\n\n if (bc) {\n DPRINTF(\"%s addr=%08x\\n\",\n (dhcp_msg_type == DHCPDISCOVER) ? \"offered\" : \"ack'ed\",\n ntohl(daddr.sin_addr.s_addr));\n\n if (dhcp_msg_type == DHCPDISCOVER) {\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPOFFER;\n } else /* DHCPREQUEST */ {\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPACK;\n }\n\n if (slirp->bootp_filename)\n snprintf((char *)rbp->bp_file, sizeof(rbp->bp_file), \"%s\",\n slirp->bootp_filename);\n\n *q++ = RFC2132_SRV_ID;\n *q++ = 4;\n memcpy(q, &saddr.sin_addr, 4);\n q += 4;\n\n *q++ = RFC1533_NETMASK;\n *q++ = 4;\n memcpy(q, &slirp->vnetwork_mask, 4);\n q += 4;\n\n if (!slirp->restricted) {\n *q++ = RFC1533_GATEWAY;\n *q++ = 4;\n memcpy(q, &saddr.sin_addr, 4);\n q += 4;\n\n *q++ = RFC1533_DNS;\n *q++ = 4;\n memcpy(q, &slirp->vnameserver_addr, 4);\n q += 4;\n }\n\n *q++ = RFC2132_LEASE_TIME;\n *q++ = 4;\n val = htonl(LEASE_TIME);\n memcpy(q, &val, 4);\n q += 4;\n\n if (*slirp->client_hostname) {\n val = strlen(slirp->client_hostname);\n *q++ = RFC1533_HOSTNAME;\n *q++ = val;\n memcpy(q, slirp->client_hostname, val);\n q += val;\n }\n } else {\n static const char nak_msg[] = \"requested address not available\";\n\n DPRINTF(\"nak'ed addr=%08x\\n\", ntohl(preq_addr->s_addr));\n\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPNAK;\n\n *q++ = RFC2132_MESSAGE;\n *q++ = sizeof(nak_msg) - 1;\n memcpy(q, nak_msg, sizeof(nak_msg) - 1);\n q += sizeof(nak_msg) - 1;\n }\n *q = RFC1533_END;\n\n daddr.sin_addr.s_addr = 0xffffffffu;\n\n m->m_len = sizeof(struct bootp_t) -\n sizeof(struct ip) - sizeof(struct udphdr);\n udp_output2(NULL, m, &saddr, &daddr, IPTOS_LOWDELAY);\n}\n\nvoid bootp_input(struct mbuf *m)\n{\n struct bootp_t *bp = mtod(m, struct bootp_t *);\n\n if (bp->bp_op == BOOTP_REQUEST) {\n bootp_reply(m->slirp, bp);\n }\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_input.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_input.c\t8.2 (Berkeley) 1/4/94\n * ip_input.c,v 1.11 1994/11/16 10:17:08 jkh Exp\n */\n\n/*\n * Changes and additions relating to SLiRP are\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n#define container_of(ptr, type, member) ({ \\\n const typeof( ((type *)0)->member ) *__mptr = (ptr); \\\n (type *)( (char *)__mptr - offsetof(type,member) );})\n\nstatic struct ip *ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp);\nstatic void ip_freef(Slirp *slirp, struct ipq *fp);\nstatic void ip_enq(register struct ipasfrag *p,\n register struct ipasfrag *prev);\nstatic void ip_deq(register struct ipasfrag *p);\n\n/*\n * IP initialization: fill in IP protocol switch table.\n * All protocols not implemented in kernel go to raw IP protocol handler.\n */\nvoid\nip_init(Slirp *slirp)\n{\n slirp->ipq.ip_link.next = slirp->ipq.ip_link.prev = &slirp->ipq.ip_link;\n udp_init(slirp);\n tcp_init(slirp);\n}\n\n/*\n * Ip input routine. Checksum and byte swap header. If fragmented\n * try to reassemble. Process options. Pass to next level.\n */\nvoid\nip_input(struct mbuf *m)\n{\n\tSlirp *slirp = m->slirp;\n\tregister struct ip *ip;\n\tint hlen;\n\n\tDEBUG_CALL(\"ip_input\");\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"m_len = %d\", m->m_len);\n\n\tif (m->m_len < sizeof (struct ip)) {\n\t\treturn;\n\t}\n\n\tip = mtod(m, struct ip *);\n\n\tif (ip->ip_v != IPVERSION) {\n\t\tgoto bad;\n\t}\n\n\thlen = ip->ip_hl << 2;\n\tif (hlenm->m_len) {/* min header length */\n\t goto bad; /* or packet too short */\n\t}\n\n /* keep ip header intact for ICMP reply\n\t * ip->ip_sum = cksum(m, hlen);\n\t * if (ip->ip_sum) {\n\t */\n\tif(cksum(m,hlen)) {\n\t goto bad;\n\t}\n\n\t/*\n\t * Convert fields to host representation.\n\t */\n\tNTOHS(ip->ip_len);\n\tif (ip->ip_len < hlen) {\n\t\tgoto bad;\n\t}\n\tNTOHS(ip->ip_id);\n\tNTOHS(ip->ip_off);\n\n\t/*\n\t * Check that the amount of data in the buffers\n\t * is as at least much as the IP header would have us expect.\n\t * Trim mbufs if longer than we expect.\n\t * Drop packet if shorter than we expect.\n\t */\n\tif (m->m_len < ip->ip_len) {\n\t\tgoto bad;\n\t}\n\n if (slirp->restricted) {\n if ((ip->ip_dst.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n if (ip->ip_dst.s_addr == 0xffffffff && ip->ip_p != IPPROTO_UDP)\n goto bad;\n } else {\n uint32_t inv_mask = ~slirp->vnetwork_mask.s_addr;\n struct ex_list *ex_ptr;\n\n if ((ip->ip_dst.s_addr & inv_mask) == inv_mask) {\n goto bad;\n }\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)\n if (ex_ptr->ex_addr.s_addr == ip->ip_dst.s_addr)\n break;\n\n if (!ex_ptr)\n goto bad;\n }\n }\n\n\t/* Should drop packet if mbuf too long? hmmm... */\n\tif (m->m_len > ip->ip_len)\n\t m_adj(m, ip->ip_len - m->m_len);\n\n\t/* check ip_ttl for a correct ICMP reply */\n\tif(ip->ip_ttl==0) {\n\t icmp_error(m, ICMP_TIMXCEED,ICMP_TIMXCEED_INTRANS, 0,\"ttl\");\n\t goto bad;\n\t}\n\n\t/*\n\t * If offset or IP_MF are set, must reassemble.\n\t * Otherwise, nothing need be done.\n\t * (We could look in the reassembly queue to see\n\t * if the packet was previously fragmented,\n\t * but it's not worth the time; just let them time out.)\n\t *\n\t * XXX This should fail, don't fragment yet\n\t */\n\tif (ip->ip_off &~ IP_DF) {\n\t register struct ipq *fp;\n struct qlink *l;\n\t\t/*\n\t\t * Look for queue of fragments\n\t\t * of this datagram.\n\t\t */\n\t\tfor (l = slirp->ipq.ip_link.next; l != &slirp->ipq.ip_link;\n\t\t l = l->next) {\n fp = container_of(l, struct ipq, ip_link);\n if (ip->ip_id == fp->ipq_id &&\n ip->ip_src.s_addr == fp->ipq_src.s_addr &&\n ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&\n ip->ip_p == fp->ipq_p)\n\t\t goto found;\n }\n fp = NULL;\n\tfound:\n\n\t\t/*\n\t\t * Adjust ip_len to not reflect header,\n\t\t * set ip_mff if more fragments are expected,\n\t\t * convert offset of this to bytes.\n\t\t */\n\t\tip->ip_len -= hlen;\n\t\tif (ip->ip_off & IP_MF)\n\t\t ip->ip_tos |= 1;\n\t\telse\n\t\t ip->ip_tos &= ~1;\n\n\t\tip->ip_off <<= 3;\n\n\t\t/*\n\t\t * If datagram marked as having more fragments\n\t\t * or if this is not the first fragment,\n\t\t * attempt reassembly; if it succeeds, proceed.\n\t\t */\n\t\tif (ip->ip_tos & 1 || ip->ip_off) {\n\t\t\tip = ip_reass(slirp, ip, fp);\n if (ip == NULL)\n\t\t\t\treturn;\n\t\t\tm = dtom(slirp, ip);\n\t\t} else\n\t\t\tif (fp)\n\t\t \t ip_freef(slirp, fp);\n\n\t} else\n\t\tip->ip_len -= hlen;\n\n\t/*\n\t * Switch out to protocol's input routine.\n\t */\n\tswitch (ip->ip_p) {\n\t case IPPROTO_TCP:\n\t\ttcp_input(m, hlen, (struct socket *)NULL);\n\t\tbreak;\n\t case IPPROTO_UDP:\n\t\tudp_input(m, hlen);\n\t\tbreak;\n\t case IPPROTO_ICMP:\n\t\ticmp_input(m, hlen);\n\t\tbreak;\n\t default:\n\t\tm_free(m);\n\t}\n\treturn;\nbad:\n\tm_freem(m);\n\treturn;\n}\n\n#define iptofrag(P) ((struct ipasfrag *)(((char*)(P)) - sizeof(struct qlink)))\n#define fragtoip(P) ((struct ip*)(((char*)(P)) + sizeof(struct qlink)))\n/*\n * Take incoming datagram fragment and try to\n * reassemble it into whole datagram. If a chain for\n * reassembly of this datagram already exists, then it\n * is given as fp; otherwise have to make a chain.\n */\nstatic struct ip *\nip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)\n{\n\tregister struct mbuf *m = dtom(slirp, ip);\n\tregister struct ipasfrag *q;\n\tint hlen = ip->ip_hl << 2;\n\tint i, next;\n\n\tDEBUG_CALL(\"ip_reass\");\n\tDEBUG_ARG(\"ip = %lx\", (long)ip);\n\tDEBUG_ARG(\"fp = %lx\", (long)fp);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n\t/*\n\t * Presence of header sizes in mbufs\n\t * would confuse code below.\n * Fragment m_data is concatenated.\n\t */\n\tm->m_data += hlen;\n\tm->m_len -= hlen;\n\n\t/*\n\t * If first fragment to arrive, create a reassembly queue.\n\t */\n if (fp == NULL) {\n\t struct mbuf *t = m_get(slirp);\n\n\t if (t == NULL) {\n\t goto dropfrag;\n\t }\n\t fp = mtod(t, struct ipq *);\n\t insque(&fp->ip_link, &slirp->ipq.ip_link);\n\t fp->ipq_ttl = IPFRAGTTL;\n\t fp->ipq_p = ip->ip_p;\n\t fp->ipq_id = ip->ip_id;\n\t fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;\n\t fp->ipq_src = ip->ip_src;\n\t fp->ipq_dst = ip->ip_dst;\n\t q = (struct ipasfrag *)fp;\n\t goto insert;\n\t}\n\n\t/*\n\t * Find a segment which begins after this one does.\n\t */\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next)\n\t\tif (q->ipf_off > ip->ip_off)\n\t\t\tbreak;\n\n\t/*\n\t * If there is a preceding segment, it may provide some of\n\t * our data already. If so, drop the data from the incoming\n\t * segment. If it provides all of our data, drop us.\n\t */\n\tif (q->ipf_prev != &fp->frag_link) {\n struct ipasfrag *pq = q->ipf_prev;\n\t\ti = pq->ipf_off + pq->ipf_len - ip->ip_off;\n\t\tif (i > 0) {\n\t\t\tif (i >= ip->ip_len)\n\t\t\t\tgoto dropfrag;\n\t\t\tm_adj(dtom(slirp, ip), i);\n\t\t\tip->ip_off += i;\n\t\t\tip->ip_len -= i;\n\t\t}\n\t}\n\n\t/*\n\t * While we overlap succeeding segments trim them or,\n\t * if they are completely covered, dequeue them.\n\t */\n\twhile (q != (struct ipasfrag*)&fp->frag_link &&\n ip->ip_off + ip->ip_len > q->ipf_off) {\n\t\ti = (ip->ip_off + ip->ip_len) - q->ipf_off;\n\t\tif (i < q->ipf_len) {\n\t\t\tq->ipf_len -= i;\n\t\t\tq->ipf_off += i;\n\t\t\tm_adj(dtom(slirp, q), i);\n\t\t\tbreak;\n\t\t}\n\t\tq = q->ipf_next;\n\t\tm_freem(dtom(slirp, q->ipf_prev));\n\t\tip_deq(q->ipf_prev);\n\t}\n\ninsert:\n\t/*\n\t * Stick new segment in its place;\n\t * check for complete reassembly.\n\t */\n\tip_enq(iptofrag(ip), q->ipf_prev);\n\tnext = 0;\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link;\n q = q->ipf_next) {\n\t\tif (q->ipf_off != next)\n return NULL;\n\t\tnext += q->ipf_len;\n\t}\n\tif (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)\n return NULL;\n\n\t/*\n\t * Reassembly is complete; concatenate fragments.\n\t */\n q = fp->frag_link.next;\n\tm = dtom(slirp, q);\n\n\tq = (struct ipasfrag *) q->ipf_next;\n\twhile (q != (struct ipasfrag*)&fp->frag_link) {\n\t struct mbuf *t = dtom(slirp, q);\n\t q = (struct ipasfrag *) q->ipf_next;\n\t m_cat(m, t);\n\t}\n\n\t/*\n\t * Create header for new ip packet by\n\t * modifying header of first packet;\n\t * dequeue and discard fragment reassembly header.\n\t * Make header visible.\n\t */\n\tq = fp->frag_link.next;\n\n\t/*\n\t * If the fragments concatenated to an mbuf that's\n\t * bigger than the total size of the fragment, then and\n\t * m_ext buffer was alloced. But fp->ipq_next points to\n\t * the old buffer (in the mbuf), so we must point ip\n\t * into the new buffer.\n\t */\n\tif (m->m_flags & M_EXT) {\n\t int delta = (char *)q - m->m_dat;\n\t q = (struct ipasfrag *)(m->m_ext + delta);\n\t}\n\n ip = fragtoip(q);\n\tip->ip_len = next;\n\tip->ip_tos &= ~1;\n\tip->ip_src = fp->ipq_src;\n\tip->ip_dst = fp->ipq_dst;\n\tremque(&fp->ip_link);\n\t(void) m_free(dtom(slirp, fp));\n\tm->m_len += (ip->ip_hl << 2);\n\tm->m_data -= (ip->ip_hl << 2);\n\n\treturn ip;\n\ndropfrag:\n\tm_freem(m);\n return NULL;\n}\n\n/*\n * Free a fragment reassembly header and all\n * associated datagrams.\n */\nstatic void\nip_freef(Slirp *slirp, struct ipq *fp)\n{\n\tregister struct ipasfrag *q, *p;\n\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link; q = p) {\n\t\tp = q->ipf_next;\n\t\tip_deq(q);\n\t\tm_freem(dtom(slirp, q));\n\t}\n\tremque(&fp->ip_link);\n\t(void) m_free(dtom(slirp, fp));\n}\n\n/*\n * Put an ip fragment on a reassembly chain.\n * Like insque, but pointers in middle of structure.\n */\nstatic void\nip_enq(register struct ipasfrag *p, register struct ipasfrag *prev)\n{\n\tDEBUG_CALL(\"ip_enq\");\n\tDEBUG_ARG(\"prev = %lx\", (long)prev);\n\tp->ipf_prev = prev;\n\tp->ipf_next = prev->ipf_next;\n\t((struct ipasfrag *)(prev->ipf_next))->ipf_prev = p;\n\tprev->ipf_next = p;\n}\n\n/*\n * To ip_enq as remque is to insque.\n */\nstatic void\nip_deq(register struct ipasfrag *p)\n{\n\t((struct ipasfrag *)(p->ipf_prev))->ipf_next = p->ipf_next;\n\t((struct ipasfrag *)(p->ipf_next))->ipf_prev = p->ipf_prev;\n}\n\n/*\n * IP timer processing;\n * if a timer expires on a reassembly\n * queue, discard it.\n */\nvoid\nip_slowtimo(Slirp *slirp)\n{\n struct qlink *l;\n\n\tDEBUG_CALL(\"ip_slowtimo\");\n\n l = slirp->ipq.ip_link.next;\n\n if (l == NULL)\n\t return;\n\n while (l != &slirp->ipq.ip_link) {\n struct ipq *fp = container_of(l, struct ipq, ip_link);\n l = l->next;\n\t\tif (--fp->ipq_ttl == 0) {\n\t\t\tip_freef(slirp, fp);\n\t\t}\n }\n}\n\n/*\n * Do option processing on a datagram,\n * possibly discarding it if bad options are encountered,\n * or forwarding it if source-routed.\n * Returns 1 if packet has been forwarded/freed,\n * 0 if the packet should be processed further.\n */\n\n#ifdef notdef\n\nint\nip_dooptions(m)\n\tstruct mbuf *m;\n{\n\tregister struct ip *ip = mtod(m, struct ip *);\n\tregister u_char *cp;\n\tregister struct ip_timestamp *ipt;\n\tregister struct in_ifaddr *ia;\n\tint opt, optlen, cnt, off, code, type, forward = 0;\n\tstruct in_addr *sin, dst;\ntypedef uint32_t n_time;\n\tn_time ntime;\n\n\tdst = ip->ip_dst;\n\tcp = (u_char *)(ip + 1);\n\tcnt = (ip->ip_hl << 2) - sizeof (struct ip);\n\tfor (; cnt > 0; cnt -= optlen, cp += optlen) {\n\t\topt = cp[IPOPT_OPTVAL];\n\t\tif (opt == IPOPT_EOL)\n\t\t\tbreak;\n\t\tif (opt == IPOPT_NOP)\n\t\t\toptlen = 1;\n\t\telse {\n\t\t\toptlen = cp[IPOPT_OLEN];\n\t\t\tif (optlen <= 0 || optlen > cnt) {\n\t\t\t\tcode = &cp[IPOPT_OLEN] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t}\n\t\tswitch (opt) {\n\n\t\tdefault:\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Source routing with record.\n\t\t * Find interface with current destination address.\n\t\t * If none on this machine then drop if strictly routed,\n\t\t * or do nothing if loosely routed.\n\t\t * Record interface address and bring up next address\n\t\t * component. If strictly routed make sure next\n\t\t * address is on directly accessible net.\n\t\t */\n\t\tcase IPOPT_LSRR:\n\t\tcase IPOPT_SSRR:\n\t\t\tif ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {\n\t\t\t\tcode = &cp[IPOPT_OFFSET] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tipaddr.sin_addr = ip->ip_dst;\n\t\t\tia = (struct in_ifaddr *)\n\t\t\t\tifa_ifwithaddr((struct sockaddr *)&ipaddr);\n\t\t\tif (ia == 0) {\n\t\t\t\tif (opt == IPOPT_SSRR) {\n\t\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\t\tcode = ICMP_UNREACH_SRCFAIL;\n\t\t\t\t\tgoto bad;\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Loose routing, and not at next destination\n\t\t\t\t * yet; nothing to do except forward.\n\t\t\t\t */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toff--;\t\t\t/ * 0 origin * /\n\t\t\tif (off > optlen - sizeof(struct in_addr)) {\n\t\t\t\t/*\n\t\t\t\t * End of source route. Should be for us.\n\t\t\t\t */\n\t\t\t\tsave_rte(cp, ip->ip_src);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/*\n\t\t\t * locate outgoing interface\n\t\t\t */\n\t\t\tbcopy((caddr_t)(cp + off), (caddr_t)&ipaddr.sin_addr,\n\t\t\t sizeof(ipaddr.sin_addr));\n\t\t\tif (opt == IPOPT_SSRR) {\n#define\tINA\tstruct in_ifaddr *\n#define\tSA\tstruct sockaddr *\n \t\t\t if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)\n\t\t\t\tia = (INA)ifa_ifwithnet((SA)&ipaddr);\n\t\t\t} else\n\t\t\t\tia = ip_rtaddr(ipaddr.sin_addr);\n\t\t\tif (ia == 0) {\n\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\tcode = ICMP_UNREACH_SRCFAIL;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tip->ip_dst = ipaddr.sin_addr;\n\t\t\tbcopy((caddr_t)&(IA_SIN(ia)->sin_addr),\n\t\t\t (caddr_t)(cp + off), sizeof(struct in_addr));\n\t\t\tcp[IPOPT_OFFSET] += sizeof(struct in_addr);\n\t\t\t/*\n\t\t\t * Let ip_intr's mcast routing check handle mcast pkts\n\t\t\t */\n\t\t\tforward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));\n\t\t\tbreak;\n\n\t\tcase IPOPT_RR:\n\t\t\tif ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {\n\t\t\t\tcode = &cp[IPOPT_OFFSET] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\t/*\n\t\t\t * If no space remains, ignore.\n\t\t\t */\n\t\t\toff--;\t\t\t * 0 origin *\n\t\t\tif (off > optlen - sizeof(struct in_addr))\n\t\t\t\tbreak;\n\t\t\tbcopy((caddr_t)(&ip->ip_dst), (caddr_t)&ipaddr.sin_addr,\n\t\t\t sizeof(ipaddr.sin_addr));\n\t\t\t/*\n\t\t\t * locate outgoing interface; if we're the destination,\n\t\t\t * use the incoming interface (should be same).\n\t\t\t */\n\t\t\tif ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&\n\t\t\t (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {\n\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\tcode = ICMP_UNREACH_HOST;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tbcopy((caddr_t)&(IA_SIN(ia)->sin_addr),\n\t\t\t (caddr_t)(cp + off), sizeof(struct in_addr));\n\t\t\tcp[IPOPT_OFFSET] += sizeof(struct in_addr);\n\t\t\tbreak;\n\n\t\tcase IPOPT_TS:\n\t\t\tcode = cp - (u_char *)ip;\n\t\t\tipt = (struct ip_timestamp *)cp;\n\t\t\tif (ipt->ipt_len < 5)\n\t\t\t\tgoto bad;\n\t\t\tif (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {\n\t\t\t\tif (++ipt->ipt_oflw == 0)\n\t\t\t\t\tgoto bad;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);\n\t\t\tswitch (ipt->ipt_flg) {\n\n\t\t\tcase IPOPT_TS_TSONLY:\n\t\t\t\tbreak;\n\n\t\t\tcase IPOPT_TS_TSANDADDR:\n\t\t\t\tif (ipt->ipt_ptr + sizeof(n_time) +\n\t\t\t\t sizeof(struct in_addr) > ipt->ipt_len)\n\t\t\t\t\tgoto bad;\n\t\t\t\tipaddr.sin_addr = dst;\n\t\t\t\tia = (INA)ifaof_ i f p foraddr((SA)&ipaddr,\n\t\t\t\t\t\t\t m->m_pkthdr.rcvif);\n\t\t\t\tif (ia == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tbcopy((caddr_t)&IA_SIN(ia)->sin_addr,\n\t\t\t\t (caddr_t)sin, sizeof(struct in_addr));\n\t\t\t\tipt->ipt_ptr += sizeof(struct in_addr);\n\t\t\t\tbreak;\n\n\t\t\tcase IPOPT_TS_PRESPEC:\n\t\t\t\tif (ipt->ipt_ptr + sizeof(n_time) +\n\t\t\t\t sizeof(struct in_addr) > ipt->ipt_len)\n\t\t\t\t\tgoto bad;\n\t\t\t\tbcopy((caddr_t)sin, (caddr_t)&ipaddr.sin_addr,\n\t\t\t\t sizeof(struct in_addr));\n\t\t\t\tif (ifa_ifwithaddr((SA)&ipaddr) == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tipt->ipt_ptr += sizeof(struct in_addr);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tntime = iptime();\n\t\t\tbcopy((caddr_t)&ntime, (caddr_t)cp + ipt->ipt_ptr - 1,\n\t\t\t sizeof(n_time));\n\t\t\tipt->ipt_ptr += sizeof(n_time);\n\t\t}\n\t}\n\tif (forward) {\n\t\tip_forward(m, 1);\n\t\treturn (1);\n\t}\n\treturn (0);\nbad:\n \ticmp_error(m, type, code, 0, 0);\n\n\treturn (1);\n}\n\n#endif /* notdef */\n\n/*\n * Strip out IP options, at higher\n * level protocol in the kernel.\n * Second argument is buffer to which options\n * will be moved, and return value is their length.\n * (XXX) should be deleted; last arg currently ignored.\n */\nvoid\nip_stripoptions(register struct mbuf *m, struct mbuf *mopt)\n{\n\tregister int i;\n\tstruct ip *ip = mtod(m, struct ip *);\n\tregister caddr_t opts;\n\tint olen;\n\n\tolen = (ip->ip_hl<<2) - sizeof (struct ip);\n\topts = (caddr_t)(ip + 1);\n\ti = m->m_len - (sizeof (struct ip) + olen);\n\tmemcpy(opts, opts + olen, (unsigned)i);\n\tm->m_len -= olen;\n\n\tip->ip_hl = sizeof(struct ip) >> 2;\n}\n"], ["/linuxpdf/tinyemu/sha256.c", "/* LibTomCrypt, modular cryptographic library -- Tom St Denis\n *\n * LibTomCrypt is a library that provides various cryptographic\n * algorithms in a highly modular and flexible manner.\n *\n * The library is free for all purposes without any express\n * guarantee it works.\n *\n * Tom St Denis, tomstdenis@gmail.com, http://libtom.org\n */\n#include \n#include \n#include \"cutils.h\"\n#include \"sha256.h\"\n\n#define LOAD32H(a, b) a = get_be32(b)\n#define STORE32H(a, b) put_be32(b, a)\n#define STORE64H(a, b) put_be64(b, a)\n#define RORc(x, y) ( ((((uint32_t)(x)&0xFFFFFFFFUL)>>(uint32_t)((y)&31)) | ((uint32_t)(x)<<(uint32_t)(32-((y)&31)))) & 0xFFFFFFFFUL)\n\n#if defined(CONFIG_EMBUE)\n#define LTC_SMALL_CODE\n#endif\n\n/**\n @file sha256.c\n LTC_SHA256 by Tom St Denis\n*/\n\n#ifdef LTC_SMALL_CODE\n/* the K array */\nstatic const uint32_t K[64] = {\n 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,\n 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,\n 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,\n 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,\n 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,\n 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,\n 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,\n 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,\n 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,\n 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,\n 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,\n 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,\n 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL\n};\n#endif\n\n/* Various logical functions */\n#define Ch(x,y,z) (z ^ (x & (y ^ z)))\n#define Maj(x,y,z) (((x | y) & z) | (x & y))\n#define S(x, n) RORc((x),(n))\n#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))\n#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))\n#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25))\n#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3))\n#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10))\n\n/* compress 512-bits */\nstatic void sha256_compress(SHA256_CTX *s, unsigned char *buf)\n{\n uint32_t S[8], W[64], t0, t1;\n#ifdef LTC_SMALL_CODE\n uint32_t t;\n#endif\n int i;\n\n /* copy state into S */\n for (i = 0; i < 8; i++) {\n S[i] = s->state[i];\n }\n\n /* copy the state into 512-bits into W[0..15] */\n for (i = 0; i < 16; i++) {\n LOAD32H(W[i], buf + (4*i));\n }\n\n /* fill W[16..63] */\n for (i = 16; i < 64; i++) {\n W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];\n }\n\n /* Compress */\n#ifdef LTC_SMALL_CODE\n#define RND(a,b,c,d,e,f,g,h,i) \\\n t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \\\n t1 = Sigma0(a) + Maj(a, b, c); \\\n d += t0; \\\n h = t0 + t1;\n\n for (i = 0; i < 64; ++i) {\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i);\n t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4];\n S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;\n }\n#else\n#define RND(a,b,c,d,e,f,g,h,i,ki) \\\n t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i]; \\\n t1 = Sigma0(a) + Maj(a, b, c); \\\n d += t0; \\\n h = t0 + t1;\n\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,0x428a2f98);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,0x71374491);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,0xb5c0fbcf);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,0xe9b5dba5);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,0x3956c25b);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],5,0x59f111f1);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],6,0x923f82a4);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],7,0xab1c5ed5);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],8,0xd807aa98);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],9,0x12835b01);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],10,0x243185be);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],11,0x550c7dc3);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],12,0x72be5d74);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],13,0x80deb1fe);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],14,0x9bdc06a7);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],15,0xc19bf174);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],16,0xe49b69c1);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],17,0xefbe4786);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],18,0x0fc19dc6);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],19,0x240ca1cc);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],20,0x2de92c6f);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],21,0x4a7484aa);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],22,0x5cb0a9dc);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],23,0x76f988da);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],24,0x983e5152);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],25,0xa831c66d);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],26,0xb00327c8);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],27,0xbf597fc7);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],28,0xc6e00bf3);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],29,0xd5a79147);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],30,0x06ca6351);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],31,0x14292967);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],32,0x27b70a85);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],33,0x2e1b2138);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],34,0x4d2c6dfc);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],35,0x53380d13);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],36,0x650a7354);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],37,0x766a0abb);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],38,0x81c2c92e);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],39,0x92722c85);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],40,0xa2bfe8a1);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],41,0xa81a664b);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],42,0xc24b8b70);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],43,0xc76c51a3);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],44,0xd192e819);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],45,0xd6990624);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],46,0xf40e3585);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],47,0x106aa070);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],48,0x19a4c116);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],49,0x1e376c08);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],50,0x2748774c);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],51,0x34b0bcb5);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],52,0x391c0cb3);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],53,0x4ed8aa4a);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],54,0x5b9cca4f);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],55,0x682e6ff3);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],56,0x748f82ee);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],57,0x78a5636f);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],58,0x84c87814);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],59,0x8cc70208);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],60,0x90befffa);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],61,0xa4506ceb);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);\n\n#undef RND\n\n#endif\n\n /* feedback */\n for (i = 0; i < 8; i++) {\n s->state[i] = s->state[i] + S[i];\n }\n}\n\n#ifdef LTC_CLEAN_STACK\nstatic int sha256_compress(hash_state * md, unsigned char *buf)\n{\n int err;\n err = _sha256_compress(md, buf);\n burn_stack(sizeof(uint32_t) * 74);\n return err;\n}\n#endif\n\n/**\n Initialize the hash state\n @param md The hash state you wish to initialize\n @return CRYPT_OK if successful\n*/\nvoid SHA256_Init(SHA256_CTX *s)\n{\n s->curlen = 0;\n s->length = 0;\n s->state[0] = 0x6A09E667UL;\n s->state[1] = 0xBB67AE85UL;\n s->state[2] = 0x3C6EF372UL;\n s->state[3] = 0xA54FF53AUL;\n s->state[4] = 0x510E527FUL;\n s->state[5] = 0x9B05688CUL;\n s->state[6] = 0x1F83D9ABUL;\n s->state[7] = 0x5BE0CD19UL;\n}\n\nvoid SHA256_Update(SHA256_CTX *s, const uint8_t *in, unsigned long inlen)\n{\n unsigned long n;\n\n if (s->curlen > sizeof(s->buf)) {\n abort();\n }\n if ((s->length + inlen) < s->length) {\n abort();\n }\n while (inlen > 0) {\n if (s->curlen == 0 && inlen >= 64) {\n sha256_compress(s, (unsigned char *)in);\n s->length += 64 * 8;\n in += 64;\n inlen -= 64;\n } else {\n n = min_int(inlen, 64 - s->curlen);\n memcpy(s->buf + s->curlen, in, (size_t)n);\n s->curlen += n;\n in += n;\n inlen -= n;\n if (s->curlen == 64) {\n sha256_compress(s, s->buf);\n s->length += 8*64;\n s->curlen = 0;\n }\n }\n } }\n\n/**\n Terminate the hash to get the digest\n @param md The hash state\n @param out [out] The destination of the hash (32 bytes)\n @return CRYPT_OK if successful\n*/\nvoid SHA256_Final(uint8_t *out, SHA256_CTX *s)\n{\n int i;\n\n if (s->curlen >= sizeof(s->buf)) {\n abort();\n }\n\n\n /* increase the length of the message */\n s->length += s->curlen * 8;\n\n /* append the '1' bit */\n s->buf[s->curlen++] = (unsigned char)0x80;\n\n /* if the length is currently above 56 bytes we append zeros\n * then compress. Then we can fall back to padding zeros and length\n * encoding like normal.\n */\n if (s->curlen > 56) {\n while (s->curlen < 64) {\n s->buf[s->curlen++] = (unsigned char)0;\n }\n sha256_compress(s, s->buf);\n s->curlen = 0;\n }\n\n /* pad upto 56 bytes of zeroes */\n while (s->curlen < 56) {\n s->buf[s->curlen++] = (unsigned char)0;\n }\n\n /* store length */\n STORE64H(s->length, s->buf+56);\n sha256_compress(s, s->buf);\n\n /* copy output */\n for (i = 0; i < 8; i++) {\n STORE32H(s->state[i], out+(4*i));\n }\n#ifdef LTC_CLEAN_STACK\n zeromem(md, sizeof(hash_state));\n#endif\n}\n\nvoid SHA256(const uint8_t *buf, int buf_len, uint8_t *out)\n{\n SHA256_CTX ctx;\n\n SHA256_Init(&ctx);\n SHA256_Update(&ctx, buf, buf_len);\n SHA256_Final(out, &ctx);\n}\n\n#if 0\n/**\n Self-test the hash\n @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled\n*/\nint sha256_test(void)\n{\n #ifndef LTC_TEST\n return CRYPT_NOP;\n #else\n static const struct {\n char *msg;\n unsigned char hash[32];\n } tests[] = {\n { \"abc\",\n { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,\n 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,\n 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,\n 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }\n },\n { \"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\",\n { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,\n 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,\n 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,\n 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }\n },\n };\n\n int i;\n unsigned char tmp[32];\n hash_state md;\n\n for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {\n sha256_init(&md);\n sha256_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));\n sha256_done(&md, tmp);\n if (XMEMCMP(tmp, tests[i].hash, 32) != 0) {\n return CRYPT_FAIL_TESTVECTOR;\n }\n }\n return CRYPT_OK;\n #endif\n}\n\n#endif\n"], ["/linuxpdf/tinyemu/json.c", "/*\n * Pseudo JSON parser\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"json.h\"\n#include \"fs_utils.h\"\n\nstatic JSONValue parse_string(const char **pp)\n{\n char buf[4096], *q;\n const char *p;\n int c, h;\n \n q = buf;\n p = *pp;\n p++;\n for(;;) {\n c = *p++;\n if (c == '\\0' || c == '\\n') {\n return json_error_new(\"unterminated string\");\n } else if (c == '\\\"') {\n break;\n } else if (c == '\\\\') {\n c = *p++;\n switch(c) {\n case '\\'':\n case '\\\"':\n case '\\\\':\n goto add_char;\n case 'n':\n c = '\\n';\n goto add_char;\n case 'r':\n c = '\\r';\n goto add_char;\n case 't':\n c = '\\t';\n goto add_char;\n case 'x':\n h = from_hex(*p++);\n if (h < 0)\n return json_error_new(\"invalig hex digit\");\n c = h << 4;\n h = from_hex(*p++);\n if (h < 0)\n return json_error_new(\"invalig hex digit\");\n c |= h;\n goto add_char;\n default:\n return json_error_new(\"unknown escape code\");\n }\n } else {\n add_char:\n if (q >= buf + sizeof(buf) - 1)\n return json_error_new(\"string too long\");\n *q++ = c;\n }\n }\n *q = '\\0';\n *pp = p;\n return json_string_new(buf);\n}\n\nstatic JSONProperty *json_object_get2(JSONObject *obj, const char *name)\n{\n JSONProperty *f;\n int i;\n for(i = 0; i < obj->len; i++) {\n f = &obj->props[i];\n if (!strcmp(f->name.u.str->data, name))\n return f;\n }\n return NULL;\n}\n\nJSONValue json_object_get(JSONValue val, const char *name)\n{\n JSONProperty *f;\n JSONObject *obj;\n \n if (val.type != JSON_OBJ)\n return json_undefined_new();\n obj = val.u.obj;\n f = json_object_get2(obj, name);\n if (!f)\n return json_undefined_new();\n return f->value;\n}\n\nint json_object_set(JSONValue val, const char *name, JSONValue prop_val)\n{\n JSONObject *obj;\n JSONProperty *f;\n int new_size;\n \n if (val.type != JSON_OBJ)\n return -1;\n obj = val.u.obj;\n f = json_object_get2(obj, name);\n if (f) {\n json_free(f->value);\n f->value = prop_val;\n } else {\n if (obj->len >= obj->size) {\n new_size = max_int(obj->len + 1, obj->size * 3 / 2);\n obj->props = realloc(obj->props, new_size * sizeof(JSONProperty));\n obj->size = new_size;\n }\n f = &obj->props[obj->len++];\n f->name = json_string_new(name);\n f->value = prop_val;\n }\n return 0;\n}\n\nJSONValue json_array_get(JSONValue val, unsigned int idx)\n{\n JSONArray *array;\n \n if (val.type != JSON_ARRAY)\n return json_undefined_new();\n array = val.u.array;\n if (idx < array->len) {\n return array->tab[idx];\n } else {\n return json_undefined_new();\n }\n}\n\nint json_array_set(JSONValue val, unsigned int idx, JSONValue prop_val)\n{\n JSONArray *array;\n int new_size;\n \n if (val.type != JSON_ARRAY)\n return -1;\n array = val.u.array;\n if (idx < array->len) {\n json_free(array->tab[idx]);\n array->tab[idx] = prop_val;\n } else if (idx == array->len) {\n if (array->len >= array->size) {\n new_size = max_int(array->len + 1, array->size * 3 / 2);\n array->tab = realloc(array->tab, new_size * sizeof(JSONValue));\n array->size = new_size;\n }\n array->tab[array->len++] = prop_val;\n } else {\n return -1;\n }\n return 0;\n}\n\nconst char *json_get_str(JSONValue val)\n{\n if (val.type != JSON_STR)\n return NULL;\n return val.u.str->data;\n}\n\nconst char *json_get_error(JSONValue val)\n{\n if (val.type != JSON_EXCEPTION)\n return NULL;\n return val.u.str->data;\n}\n\nJSONValue json_string_new2(const char *str, int len)\n{\n JSONValue val;\n JSONString *str1;\n\n str1 = malloc(sizeof(JSONString) + len + 1);\n str1->len = len;\n memcpy(str1->data, str, len + 1);\n val.type = JSON_STR;\n val.u.str = str1;\n return val;\n}\n\nJSONValue json_string_new(const char *str)\n{\n return json_string_new2(str, strlen(str));\n}\n\nJSONValue __attribute__((format(printf, 1, 2))) json_error_new(const char *fmt, ...)\n{\n JSONValue val;\n va_list ap;\n char buf[256];\n \n va_start(ap, fmt);\n vsnprintf(buf, sizeof(buf), fmt, ap);\n va_end(ap);\n val = json_string_new(buf);\n val.type = JSON_EXCEPTION;\n return val;\n}\n\nJSONValue json_object_new(void)\n{\n JSONValue val;\n JSONObject *obj;\n obj = mallocz(sizeof(JSONObject));\n val.type = JSON_OBJ;\n val.u.obj = obj;\n return val;\n}\n\nJSONValue json_array_new(void)\n{\n JSONValue val;\n JSONArray *array;\n array = mallocz(sizeof(JSONArray));\n val.type = JSON_ARRAY;\n val.u.array = array;\n return val;\n}\n\nvoid json_free(JSONValue val)\n{\n switch(val.type) {\n case JSON_STR:\n case JSON_EXCEPTION:\n free(val.u.str);\n break;\n case JSON_INT:\n case JSON_BOOL:\n case JSON_NULL:\n case JSON_UNDEFINED:\n break;\n case JSON_ARRAY:\n {\n JSONArray *array = val.u.array;\n int i;\n \n for(i = 0; i < array->len; i++) {\n json_free(array->tab[i]);\n }\n free(array);\n }\n break;\n case JSON_OBJ:\n {\n JSONObject *obj = val.u.obj;\n JSONProperty *f;\n int i;\n \n for(i = 0; i < obj->len; i++) {\n f = &obj->props[i];\n json_free(f->name);\n json_free(f->value);\n }\n free(obj);\n }\n break;\n default:\n abort();\n }\n}\n\nstatic void skip_spaces(const char **pp)\n{\n const char *p;\n p = *pp;\n for(;;) {\n if (isspace(*p)) {\n p++;\n } else if (p[0] == '/' && p[1] == '/') {\n p += 2;\n while (*p != '\\0' && *p != '\\n')\n p++;\n } else if (p[0] == '/' && p[1] == '*') {\n p += 2;\n while (*p != '\\0' && (p[0] != '*' || p[1] != '/'))\n p++;\n if (*p != '\\0')\n p += 2;\n } else {\n break;\n }\n }\n *pp = p;\n}\n\nstatic inline BOOL is_ident_first(int c)\n{\n return (c >= 'a' && c <= 'z') ||\n (c >= 'A' && c <= 'Z') ||\n c == '_' || c == '$';\n}\n\nstatic int parse_ident(char *buf, int buf_size, const char **pp)\n{\n char *q;\n const char *p;\n p = *pp;\n q = buf;\n *q++ = *p++; /* first char is already tested */\n while (is_ident_first(*p) || isdigit(*p)) {\n if ((q - buf) >= buf_size - 1)\n return -1;\n *q++ = *p++;\n }\n *pp = p;\n *q = '\\0';\n return 0;\n}\n\nJSONValue json_parse_value2(const char **pp)\n{\n char buf[128];\n const char *p;\n JSONValue val, val1, tag;\n \n p = *pp;\n skip_spaces(&p);\n if (*p == '\\0') {\n return json_error_new(\"unexpected end of file\");\n }\n if (isdigit(*p)) {\n val = json_int32_new(strtol(p, (char **)&p, 0));\n } else if (*p == '\"') {\n val = parse_string(&p);\n } else if (*p == '{') {\n p++;\n val = json_object_new();\n for(;;) {\n skip_spaces(&p);\n if (*p == '}') {\n p++;\n break;\n }\n if (*p == '\"') {\n tag = parse_string(&p);\n if (json_is_error(tag))\n return tag;\n } else if (is_ident_first(*p)) {\n if (parse_ident(buf, sizeof(buf), &p) < 0)\n goto invalid_prop;\n tag = json_string_new(buf);\n } else {\n goto invalid_prop;\n }\n // printf(\"property: %s\\n\", json_get_str(tag));\n if (tag.u.str->len == 0) {\n invalid_prop:\n return json_error_new(\"Invalid property name\");\n }\n skip_spaces(&p);\n if (*p != ':') {\n return json_error_new(\"':' expected\");\n }\n p++;\n \n val1 = json_parse_value2(&p);\n json_object_set(val, tag.u.str->data, val1);\n\n skip_spaces(&p);\n if (*p == ',') {\n p++;\n } else if (*p != '}') {\n return json_error_new(\"expecting ',' or '}'\");\n }\n }\n } else if (*p == '[') {\n int idx;\n \n p++;\n val = json_array_new();\n idx = 0;\n for(;;) {\n skip_spaces(&p);\n if (*p == ']') {\n p++;\n break;\n }\n val1 = json_parse_value2(&p);\n json_array_set(val, idx++, val1);\n\n skip_spaces(&p);\n if (*p == ',') {\n p++;\n } else if (*p != ']') {\n return json_error_new(\"expecting ',' or ']'\");\n }\n }\n } else if (is_ident_first(*p)) {\n if (parse_ident(buf, sizeof(buf), &p) < 0)\n goto unknown_id;\n if (!strcmp(buf, \"null\")) {\n val = json_null_new();\n } else if (!strcmp(buf, \"true\")) {\n val = json_bool_new(TRUE);\n } else if (!strcmp(buf, \"false\")) {\n val = json_bool_new(FALSE);\n } else {\n unknown_id:\n return json_error_new(\"unknown identifier: '%s'\", buf);\n }\n } else {\n return json_error_new(\"unexpected character\");\n }\n *pp = p;\n return val;\n}\n\nJSONValue json_parse_value(const char *p)\n{\n JSONValue val;\n val = json_parse_value2(&p); \n if (json_is_error(val))\n return val;\n skip_spaces(&p);\n if (*p != '\\0') {\n json_free(val);\n return json_error_new(\"unexpected characters at the end\");\n }\n return val;\n}\n\nJSONValue json_parse_value_len(const char *p, int len)\n{\n char *str;\n JSONValue val;\n str = malloc(len + 1);\n memcpy(str, p, len);\n str[len] = '\\0';\n val = json_parse_value(str);\n free(str);\n return val;\n}\n"], ["/linuxpdf/tinyemu/x86_cpu.c", "/*\n * x86 CPU emulator stub\n * \n * Copyright (c) 2011-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"x86_cpu.h\"\n\nX86CPUState *x86_cpu_init(PhysMemoryMap *mem_map)\n{\n fprintf(stderr, \"x86 emulator is not supported\\n\");\n exit(1);\n}\n\nvoid x86_cpu_end(X86CPUState *s)\n{\n}\n\nvoid x86_cpu_interp(X86CPUState *s, int max_cycles1)\n{\n}\n\nvoid x86_cpu_set_irq(X86CPUState *s, BOOL set)\n{\n}\n\nvoid x86_cpu_set_reg(X86CPUState *s, int reg, uint32_t val)\n{\n}\n\nuint32_t x86_cpu_get_reg(X86CPUState *s, int reg)\n{\n return 0;\n}\n\nvoid x86_cpu_set_seg(X86CPUState *s, int seg, const X86CPUSeg *sd)\n{\n}\n\nvoid x86_cpu_set_get_hard_intno(X86CPUState *s,\n int (*get_hard_intno)(void *opaque),\n void *opaque)\n{\n}\n\nvoid x86_cpu_set_get_tsc(X86CPUState *s,\n uint64_t (*get_tsc)(void *opaque),\n void *opaque)\n{\n}\n\nvoid x86_cpu_set_port_io(X86CPUState *s, \n DeviceReadFunc *port_read, DeviceWriteFunc *port_write,\n void *opaque)\n{\n}\n\nint64_t x86_cpu_get_cycles(X86CPUState *s)\n{\n return 0;\n}\n\nBOOL x86_cpu_get_power_down(X86CPUState *s)\n{\n return FALSE;\n}\n\nvoid x86_cpu_flush_tlb_write_range_ram(X86CPUState *s,\n uint8_t *ram_ptr, size_t ram_size)\n{\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_timer.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_timer.c\t8.1 (Berkeley) 6/10/93\n * tcp_timer.c,v 1.2 1994/08/02 07:49:10 davidg Exp\n */\n\n#include \"slirp.h\"\n\nstatic struct tcpcb *tcp_timers(register struct tcpcb *tp, int timer);\n\n/*\n * Fast timeout routine for processing delayed acks\n */\nvoid\ntcp_fasttimo(Slirp *slirp)\n{\n\tregister struct socket *so;\n\tregister struct tcpcb *tp;\n\n\tDEBUG_CALL(\"tcp_fasttimo\");\n\n\tso = slirp->tcb.so_next;\n\tif (so)\n\tfor (; so != &slirp->tcb; so = so->so_next)\n\t\tif ((tp = (struct tcpcb *)so->so_tcpcb) &&\n\t\t (tp->t_flags & TF_DELACK)) {\n\t\t\ttp->t_flags &= ~TF_DELACK;\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\t(void) tcp_output(tp);\n\t\t}\n}\n\n/*\n * Tcp protocol timeout routine called every 500 ms.\n * Updates the timers in all active tcb's and\n * causes finite state machine actions if timers expire.\n */\nvoid\ntcp_slowtimo(Slirp *slirp)\n{\n\tregister struct socket *ip, *ipnxt;\n\tregister struct tcpcb *tp;\n\tregister int i;\n\n\tDEBUG_CALL(\"tcp_slowtimo\");\n\n\t/*\n\t * Search through tcb's and update active timers.\n\t */\n\tip = slirp->tcb.so_next;\n if (ip == NULL) {\n return;\n }\n\tfor (; ip != &slirp->tcb; ip = ipnxt) {\n\t\tipnxt = ip->so_next;\n\t\ttp = sototcpcb(ip);\n if (tp == NULL) {\n continue;\n }\n\t\tfor (i = 0; i < TCPT_NTIMERS; i++) {\n\t\t\tif (tp->t_timer[i] && --tp->t_timer[i] == 0) {\n\t\t\t\ttcp_timers(tp,i);\n\t\t\t\tif (ipnxt->so_prev != ip)\n\t\t\t\t\tgoto tpgone;\n\t\t\t}\n\t\t}\n\t\ttp->t_idle++;\n\t\tif (tp->t_rtt)\n\t\t tp->t_rtt++;\ntpgone:\n\t\t;\n\t}\n\tslirp->tcp_iss += TCP_ISSINCR/PR_SLOWHZ;\t/* increment iss */\n\tslirp->tcp_now++;\t\t\t\t/* for timestamps */\n}\n\n/*\n * Cancel all timers for TCP tp.\n */\nvoid\ntcp_canceltimers(struct tcpcb *tp)\n{\n\tregister int i;\n\n\tfor (i = 0; i < TCPT_NTIMERS; i++)\n\t\ttp->t_timer[i] = 0;\n}\n\nconst int tcp_backoff[TCP_MAXRXTSHIFT + 1] =\n { 1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64 };\n\n/*\n * TCP timer processing.\n */\nstatic struct tcpcb *\ntcp_timers(register struct tcpcb *tp, int timer)\n{\n\tregister int rexmt;\n\n\tDEBUG_CALL(\"tcp_timers\");\n\n\tswitch (timer) {\n\n\t/*\n\t * 2 MSL timeout in shutdown went off. If we're closed but\n\t * still waiting for peer to close and connection has been idle\n\t * too long, or if 2MSL time is up from TIME_WAIT, delete connection\n\t * control block. Otherwise, check again in a bit.\n\t */\n\tcase TCPT_2MSL:\n\t\tif (tp->t_state != TCPS_TIME_WAIT &&\n\t\t tp->t_idle <= TCP_MAXIDLE)\n\t\t\ttp->t_timer[TCPT_2MSL] = TCPTV_KEEPINTVL;\n\t\telse\n\t\t\ttp = tcp_close(tp);\n\t\tbreak;\n\n\t/*\n\t * Retransmission timer went off. Message has not\n\t * been acked within retransmit interval. Back off\n\t * to a longer retransmit interval and retransmit one segment.\n\t */\n\tcase TCPT_REXMT:\n\n\t\t/*\n\t\t * XXXXX If a packet has timed out, then remove all the queued\n\t\t * packets for that session.\n\t\t */\n\n\t\tif (++tp->t_rxtshift > TCP_MAXRXTSHIFT) {\n\t\t\t/*\n\t\t\t * This is a hack to suit our terminal server here at the uni of canberra\n\t\t\t * since they have trouble with zeroes... It usually lets them through\n\t\t\t * unharmed, but under some conditions, it'll eat the zeros. If we\n\t\t\t * keep retransmitting it, it'll keep eating the zeroes, so we keep\n\t\t\t * retransmitting, and eventually the connection dies...\n\t\t\t * (this only happens on incoming data)\n\t\t\t *\n\t\t\t * So, if we were gonna drop the connection from too many retransmits,\n\t\t\t * don't... instead halve the t_maxseg, which might break up the NULLs and\n\t\t\t * let them through\n\t\t\t *\n\t\t\t * *sigh*\n\t\t\t */\n\n\t\t\ttp->t_maxseg >>= 1;\n\t\t\tif (tp->t_maxseg < 32) {\n\t\t\t\t/*\n\t\t\t\t * We tried our best, now the connection must die!\n\t\t\t\t */\n\t\t\t\ttp->t_rxtshift = TCP_MAXRXTSHIFT;\n\t\t\t\ttp = tcp_drop(tp, tp->t_softerror);\n\t\t\t\t/* tp->t_softerror : ETIMEDOUT); */ /* XXX */\n\t\t\t\treturn (tp); /* XXX */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set rxtshift to 6, which is still at the maximum\n\t\t\t * backoff time\n\t\t\t */\n\t\t\ttp->t_rxtshift = 6;\n\t\t}\n\t\trexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];\n\t\tTCPT_RANGESET(tp->t_rxtcur, rexmt,\n\t\t (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */\n\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t/*\n\t\t * If losing, let the lower level know and try for\n\t\t * a better route. Also, if we backed off this far,\n\t\t * our srtt estimate is probably bogus. Clobber it\n\t\t * so we'll take the next rtt measurement as our srtt;\n\t\t * move the current srtt into rttvar to keep the current\n\t\t * retransmit times until then.\n\t\t */\n\t\tif (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {\n\t\t\ttp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);\n\t\t\ttp->t_srtt = 0;\n\t\t}\n\t\ttp->snd_nxt = tp->snd_una;\n\t\t/*\n\t\t * If timing a segment in this window, stop the timer.\n\t\t */\n\t\ttp->t_rtt = 0;\n\t\t/*\n\t\t * Close the congestion window down to one segment\n\t\t * (we'll open it by one segment for each ack we get).\n\t\t * Since we probably have a window's worth of unacked\n\t\t * data accumulated, this \"slow start\" keeps us from\n\t\t * dumping all that data as back-to-back packets (which\n\t\t * might overwhelm an intermediate gateway).\n\t\t *\n\t\t * There are two phases to the opening: Initially we\n\t\t * open by one mss on each ack. This makes the window\n\t\t * size increase exponentially with time. If the\n\t\t * window is larger than the path can handle, this\n\t\t * exponential growth results in dropped packet(s)\n\t\t * almost immediately. To get more time between\n\t\t * drops but still \"push\" the network to take advantage\n\t\t * of improving conditions, we switch from exponential\n\t\t * to linear window opening at some threshold size.\n\t\t * For a threshold, we use half the current window\n\t\t * size, truncated to a multiple of the mss.\n\t\t *\n\t\t * (the minimum cwnd that will give us exponential\n\t\t * growth is 2 mss. We don't allow the threshold\n\t\t * to go below this.)\n\t\t */\n\t\t{\n\t\tu_int win = min(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg;\n\t\tif (win < 2)\n\t\t\twin = 2;\n\t\ttp->snd_cwnd = tp->t_maxseg;\n\t\ttp->snd_ssthresh = win * tp->t_maxseg;\n\t\ttp->t_dupacks = 0;\n\t\t}\n\t\t(void) tcp_output(tp);\n\t\tbreak;\n\n\t/*\n\t * Persistence timer into zero window.\n\t * Force a byte to be output, if possible.\n\t */\n\tcase TCPT_PERSIST:\n\t\ttcp_setpersist(tp);\n\t\ttp->t_force = 1;\n\t\t(void) tcp_output(tp);\n\t\ttp->t_force = 0;\n\t\tbreak;\n\n\t/*\n\t * Keep-alive timer went off; send something\n\t * or drop connection if idle for too long.\n\t */\n\tcase TCPT_KEEP:\n\t\tif (tp->t_state < TCPS_ESTABLISHED)\n\t\t\tgoto dropit;\n\n\t\tif ((SO_OPTIONS) && tp->t_state <= TCPS_CLOSE_WAIT) {\n\t\t \tif (tp->t_idle >= TCPTV_KEEP_IDLE + TCP_MAXIDLE)\n\t\t\t\tgoto dropit;\n\t\t\t/*\n\t\t\t * Send a packet designed to force a response\n\t\t\t * if the peer is up and reachable:\n\t\t\t * either an ACK if the connection is still alive,\n\t\t\t * or an RST if the peer has closed the connection\n\t\t\t * due to timeout or reboot.\n\t\t\t * Using sequence number tp->snd_una-1\n\t\t\t * causes the transmitted zero-length segment\n\t\t\t * to lie outside the receive window;\n\t\t\t * by the protocol spec, this requires the\n\t\t\t * correspondent TCP to respond.\n\t\t\t */\n\t\t\ttcp_respond(tp, &tp->t_template, (struct mbuf *)NULL,\n\t\t\t tp->rcv_nxt, tp->snd_una - 1, 0);\n\t\t\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;\n\t\t} else\n\t\t\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;\n\t\tbreak;\n\n\tdropit:\n\t\ttp = tcp_drop(tp, 0);\n\t\tbreak;\n\t}\n\n\treturn (tp);\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_output.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_output.c\t8.3 (Berkeley) 12/30/93\n * tcp_output.c,v 1.3 1994/09/15 10:36:55 davidg Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\nstatic const u_char tcp_outflags[TCP_NSTATES] = {\n\tTH_RST|TH_ACK, 0, TH_SYN, TH_SYN|TH_ACK,\n\tTH_ACK, TH_ACK, TH_FIN|TH_ACK, TH_FIN|TH_ACK,\n\tTH_FIN|TH_ACK, TH_ACK, TH_ACK,\n};\n\n\n#define MAX_TCPOPTLEN\t32\t/* max # bytes that go in options */\n\n/*\n * Tcp output routine: figure out what should be sent and send it.\n */\nint\ntcp_output(struct tcpcb *tp)\n{\n\tregister struct socket *so = tp->t_socket;\n\tregister long len, win;\n\tint off, flags, error;\n\tregister struct mbuf *m;\n\tregister struct tcpiphdr *ti;\n\tu_char opt[MAX_TCPOPTLEN];\n\tunsigned optlen, hdrlen;\n\tint idle, sendalot;\n\n\tDEBUG_CALL(\"tcp_output\");\n\tDEBUG_ARG(\"tp = %lx\", (long )tp);\n\n\t/*\n\t * Determine length of data that should be transmitted,\n\t * and flags that will be used.\n\t * If there is some data or critical controls (SYN, RST)\n\t * to send, then transmit; otherwise, investigate further.\n\t */\n\tidle = (tp->snd_max == tp->snd_una);\n\tif (idle && tp->t_idle >= tp->t_rxtcur)\n\t\t/*\n\t\t * We have been idle for \"a while\" and no acks are\n\t\t * expected to clock out any data we send --\n\t\t * slow start to get ack \"clock\" running again.\n\t\t */\n\t\ttp->snd_cwnd = tp->t_maxseg;\nagain:\n\tsendalot = 0;\n\toff = tp->snd_nxt - tp->snd_una;\n\twin = min(tp->snd_wnd, tp->snd_cwnd);\n\n\tflags = tcp_outflags[tp->t_state];\n\n\tDEBUG_MISC((dfd, \" --- tcp_output flags = 0x%x\\n\",flags));\n\n\t/*\n\t * If in persist timeout with window of 0, send 1 byte.\n\t * Otherwise, if window is small but nonzero\n\t * and timer expired, we will send what we can\n\t * and go to transmit state.\n\t */\n\tif (tp->t_force) {\n\t\tif (win == 0) {\n\t\t\t/*\n\t\t\t * If we still have some data to send, then\n\t\t\t * clear the FIN bit. Usually this would\n\t\t\t * happen below when it realizes that we\n\t\t\t * aren't sending all the data. However,\n\t\t\t * if we have exactly 1 byte of unset data,\n\t\t\t * then it won't clear the FIN bit below,\n\t\t\t * and if we are in persist state, we wind\n\t\t\t * up sending the packet without recording\n\t\t\t * that we sent the FIN bit.\n\t\t\t *\n\t\t\t * We can't just blindly clear the FIN bit,\n\t\t\t * because if we don't have any more data\n\t\t\t * to send then the probe will be the FIN\n\t\t\t * itself.\n\t\t\t */\n\t\t\tif (off < so->so_snd.sb_cc)\n\t\t\t\tflags &= ~TH_FIN;\n\t\t\twin = 1;\n\t\t} else {\n\t\t\ttp->t_timer[TCPT_PERSIST] = 0;\n\t\t\ttp->t_rxtshift = 0;\n\t\t}\n\t}\n\n\tlen = min(so->so_snd.sb_cc, win) - off;\n\n\tif (len < 0) {\n\t\t/*\n\t\t * If FIN has been sent but not acked,\n\t\t * but we haven't been called to retransmit,\n\t\t * len will be -1. Otherwise, window shrank\n\t\t * after we sent into it. If window shrank to 0,\n\t\t * cancel pending retransmit and pull snd_nxt\n\t\t * back to (closed) window. We will enter persist\n\t\t * state below. If the window didn't close completely,\n\t\t * just wait for an ACK.\n\t\t */\n\t\tlen = 0;\n\t\tif (win == 0) {\n\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\ttp->snd_nxt = tp->snd_una;\n\t\t}\n\t}\n\n\tif (len > tp->t_maxseg) {\n\t\tlen = tp->t_maxseg;\n\t\tsendalot = 1;\n\t}\n\tif (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc))\n\t\tflags &= ~TH_FIN;\n\n\twin = sbspace(&so->so_rcv);\n\n\t/*\n\t * Sender silly window avoidance. If connection is idle\n\t * and can send all data, a maximum segment,\n\t * at least a maximum default-size segment do it,\n\t * or are forced, do it; otherwise don't bother.\n\t * If peer's buffer is tiny, then send\n\t * when window is at least half open.\n\t * If retransmitting (possibly after persist timer forced us\n\t * to send into a small window), then must resend.\n\t */\n\tif (len) {\n\t\tif (len == tp->t_maxseg)\n\t\t\tgoto send;\n\t\tif ((1 || idle || tp->t_flags & TF_NODELAY) &&\n\t\t len + off >= so->so_snd.sb_cc)\n\t\t\tgoto send;\n\t\tif (tp->t_force)\n\t\t\tgoto send;\n\t\tif (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)\n\t\t\tgoto send;\n\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_max))\n\t\t\tgoto send;\n\t}\n\n\t/*\n\t * Compare available window to amount of window\n\t * known to peer (as advertised window less\n\t * next expected input). If the difference is at least two\n\t * max size segments, or at least 50% of the maximum possible\n\t * window, then want to send a window update to peer.\n\t */\n\tif (win > 0) {\n\t\t/*\n\t\t * \"adv\" is the amount we can increase the window,\n\t\t * taking into account that we are limited by\n\t\t * TCP_MAXWIN << tp->rcv_scale.\n\t\t */\n\t\tlong adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -\n\t\t\t(tp->rcv_adv - tp->rcv_nxt);\n\n\t\tif (adv >= (long) (2 * tp->t_maxseg))\n\t\t\tgoto send;\n\t\tif (2 * adv >= (long) so->so_rcv.sb_datalen)\n\t\t\tgoto send;\n\t}\n\n\t/*\n\t * Send if we owe peer an ACK.\n\t */\n\tif (tp->t_flags & TF_ACKNOW)\n\t\tgoto send;\n\tif (flags & (TH_SYN|TH_RST))\n\t\tgoto send;\n\tif (SEQ_GT(tp->snd_up, tp->snd_una))\n\t\tgoto send;\n\t/*\n\t * If our state indicates that FIN should be sent\n\t * and we have not yet done so, or we're retransmitting the FIN,\n\t * then we need to send.\n\t */\n\tif (flags & TH_FIN &&\n\t ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))\n\t\tgoto send;\n\n\t/*\n\t * TCP window updates are not reliable, rather a polling protocol\n\t * using ``persist'' packets is used to insure receipt of window\n\t * updates. The three ``states'' for the output side are:\n\t *\tidle\t\t\tnot doing retransmits or persists\n\t *\tpersisting\t\tto move a small or zero window\n\t *\t(re)transmitting\tand thereby not persisting\n\t *\n\t * tp->t_timer[TCPT_PERSIST]\n\t *\tis set when we are in persist state.\n\t * tp->t_force\n\t *\tis set when we are called to send a persist packet.\n\t * tp->t_timer[TCPT_REXMT]\n\t *\tis set when we are retransmitting\n\t * The output side is idle when both timers are zero.\n\t *\n\t * If send window is too small, there is data to transmit, and no\n\t * retransmit or persist is pending, then go to persist state.\n\t * If nothing happens soon, send when timer expires:\n\t * if window is nonzero, transmit what we can,\n\t * otherwise force out a byte.\n\t */\n\tif (so->so_snd.sb_cc && tp->t_timer[TCPT_REXMT] == 0 &&\n\t tp->t_timer[TCPT_PERSIST] == 0) {\n\t\ttp->t_rxtshift = 0;\n\t\ttcp_setpersist(tp);\n\t}\n\n\t/*\n\t * No reason to send a segment, just return.\n\t */\n\treturn (0);\n\nsend:\n\t/*\n\t * Before ESTABLISHED, force sending of initial options\n\t * unless TCP set not to do any options.\n\t * NOTE: we assume that the IP/TCP header plus TCP options\n\t * always fit in a single mbuf, leaving room for a maximum\n\t * link header, i.e.\n\t *\tmax_linkhdr + sizeof (struct tcpiphdr) + optlen <= MHLEN\n\t */\n\toptlen = 0;\n\thdrlen = sizeof (struct tcpiphdr);\n\tif (flags & TH_SYN) {\n\t\ttp->snd_nxt = tp->iss;\n\t\tif ((tp->t_flags & TF_NOOPT) == 0) {\n\t\t\tuint16_t mss;\n\n\t\t\topt[0] = TCPOPT_MAXSEG;\n\t\t\topt[1] = 4;\n\t\t\tmss = htons((uint16_t) tcp_mss(tp, 0));\n\t\t\tmemcpy((caddr_t)(opt + 2), (caddr_t)&mss, sizeof(mss));\n\t\t\toptlen = 4;\n\t\t}\n \t}\n\n \thdrlen += optlen;\n\n\t/*\n\t * Adjust data length if insertion of options will\n\t * bump the packet length beyond the t_maxseg length.\n\t */\n\t if (len > tp->t_maxseg - optlen) {\n\t\tlen = tp->t_maxseg - optlen;\n\t\tsendalot = 1;\n\t }\n\n\t/*\n\t * Grab a header mbuf, attaching a copy of data to\n\t * be transmitted, and initialize the header from\n\t * the template for sends on this connection.\n\t */\n\tif (len) {\n\t\tm = m_get(so->slirp);\n\t\tif (m == NULL) {\n\t\t\terror = 1;\n\t\t\tgoto out;\n\t\t}\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\tm->m_len = hdrlen;\n\n\t\tsbcopy(&so->so_snd, off, (int) len, mtod(m, caddr_t) + hdrlen);\n\t\tm->m_len += len;\n\n\t\t/*\n\t\t * If we're sending everything we've got, set PUSH.\n\t\t * (This will keep happy those implementations which only\n\t\t * give data to the user when a buffer fills or\n\t\t * a PUSH comes in.)\n\t\t */\n\t\tif (off + len == so->so_snd.sb_cc)\n\t\t\tflags |= TH_PUSH;\n\t} else {\n\t\tm = m_get(so->slirp);\n\t\tif (m == NULL) {\n\t\t\terror = 1;\n\t\t\tgoto out;\n\t\t}\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\tm->m_len = hdrlen;\n\t}\n\n\tti = mtod(m, struct tcpiphdr *);\n\n\tmemcpy((caddr_t)ti, &tp->t_template, sizeof (struct tcpiphdr));\n\n\t/*\n\t * Fill in fields, remembering maximum advertised\n\t * window for use in delaying messages about window sizes.\n\t * If resending a FIN, be sure not to use a new sequence number.\n\t */\n\tif (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&\n\t tp->snd_nxt == tp->snd_max)\n\t\ttp->snd_nxt--;\n\t/*\n\t * If we are doing retransmissions, then snd_nxt will\n\t * not reflect the first unsent octet. For ACK only\n\t * packets, we do not want the sequence number of the\n\t * retransmitted packet, we want the sequence number\n\t * of the next unsent octet. So, if there is no data\n\t * (and no SYN or FIN), use snd_max instead of snd_nxt\n\t * when filling in ti_seq. But if we are in persist\n\t * state, snd_max might reflect one byte beyond the\n\t * right edge of the window, so use snd_nxt in that\n\t * case, since we know we aren't doing a retransmission.\n\t * (retransmit and persist are mutually exclusive...)\n\t */\n\tif (len || (flags & (TH_SYN|TH_FIN)) || tp->t_timer[TCPT_PERSIST])\n\t\tti->ti_seq = htonl(tp->snd_nxt);\n\telse\n\t\tti->ti_seq = htonl(tp->snd_max);\n\tti->ti_ack = htonl(tp->rcv_nxt);\n\tif (optlen) {\n\t\tmemcpy((caddr_t)(ti + 1), (caddr_t)opt, optlen);\n\t\tti->ti_off = (sizeof (struct tcphdr) + optlen) >> 2;\n\t}\n\tti->ti_flags = flags;\n\t/*\n\t * Calculate receive window. Don't shrink window,\n\t * but avoid silly window syndrome.\n\t */\n\tif (win < (long)(so->so_rcv.sb_datalen / 4) && win < (long)tp->t_maxseg)\n\t\twin = 0;\n\tif (win > (long)TCP_MAXWIN << tp->rcv_scale)\n\t\twin = (long)TCP_MAXWIN << tp->rcv_scale;\n\tif (win < (long)(tp->rcv_adv - tp->rcv_nxt))\n\t\twin = (long)(tp->rcv_adv - tp->rcv_nxt);\n\tti->ti_win = htons((uint16_t) (win>>tp->rcv_scale));\n\n\tif (SEQ_GT(tp->snd_up, tp->snd_una)) {\n\t\tti->ti_urp = htons((uint16_t)(tp->snd_up - ntohl(ti->ti_seq)));\n\t\tti->ti_flags |= TH_URG;\n\t} else\n\t\t/*\n\t\t * If no urgent pointer to send, then we pull\n\t\t * the urgent pointer to the left edge of the send window\n\t\t * so that it doesn't drift into the send window on sequence\n\t\t * number wraparound.\n\t\t */\n\t\ttp->snd_up = tp->snd_una;\t\t/* drag it along */\n\n\t/*\n\t * Put TCP length in extended header, and then\n\t * checksum extended header and data.\n\t */\n\tif (len + optlen)\n\t\tti->ti_len = htons((uint16_t)(sizeof (struct tcphdr) +\n\t\t optlen + len));\n\tti->ti_sum = cksum(m, (int)(hdrlen + len));\n\n\t/*\n\t * In transmit state, time the transmission and arrange for\n\t * the retransmit. In persist state, just set snd_max.\n\t */\n\tif (tp->t_force == 0 || tp->t_timer[TCPT_PERSIST] == 0) {\n\t\ttcp_seq startseq = tp->snd_nxt;\n\n\t\t/*\n\t\t * Advance snd_nxt over sequence space of this segment.\n\t\t */\n\t\tif (flags & (TH_SYN|TH_FIN)) {\n\t\t\tif (flags & TH_SYN)\n\t\t\t\ttp->snd_nxt++;\n\t\t\tif (flags & TH_FIN) {\n\t\t\t\ttp->snd_nxt++;\n\t\t\t\ttp->t_flags |= TF_SENTFIN;\n\t\t\t}\n\t\t}\n\t\ttp->snd_nxt += len;\n\t\tif (SEQ_GT(tp->snd_nxt, tp->snd_max)) {\n\t\t\ttp->snd_max = tp->snd_nxt;\n\t\t\t/*\n\t\t\t * Time this transmission if not a retransmission and\n\t\t\t * not currently timing anything.\n\t\t\t */\n\t\t\tif (tp->t_rtt == 0) {\n\t\t\t\ttp->t_rtt = 1;\n\t\t\t\ttp->t_rtseq = startseq;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Set retransmit timer if not currently set,\n\t\t * and not doing an ack or a keep-alive probe.\n\t\t * Initial value for retransmit timer is smoothed\n\t\t * round-trip time + 2 * round-trip time variance.\n\t\t * Initialize shift counter which is used for backoff\n\t\t * of retransmit time.\n\t\t */\n\t\tif (tp->t_timer[TCPT_REXMT] == 0 &&\n\t\t tp->snd_nxt != tp->snd_una) {\n\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t\tif (tp->t_timer[TCPT_PERSIST]) {\n\t\t\t\ttp->t_timer[TCPT_PERSIST] = 0;\n\t\t\t\ttp->t_rxtshift = 0;\n\t\t\t}\n\t\t}\n\t} else\n\t\tif (SEQ_GT(tp->snd_nxt + len, tp->snd_max))\n\t\t\ttp->snd_max = tp->snd_nxt + len;\n\n\t/*\n\t * Fill in IP length and desired time to live and\n\t * send to IP level. There should be a better way\n\t * to handle ttl and tos; we could keep them in\n\t * the template, but need a way to checksum without them.\n\t */\n\tm->m_len = hdrlen + len; /* XXX Needed? m_len should be correct */\n\n {\n\n\t((struct ip *)ti)->ip_len = m->m_len;\n\n\t((struct ip *)ti)->ip_ttl = IPDEFTTL;\n\t((struct ip *)ti)->ip_tos = so->so_iptos;\n\n\terror = ip_output(so, m);\n }\n\tif (error) {\nout:\n\t\treturn (error);\n\t}\n\n\t/*\n\t * Data sent (as far as we can tell).\n\t * If this advertises a larger window than any other segment,\n\t * then remember the size of the advertised window.\n\t * Any pending ACK has now been sent.\n\t */\n\tif (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))\n\t\ttp->rcv_adv = tp->rcv_nxt + win;\n\ttp->last_ack_sent = tp->rcv_nxt;\n\ttp->t_flags &= ~(TF_ACKNOW|TF_DELACK);\n\tif (sendalot)\n\t\tgoto again;\n\n\treturn (0);\n}\n\nvoid\ntcp_setpersist(struct tcpcb *tp)\n{\n int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;\n\n\t/*\n\t * Start/restart persistence timer.\n\t */\n\tTCPT_RANGESET(tp->t_timer[TCPT_PERSIST],\n\t t * tcp_backoff[tp->t_rxtshift],\n\t TCPTV_PERSMIN, TCPTV_PERSMAX);\n\tif (tp->t_rxtshift < TCP_MAXRXTSHIFT)\n\t\ttp->t_rxtshift++;\n}\n"], ["/linuxpdf/tinyemu/fs_utils.c", "/*\n * Misc FS utilities\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs_utils.h\"\n\n/* last byte is the version */\nconst uint8_t encrypted_file_magic[4] = { 0xfb, 0xa2, 0xe9, 0x01 };\n\nchar *compose_path(const char *path, const char *name)\n{\n int path_len, name_len;\n char *d, *q;\n\n if (path[0] == '\\0') {\n d = strdup(name);\n } else {\n path_len = strlen(path);\n name_len = strlen(name);\n d = malloc(path_len + 1 + name_len + 1);\n q = d;\n memcpy(q, path, path_len);\n q += path_len;\n if (path[path_len - 1] != '/')\n *q++ = '/';\n memcpy(q, name, name_len + 1);\n }\n return d;\n}\n\nchar *compose_url(const char *base_url, const char *name)\n{\n if (strchr(name, ':')) {\n return strdup(name);\n } else {\n return compose_path(base_url, name);\n }\n}\n\nvoid skip_line(const char **pp)\n{\n const char *p;\n p = *pp;\n while (*p != '\\n' && *p != '\\0')\n p++;\n if (*p == '\\n')\n p++;\n *pp = p;\n}\n\nchar *quoted_str(const char *str)\n{\n const char *s;\n char *q;\n int c;\n char *buf;\n\n if (str[0] == '\\0')\n goto use_quote;\n s = str;\n while (*s != '\\0') {\n if (*s <= ' ' || *s > '~')\n goto use_quote;\n s++;\n }\n return strdup(str);\n use_quote:\n buf = malloc(strlen(str) * 4 + 2 + 1);\n q = buf;\n s = str;\n *q++ = '\"';\n while (*s != '\\0') {\n c = *(uint8_t *)s;\n if (c < ' ' || c == 127) {\n q += sprintf(q, \"\\\\x%02x\", c);\n } else if (c == '\\\\' || c == '\\\"') {\n q += sprintf(q, \"\\\\%c\", c);\n } else {\n *q++ = c;\n }\n s++;\n }\n *q++ = '\"';\n *q = '\\0';\n return buf;\n}\n\nint parse_fname(char *buf, int buf_size, const char **pp)\n{\n const char *p;\n char *q;\n int c, h;\n \n p = *pp;\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\0')\n return -1;\n q = buf;\n if (*p == '\"') {\n p++;\n for(;;) {\n c = *p++;\n if (c == '\\0' || c == '\\n') {\n return -1;\n } else if (c == '\\\"') {\n break;\n } else if (c == '\\\\') {\n c = *p++;\n switch(c) {\n case '\\'':\n case '\\\"':\n case '\\\\':\n goto add_char;\n case 'n':\n c = '\\n';\n goto add_char;\n case 'r':\n c = '\\r';\n goto add_char;\n case 't':\n c = '\\t';\n goto add_char;\n case 'x':\n h = from_hex(*p++);\n if (h < 0)\n return -1;\n c = h << 4;\n h = from_hex(*p++);\n if (h < 0)\n return -1;\n c |= h;\n goto add_char;\n default:\n return -1;\n }\n } else {\n add_char:\n if (q >= buf + buf_size - 1)\n return -1;\n *q++ = c;\n }\n }\n } else {\n while (!isspace_nolf(*p) && *p != '\\0' && *p != '\\n') {\n if (q >= buf + buf_size - 1)\n return -1;\n *q++ = *p++;\n }\n }\n *q = '\\0';\n *pp = p;\n return 0;\n}\n\nint parse_uint32_base(uint32_t *pval, const char **pp, int base)\n{\n const char *p, *p1;\n p = *pp;\n while (isspace_nolf(*p))\n p++;\n *pval = strtoul(p, (char **)&p1, base);\n if (p1 == p)\n return -1;\n *pp = p1;\n return 0;\n}\n\nint parse_uint64_base(uint64_t *pval, const char **pp, int base)\n{\n const char *p, *p1;\n p = *pp;\n while (isspace_nolf(*p))\n p++;\n *pval = strtoull(p, (char **)&p1, base);\n if (p1 == p)\n return -1;\n *pp = p1;\n return 0;\n}\n\nint parse_uint64(uint64_t *pval, const char **pp)\n{\n return parse_uint64_base(pval, pp, 0);\n}\n\nint parse_uint32(uint32_t *pval, const char **pp)\n{\n return parse_uint32_base(pval, pp, 0);\n}\n\nint parse_time(uint32_t *psec, uint32_t *pnsec, const char **pp)\n{\n const char *p;\n uint32_t v, m;\n p = *pp;\n if (parse_uint32(psec, &p) < 0)\n return -1;\n v = 0;\n if (*p == '.') {\n p++;\n /* XXX: inefficient */\n m = 1000000000;\n v = 0;\n while (*p >= '0' && *p <= '9') {\n m /= 10;\n v += (*p - '0') * m;\n p++;\n }\n }\n *pnsec = v;\n *pp = p;\n return 0;\n}\n\nint parse_file_id(FSFileID *pval, const char **pp)\n{\n return parse_uint64_base(pval, pp, 16);\n}\n\nchar *file_id_to_filename(char *buf, FSFileID file_id)\n{\n sprintf(buf, \"%016\" PRIx64, file_id);\n return buf;\n}\n\nvoid encode_hex(char *str, const uint8_t *buf, int len)\n{\n int i;\n for(i = 0; i < len; i++)\n sprintf(str + 2 * i, \"%02x\", buf[i]);\n}\n\nint decode_hex(uint8_t *buf, const char *str, int len)\n{\n int h0, h1, i;\n\n for(i = 0; i < len; i++) {\n h0 = from_hex(str[2 * i]);\n if (h0 < 0)\n return -1;\n h1 = from_hex(str[2 * i + 1]);\n if (h1 < 0)\n return -1;\n buf[i] = (h0 << 4) | h1;\n }\n return 0;\n}\n\n/* return NULL if no end of header found */\nconst char *skip_header(const char *p)\n{\n p = strstr(p, \"\\n\\n\");\n if (!p)\n return NULL;\n return p + 2;\n}\n\n/* return 0 if OK, < 0 if error */\nint parse_tag(char *buf, int buf_size, const char *str, const char *tag)\n{\n char tagname[128], *q;\n const char *p, *p1;\n int len;\n \n p = str;\n for(;;) {\n if (*p == '\\0' || *p == '\\n')\n break;\n q = tagname;\n while (*p != ':' && *p != '\\n' && *p != '\\0') {\n if ((q - tagname) < sizeof(tagname) - 1)\n *q++ = *p;\n p++;\n }\n *q = '\\0';\n if (*p != ':')\n return -1;\n p++;\n while (isspace_nolf(*p))\n p++;\n p1 = p;\n p = strchr(p, '\\n');\n if (!p)\n len = strlen(p1);\n else\n len = p - p1;\n if (!strcmp(tagname, tag)) {\n if (len > buf_size - 1)\n len = buf_size - 1;\n memcpy(buf, p1, len);\n buf[len] = '\\0';\n return 0;\n }\n if (!p)\n break;\n else\n p++;\n }\n return -1;\n}\n\nint parse_tag_uint64(uint64_t *pval, const char *str, const char *tag)\n{\n char buf[64];\n const char *p;\n if (parse_tag(buf, sizeof(buf), str, tag))\n return -1;\n p = buf;\n return parse_uint64(pval, &p);\n}\n\nint parse_tag_file_id(FSFileID *pval, const char *str, const char *tag)\n{\n char buf[64];\n const char *p;\n if (parse_tag(buf, sizeof(buf), str, tag))\n return -1;\n p = buf;\n return parse_uint64_base(pval, &p, 16);\n}\n\nint parse_tag_version(const char *str)\n{\n uint64_t version;\n if (parse_tag_uint64(&version, str, \"Version\"))\n return -1;\n return version;\n}\n\nBOOL is_url(const char *path)\n{\n return (strstart(path, \"http:\", NULL) ||\n strstart(path, \"https:\", NULL) ||\n strstart(path, \"file:\", NULL));\n}\n"], ["/linuxpdf/tinyemu/aes.c", "/**\n *\n * aes.c - integrated in QEMU by Fabrice Bellard from the OpenSSL project.\n */\n/*\n * rijndael-alg-fst.c\n *\n * @version 3.0 (December 2000)\n *\n * Optimised ANSI C code for the Rijndael cipher (now AES)\n *\n * @author Vincent Rijmen \n * @author Antoon Bosselaers \n * @author Paulo Barreto \n *\n * This code is hereby placed in the public domain.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS\n * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n#include \n#include \n#include \"aes.h\"\n\n#ifndef NDEBUG\n#define NDEBUG\n#endif\n\n#include \n\ntypedef uint32_t u32;\ntypedef uint16_t u16;\ntypedef uint8_t u8;\n\n#define MAXKC (256/32)\n#define MAXKB (256/8)\n#define MAXNR 14\n\n/* This controls loop-unrolling in aes_core.c */\n#undef FULL_UNROLL\n# define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3]))\n# define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); }\n\n/*\nTe0[x] = S [x].[02, 01, 01, 03];\nTe1[x] = S [x].[03, 02, 01, 01];\nTe2[x] = S [x].[01, 03, 02, 01];\nTe3[x] = S [x].[01, 01, 03, 02];\nTe4[x] = S [x].[01, 01, 01, 01];\n\nTd0[x] = Si[x].[0e, 09, 0d, 0b];\nTd1[x] = Si[x].[0b, 0e, 09, 0d];\nTd2[x] = Si[x].[0d, 0b, 0e, 09];\nTd3[x] = Si[x].[09, 0d, 0b, 0e];\nTd4[x] = Si[x].[01, 01, 01, 01];\n*/\n\nstatic const u32 Te0[256] = {\n 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU,\n 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U,\n 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU,\n 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU,\n 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U,\n 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU,\n 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU,\n 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU,\n 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU,\n 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU,\n 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U,\n 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU,\n 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU,\n 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U,\n 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU,\n 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU,\n 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU,\n 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU,\n 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU,\n 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U,\n 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU,\n 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU,\n 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU,\n 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU,\n 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U,\n 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U,\n 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U,\n 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U,\n 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU,\n 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U,\n 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U,\n 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU,\n 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU,\n 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U,\n 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U,\n 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U,\n 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU,\n 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U,\n 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU,\n 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U,\n 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU,\n 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U,\n 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U,\n 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU,\n 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U,\n 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U,\n 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U,\n 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U,\n 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U,\n 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U,\n 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U,\n 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U,\n 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU,\n 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U,\n 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U,\n 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U,\n 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U,\n 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U,\n 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U,\n 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU,\n 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U,\n 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U,\n 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U,\n 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU,\n};\nstatic const u32 Te1[256] = {\n 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU,\n 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U,\n 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU,\n 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U,\n 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU,\n 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U,\n 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU,\n 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U,\n 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U,\n 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU,\n 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U,\n 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U,\n 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U,\n 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU,\n 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U,\n 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U,\n 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU,\n 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U,\n 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U,\n 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U,\n 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU,\n 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU,\n 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U,\n 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU,\n 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU,\n 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U,\n 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU,\n 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U,\n 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU,\n 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U,\n 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U,\n 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U,\n 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU,\n 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U,\n 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU,\n 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U,\n 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU,\n 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U,\n 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U,\n 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU,\n 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU,\n 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU,\n 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U,\n 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U,\n 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU,\n 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U,\n 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU,\n 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U,\n 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU,\n 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U,\n 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU,\n 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU,\n 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U,\n 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU,\n 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U,\n 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU,\n 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U,\n 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U,\n 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U,\n 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU,\n 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU,\n 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U,\n 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU,\n 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U,\n};\nstatic const u32 Te2[256] = {\n 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU,\n 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U,\n 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU,\n 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U,\n 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU,\n 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U,\n 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU,\n 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U,\n 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U,\n 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU,\n 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U,\n 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U,\n 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U,\n 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU,\n 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U,\n 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U,\n 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU,\n 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U,\n 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U,\n 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U,\n 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU,\n 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU,\n 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U,\n 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU,\n 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU,\n 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U,\n 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU,\n 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U,\n 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU,\n 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U,\n 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U,\n 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U,\n 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU,\n 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U,\n 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU,\n 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U,\n 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU,\n 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U,\n 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U,\n 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU,\n 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU,\n 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU,\n 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U,\n 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U,\n 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU,\n 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U,\n 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU,\n 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U,\n 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU,\n 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U,\n 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU,\n 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU,\n 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U,\n 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU,\n 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U,\n 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU,\n 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U,\n 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U,\n 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U,\n 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU,\n 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU,\n 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U,\n 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU,\n 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U,\n};\nstatic const u32 Te3[256] = {\n\n 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U,\n 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U,\n 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U,\n 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU,\n 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU,\n 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU,\n 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U,\n 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU,\n 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU,\n 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U,\n 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U,\n 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU,\n 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU,\n 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU,\n 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU,\n 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU,\n 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U,\n 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU,\n 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU,\n 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U,\n 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U,\n 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U,\n 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U,\n 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U,\n 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU,\n 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U,\n 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU,\n 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU,\n 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U,\n 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U,\n 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U,\n 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU,\n 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U,\n 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU,\n 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU,\n 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U,\n 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U,\n 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU,\n 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U,\n 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU,\n 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U,\n 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U,\n 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U,\n 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U,\n 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU,\n 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U,\n 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU,\n 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U,\n 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU,\n 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U,\n 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU,\n 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU,\n 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU,\n 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU,\n 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U,\n 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U,\n 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U,\n 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U,\n 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U,\n 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U,\n 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU,\n 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U,\n 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU,\n 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU,\n};\nstatic const u32 Te4[256] = {\n 0x63636363U, 0x7c7c7c7cU, 0x77777777U, 0x7b7b7b7bU,\n 0xf2f2f2f2U, 0x6b6b6b6bU, 0x6f6f6f6fU, 0xc5c5c5c5U,\n 0x30303030U, 0x01010101U, 0x67676767U, 0x2b2b2b2bU,\n 0xfefefefeU, 0xd7d7d7d7U, 0xababababU, 0x76767676U,\n 0xcacacacaU, 0x82828282U, 0xc9c9c9c9U, 0x7d7d7d7dU,\n 0xfafafafaU, 0x59595959U, 0x47474747U, 0xf0f0f0f0U,\n 0xadadadadU, 0xd4d4d4d4U, 0xa2a2a2a2U, 0xafafafafU,\n 0x9c9c9c9cU, 0xa4a4a4a4U, 0x72727272U, 0xc0c0c0c0U,\n 0xb7b7b7b7U, 0xfdfdfdfdU, 0x93939393U, 0x26262626U,\n 0x36363636U, 0x3f3f3f3fU, 0xf7f7f7f7U, 0xccccccccU,\n 0x34343434U, 0xa5a5a5a5U, 0xe5e5e5e5U, 0xf1f1f1f1U,\n 0x71717171U, 0xd8d8d8d8U, 0x31313131U, 0x15151515U,\n 0x04040404U, 0xc7c7c7c7U, 0x23232323U, 0xc3c3c3c3U,\n 0x18181818U, 0x96969696U, 0x05050505U, 0x9a9a9a9aU,\n 0x07070707U, 0x12121212U, 0x80808080U, 0xe2e2e2e2U,\n 0xebebebebU, 0x27272727U, 0xb2b2b2b2U, 0x75757575U,\n 0x09090909U, 0x83838383U, 0x2c2c2c2cU, 0x1a1a1a1aU,\n 0x1b1b1b1bU, 0x6e6e6e6eU, 0x5a5a5a5aU, 0xa0a0a0a0U,\n 0x52525252U, 0x3b3b3b3bU, 0xd6d6d6d6U, 0xb3b3b3b3U,\n 0x29292929U, 0xe3e3e3e3U, 0x2f2f2f2fU, 0x84848484U,\n 0x53535353U, 0xd1d1d1d1U, 0x00000000U, 0xededededU,\n 0x20202020U, 0xfcfcfcfcU, 0xb1b1b1b1U, 0x5b5b5b5bU,\n 0x6a6a6a6aU, 0xcbcbcbcbU, 0xbebebebeU, 0x39393939U,\n 0x4a4a4a4aU, 0x4c4c4c4cU, 0x58585858U, 0xcfcfcfcfU,\n 0xd0d0d0d0U, 0xefefefefU, 0xaaaaaaaaU, 0xfbfbfbfbU,\n 0x43434343U, 0x4d4d4d4dU, 0x33333333U, 0x85858585U,\n 0x45454545U, 0xf9f9f9f9U, 0x02020202U, 0x7f7f7f7fU,\n 0x50505050U, 0x3c3c3c3cU, 0x9f9f9f9fU, 0xa8a8a8a8U,\n 0x51515151U, 0xa3a3a3a3U, 0x40404040U, 0x8f8f8f8fU,\n 0x92929292U, 0x9d9d9d9dU, 0x38383838U, 0xf5f5f5f5U,\n 0xbcbcbcbcU, 0xb6b6b6b6U, 0xdadadadaU, 0x21212121U,\n 0x10101010U, 0xffffffffU, 0xf3f3f3f3U, 0xd2d2d2d2U,\n 0xcdcdcdcdU, 0x0c0c0c0cU, 0x13131313U, 0xececececU,\n 0x5f5f5f5fU, 0x97979797U, 0x44444444U, 0x17171717U,\n 0xc4c4c4c4U, 0xa7a7a7a7U, 0x7e7e7e7eU, 0x3d3d3d3dU,\n 0x64646464U, 0x5d5d5d5dU, 0x19191919U, 0x73737373U,\n 0x60606060U, 0x81818181U, 0x4f4f4f4fU, 0xdcdcdcdcU,\n 0x22222222U, 0x2a2a2a2aU, 0x90909090U, 0x88888888U,\n 0x46464646U, 0xeeeeeeeeU, 0xb8b8b8b8U, 0x14141414U,\n 0xdedededeU, 0x5e5e5e5eU, 0x0b0b0b0bU, 0xdbdbdbdbU,\n 0xe0e0e0e0U, 0x32323232U, 0x3a3a3a3aU, 0x0a0a0a0aU,\n 0x49494949U, 0x06060606U, 0x24242424U, 0x5c5c5c5cU,\n 0xc2c2c2c2U, 0xd3d3d3d3U, 0xacacacacU, 0x62626262U,\n 0x91919191U, 0x95959595U, 0xe4e4e4e4U, 0x79797979U,\n 0xe7e7e7e7U, 0xc8c8c8c8U, 0x37373737U, 0x6d6d6d6dU,\n 0x8d8d8d8dU, 0xd5d5d5d5U, 0x4e4e4e4eU, 0xa9a9a9a9U,\n 0x6c6c6c6cU, 0x56565656U, 0xf4f4f4f4U, 0xeaeaeaeaU,\n 0x65656565U, 0x7a7a7a7aU, 0xaeaeaeaeU, 0x08080808U,\n 0xbabababaU, 0x78787878U, 0x25252525U, 0x2e2e2e2eU,\n 0x1c1c1c1cU, 0xa6a6a6a6U, 0xb4b4b4b4U, 0xc6c6c6c6U,\n 0xe8e8e8e8U, 0xddddddddU, 0x74747474U, 0x1f1f1f1fU,\n 0x4b4b4b4bU, 0xbdbdbdbdU, 0x8b8b8b8bU, 0x8a8a8a8aU,\n 0x70707070U, 0x3e3e3e3eU, 0xb5b5b5b5U, 0x66666666U,\n 0x48484848U, 0x03030303U, 0xf6f6f6f6U, 0x0e0e0e0eU,\n 0x61616161U, 0x35353535U, 0x57575757U, 0xb9b9b9b9U,\n 0x86868686U, 0xc1c1c1c1U, 0x1d1d1d1dU, 0x9e9e9e9eU,\n 0xe1e1e1e1U, 0xf8f8f8f8U, 0x98989898U, 0x11111111U,\n 0x69696969U, 0xd9d9d9d9U, 0x8e8e8e8eU, 0x94949494U,\n 0x9b9b9b9bU, 0x1e1e1e1eU, 0x87878787U, 0xe9e9e9e9U,\n 0xcecececeU, 0x55555555U, 0x28282828U, 0xdfdfdfdfU,\n 0x8c8c8c8cU, 0xa1a1a1a1U, 0x89898989U, 0x0d0d0d0dU,\n 0xbfbfbfbfU, 0xe6e6e6e6U, 0x42424242U, 0x68686868U,\n 0x41414141U, 0x99999999U, 0x2d2d2d2dU, 0x0f0f0f0fU,\n 0xb0b0b0b0U, 0x54545454U, 0xbbbbbbbbU, 0x16161616U,\n};\nstatic const u32 Td0[256] = {\n 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U,\n 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U,\n 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U,\n 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU,\n 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U,\n 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U,\n 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU,\n 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U,\n 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU,\n 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U,\n 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U,\n 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U,\n 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U,\n 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU,\n 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U,\n 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU,\n 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U,\n 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU,\n 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U,\n 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U,\n 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U,\n 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU,\n 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U,\n 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU,\n 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U,\n 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU,\n 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U,\n 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU,\n 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU,\n 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U,\n 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU,\n 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U,\n 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU,\n 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U,\n 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U,\n 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U,\n 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU,\n 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U,\n 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U,\n 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU,\n 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U,\n 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U,\n 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U,\n 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U,\n 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U,\n 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU,\n 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U,\n 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U,\n 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U,\n 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U,\n 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U,\n 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU,\n 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU,\n 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU,\n 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU,\n 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U,\n 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U,\n 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU,\n 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU,\n 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U,\n 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU,\n 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U,\n 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U,\n 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U,\n};\nstatic const u32 Td1[256] = {\n 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU,\n 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U,\n 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU,\n 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U,\n 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U,\n 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U,\n 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U,\n 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U,\n 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U,\n 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU,\n 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU,\n 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU,\n 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U,\n 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU,\n 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U,\n 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U,\n 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U,\n 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU,\n 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU,\n 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U,\n 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU,\n 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U,\n 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU,\n 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU,\n 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U,\n 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U,\n 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U,\n 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU,\n 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U,\n 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU,\n 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U,\n 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U,\n 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U,\n 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU,\n 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U,\n 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U,\n 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U,\n 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U,\n 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U,\n 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U,\n 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU,\n 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU,\n 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U,\n 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU,\n 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U,\n 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU,\n 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU,\n 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U,\n 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU,\n 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U,\n 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U,\n 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U,\n 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U,\n 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U,\n 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U,\n 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U,\n 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU,\n 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U,\n 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U,\n 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU,\n 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U,\n 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U,\n 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U,\n 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U,\n};\nstatic const u32 Td2[256] = {\n 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U,\n 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U,\n 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U,\n 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U,\n 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU,\n 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U,\n 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U,\n 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U,\n 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U,\n 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU,\n 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U,\n 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U,\n 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU,\n 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U,\n 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U,\n 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U,\n 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U,\n 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U,\n 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U,\n 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU,\n\n 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U,\n 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U,\n 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U,\n 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U,\n 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U,\n 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU,\n 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU,\n 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U,\n 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU,\n 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U,\n 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU,\n 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU,\n 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU,\n 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU,\n 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U,\n 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U,\n 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U,\n 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U,\n 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U,\n 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U,\n 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U,\n 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU,\n 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU,\n 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U,\n 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U,\n 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU,\n 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU,\n 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U,\n 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U,\n 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U,\n 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U,\n 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U,\n 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U,\n 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U,\n 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU,\n 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U,\n 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U,\n 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U,\n 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U,\n 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U,\n 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U,\n 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU,\n 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U,\n 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U,\n};\nstatic const u32 Td3[256] = {\n 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU,\n 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU,\n 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U,\n 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U,\n 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU,\n 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU,\n 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U,\n 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU,\n 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U,\n 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU,\n 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U,\n 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U,\n 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U,\n 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U,\n 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U,\n 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU,\n 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU,\n 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U,\n 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U,\n 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU,\n 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU,\n 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U,\n 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U,\n 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U,\n 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U,\n 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU,\n 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U,\n 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U,\n 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU,\n 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU,\n 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U,\n 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U,\n 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U,\n 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU,\n 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U,\n 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U,\n 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U,\n 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U,\n 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U,\n 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U,\n 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U,\n 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU,\n 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U,\n 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U,\n 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU,\n 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU,\n 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U,\n 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU,\n 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U,\n 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U,\n 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U,\n 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U,\n 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U,\n 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U,\n 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU,\n 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU,\n 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU,\n 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU,\n 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U,\n 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U,\n 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U,\n 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU,\n 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U,\n 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U,\n};\nstatic const u32 Td4[256] = {\n 0x52525252U, 0x09090909U, 0x6a6a6a6aU, 0xd5d5d5d5U,\n 0x30303030U, 0x36363636U, 0xa5a5a5a5U, 0x38383838U,\n 0xbfbfbfbfU, 0x40404040U, 0xa3a3a3a3U, 0x9e9e9e9eU,\n 0x81818181U, 0xf3f3f3f3U, 0xd7d7d7d7U, 0xfbfbfbfbU,\n 0x7c7c7c7cU, 0xe3e3e3e3U, 0x39393939U, 0x82828282U,\n 0x9b9b9b9bU, 0x2f2f2f2fU, 0xffffffffU, 0x87878787U,\n 0x34343434U, 0x8e8e8e8eU, 0x43434343U, 0x44444444U,\n 0xc4c4c4c4U, 0xdedededeU, 0xe9e9e9e9U, 0xcbcbcbcbU,\n 0x54545454U, 0x7b7b7b7bU, 0x94949494U, 0x32323232U,\n 0xa6a6a6a6U, 0xc2c2c2c2U, 0x23232323U, 0x3d3d3d3dU,\n 0xeeeeeeeeU, 0x4c4c4c4cU, 0x95959595U, 0x0b0b0b0bU,\n 0x42424242U, 0xfafafafaU, 0xc3c3c3c3U, 0x4e4e4e4eU,\n 0x08080808U, 0x2e2e2e2eU, 0xa1a1a1a1U, 0x66666666U,\n 0x28282828U, 0xd9d9d9d9U, 0x24242424U, 0xb2b2b2b2U,\n 0x76767676U, 0x5b5b5b5bU, 0xa2a2a2a2U, 0x49494949U,\n 0x6d6d6d6dU, 0x8b8b8b8bU, 0xd1d1d1d1U, 0x25252525U,\n 0x72727272U, 0xf8f8f8f8U, 0xf6f6f6f6U, 0x64646464U,\n 0x86868686U, 0x68686868U, 0x98989898U, 0x16161616U,\n 0xd4d4d4d4U, 0xa4a4a4a4U, 0x5c5c5c5cU, 0xccccccccU,\n 0x5d5d5d5dU, 0x65656565U, 0xb6b6b6b6U, 0x92929292U,\n 0x6c6c6c6cU, 0x70707070U, 0x48484848U, 0x50505050U,\n 0xfdfdfdfdU, 0xededededU, 0xb9b9b9b9U, 0xdadadadaU,\n 0x5e5e5e5eU, 0x15151515U, 0x46464646U, 0x57575757U,\n 0xa7a7a7a7U, 0x8d8d8d8dU, 0x9d9d9d9dU, 0x84848484U,\n 0x90909090U, 0xd8d8d8d8U, 0xababababU, 0x00000000U,\n 0x8c8c8c8cU, 0xbcbcbcbcU, 0xd3d3d3d3U, 0x0a0a0a0aU,\n 0xf7f7f7f7U, 0xe4e4e4e4U, 0x58585858U, 0x05050505U,\n 0xb8b8b8b8U, 0xb3b3b3b3U, 0x45454545U, 0x06060606U,\n 0xd0d0d0d0U, 0x2c2c2c2cU, 0x1e1e1e1eU, 0x8f8f8f8fU,\n 0xcacacacaU, 0x3f3f3f3fU, 0x0f0f0f0fU, 0x02020202U,\n 0xc1c1c1c1U, 0xafafafafU, 0xbdbdbdbdU, 0x03030303U,\n 0x01010101U, 0x13131313U, 0x8a8a8a8aU, 0x6b6b6b6bU,\n 0x3a3a3a3aU, 0x91919191U, 0x11111111U, 0x41414141U,\n 0x4f4f4f4fU, 0x67676767U, 0xdcdcdcdcU, 0xeaeaeaeaU,\n 0x97979797U, 0xf2f2f2f2U, 0xcfcfcfcfU, 0xcecececeU,\n 0xf0f0f0f0U, 0xb4b4b4b4U, 0xe6e6e6e6U, 0x73737373U,\n 0x96969696U, 0xacacacacU, 0x74747474U, 0x22222222U,\n 0xe7e7e7e7U, 0xadadadadU, 0x35353535U, 0x85858585U,\n 0xe2e2e2e2U, 0xf9f9f9f9U, 0x37373737U, 0xe8e8e8e8U,\n 0x1c1c1c1cU, 0x75757575U, 0xdfdfdfdfU, 0x6e6e6e6eU,\n 0x47474747U, 0xf1f1f1f1U, 0x1a1a1a1aU, 0x71717171U,\n 0x1d1d1d1dU, 0x29292929U, 0xc5c5c5c5U, 0x89898989U,\n 0x6f6f6f6fU, 0xb7b7b7b7U, 0x62626262U, 0x0e0e0e0eU,\n 0xaaaaaaaaU, 0x18181818U, 0xbebebebeU, 0x1b1b1b1bU,\n 0xfcfcfcfcU, 0x56565656U, 0x3e3e3e3eU, 0x4b4b4b4bU,\n 0xc6c6c6c6U, 0xd2d2d2d2U, 0x79797979U, 0x20202020U,\n 0x9a9a9a9aU, 0xdbdbdbdbU, 0xc0c0c0c0U, 0xfefefefeU,\n 0x78787878U, 0xcdcdcdcdU, 0x5a5a5a5aU, 0xf4f4f4f4U,\n 0x1f1f1f1fU, 0xddddddddU, 0xa8a8a8a8U, 0x33333333U,\n 0x88888888U, 0x07070707U, 0xc7c7c7c7U, 0x31313131U,\n 0xb1b1b1b1U, 0x12121212U, 0x10101010U, 0x59595959U,\n 0x27272727U, 0x80808080U, 0xececececU, 0x5f5f5f5fU,\n 0x60606060U, 0x51515151U, 0x7f7f7f7fU, 0xa9a9a9a9U,\n 0x19191919U, 0xb5b5b5b5U, 0x4a4a4a4aU, 0x0d0d0d0dU,\n 0x2d2d2d2dU, 0xe5e5e5e5U, 0x7a7a7a7aU, 0x9f9f9f9fU,\n 0x93939393U, 0xc9c9c9c9U, 0x9c9c9c9cU, 0xefefefefU,\n 0xa0a0a0a0U, 0xe0e0e0e0U, 0x3b3b3b3bU, 0x4d4d4d4dU,\n 0xaeaeaeaeU, 0x2a2a2a2aU, 0xf5f5f5f5U, 0xb0b0b0b0U,\n 0xc8c8c8c8U, 0xebebebebU, 0xbbbbbbbbU, 0x3c3c3c3cU,\n 0x83838383U, 0x53535353U, 0x99999999U, 0x61616161U,\n 0x17171717U, 0x2b2b2b2bU, 0x04040404U, 0x7e7e7e7eU,\n 0xbabababaU, 0x77777777U, 0xd6d6d6d6U, 0x26262626U,\n 0xe1e1e1e1U, 0x69696969U, 0x14141414U, 0x63636363U,\n 0x55555555U, 0x21212121U, 0x0c0c0c0cU, 0x7d7d7d7dU,\n};\nstatic const u32 rcon[] = {\n\t0x01000000, 0x02000000, 0x04000000, 0x08000000,\n\t0x10000000, 0x20000000, 0x40000000, 0x80000000,\n\t0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */\n};\n\n/**\n * Expand the cipher key into the encryption key schedule.\n */\nint AES_set_encrypt_key(const unsigned char *userKey, const int bits,\n\t\t\tAES_KEY *key) {\n\n\tu32 *rk;\n \tint i = 0;\n\tu32 temp;\n\n\tif (!userKey || !key)\n\t\treturn -1;\n\tif (bits != 128 && bits != 192 && bits != 256)\n\t\treturn -2;\n\n\trk = key->rd_key;\n\n\tif (bits==128)\n\t\tkey->rounds = 10;\n\telse if (bits==192)\n\t\tkey->rounds = 12;\n\telse\n\t\tkey->rounds = 14;\n\n\trk[0] = GETU32(userKey );\n\trk[1] = GETU32(userKey + 4);\n\trk[2] = GETU32(userKey + 8);\n\trk[3] = GETU32(userKey + 12);\n\tif (bits == 128) {\n\t\twhile (1) {\n\t\t\ttemp = rk[3];\n\t\t\trk[4] = rk[0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[5] = rk[1] ^ rk[4];\n\t\t\trk[6] = rk[2] ^ rk[5];\n\t\t\trk[7] = rk[3] ^ rk[6];\n\t\t\tif (++i == 10) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\trk += 4;\n\t\t}\n\t}\n\trk[4] = GETU32(userKey + 16);\n\trk[5] = GETU32(userKey + 20);\n\tif (bits == 192) {\n\t\twhile (1) {\n\t\t\ttemp = rk[ 5];\n\t\t\trk[ 6] = rk[ 0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[ 7] = rk[ 1] ^ rk[ 6];\n\t\t\trk[ 8] = rk[ 2] ^ rk[ 7];\n\t\t\trk[ 9] = rk[ 3] ^ rk[ 8];\n\t\t\tif (++i == 8) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\trk[10] = rk[ 4] ^ rk[ 9];\n\t\t\trk[11] = rk[ 5] ^ rk[10];\n\t\t\trk += 6;\n\t\t}\n\t}\n\trk[6] = GETU32(userKey + 24);\n\trk[7] = GETU32(userKey + 28);\n\tif (bits == 256) {\n\t\twhile (1) {\n\t\t\ttemp = rk[ 7];\n\t\t\trk[ 8] = rk[ 0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[ 9] = rk[ 1] ^ rk[ 8];\n\t\t\trk[10] = rk[ 2] ^ rk[ 9];\n\t\t\trk[11] = rk[ 3] ^ rk[10];\n\t\t\tif (++i == 7) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\ttemp = rk[11];\n\t\t\trk[12] = rk[ 4] ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x000000ff);\n\t\t\trk[13] = rk[ 5] ^ rk[12];\n\t\t\trk[14] = rk[ 6] ^ rk[13];\n\t\t\trk[15] = rk[ 7] ^ rk[14];\n\n\t\t\trk += 8;\n \t}\n\t}\n\treturn 0;\n}\n\n/**\n * Expand the cipher key into the decryption key schedule.\n */\nint AES_set_decrypt_key(const unsigned char *userKey, const int bits,\n\t\t\t AES_KEY *key) {\n\n u32 *rk;\n\tint i, j, status;\n\tu32 temp;\n\n\t/* first, start with an encryption schedule */\n\tstatus = AES_set_encrypt_key(userKey, bits, key);\n\tif (status < 0)\n\t\treturn status;\n\n\trk = key->rd_key;\n\n\t/* invert the order of the round keys: */\n\tfor (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) {\n\t\ttemp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp;\n\t\ttemp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;\n\t\ttemp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;\n\t\ttemp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;\n\t}\n\t/* apply the inverse MixColumn transform to all round keys but the first and the last: */\n\tfor (i = 1; i < (key->rounds); i++) {\n\t\trk += 4;\n\t\trk[0] =\n\t\t\tTd0[Te4[(rk[0] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[0] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[0] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[0] ) & 0xff] & 0xff];\n\t\trk[1] =\n\t\t\tTd0[Te4[(rk[1] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[1] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[1] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[1] ) & 0xff] & 0xff];\n\t\trk[2] =\n\t\t\tTd0[Te4[(rk[2] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[2] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[2] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[2] ) & 0xff] & 0xff];\n\t\trk[3] =\n\t\t\tTd0[Te4[(rk[3] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[3] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[3] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[3] ) & 0xff] & 0xff];\n\t}\n\treturn 0;\n}\n\n#ifndef AES_ASM\n/*\n * Encrypt a single block\n * in and out can overlap\n */\nvoid AES_encrypt(const unsigned char *in, unsigned char *out,\n\t\t const AES_KEY *key) {\n\n\tconst u32 *rk;\n\tu32 s0, s1, s2, s3, t0, t1, t2, t3;\n#ifndef FULL_UNROLL\n\tint r;\n#endif /* ?FULL_UNROLL */\n\n\tassert(in && out && key);\n\trk = key->rd_key;\n\n\t/*\n\t * map byte array block to cipher state\n\t * and add initial round key:\n\t */\n\ts0 = GETU32(in ) ^ rk[0];\n\ts1 = GETU32(in + 4) ^ rk[1];\n\ts2 = GETU32(in + 8) ^ rk[2];\n\ts3 = GETU32(in + 12) ^ rk[3];\n#ifdef FULL_UNROLL\n\t/* round 1: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7];\n \t/* round 2: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11];\n\t/* round 3: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15];\n \t/* round 4: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19];\n\t/* round 5: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23];\n \t/* round 6: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27];\n\t/* round 7: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31];\n \t/* round 8: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35];\n\t/* round 9: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39];\n if (key->rounds > 10) {\n /* round 10: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43];\n /* round 11: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47];\n if (key->rounds > 12) {\n /* round 12: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51];\n /* round 13: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55];\n }\n }\n rk += key->rounds << 2;\n#else /* !FULL_UNROLL */\n /*\n * Nr - 1 full rounds:\n */\n r = key->rounds >> 1;\n for (;;) {\n t0 =\n Te0[(s0 >> 24) ] ^\n Te1[(s1 >> 16) & 0xff] ^\n Te2[(s2 >> 8) & 0xff] ^\n Te3[(s3 ) & 0xff] ^\n rk[4];\n t1 =\n Te0[(s1 >> 24) ] ^\n Te1[(s2 >> 16) & 0xff] ^\n Te2[(s3 >> 8) & 0xff] ^\n Te3[(s0 ) & 0xff] ^\n rk[5];\n t2 =\n Te0[(s2 >> 24) ] ^\n Te1[(s3 >> 16) & 0xff] ^\n Te2[(s0 >> 8) & 0xff] ^\n Te3[(s1 ) & 0xff] ^\n rk[6];\n t3 =\n Te0[(s3 >> 24) ] ^\n Te1[(s0 >> 16) & 0xff] ^\n Te2[(s1 >> 8) & 0xff] ^\n Te3[(s2 ) & 0xff] ^\n rk[7];\n\n rk += 8;\n if (--r == 0) {\n break;\n }\n\n s0 =\n Te0[(t0 >> 24) ] ^\n Te1[(t1 >> 16) & 0xff] ^\n Te2[(t2 >> 8) & 0xff] ^\n Te3[(t3 ) & 0xff] ^\n rk[0];\n s1 =\n Te0[(t1 >> 24) ] ^\n Te1[(t2 >> 16) & 0xff] ^\n Te2[(t3 >> 8) & 0xff] ^\n Te3[(t0 ) & 0xff] ^\n rk[1];\n s2 =\n Te0[(t2 >> 24) ] ^\n Te1[(t3 >> 16) & 0xff] ^\n Te2[(t0 >> 8) & 0xff] ^\n Te3[(t1 ) & 0xff] ^\n rk[2];\n s3 =\n Te0[(t3 >> 24) ] ^\n Te1[(t0 >> 16) & 0xff] ^\n Te2[(t1 >> 8) & 0xff] ^\n Te3[(t2 ) & 0xff] ^\n rk[3];\n }\n#endif /* ?FULL_UNROLL */\n /*\n\t * apply last round and\n\t * map cipher state to byte array block:\n\t */\n\ts0 =\n\t\t(Te4[(t0 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t3 ) & 0xff] & 0x000000ff) ^\n\t\trk[0];\n\tPUTU32(out , s0);\n\ts1 =\n\t\t(Te4[(t1 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t0 ) & 0xff] & 0x000000ff) ^\n\t\trk[1];\n\tPUTU32(out + 4, s1);\n\ts2 =\n\t\t(Te4[(t2 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t1 ) & 0xff] & 0x000000ff) ^\n\t\trk[2];\n\tPUTU32(out + 8, s2);\n\ts3 =\n\t\t(Te4[(t3 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t2 ) & 0xff] & 0x000000ff) ^\n\t\trk[3];\n\tPUTU32(out + 12, s3);\n}\n\n/*\n * Decrypt a single block\n * in and out can overlap\n */\nvoid AES_decrypt(const unsigned char *in, unsigned char *out,\n\t\t const AES_KEY *key) {\n\n\tconst u32 *rk;\n\tu32 s0, s1, s2, s3, t0, t1, t2, t3;\n#ifndef FULL_UNROLL\n\tint r;\n#endif /* ?FULL_UNROLL */\n\n\tassert(in && out && key);\n\trk = key->rd_key;\n\n\t/*\n\t * map byte array block to cipher state\n\t * and add initial round key:\n\t */\n s0 = GETU32(in ) ^ rk[0];\n s1 = GETU32(in + 4) ^ rk[1];\n s2 = GETU32(in + 8) ^ rk[2];\n s3 = GETU32(in + 12) ^ rk[3];\n#ifdef FULL_UNROLL\n /* round 1: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[ 4];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[ 5];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[ 6];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[ 7];\n /* round 2: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[ 8];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[ 9];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11];\n /* round 3: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15];\n /* round 4: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19];\n /* round 5: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23];\n /* round 6: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27];\n /* round 7: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31];\n /* round 8: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35];\n /* round 9: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39];\n if (key->rounds > 10) {\n /* round 10: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43];\n /* round 11: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47];\n if (key->rounds > 12) {\n /* round 12: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51];\n /* round 13: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55];\n }\n }\n\trk += key->rounds << 2;\n#else /* !FULL_UNROLL */\n /*\n * Nr - 1 full rounds:\n */\n r = key->rounds >> 1;\n for (;;) {\n t0 =\n Td0[(s0 >> 24) ] ^\n Td1[(s3 >> 16) & 0xff] ^\n Td2[(s2 >> 8) & 0xff] ^\n Td3[(s1 ) & 0xff] ^\n rk[4];\n t1 =\n Td0[(s1 >> 24) ] ^\n Td1[(s0 >> 16) & 0xff] ^\n Td2[(s3 >> 8) & 0xff] ^\n Td3[(s2 ) & 0xff] ^\n rk[5];\n t2 =\n Td0[(s2 >> 24) ] ^\n Td1[(s1 >> 16) & 0xff] ^\n Td2[(s0 >> 8) & 0xff] ^\n Td3[(s3 ) & 0xff] ^\n rk[6];\n t3 =\n Td0[(s3 >> 24) ] ^\n Td1[(s2 >> 16) & 0xff] ^\n Td2[(s1 >> 8) & 0xff] ^\n Td3[(s0 ) & 0xff] ^\n rk[7];\n\n rk += 8;\n if (--r == 0) {\n break;\n }\n\n s0 =\n Td0[(t0 >> 24) ] ^\n Td1[(t3 >> 16) & 0xff] ^\n Td2[(t2 >> 8) & 0xff] ^\n Td3[(t1 ) & 0xff] ^\n rk[0];\n s1 =\n Td0[(t1 >> 24) ] ^\n Td1[(t0 >> 16) & 0xff] ^\n Td2[(t3 >> 8) & 0xff] ^\n Td3[(t2 ) & 0xff] ^\n rk[1];\n s2 =\n Td0[(t2 >> 24) ] ^\n Td1[(t1 >> 16) & 0xff] ^\n Td2[(t0 >> 8) & 0xff] ^\n Td3[(t3 ) & 0xff] ^\n rk[2];\n s3 =\n Td0[(t3 >> 24) ] ^\n Td1[(t2 >> 16) & 0xff] ^\n Td2[(t1 >> 8) & 0xff] ^\n Td3[(t0 ) & 0xff] ^\n rk[3];\n }\n#endif /* ?FULL_UNROLL */\n /*\n\t * apply last round and\n\t * map cipher state to byte array block:\n\t */\n \ts0 =\n \t\t(Td4[(t0 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t3 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t2 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t1 ) & 0xff] & 0x000000ff) ^\n \t\trk[0];\n\tPUTU32(out , s0);\n \ts1 =\n \t\t(Td4[(t1 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t0 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t3 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t2 ) & 0xff] & 0x000000ff) ^\n \t\trk[1];\n\tPUTU32(out + 4, s1);\n \ts2 =\n \t\t(Td4[(t2 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t1 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t0 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t3 ) & 0xff] & 0x000000ff) ^\n \t\trk[2];\n\tPUTU32(out + 8, s2);\n \ts3 =\n \t\t(Td4[(t3 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t2 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t1 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t0 ) & 0xff] & 0x000000ff) ^\n \t\trk[3];\n\tPUTU32(out + 12, s3);\n}\n\n#endif /* AES_ASM */\n\nvoid AES_cbc_encrypt(const unsigned char *in, unsigned char *out,\n\t\t const unsigned long length, const AES_KEY *key,\n\t\t unsigned char *ivec, const int enc)\n{\n\n\tunsigned long n;\n\tunsigned long len = length;\n\tunsigned char tmp[AES_BLOCK_SIZE];\n\n\tassert(in && out && key && ivec);\n\n\tif (enc) {\n\t\twhile (len >= AES_BLOCK_SIZE) {\n\t\t\tfor(n=0; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\ttmp[n] = in[n] ^ ivec[n];\n\t\t\tAES_encrypt(tmp, out, key);\n\t\t\tmemcpy(ivec, out, AES_BLOCK_SIZE);\n\t\t\tlen -= AES_BLOCK_SIZE;\n\t\t\tin += AES_BLOCK_SIZE;\n\t\t\tout += AES_BLOCK_SIZE;\n\t\t}\n\t\tif (len) {\n\t\t\tfor(n=0; n < len; ++n)\n\t\t\t\ttmp[n] = in[n] ^ ivec[n];\n\t\t\tfor(n=len; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\ttmp[n] = ivec[n];\n\t\t\tAES_encrypt(tmp, tmp, key);\n\t\t\tmemcpy(out, tmp, AES_BLOCK_SIZE);\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t}\n\t} else {\n\t\twhile (len >= AES_BLOCK_SIZE) {\n\t\t\tmemcpy(tmp, in, AES_BLOCK_SIZE);\n\t\t\tAES_decrypt(in, out, key);\n\t\t\tfor(n=0; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\tout[n] ^= ivec[n];\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t\tlen -= AES_BLOCK_SIZE;\n\t\t\tin += AES_BLOCK_SIZE;\n\t\t\tout += AES_BLOCK_SIZE;\n\t\t}\n\t\tif (len) {\n\t\t\tmemcpy(tmp, in, AES_BLOCK_SIZE);\n\t\t\tAES_decrypt(tmp, tmp, key);\n\t\t\tfor(n=0; n < len; ++n)\n\t\t\t\tout[n] = tmp[n] ^ ivec[n];\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t}\n\t}\n}\n"], ["/linuxpdf/tinyemu/cutils.c", "/*\n * Misc C utilities\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n\nvoid *mallocz(size_t size)\n{\n void *ptr;\n ptr = malloc(size);\n if (!ptr)\n return NULL;\n memset(ptr, 0, size);\n return ptr;\n}\n\nvoid pstrcpy(char *buf, int buf_size, const char *str)\n{\n int c;\n char *q = buf;\n\n if (buf_size <= 0)\n return;\n\n for(;;) {\n c = *str++;\n if (c == 0 || q >= buf + buf_size - 1)\n break;\n *q++ = c;\n }\n *q = '\\0';\n}\n\nchar *pstrcat(char *buf, int buf_size, const char *s)\n{\n int len;\n len = strlen(buf);\n if (len < buf_size)\n pstrcpy(buf + len, buf_size - len, s);\n return buf;\n}\n\nint strstart(const char *str, const char *val, const char **ptr)\n{\n const char *p, *q;\n p = str;\n q = val;\n while (*q != '\\0') {\n if (*p != *q)\n return 0;\n p++;\n q++;\n }\n if (ptr)\n *ptr = p;\n return 1;\n}\n\nvoid dbuf_init(DynBuf *s)\n{\n memset(s, 0, sizeof(*s));\n}\n\nvoid dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len)\n{\n size_t end, new_size;\n new_size = end = offset + len;\n if (new_size > s->allocated_size) {\n new_size = max_int(new_size, s->allocated_size * 3 / 2);\n s->buf = realloc(s->buf, new_size);\n s->allocated_size = new_size;\n }\n memcpy(s->buf + offset, data, len);\n if (end > s->size)\n s->size = end;\n}\n\nvoid dbuf_putc(DynBuf *s, uint8_t c)\n{\n dbuf_write(s, s->size, &c, 1);\n}\n\nvoid dbuf_putstr(DynBuf *s, const char *str)\n{\n dbuf_write(s, s->size, (const uint8_t *)str, strlen(str));\n}\n\nvoid dbuf_free(DynBuf *s)\n{\n free(s->buf);\n memset(s, 0, sizeof(*s));\n}\n"], ["/linuxpdf/tinyemu/slirp/cksum.c", "/*\n * Copyright (c) 1988, 1992, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)in_cksum.c\t8.1 (Berkeley) 6/10/93\n * in_cksum.c,v 1.2 1994/08/02 07:48:16 davidg Exp\n */\n\n#include \"slirp.h\"\n\n/*\n * Checksum routine for Internet Protocol family headers (Portable Version).\n *\n * This routine is very heavily used in the network\n * code and should be modified for each CPU to be as fast as possible.\n *\n * XXX Since we will never span more than 1 mbuf, we can optimise this\n */\n\n#define ADDCARRY(x) (x > 65535 ? x -= 65535 : x)\n#define REDUCE {l_util.l = sum; sum = l_util.s[0] + l_util.s[1]; \\\n (void)ADDCARRY(sum);}\n\nint cksum(struct mbuf *m, int len)\n{\n\tregister uint16_t *w;\n\tregister int sum = 0;\n\tregister int mlen = 0;\n\tint byte_swapped = 0;\n\n\tunion {\n\t\tuint8_t c[2];\n\t\tuint16_t s;\n\t} s_util;\n\tunion {\n\t\tuint16_t s[2];\n\t\tuint32_t l;\n\t} l_util;\n\n\tif (m->m_len == 0)\n\t goto cont;\n\tw = mtod(m, uint16_t *);\n\n\tmlen = m->m_len;\n\n\tif (len < mlen)\n\t mlen = len;\n#ifdef DEBUG\n\tlen -= mlen;\n#endif\n\t/*\n\t * Force to even boundary.\n\t */\n\tif ((1 & (long) w) && (mlen > 0)) {\n\t\tREDUCE;\n\t\tsum <<= 8;\n\t\ts_util.c[0] = *(uint8_t *)w;\n\t\tw = (uint16_t *)((int8_t *)w + 1);\n\t\tmlen--;\n\t\tbyte_swapped = 1;\n\t}\n\t/*\n\t * Unroll the loop to make overhead from\n\t * branches &c small.\n\t */\n\twhile ((mlen -= 32) >= 0) {\n\t\tsum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];\n\t\tsum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];\n\t\tsum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];\n\t\tsum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];\n\t\tw += 16;\n\t}\n\tmlen += 32;\n\twhile ((mlen -= 8) >= 0) {\n\t\tsum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];\n\t\tw += 4;\n\t}\n\tmlen += 8;\n\tif (mlen == 0 && byte_swapped == 0)\n\t goto cont;\n\tREDUCE;\n\twhile ((mlen -= 2) >= 0) {\n\t\tsum += *w++;\n\t}\n\n\tif (byte_swapped) {\n\t\tREDUCE;\n\t\tsum <<= 8;\n\t\tif (mlen == -1) {\n\t\t\ts_util.c[1] = *(uint8_t *)w;\n\t\t\tsum += s_util.s;\n\t\t\tmlen = 0;\n\t\t} else\n\n\t\t mlen = -1;\n\t} else if (mlen == -1)\n\t s_util.c[0] = *(uint8_t *)w;\n\ncont:\n#ifdef DEBUG\n\tif (len) {\n\t\tDEBUG_ERROR((dfd, \"cksum: out of data\\n\"));\n\t\tDEBUG_ERROR((dfd, \" len = %d\\n\", len));\n\t}\n#endif\n\tif (mlen == -1) {\n\t\t/* The last mbuf has odd # of bytes. Follow the\n\t\t standard (the odd byte may be shifted left by 8 bits\n\t\t\t or not as determined by endian-ness of the machine) */\n\t\ts_util.c[1] = 0;\n\t\tsum += s_util.s;\n\t}\n\tREDUCE;\n\treturn (~sum & 0xffff);\n}\n"], ["/linuxpdf/tinyemu/slirp/if.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n#define ifs_init(ifm) ((ifm)->ifs_next = (ifm)->ifs_prev = (ifm))\n\nstatic void\nifs_insque(struct mbuf *ifm, struct mbuf *ifmhead)\n{\n\tifm->ifs_next = ifmhead->ifs_next;\n\tifmhead->ifs_next = ifm;\n\tifm->ifs_prev = ifmhead;\n\tifm->ifs_next->ifs_prev = ifm;\n}\n\nstatic void\nifs_remque(struct mbuf *ifm)\n{\n\tifm->ifs_prev->ifs_next = ifm->ifs_next;\n\tifm->ifs_next->ifs_prev = ifm->ifs_prev;\n}\n\nvoid\nif_init(Slirp *slirp)\n{\n slirp->if_fastq.ifq_next = slirp->if_fastq.ifq_prev = &slirp->if_fastq;\n slirp->if_batchq.ifq_next = slirp->if_batchq.ifq_prev = &slirp->if_batchq;\n slirp->next_m = &slirp->if_batchq;\n}\n\n/*\n * if_output: Queue packet into an output queue.\n * There are 2 output queue's, if_fastq and if_batchq.\n * Each output queue is a doubly linked list of double linked lists\n * of mbufs, each list belonging to one \"session\" (socket). This\n * way, we can output packets fairly by sending one packet from each\n * session, instead of all the packets from one session, then all packets\n * from the next session, etc. Packets on the if_fastq get absolute\n * priority, but if one session hogs the link, it gets \"downgraded\"\n * to the batchq until it runs out of packets, then it'll return\n * to the fastq (eg. if the user does an ls -alR in a telnet session,\n * it'll temporarily get downgraded to the batchq)\n */\nvoid\nif_output(struct socket *so, struct mbuf *ifm)\n{\n\tSlirp *slirp = ifm->slirp;\n\tstruct mbuf *ifq;\n\tint on_fastq = 1;\n\n\tDEBUG_CALL(\"if_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"ifm = %lx\", (long)ifm);\n\n\t/*\n\t * First remove the mbuf from m_usedlist,\n\t * since we're gonna use m_next and m_prev ourselves\n\t * XXX Shouldn't need this, gotta change dtom() etc.\n\t */\n\tif (ifm->m_flags & M_USEDLIST) {\n\t\tremque(ifm);\n\t\tifm->m_flags &= ~M_USEDLIST;\n\t}\n\n\t/*\n\t * See if there's already a batchq list for this session.\n\t * This can include an interactive session, which should go on fastq,\n\t * but gets too greedy... hence it'll be downgraded from fastq to batchq.\n\t * We mustn't put this packet back on the fastq (or we'll send it out of order)\n\t * XXX add cache here?\n\t */\n\tfor (ifq = slirp->if_batchq.ifq_prev; ifq != &slirp->if_batchq;\n\t ifq = ifq->ifq_prev) {\n\t\tif (so == ifq->ifq_so) {\n\t\t\t/* A match! */\n\t\t\tifm->ifq_so = so;\n\t\t\tifs_insque(ifm, ifq->ifs_prev);\n\t\t\tgoto diddit;\n\t\t}\n\t}\n\n\t/* No match, check which queue to put it on */\n\tif (so && (so->so_iptos & IPTOS_LOWDELAY)) {\n\t\tifq = slirp->if_fastq.ifq_prev;\n\t\ton_fastq = 1;\n\t\t/*\n\t\t * Check if this packet is a part of the last\n\t\t * packet's session\n\t\t */\n\t\tif (ifq->ifq_so == so) {\n\t\t\tifm->ifq_so = so;\n\t\t\tifs_insque(ifm, ifq->ifs_prev);\n\t\t\tgoto diddit;\n\t\t}\n\t} else\n\t\tifq = slirp->if_batchq.ifq_prev;\n\n\t/* Create a new doubly linked list for this session */\n\tifm->ifq_so = so;\n\tifs_init(ifm);\n\tinsque(ifm, ifq);\n\ndiddit:\n\tslirp->if_queued++;\n\n\tif (so) {\n\t\t/* Update *_queued */\n\t\tso->so_queued++;\n\t\tso->so_nqueued++;\n\t\t/*\n\t\t * Check if the interactive session should be downgraded to\n\t\t * the batchq. A session is downgraded if it has queued 6\n\t\t * packets without pausing, and at least 3 of those packets\n\t\t * have been sent over the link\n\t\t * (XXX These are arbitrary numbers, probably not optimal..)\n\t\t */\n\t\tif (on_fastq && ((so->so_nqueued >= 6) &&\n\t\t\t\t (so->so_nqueued - so->so_queued) >= 3)) {\n\n\t\t\t/* Remove from current queue... */\n\t\t\tremque(ifm->ifs_next);\n\n\t\t\t/* ...And insert in the new. That'll teach ya! */\n\t\t\tinsque(ifm->ifs_next, &slirp->if_batchq);\n\t\t}\n\t}\n\n#ifndef FULL_BOLT\n\t/*\n\t * This prevents us from malloc()ing too many mbufs\n\t */\n\tif_start(ifm->slirp);\n#endif\n}\n\n/*\n * Send a packet\n * We choose a packet based on it's position in the output queues;\n * If there are packets on the fastq, they are sent FIFO, before\n * everything else. Otherwise we choose the first packet from the\n * batchq and send it. the next packet chosen will be from the session\n * after this one, then the session after that one, and so on.. So,\n * for example, if there are 3 ftp session's fighting for bandwidth,\n * one packet will be sent from the first session, then one packet\n * from the second session, then one packet from the third, then back\n * to the first, etc. etc.\n */\nvoid\nif_start(Slirp *slirp)\n{\n\tstruct mbuf *ifm, *ifqt;\n\n\tDEBUG_CALL(\"if_start\");\n\n\tif (slirp->if_queued == 0)\n\t return; /* Nothing to do */\n\n again:\n /* check if we can really output */\n if (!slirp_can_output(slirp->opaque))\n return;\n\n\t/*\n\t * See which queue to get next packet from\n\t * If there's something in the fastq, select it immediately\n\t */\n\tif (slirp->if_fastq.ifq_next != &slirp->if_fastq) {\n\t\tifm = slirp->if_fastq.ifq_next;\n\t} else {\n\t\t/* Nothing on fastq, see if next_m is valid */\n\t\tif (slirp->next_m != &slirp->if_batchq)\n\t\t ifm = slirp->next_m;\n\t\telse\n\t\t ifm = slirp->if_batchq.ifq_next;\n\n\t\t/* Set which packet to send on next iteration */\n\t\tslirp->next_m = ifm->ifq_next;\n\t}\n\t/* Remove it from the queue */\n\tifqt = ifm->ifq_prev;\n\tremque(ifm);\n\tslirp->if_queued--;\n\n\t/* If there are more packets for this session, re-queue them */\n\tif (ifm->ifs_next != /* ifm->ifs_prev != */ ifm) {\n\t\tinsque(ifm->ifs_next, ifqt);\n\t\tifs_remque(ifm);\n\t}\n\n\t/* Update so_queued */\n\tif (ifm->ifq_so) {\n\t\tif (--ifm->ifq_so->so_queued == 0)\n\t\t /* If there's no more queued, reset nqueued */\n\t\t ifm->ifq_so->so_nqueued = 0;\n\t}\n\n\t/* Encapsulate the packet for sending */\n if_encap(slirp, (uint8_t *)ifm->m_data, ifm->m_len);\n\n m_free(ifm);\n\n\tif (slirp->if_queued)\n\t goto again;\n}\n"], ["/linuxpdf/tinyemu/slirp/mbuf.c", "/*\n * Copyright (c) 1995 Danny Gasparovski\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n/*\n * mbuf's in SLiRP are much simpler than the real mbufs in\n * FreeBSD. They are fixed size, determined by the MTU,\n * so that one whole packet can fit. Mbuf's cannot be\n * chained together. If there's more data than the mbuf\n * could hold, an external malloced buffer is pointed to\n * by m_ext (and the data pointers) and M_EXT is set in\n * the flags\n */\n\n#include \"slirp.h\"\n\n#define MBUF_THRESH 30\n\n/*\n * Find a nice value for msize\n * XXX if_maxlinkhdr already in mtu\n */\n#define SLIRP_MSIZE (IF_MTU + IF_MAXLINKHDR + offsetof(struct mbuf, m_dat) + 6)\n\nvoid\nm_init(Slirp *slirp)\n{\n slirp->m_freelist.m_next = slirp->m_freelist.m_prev = &slirp->m_freelist;\n slirp->m_usedlist.m_next = slirp->m_usedlist.m_prev = &slirp->m_usedlist;\n}\n\n/*\n * Get an mbuf from the free list, if there are none\n * malloc one\n *\n * Because fragmentation can occur if we alloc new mbufs and\n * free old mbufs, we mark all mbufs above mbuf_thresh as M_DOFREE,\n * which tells m_free to actually free() it\n */\nstruct mbuf *\nm_get(Slirp *slirp)\n{\n\tregister struct mbuf *m;\n\tint flags = 0;\n\n\tDEBUG_CALL(\"m_get\");\n\n\tif (slirp->m_freelist.m_next == &slirp->m_freelist) {\n\t\tm = (struct mbuf *)malloc(SLIRP_MSIZE);\n\t\tif (m == NULL) goto end_error;\n\t\tslirp->mbuf_alloced++;\n\t\tif (slirp->mbuf_alloced > MBUF_THRESH)\n\t\t\tflags = M_DOFREE;\n\t\tm->slirp = slirp;\n\t} else {\n\t\tm = slirp->m_freelist.m_next;\n\t\tremque(m);\n\t}\n\n\t/* Insert it in the used list */\n\tinsque(m,&slirp->m_usedlist);\n\tm->m_flags = (flags | M_USEDLIST);\n\n\t/* Initialise it */\n\tm->m_size = SLIRP_MSIZE - offsetof(struct mbuf, m_dat);\n\tm->m_data = m->m_dat;\n\tm->m_len = 0;\n m->m_nextpkt = NULL;\n m->m_prevpkt = NULL;\nend_error:\n\tDEBUG_ARG(\"m = %lx\", (long )m);\n\treturn m;\n}\n\nvoid\nm_free(struct mbuf *m)\n{\n\n DEBUG_CALL(\"m_free\");\n DEBUG_ARG(\"m = %lx\", (long )m);\n\n if(m) {\n\t/* Remove from m_usedlist */\n\tif (m->m_flags & M_USEDLIST)\n\t remque(m);\n\n\t/* If it's M_EXT, free() it */\n\tif (m->m_flags & M_EXT)\n\t free(m->m_ext);\n\n\t/*\n\t * Either free() it or put it on the free list\n\t */\n\tif (m->m_flags & M_DOFREE) {\n\t\tm->slirp->mbuf_alloced--;\n\t\tfree(m);\n\t} else if ((m->m_flags & M_FREELIST) == 0) {\n\t\tinsque(m,&m->slirp->m_freelist);\n\t\tm->m_flags = M_FREELIST; /* Clobber other flags */\n\t}\n } /* if(m) */\n}\n\n/*\n * Copy data from one mbuf to the end of\n * the other.. if result is too big for one mbuf, malloc()\n * an M_EXT data segment\n */\nvoid\nm_cat(struct mbuf *m, struct mbuf *n)\n{\n\t/*\n\t * If there's no room, realloc\n\t */\n\tif (M_FREEROOM(m) < n->m_len)\n\t\tm_inc(m,m->m_size+MINCSIZE);\n\n\tmemcpy(m->m_data+m->m_len, n->m_data, n->m_len);\n\tm->m_len += n->m_len;\n\n\tm_free(n);\n}\n\n\n/* make m size bytes large */\nvoid\nm_inc(struct mbuf *m, int size)\n{\n\tint datasize;\n\n\t/* some compiles throw up on gotos. This one we can fake. */\n if(m->m_size>size) return;\n\n if (m->m_flags & M_EXT) {\n\t datasize = m->m_data - m->m_ext;\n\t m->m_ext = (char *)realloc(m->m_ext,size);\n\t m->m_data = m->m_ext + datasize;\n } else {\n\t char *dat;\n\t datasize = m->m_data - m->m_dat;\n\t dat = (char *)malloc(size);\n\t memcpy(dat, m->m_dat, m->m_size);\n\n\t m->m_ext = dat;\n\t m->m_data = m->m_ext + datasize;\n\t m->m_flags |= M_EXT;\n }\n\n m->m_size = size;\n\n}\n\n\n\nvoid\nm_adj(struct mbuf *m, int len)\n{\n\tif (m == NULL)\n\t\treturn;\n\tif (len >= 0) {\n\t\t/* Trim from head */\n\t\tm->m_data += len;\n\t\tm->m_len -= len;\n\t} else {\n\t\t/* Trim from tail */\n\t\tlen = -len;\n\t\tm->m_len -= len;\n\t}\n}\n\n\n/*\n * Copy len bytes from m, starting off bytes into n\n */\nint\nm_copy(struct mbuf *n, struct mbuf *m, int off, int len)\n{\n\tif (len > M_FREEROOM(n))\n\t\treturn -1;\n\n\tmemcpy((n->m_data + n->m_len), (m->m_data + off), len);\n\tn->m_len += len;\n\treturn 0;\n}\n\n\n/*\n * Given a pointer into an mbuf, return the mbuf\n * XXX This is a kludge, I should eliminate the need for it\n * Fortunately, it's not used often\n */\nstruct mbuf *\ndtom(Slirp *slirp, void *dat)\n{\n\tstruct mbuf *m;\n\n\tDEBUG_CALL(\"dtom\");\n\tDEBUG_ARG(\"dat = %lx\", (long )dat);\n\n\t/* bug corrected for M_EXT buffers */\n\tfor (m = slirp->m_usedlist.m_next; m != &slirp->m_usedlist;\n\t m = m->m_next) {\n\t if (m->m_flags & M_EXT) {\n\t if( (char *)dat>=m->m_ext && (char *)dat<(m->m_ext + m->m_size) )\n\t return m;\n\t } else {\n\t if( (char *)dat >= m->m_dat && (char *)dat<(m->m_dat + m->m_size) )\n\t return m;\n\t }\n\t}\n\n\tDEBUG_ERROR((dfd, \"dtom failed\"));\n\n\treturn (struct mbuf *)0;\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_output.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_output.c\t8.3 (Berkeley) 1/21/94\n * ip_output.c,v 1.9 1994/11/16 10:17:10 jkh Exp\n */\n\n/*\n * Changes and additions relating to SLiRP are\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n/* Number of packets queued before we start sending\n * (to prevent allocing too many mbufs) */\n#define IF_THRESH 10\n\n/*\n * IP output. The packet in mbuf chain m contains a skeletal IP\n * header (with len, off, ttl, proto, tos, src, dst).\n * The mbuf chain containing the packet will be freed.\n * The mbuf opt, if present, will not be freed.\n */\nint\nip_output(struct socket *so, struct mbuf *m0)\n{\n\tSlirp *slirp = m0->slirp;\n\tregister struct ip *ip;\n\tregister struct mbuf *m = m0;\n\tregister int hlen = sizeof(struct ip );\n\tint len, off, error = 0;\n\n\tDEBUG_CALL(\"ip_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m0 = %lx\", (long)m0);\n\n\tip = mtod(m, struct ip *);\n\t/*\n\t * Fill in IP header.\n\t */\n\tip->ip_v = IPVERSION;\n\tip->ip_off &= IP_DF;\n\tip->ip_id = htons(slirp->ip_id++);\n\tip->ip_hl = hlen >> 2;\n\n\t/*\n\t * If small enough for interface, can just send directly.\n\t */\n\tif ((uint16_t)ip->ip_len <= IF_MTU) {\n\t\tip->ip_len = htons((uint16_t)ip->ip_len);\n\t\tip->ip_off = htons((uint16_t)ip->ip_off);\n\t\tip->ip_sum = 0;\n\t\tip->ip_sum = cksum(m, hlen);\n\n\t\tif_output(so, m);\n\t\tgoto done;\n\t}\n\n\t/*\n\t * Too large for interface; fragment if possible.\n\t * Must be able to put at least 8 bytes per fragment.\n\t */\n\tif (ip->ip_off & IP_DF) {\n\t\terror = -1;\n\t\tgoto bad;\n\t}\n\n\tlen = (IF_MTU - hlen) &~ 7; /* ip databytes per packet */\n\tif (len < 8) {\n\t\terror = -1;\n\t\tgoto bad;\n\t}\n\n {\n\tint mhlen, firstlen = len;\n\tstruct mbuf **mnext = &m->m_nextpkt;\n\n\t/*\n\t * Loop through length of segment after first fragment,\n\t * make new header and copy data of each part and link onto chain.\n\t */\n\tm0 = m;\n\tmhlen = sizeof (struct ip);\n\tfor (off = hlen + len; off < (uint16_t)ip->ip_len; off += len) {\n\t register struct ip *mhip;\n\t m = m_get(slirp);\n if (m == NULL) {\n\t error = -1;\n\t goto sendorfree;\n\t }\n\t m->m_data += IF_MAXLINKHDR;\n\t mhip = mtod(m, struct ip *);\n\t *mhip = *ip;\n\n\t m->m_len = mhlen;\n\t mhip->ip_off = ((off - hlen) >> 3) + (ip->ip_off & ~IP_MF);\n\t if (ip->ip_off & IP_MF)\n\t mhip->ip_off |= IP_MF;\n\t if (off + len >= (uint16_t)ip->ip_len)\n\t len = (uint16_t)ip->ip_len - off;\n\t else\n\t mhip->ip_off |= IP_MF;\n\t mhip->ip_len = htons((uint16_t)(len + mhlen));\n\n\t if (m_copy(m, m0, off, len) < 0) {\n\t error = -1;\n\t goto sendorfree;\n\t }\n\n\t mhip->ip_off = htons((uint16_t)mhip->ip_off);\n\t mhip->ip_sum = 0;\n\t mhip->ip_sum = cksum(m, mhlen);\n\t *mnext = m;\n\t mnext = &m->m_nextpkt;\n\t}\n\t/*\n\t * Update first fragment by trimming what's been copied out\n\t * and updating header, then send each fragment (in order).\n\t */\n\tm = m0;\n\tm_adj(m, hlen + firstlen - (uint16_t)ip->ip_len);\n\tip->ip_len = htons((uint16_t)m->m_len);\n\tip->ip_off = htons((uint16_t)(ip->ip_off | IP_MF));\n\tip->ip_sum = 0;\n\tip->ip_sum = cksum(m, hlen);\nsendorfree:\n\tfor (m = m0; m; m = m0) {\n\t\tm0 = m->m_nextpkt;\n m->m_nextpkt = NULL;\n\t\tif (error == 0)\n\t\t\tif_output(so, m);\n\t\telse\n\t\t\tm_freem(m);\n\t}\n }\n\ndone:\n\treturn (error);\n\nbad:\n\tm_freem(m0);\n\tgoto done;\n}\n"], ["/linuxpdf/tinyemu/splitimg.c", "/*\n * Disk image splitter\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n int blocksize, ret, i;\n const char *infilename, *outpath;\n FILE *f, *fo;\n char buf1[1024];\n uint8_t *buf;\n\n if ((optind + 1) >= argc) {\n printf(\"splitimg version \" CONFIG_VERSION \", Copyright (c) 2011-2016 Fabrice Bellard\\n\"\n \"usage: splitimg infile outpath [blocksize]\\n\"\n \"Create a multi-file disk image for the RISCVEMU HTTP block device\\n\"\n \"\\n\"\n \"outpath must be a directory\\n\"\n \"blocksize is the block size in KB\\n\");\n exit(1);\n }\n\n infilename = argv[optind++];\n outpath = argv[optind++];\n blocksize = 256;\n if (optind < argc)\n blocksize = strtol(argv[optind++], NULL, 0);\n\n blocksize *= 1024;\n \n buf = malloc(blocksize);\n\n f = fopen(infilename, \"rb\");\n if (!f) {\n perror(infilename);\n exit(1);\n }\n i = 0;\n for(;;) {\n ret = fread(buf, 1, blocksize, f);\n if (ret < 0) {\n perror(\"fread\");\n exit(1);\n }\n if (ret == 0)\n break;\n if (ret < blocksize) {\n printf(\"warning: last block is not full\\n\");\n memset(buf + ret, 0, blocksize - ret);\n }\n snprintf(buf1, sizeof(buf1), \"%s/blk%09u.bin\", outpath, i);\n fo = fopen(buf1, \"wb\");\n if (!fo) {\n perror(buf1);\n exit(1);\n }\n fwrite(buf, 1, blocksize, fo);\n fclose(fo);\n i++;\n }\n fclose(f);\n printf(\"%d blocks\\n\", i);\n\n snprintf(buf1, sizeof(buf1), \"%s/blk.txt\", outpath);\n fo = fopen(buf1, \"wb\");\n if (!fo) {\n perror(buf1);\n exit(1);\n }\n fprintf(fo, \"{\\n\");\n fprintf(fo, \" block_size: %d,\\n\", blocksize / 1024);\n fprintf(fo, \" n_block: %d,\\n\", i);\n fprintf(fo, \"}\\n\");\n fclose(fo);\n return 0;\n}\n"], ["/linuxpdf/tinyemu/slirp/sbuf.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\nstatic void sbappendsb(struct sbuf *sb, struct mbuf *m);\n\nvoid\nsbfree(struct sbuf *sb)\n{\n\tfree(sb->sb_data);\n}\n\nvoid\nsbdrop(struct sbuf *sb, int num)\n{\n\t/*\n\t * We can only drop how much we have\n\t * This should never succeed\n\t */\n\tif(num > sb->sb_cc)\n\t\tnum = sb->sb_cc;\n\tsb->sb_cc -= num;\n\tsb->sb_rptr += num;\n\tif(sb->sb_rptr >= sb->sb_data + sb->sb_datalen)\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n}\n\nvoid\nsbreserve(struct sbuf *sb, int size)\n{\n\tif (sb->sb_data) {\n\t\t/* Already alloced, realloc if necessary */\n\t\tif (sb->sb_datalen != size) {\n\t\t\tsb->sb_wptr = sb->sb_rptr = sb->sb_data = (char *)realloc(sb->sb_data, size);\n\t\t\tsb->sb_cc = 0;\n\t\t\tif (sb->sb_wptr)\n\t\t\t sb->sb_datalen = size;\n\t\t\telse\n\t\t\t sb->sb_datalen = 0;\n\t\t}\n\t} else {\n\t\tsb->sb_wptr = sb->sb_rptr = sb->sb_data = (char *)malloc(size);\n\t\tsb->sb_cc = 0;\n\t\tif (sb->sb_wptr)\n\t\t sb->sb_datalen = size;\n\t\telse\n\t\t sb->sb_datalen = 0;\n\t}\n}\n\n/*\n * Try and write() to the socket, whatever doesn't get written\n * append to the buffer... for a host with a fast net connection,\n * this prevents an unnecessary copy of the data\n * (the socket is non-blocking, so we won't hang)\n */\nvoid\nsbappend(struct socket *so, struct mbuf *m)\n{\n\tint ret = 0;\n\n\tDEBUG_CALL(\"sbappend\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"m->m_len = %d\", m->m_len);\n\n\t/* Shouldn't happen, but... e.g. foreign host closes connection */\n\tif (m->m_len <= 0) {\n\t\tm_free(m);\n\t\treturn;\n\t}\n\n\t/*\n\t * If there is urgent data, call sosendoob\n\t * if not all was sent, sowrite will take care of the rest\n\t * (The rest of this function is just an optimisation)\n\t */\n\tif (so->so_urgc) {\n\t\tsbappendsb(&so->so_rcv, m);\n\t\tm_free(m);\n\t\tsosendoob(so);\n\t\treturn;\n\t}\n\n\t/*\n\t * We only write if there's nothing in the buffer,\n\t * ottherwise it'll arrive out of order, and hence corrupt\n\t */\n\tif (!so->so_rcv.sb_cc)\n\t ret = slirp_send(so, m->m_data, m->m_len, 0);\n\n\tif (ret <= 0) {\n\t\t/*\n\t\t * Nothing was written\n\t\t * It's possible that the socket has closed, but\n\t\t * we don't need to check because if it has closed,\n\t\t * it will be detected in the normal way by soread()\n\t\t */\n\t\tsbappendsb(&so->so_rcv, m);\n\t} else if (ret != m->m_len) {\n\t\t/*\n\t\t * Something was written, but not everything..\n\t\t * sbappendsb the rest\n\t\t */\n\t\tm->m_len -= ret;\n\t\tm->m_data += ret;\n\t\tsbappendsb(&so->so_rcv, m);\n\t} /* else */\n\t/* Whatever happened, we free the mbuf */\n\tm_free(m);\n}\n\n/*\n * Copy the data from m into sb\n * The caller is responsible to make sure there's enough room\n */\nstatic void\nsbappendsb(struct sbuf *sb, struct mbuf *m)\n{\n\tint len, n, nn;\n\n\tlen = m->m_len;\n\n\tif (sb->sb_wptr < sb->sb_rptr) {\n\t\tn = sb->sb_rptr - sb->sb_wptr;\n\t\tif (n > len) n = len;\n\t\tmemcpy(sb->sb_wptr, m->m_data, n);\n\t} else {\n\t\t/* Do the right edge first */\n\t\tn = sb->sb_data + sb->sb_datalen - sb->sb_wptr;\n\t\tif (n > len) n = len;\n\t\tmemcpy(sb->sb_wptr, m->m_data, n);\n\t\tlen -= n;\n\t\tif (len) {\n\t\t\t/* Now the left edge */\n\t\t\tnn = sb->sb_rptr - sb->sb_data;\n\t\t\tif (nn > len) nn = len;\n\t\t\tmemcpy(sb->sb_data,m->m_data+n,nn);\n\t\t\tn += nn;\n\t\t}\n\t}\n\n\tsb->sb_cc += n;\n\tsb->sb_wptr += n;\n\tif (sb->sb_wptr >= sb->sb_data + sb->sb_datalen)\n\t\tsb->sb_wptr -= sb->sb_datalen;\n}\n\n/*\n * Copy data from sbuf to a normal, straight buffer\n * Don't update the sbuf rptr, this will be\n * done in sbdrop when the data is acked\n */\nvoid\nsbcopy(struct sbuf *sb, int off, int len, char *to)\n{\n\tchar *from;\n\n\tfrom = sb->sb_rptr + off;\n\tif (from >= sb->sb_data + sb->sb_datalen)\n\t\tfrom -= sb->sb_datalen;\n\n\tif (from < sb->sb_wptr) {\n\t\tif (len > sb->sb_cc) len = sb->sb_cc;\n\t\tmemcpy(to,from,len);\n\t} else {\n\t\t/* re-use off */\n\t\toff = (sb->sb_data + sb->sb_datalen) - from;\n\t\tif (off > len) off = len;\n\t\tmemcpy(to,from,off);\n\t\tlen -= off;\n\t\tif (len)\n\t\t memcpy(to+off,sb->sb_data,len);\n\t}\n}\n"], ["/linuxpdf/tinyemu/fs.c", "/*\n * Filesystem utilities\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"fs.h\"\n\nFSFile *fs_dup(FSDevice *fs, FSFile *f)\n{\n FSQID qid;\n fs->fs_walk(fs, &f, &qid, f, 0, NULL);\n return f;\n}\n\nFSFile *fs_walk_path1(FSDevice *fs, FSFile *f, const char *path,\n char **pname)\n{\n const char *p;\n char *name;\n FSFile *f1;\n FSQID qid;\n int len, ret;\n BOOL is_last, is_first;\n\n if (path[0] == '/')\n path++;\n \n is_first = TRUE;\n for(;;) {\n p = strchr(path, '/');\n if (!p) {\n name = (char *)path;\n if (pname) {\n *pname = name;\n if (is_first) {\n ret = fs->fs_walk(fs, &f, &qid, f, 0, NULL);\n if (ret < 0)\n f = NULL;\n }\n return f;\n }\n is_last = TRUE;\n } else {\n len = p - path;\n name = malloc(len + 1);\n memcpy(name, path, len);\n name[len] = '\\0';\n is_last = FALSE;\n }\n ret = fs->fs_walk(fs, &f1, &qid, f, 1, &name);\n if (!is_last)\n free(name);\n if (!is_first)\n fs->fs_delete(fs, f);\n f = f1;\n is_first = FALSE;\n if (ret <= 0) {\n fs->fs_delete(fs, f);\n f = NULL;\n break;\n } else if (is_last) {\n break;\n }\n path = p + 1;\n }\n return f;\n}\n\nFSFile *fs_walk_path(FSDevice *fs, FSFile *f, const char *path)\n{\n return fs_walk_path1(fs, f, path, NULL);\n}\n\nvoid fs_end(FSDevice *fs)\n{\n fs->fs_end(fs);\n free(fs);\n}\n"], ["/linuxpdf/tinyemu/softfp.c", "/*\n * SoftFP Library\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"softfp.h\"\n\nstatic inline int clz32(uint32_t a)\n{\n int r;\n if (a == 0) {\n r = 32;\n } else {\n r = __builtin_clz(a);\n }\n return r;\n}\n\nstatic inline int clz64(uint64_t a)\n{\n int r;\n if (a == 0) {\n r = 64;\n } else \n {\n r = __builtin_clzll(a);\n }\n return r;\n}\n\n#ifdef HAVE_INT128\nstatic inline int clz128(uint128_t a)\n{\n int r;\n if (a == 0) {\n r = 128;\n } else \n {\n uint64_t ah, al;\n ah = a >> 64;\n al = a;\n if (ah != 0)\n r = __builtin_clzll(ah);\n else\n r = __builtin_clzll(al) + 64;\n }\n return r;\n}\n#endif\n\n#define F_SIZE 32\n#include \"softfp_template.h\"\n\n#define F_SIZE 64\n#include \"softfp_template.h\"\n\n#ifdef HAVE_INT128\n\n#define F_SIZE 128\n#include \"softfp_template.h\"\n\n#endif\n\n"]], "task_instance_info": {"created_time": "2025-08-20 17:59:23", "created_task_model": "DeepSeek-R1", "function_skeleton": "static void pc_machine_end(VirtMachine *s1) {}", "code_description": "This code segment functions to: Release allocated resources and perform cleanup operations for system components during machine termination, including deallocating memory structures, terminating hardware emulation modules, and finalizing system state management."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c\n[TASK_BEGIN]\nstatic void pc_machine_end(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n munmap(s->kvm_run, s->kvm_run_size);\n close(s->vcpu_fd);\n close(s->vm_fd);\n close(s->kvm_fd);\n }\n#endif\n\n phys_mem_map_end(s->mem_map);\n phys_mem_map_end(s->port_map);\n\n free(s->cmos_state);\n free(s->pic_state);\n free(s->pit_state);\n if (s->i440fx_state) {\n i440fx_end(s->i440fx_state);\n free(s->i440fx_state);\n }\n free(s->serial_state);\n\n if (s->common.console_dev) {\n virtio_console_end(s->common.console_dev);\n }\n if (s->keyboard_dev) {\n virtio_input_end(s->keyboard_dev);\n }\n if (s->mouse_dev) {\n virtio_input_end(s->mouse_dev);\n }\n\n free(s);\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 18-00-16"}, "editdistance_info": {"edit_distance": 26.5306, "calculate_time": "2025-08-20 18:00:16", "true_code_clean": "static void pc_machine_end(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->cpu_state) {\n x86_cpu_end(s->cpu_state);\n }\n phys_mem_map_end(s->mem_map);\n phys_mem_map_end(s->port_map);\n free(s);\n}", "predict_code_clean": "static void pc_machine_end(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n munmap(s->kvm_run, s->kvm_run_size);\n close(s->vcpu_fd);\n close(s->vm_fd);\n close(s->kvm_fd);\n }\n#endif\n phys_mem_map_end(s->mem_map);\n phys_mem_map_end(s->port_map);\n free(s->cmos_state);\n free(s->pic_state);\n free(s->pit_state);\n if (s->i440fx_state) {\n i440fx_end(s->i440fx_state);\n free(s->i440fx_state);\n }\n free(s->serial_state);\n if (s->common.console_dev) {\n virtio_console_end(s->common.console_dev);\n }\n if (s->keyboard_dev) {\n virtio_input_end(s->keyboard_dev);\n }\n if (s->mouse_dev) {\n virtio_input_end(s->mouse_dev);\n }\n free(s);\n}"}} {"repo_name": "linuxpdf", "file_name": "/linuxpdf/tinyemu/slirp/socket.c", "inference_info": {"prefix_code": "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\nstatic void sofcantrcvmore(struct socket *so);\nstatic void sofcantsendmore(struct socket *so);\n\nstruct socket *\nsolookup(struct socket *head, struct in_addr laddr, u_int lport,\n struct in_addr faddr, u_int fport)\n{\n\tstruct socket *so;\n\n\tfor (so = head->so_next; so != head; so = so->so_next) {\n\t\tif (so->so_lport == lport &&\n\t\t so->so_laddr.s_addr == laddr.s_addr &&\n\t\t so->so_faddr.s_addr == faddr.s_addr &&\n\t\t so->so_fport == fport)\n\t\t break;\n\t}\n\n\tif (so == head)\n\t return (struct socket *)NULL;\n\treturn so;\n\n}\n\n/*\n * Create a new socket, initialise the fields\n * It is the responsibility of the caller to\n * insque() it into the correct linked-list\n */\nstruct socket *\nsocreate(Slirp *slirp)\n{\n struct socket *so;\n\n so = (struct socket *)malloc(sizeof(struct socket));\n if(so) {\n memset(so, 0, sizeof(struct socket));\n so->so_state = SS_NOFDREF;\n so->s = -1;\n so->slirp = slirp;\n }\n return(so);\n}\n\n/*\n * remque and free a socket, clobber cache\n */\nvoid\nsofree(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n\n if (so->so_emu==EMU_RSH && so->extra) {\n\tsofree(so->extra);\n\tso->extra=NULL;\n }\n if (so == slirp->tcp_last_so) {\n slirp->tcp_last_so = &slirp->tcb;\n } else if (so == slirp->udp_last_so) {\n slirp->udp_last_so = &slirp->udb;\n }\n m_free(so->so_m);\n\n if(so->so_next && so->so_prev)\n remque(so); /* crashes if so is not in a queue */\n\n free(so);\n}\n\nsize_t sopreprbuf(struct socket *so, struct iovec *iov, int *np)\n{\n\tint n, lss, total;\n\tstruct sbuf *sb = &so->so_snd;\n\tint len = sb->sb_datalen - sb->sb_cc;\n\tint mss = so->so_tcpcb->t_maxseg;\n\n\tDEBUG_CALL(\"sopreprbuf\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\tif (len <= 0)\n\t\treturn 0;\n\n\tiov[0].iov_base = sb->sb_wptr;\n iov[1].iov_base = NULL;\n iov[1].iov_len = 0;\n\tif (sb->sb_wptr < sb->sb_rptr) {\n\t\tiov[0].iov_len = sb->sb_rptr - sb->sb_wptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len)\n\t\t iov[0].iov_len = len;\n\t\tif (iov[0].iov_len > mss)\n\t\t iov[0].iov_len -= iov[0].iov_len%mss;\n\t\tn = 1;\n\t} else {\n\t\tiov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_wptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tlen -= iov[0].iov_len;\n\t\tif (len) {\n\t\t\tiov[1].iov_base = sb->sb_data;\n\t\t\tiov[1].iov_len = sb->sb_rptr - sb->sb_data;\n\t\t\tif(iov[1].iov_len > len)\n\t\t\t iov[1].iov_len = len;\n\t\t\ttotal = iov[0].iov_len + iov[1].iov_len;\n\t\t\tif (total > mss) {\n\t\t\t\tlss = total%mss;\n\t\t\t\tif (iov[1].iov_len > lss) {\n\t\t\t\t\tiov[1].iov_len -= lss;\n\t\t\t\t\tn = 2;\n\t\t\t\t} else {\n\t\t\t\t\tlss -= iov[1].iov_len;\n\t\t\t\t\tiov[0].iov_len -= lss;\n\t\t\t\t\tn = 1;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tn = 2;\n\t\t} else {\n\t\t\tif (iov[0].iov_len > mss)\n\t\t\t iov[0].iov_len -= iov[0].iov_len%mss;\n\t\t\tn = 1;\n\t\t}\n\t}\n\tif (np)\n\t\t*np = n;\n\n\treturn iov[0].iov_len + (n - 1) * iov[1].iov_len;\n}\n\n/*\n * Read from so's socket into sb_snd, updating all relevant sbuf fields\n * NOTE: This will only be called if it is select()ed for reading, so\n * a read() of 0 (or less) means it's disconnected\n */\nint\nsoread(struct socket *so)\n{\n\tint n, nn;\n\tstruct sbuf *sb = &so->so_snd;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"soread\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\t/*\n\t * No need to check if there's enough room to read.\n\t * soread wouldn't have been called if there weren't\n\t */\n\tsopreprbuf(so, iov, &n);\n\n#ifdef HAVE_READV\n\tnn = readv(so->s, (struct iovec *)iov, n);\n\tDEBUG_MISC((dfd, \" ... read nn = %d bytes\\n\", nn));\n#else\n\tnn = recv(so->s, iov[0].iov_base, iov[0].iov_len,0);\n#endif\n\tif (nn <= 0) {\n\t\tif (nn < 0 && (errno == EINTR || errno == EAGAIN))\n\t\t\treturn 0;\n\t\telse {\n\t\t\tDEBUG_MISC((dfd, \" --- soread() disconnected, nn = %d, errno = %d-%s\\n\", nn, errno,strerror(errno)));\n\t\t\tsofcantrcvmore(so);\n\t\t\ttcp_sockclosed(sototcpcb(so));\n\t\t\treturn -1;\n\t\t}\n\t}\n\n#ifndef HAVE_READV\n\t/*\n\t * If there was no error, try and read the second time round\n\t * We read again if n = 2 (ie, there's another part of the buffer)\n\t * and we read as much as we could in the first read\n\t * We don't test for <= 0 this time, because there legitimately\n\t * might not be any more data (since the socket is non-blocking),\n\t * a close will be detected on next iteration.\n\t * A return of -1 wont (shouldn't) happen, since it didn't happen above\n\t */\n\tif (n == 2 && nn == iov[0].iov_len) {\n int ret;\n ret = recv(so->s, iov[1].iov_base, iov[1].iov_len,0);\n if (ret > 0)\n nn += ret;\n }\n\n\tDEBUG_MISC((dfd, \" ... read nn = %d bytes\\n\", nn));\n#endif\n\n\t/* Update fields */\n\tsb->sb_cc += nn;\n\tsb->sb_wptr += nn;\n\tif (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_wptr -= sb->sb_datalen;\n\treturn nn;\n}\n\nint soreadbuf(struct socket *so, const char *buf, int size)\n{\n int n, nn, copy = size;\n\tstruct sbuf *sb = &so->so_snd;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"soreadbuf\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\t/*\n\t * No need to check if there's enough room to read.\n\t * soread wouldn't have been called if there weren't\n\t */\n\tif (sopreprbuf(so, iov, &n) < size)\n goto err;\n\n nn = min(iov[0].iov_len, copy);\n memcpy(iov[0].iov_base, buf, nn);\n\n copy -= nn;\n buf += nn;\n\n if (copy == 0)\n goto done;\n\n memcpy(iov[1].iov_base, buf, copy);\n\ndone:\n /* Update fields */\n\tsb->sb_cc += size;\n\tsb->sb_wptr += size;\n\tif (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_wptr -= sb->sb_datalen;\n return size;\nerr:\n\n sofcantrcvmore(so);\n tcp_sockclosed(sototcpcb(so));\n fprintf(stderr, \"soreadbuf buffer to small\");\n return -1;\n}\n\n/*\n * Get urgent data\n *\n * When the socket is created, we set it SO_OOBINLINE,\n * so when OOB data arrives, we soread() it and everything\n * in the send buffer is sent as urgent data\n */\nvoid\nsorecvoob(struct socket *so)\n{\n\tstruct tcpcb *tp = sototcpcb(so);\n\n\tDEBUG_CALL(\"sorecvoob\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\t/*\n\t * We take a guess at how much urgent data has arrived.\n\t * In most situations, when urgent data arrives, the next\n\t * read() should get all the urgent data. This guess will\n\t * be wrong however if more data arrives just after the\n\t * urgent data, or the read() doesn't return all the\n\t * urgent data.\n\t */\n\tsoread(so);\n\ttp->snd_up = tp->snd_una + so->so_snd.sb_cc;\n\ttp->t_force = 1;\n\ttcp_output(tp);\n\ttp->t_force = 0;\n}\n\n/*\n * Send urgent data\n * There's a lot duplicated code here, but...\n */\nint\nsosendoob(struct socket *so)\n{\n\tstruct sbuf *sb = &so->so_rcv;\n\tchar buff[2048]; /* XXX Shouldn't be sending more oob data than this */\n\n\tint n, len;\n\n\tDEBUG_CALL(\"sosendoob\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"sb->sb_cc = %d\", sb->sb_cc);\n\n\tif (so->so_urgc > 2048)\n\t so->so_urgc = 2048; /* XXXX */\n\n\tif (sb->sb_rptr < sb->sb_wptr) {\n\t\t/* We can send it directly */\n\t\tn = slirp_send(so, sb->sb_rptr, so->so_urgc, (MSG_OOB)); /* |MSG_DONTWAIT)); */\n\t\tso->so_urgc -= n;\n\n\t\tDEBUG_MISC((dfd, \" --- sent %d bytes urgent data, %d urgent bytes left\\n\", n, so->so_urgc));\n\t} else {\n\t\t/*\n\t\t * Since there's no sendv or sendtov like writev,\n\t\t * we must copy all data to a linear buffer then\n\t\t * send it all\n\t\t */\n\t\tlen = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;\n\t\tif (len > so->so_urgc) len = so->so_urgc;\n\t\tmemcpy(buff, sb->sb_rptr, len);\n\t\tso->so_urgc -= len;\n\t\tif (so->so_urgc) {\n\t\t\tn = sb->sb_wptr - sb->sb_data;\n\t\t\tif (n > so->so_urgc) n = so->so_urgc;\n\t\t\tmemcpy((buff + len), sb->sb_data, n);\n\t\t\tso->so_urgc -= n;\n\t\t\tlen += n;\n\t\t}\n\t\tn = slirp_send(so, buff, len, (MSG_OOB)); /* |MSG_DONTWAIT)); */\n#ifdef DEBUG\n\t\tif (n != len)\n\t\t DEBUG_ERROR((dfd, \"Didn't send all data urgently XXXXX\\n\"));\n#endif\n\t\tDEBUG_MISC((dfd, \" ---2 sent %d bytes urgent data, %d urgent bytes left\\n\", n, so->so_urgc));\n\t}\n\n\tsb->sb_cc -= n;\n\tsb->sb_rptr += n;\n\tif (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n\treturn n;\n}\n\n/*\n * Write data from so_rcv to so's socket,\n * updating all sbuf field as necessary\n */\nint\nsowrite(struct socket *so)\n{\n\tint n,nn;\n\tstruct sbuf *sb = &so->so_rcv;\n\tint len = sb->sb_cc;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"sowrite\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\tif (so->so_urgc) {\n\t\tsosendoob(so);\n\t\tif (sb->sb_cc == 0)\n\t\t\treturn 0;\n\t}\n\n\t/*\n\t * No need to check if there's something to write,\n\t * sowrite wouldn't have been called otherwise\n\t */\n\n\tiov[0].iov_base = sb->sb_rptr;\n iov[1].iov_base = NULL;\n iov[1].iov_len = 0;\n\tif (sb->sb_rptr < sb->sb_wptr) {\n\t\tiov[0].iov_len = sb->sb_wptr - sb->sb_rptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tn = 1;\n\t} else {\n\t\tiov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tlen -= iov[0].iov_len;\n\t\tif (len) {\n\t\t\tiov[1].iov_base = sb->sb_data;\n\t\t\tiov[1].iov_len = sb->sb_wptr - sb->sb_data;\n\t\t\tif (iov[1].iov_len > len) iov[1].iov_len = len;\n\t\t\tn = 2;\n\t\t} else\n\t\t\tn = 1;\n\t}\n\t/* Check if there's urgent data to send, and if so, send it */\n\n#ifdef HAVE_READV\n\tnn = writev(so->s, (const struct iovec *)iov, n);\n\n\tDEBUG_MISC((dfd, \" ... wrote nn = %d bytes\\n\", nn));\n#else\n\tnn = slirp_send(so, iov[0].iov_base, iov[0].iov_len,0);\n#endif\n\t/* This should never happen, but people tell me it does *shrug* */\n\tif (nn < 0 && (errno == EAGAIN || errno == EINTR))\n\t\treturn 0;\n\n\tif (nn <= 0) {\n\t\tDEBUG_MISC((dfd, \" --- sowrite disconnected, so->so_state = %x, errno = %d\\n\",\n\t\t\tso->so_state, errno));\n\t\tsofcantsendmore(so);\n\t\ttcp_sockclosed(sototcpcb(so));\n\t\treturn -1;\n\t}\n\n#ifndef HAVE_READV\n\tif (n == 2 && nn == iov[0].iov_len) {\n int ret;\n ret = slirp_send(so, iov[1].iov_base, iov[1].iov_len,0);\n if (ret > 0)\n nn += ret;\n }\n DEBUG_MISC((dfd, \" ... wrote nn = %d bytes\\n\", nn));\n#endif\n\n\t/* Update sbuf */\n\tsb->sb_cc -= nn;\n\tsb->sb_rptr += nn;\n\tif (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n\t/*\n\t * If in DRAIN mode, and there's no more data, set\n\t * it CANTSENDMORE\n\t */\n\tif ((so->so_state & SS_FWDRAIN) && sb->sb_cc == 0)\n\t\tsofcantsendmore(so);\n\n\treturn nn;\n}\n\n/*\n * recvfrom() a UDP socket\n */\nvoid\nsorecvfrom(struct socket *so)\n{\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\n\tDEBUG_CALL(\"sorecvfrom\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\tif (so->so_type == IPPROTO_ICMP) { /* This is a \"ping\" reply */\n\t char buff[256];\n\t int len;\n\n\t len = recvfrom(so->s, buff, 256, 0,\n\t\t\t (struct sockaddr *)&addr, &addrlen);\n\t /* XXX Check if reply is \"correct\"? */\n\n\t if(len == -1 || len == 0) {\n\t u_char code=ICMP_UNREACH_PORT;\n\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;\n\n\t DEBUG_MISC((dfd,\" udp icmp rx errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));\n\t } else {\n\t icmp_reflect(so->so_m);\n so->so_m = NULL; /* Don't m_free() it again! */\n\t }\n\t /* No need for this socket anymore, udp_detach it */\n\t udp_detach(so);\n\t} else { \t/* A \"normal\" UDP packet */\n\t struct mbuf *m;\n int len;\n#ifdef _WIN32\n unsigned long n;\n#else\n int n;\n#endif\n\n\t m = m_get(so->slirp);\n\t if (!m) {\n\t return;\n\t }\n\t m->m_data += IF_MAXLINKHDR;\n\n\t /*\n\t * XXX Shouldn't FIONREAD packets destined for port 53,\n\t * but I don't know the max packet size for DNS lookups\n\t */\n\t len = M_FREEROOM(m);\n\t /* if (so->so_fport != htons(53)) { */\n\t ioctlsocket(so->s, FIONREAD, &n);\n\n\t if (n > len) {\n\t n = (m->m_data - m->m_dat) + m->m_len + n + 1;\n\t m_inc(m, n);\n\t len = M_FREEROOM(m);\n\t }\n\t /* } */\n\n\t m->m_len = recvfrom(so->s, m->m_data, len, 0,\n\t\t\t (struct sockaddr *)&addr, &addrlen);\n\t DEBUG_MISC((dfd, \" did recvfrom %d, errno = %d-%s\\n\",\n\t\t m->m_len, errno,strerror(errno)));\n\t if(m->m_len<0) {\n\t u_char code=ICMP_UNREACH_PORT;\n\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;\n\n\t DEBUG_MISC((dfd,\" rx error, tx icmp ICMP_UNREACH:%i\\n\", code));\n\t icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));\n\t m_free(m);\n\t } else {\n\t /*\n\t * Hack: domain name lookup will be used the most for UDP,\n\t * and since they'll only be used once there's no need\n\t * for the 4 minute (or whatever) timeout... So we time them\n\t * out much quicker (10 seconds for now...)\n\t */\n\t if (so->so_expire) {\n\t if (so->so_fport == htons(53))\n\t\tso->so_expire = curtime + SO_EXPIREFAST;\n\t else\n\t\tso->so_expire = curtime + SO_EXPIRE;\n\t }\n\n\t /*\n\t * If this packet was destined for CTL_ADDR,\n\t * make it look like that's where it came from, done by udp_output\n\t */\n\t udp_output(so, m, &addr);\n\t } /* rx error */\n\t} /* if ping packet */\n}\n\n/*\n * sendto() a socket\n */\n", "suffix_code": "\n\n/*\n * Listen for incoming TCP connections\n */\nstruct socket *\ntcp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,\n u_int lport, int flags)\n{\n\tstruct sockaddr_in addr;\n\tstruct socket *so;\n\tint s, opt = 1;\n\tsocklen_t addrlen = sizeof(addr);\n\tmemset(&addr, 0, addrlen);\n\n\tDEBUG_CALL(\"tcp_listen\");\n\tDEBUG_ARG(\"haddr = %x\", haddr);\n\tDEBUG_ARG(\"hport = %d\", hport);\n\tDEBUG_ARG(\"laddr = %x\", laddr);\n\tDEBUG_ARG(\"lport = %d\", lport);\n\tDEBUG_ARG(\"flags = %x\", flags);\n\n\tso = socreate(slirp);\n\tif (!so) {\n\t return NULL;\n\t}\n\n\t/* Don't tcp_attach... we don't need so_snd nor so_rcv */\n\tif ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL) {\n\t\tfree(so);\n\t\treturn NULL;\n\t}\n\tinsque(so, &slirp->tcb);\n\n\t/*\n\t * SS_FACCEPTONCE sockets must time out.\n\t */\n\tif (flags & SS_FACCEPTONCE)\n\t so->so_tcpcb->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT*2;\n\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= (SS_FACCEPTCONN | flags);\n\tso->so_lport = lport; /* Kept in network format */\n\tso->so_laddr.s_addr = laddr; /* Ditto */\n\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = haddr;\n\taddr.sin_port = hport;\n\n\tif (((s = os_socket(AF_INET,SOCK_STREAM,0)) < 0) ||\n\t (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int)) < 0) ||\n\t (bind(s,(struct sockaddr *)&addr, sizeof(addr)) < 0) ||\n\t (listen(s,1) < 0)) {\n\t\tint tmperrno = errno; /* Don't clobber the real reason we failed */\n\n\t\tclose(s);\n\t\tsofree(so);\n\t\t/* Restore the real errno */\n#ifdef _WIN32\n\t\tWSASetLastError(tmperrno);\n#else\n\t\terrno = tmperrno;\n#endif\n\t\treturn NULL;\n\t}\n\tsetsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\n\tgetsockname(s,(struct sockaddr *)&addr,&addrlen);\n\tso->so_fport = addr.sin_port;\n\tif (addr.sin_addr.s_addr == 0 || addr.sin_addr.s_addr == loopback_addr.s_addr)\n\t so->so_faddr = slirp->vhost_addr;\n\telse\n\t so->so_faddr = addr.sin_addr;\n\n\tso->s = s;\n\treturn so;\n}\n\n/*\n * Various session state calls\n * XXX Should be #define's\n * The socket state stuff needs work, these often get call 2 or 3\n * times each when only 1 was needed\n */\nvoid\nsoisfconnecting(struct socket *so)\n{\n\tso->so_state &= ~(SS_NOFDREF|SS_ISFCONNECTED|SS_FCANTRCVMORE|\n\t\t\t SS_FCANTSENDMORE|SS_FWDRAIN);\n\tso->so_state |= SS_ISFCONNECTING; /* Clobber other states */\n}\n\nvoid\nsoisfconnected(struct socket *so)\n{\n\tso->so_state &= ~(SS_ISFCONNECTING|SS_FWDRAIN|SS_NOFDREF);\n\tso->so_state |= SS_ISFCONNECTED; /* Clobber other states */\n}\n\nstatic void\nsofcantrcvmore(struct socket *so)\n{\n\tif ((so->so_state & SS_NOFDREF) == 0) {\n\t\tshutdown(so->s,0);\n\t\tif(global_writefds) {\n\t\t FD_CLR(so->s,global_writefds);\n\t\t}\n\t}\n\tso->so_state &= ~(SS_ISFCONNECTING);\n\tif (so->so_state & SS_FCANTSENDMORE) {\n\t so->so_state &= SS_PERSISTENT_MASK;\n\t so->so_state |= SS_NOFDREF; /* Don't select it */\n\t} else {\n\t so->so_state |= SS_FCANTRCVMORE;\n\t}\n}\n\nstatic void\nsofcantsendmore(struct socket *so)\n{\n\tif ((so->so_state & SS_NOFDREF) == 0) {\n shutdown(so->s,1); /* send FIN to fhost */\n if (global_readfds) {\n FD_CLR(so->s,global_readfds);\n }\n if (global_xfds) {\n FD_CLR(so->s,global_xfds);\n }\n\t}\n\tso->so_state &= ~(SS_ISFCONNECTING);\n\tif (so->so_state & SS_FCANTRCVMORE) {\n\t so->so_state &= SS_PERSISTENT_MASK;\n\t so->so_state |= SS_NOFDREF; /* as above */\n\t} else {\n\t so->so_state |= SS_FCANTSENDMORE;\n\t}\n}\n\n/*\n * Set write drain mode\n * Set CANTSENDMORE once all data has been write()n\n */\nvoid\nsofwdrain(struct socket *so)\n{\n\tif (so->so_rcv.sb_cc)\n\t\tso->so_state |= SS_FWDRAIN;\n\telse\n\t\tsofcantsendmore(so);\n}\n", "middle_code": "int\nsosendto(struct socket *so, struct mbuf *m)\n{\n\tSlirp *slirp = so->slirp;\n\tint ret;\n\tstruct sockaddr_in addr;\n\tDEBUG_CALL(\"sosendto\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n addr.sin_family = AF_INET;\n\tif ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n\t slirp->vnetwork_addr.s_addr) {\n\t if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\t if (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n\t } else {\n\t addr.sin_addr = loopback_addr;\n\t }\n\t} else\n\t addr.sin_addr = so->so_faddr;\n\taddr.sin_port = so->so_fport;\n\tDEBUG_MISC((dfd, \" sendto()ing, addr.sin_port=%d, addr.sin_addr.s_addr=%.16s\\n\", ntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));\n\tret = sendto(so->s, m->m_data, m->m_len, 0,\n\t\t (struct sockaddr *)&addr, sizeof (struct sockaddr));\n\tif (ret < 0)\n\t\treturn -1;\n\tif (so->so_expire)\n\t\tso->so_expire = curtime + SO_EXPIRE;\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= SS_ISFCONNECTED; \n\treturn 0;\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c", "sub_task_type": null}, "context_code": [["/linuxpdf/tinyemu/slirp/tcp_subr.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_subr.c\t8.1 (Berkeley) 6/10/93\n * tcp_subr.c,v 1.5 1994/10/08 22:39:58 phk Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n/* patchable/settable parameters for tcp */\n/* Don't do rfc1323 performance enhancements */\n#define TCP_DO_RFC1323 0\n\n/*\n * Tcp initialization\n */\nvoid\ntcp_init(Slirp *slirp)\n{\n slirp->tcp_iss = 1;\t\t/* wrong */\n slirp->tcb.so_next = slirp->tcb.so_prev = &slirp->tcb;\n slirp->tcp_last_so = &slirp->tcb;\n}\n\n/*\n * Create template to be used to send tcp packets on a connection.\n * Call after host entry created, fills\n * in a skeletal tcp/ip header, minimizing the amount of work\n * necessary when the connection is used.\n */\nvoid\ntcp_template(struct tcpcb *tp)\n{\n\tstruct socket *so = tp->t_socket;\n\tregister struct tcpiphdr *n = &tp->t_template;\n\n\tn->ti_mbuf = NULL;\n\tn->ti_x1 = 0;\n\tn->ti_pr = IPPROTO_TCP;\n\tn->ti_len = htons(sizeof (struct tcpiphdr) - sizeof (struct ip));\n\tn->ti_src = so->so_faddr;\n\tn->ti_dst = so->so_laddr;\n\tn->ti_sport = so->so_fport;\n\tn->ti_dport = so->so_lport;\n\n\tn->ti_seq = 0;\n\tn->ti_ack = 0;\n\tn->ti_x2 = 0;\n\tn->ti_off = 5;\n\tn->ti_flags = 0;\n\tn->ti_win = 0;\n\tn->ti_sum = 0;\n\tn->ti_urp = 0;\n}\n\n/*\n * Send a single message to the TCP at address specified by\n * the given TCP/IP header. If m == 0, then we make a copy\n * of the tcpiphdr at ti and send directly to the addressed host.\n * This is used to force keep alive messages out using the TCP\n * template for a connection tp->t_template. If flags are given\n * then we send a message back to the TCP which originated the\n * segment ti, and discard the mbuf containing it and any other\n * attached mbufs.\n *\n * In any case the ack and sequence number of the transmitted\n * segment are as specified by the parameters.\n */\nvoid\ntcp_respond(struct tcpcb *tp, struct tcpiphdr *ti, struct mbuf *m,\n tcp_seq ack, tcp_seq seq, int flags)\n{\n\tregister int tlen;\n\tint win = 0;\n\n\tDEBUG_CALL(\"tcp_respond\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"ti = %lx\", (long)ti);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"ack = %u\", ack);\n\tDEBUG_ARG(\"seq = %u\", seq);\n\tDEBUG_ARG(\"flags = %x\", flags);\n\n\tif (tp)\n\t\twin = sbspace(&tp->t_socket->so_rcv);\n if (m == NULL) {\n\t\tif ((m = m_get(tp->t_socket->slirp)) == NULL)\n\t\t\treturn;\n\t\ttlen = 0;\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\t*mtod(m, struct tcpiphdr *) = *ti;\n\t\tti = mtod(m, struct tcpiphdr *);\n\t\tflags = TH_ACK;\n\t} else {\n\t\t/*\n\t\t * ti points into m so the next line is just making\n\t\t * the mbuf point to ti\n\t\t */\n\t\tm->m_data = (caddr_t)ti;\n\n\t\tm->m_len = sizeof (struct tcpiphdr);\n\t\ttlen = 0;\n#define xchg(a,b,type) { type t; t=a; a=b; b=t; }\n\t\txchg(ti->ti_dst.s_addr, ti->ti_src.s_addr, uint32_t);\n\t\txchg(ti->ti_dport, ti->ti_sport, uint16_t);\n#undef xchg\n\t}\n\tti->ti_len = htons((u_short)(sizeof (struct tcphdr) + tlen));\n\ttlen += sizeof (struct tcpiphdr);\n\tm->m_len = tlen;\n\n ti->ti_mbuf = NULL;\n\tti->ti_x1 = 0;\n\tti->ti_seq = htonl(seq);\n\tti->ti_ack = htonl(ack);\n\tti->ti_x2 = 0;\n\tti->ti_off = sizeof (struct tcphdr) >> 2;\n\tti->ti_flags = flags;\n\tif (tp)\n\t\tti->ti_win = htons((uint16_t) (win >> tp->rcv_scale));\n\telse\n\t\tti->ti_win = htons((uint16_t)win);\n\tti->ti_urp = 0;\n\tti->ti_sum = 0;\n\tti->ti_sum = cksum(m, tlen);\n\t((struct ip *)ti)->ip_len = tlen;\n\n\tif(flags & TH_RST)\n\t ((struct ip *)ti)->ip_ttl = MAXTTL;\n\telse\n\t ((struct ip *)ti)->ip_ttl = IPDEFTTL;\n\n\t(void) ip_output((struct socket *)0, m);\n}\n\n/*\n * Create a new TCP control block, making an\n * empty reassembly queue and hooking it to the argument\n * protocol control block.\n */\nstruct tcpcb *\ntcp_newtcpcb(struct socket *so)\n{\n\tregister struct tcpcb *tp;\n\n\ttp = (struct tcpcb *)malloc(sizeof(*tp));\n\tif (tp == NULL)\n\t\treturn ((struct tcpcb *)0);\n\n\tmemset((char *) tp, 0, sizeof(struct tcpcb));\n\ttp->seg_next = tp->seg_prev = (struct tcpiphdr*)tp;\n\ttp->t_maxseg = TCP_MSS;\n\n\ttp->t_flags = TCP_DO_RFC1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;\n\ttp->t_socket = so;\n\n\t/*\n\t * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no\n\t * rtt estimate. Set rttvar so that srtt + 2 * rttvar gives\n\t * reasonable initial retransmit time.\n\t */\n\ttp->t_srtt = TCPTV_SRTTBASE;\n\ttp->t_rttvar = TCPTV_SRTTDFLT << 2;\n\ttp->t_rttmin = TCPTV_MIN;\n\n\tTCPT_RANGESET(tp->t_rxtcur,\n\t ((TCPTV_SRTTBASE >> 2) + (TCPTV_SRTTDFLT << 2)) >> 1,\n\t TCPTV_MIN, TCPTV_REXMTMAX);\n\n\ttp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;\n\ttp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;\n\ttp->t_state = TCPS_CLOSED;\n\n\tso->so_tcpcb = tp;\n\n\treturn (tp);\n}\n\n/*\n * Drop a TCP connection, reporting\n * the specified error. If connection is synchronized,\n * then send a RST to peer.\n */\nstruct tcpcb *tcp_drop(struct tcpcb *tp, int err)\n{\n\tDEBUG_CALL(\"tcp_drop\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"errno = %d\", errno);\n\n\tif (TCPS_HAVERCVDSYN(tp->t_state)) {\n\t\ttp->t_state = TCPS_CLOSED;\n\t\t(void) tcp_output(tp);\n\t}\n\treturn (tcp_close(tp));\n}\n\n/*\n * Close a TCP control block:\n *\tdiscard all space held by the tcp\n *\tdiscard internet protocol block\n *\twake up any sleepers\n */\nstruct tcpcb *\ntcp_close(struct tcpcb *tp)\n{\n\tregister struct tcpiphdr *t;\n\tstruct socket *so = tp->t_socket;\n\tSlirp *slirp = so->slirp;\n\tregister struct mbuf *m;\n\n\tDEBUG_CALL(\"tcp_close\");\n\tDEBUG_ARG(\"tp = %lx\", (long )tp);\n\n\t/* free the reassembly queue, if any */\n\tt = tcpfrag_list_first(tp);\n\twhile (!tcpfrag_list_end(t, tp)) {\n\t\tt = tcpiphdr_next(t);\n\t\tm = tcpiphdr_prev(t)->ti_mbuf;\n\t\tremque(tcpiphdr2qlink(tcpiphdr_prev(t)));\n\t\tm_freem(m);\n\t}\n\tfree(tp);\n so->so_tcpcb = NULL;\n\t/* clobber input socket cache if we're closing the cached connection */\n\tif (so == slirp->tcp_last_so)\n\t\tslirp->tcp_last_so = &slirp->tcb;\n\tclosesocket(so->s);\n\tsbfree(&so->so_rcv);\n\tsbfree(&so->so_snd);\n\tsofree(so);\n\treturn ((struct tcpcb *)0);\n}\n\n/*\n * TCP protocol interface to socket abstraction.\n */\n\n/*\n * User issued close, and wish to trail through shutdown states:\n * if never received SYN, just forget it. If got a SYN from peer,\n * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.\n * If already got a FIN from peer, then almost done; go to LAST_ACK\n * state. In all other cases, have already sent FIN to peer (e.g.\n * after PRU_SHUTDOWN), and just have to play tedious game waiting\n * for peer to send FIN or not respond to keep-alives, etc.\n * We can let the user exit from the close as soon as the FIN is acked.\n */\nvoid\ntcp_sockclosed(struct tcpcb *tp)\n{\n\n\tDEBUG_CALL(\"tcp_sockclosed\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\n\tswitch (tp->t_state) {\n\n\tcase TCPS_CLOSED:\n\tcase TCPS_LISTEN:\n\tcase TCPS_SYN_SENT:\n\t\ttp->t_state = TCPS_CLOSED;\n\t\ttp = tcp_close(tp);\n\t\tbreak;\n\n\tcase TCPS_SYN_RECEIVED:\n\tcase TCPS_ESTABLISHED:\n\t\ttp->t_state = TCPS_FIN_WAIT_1;\n\t\tbreak;\n\n\tcase TCPS_CLOSE_WAIT:\n\t\ttp->t_state = TCPS_LAST_ACK;\n\t\tbreak;\n\t}\n\tif (tp)\n\t\ttcp_output(tp);\n}\n\n/*\n * Connect to a host on the Internet\n * Called by tcp_input\n * Only do a connect, the tcp fields will be set in tcp_input\n * return 0 if there's a result of the connect,\n * else return -1 means we're still connecting\n * The return value is almost always -1 since the socket is\n * nonblocking. Connect returns after the SYN is sent, and does\n * not wait for ACK+SYN.\n */\nint tcp_fconnect(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n int ret=0;\n\n DEBUG_CALL(\"tcp_fconnect\");\n DEBUG_ARG(\"so = %lx\", (long )so);\n\n if( (ret = so->s = os_socket(AF_INET,SOCK_STREAM,0)) >= 0) {\n int opt, s=so->s;\n struct sockaddr_in addr;\n\n fd_nonblock(s);\n opt = 1;\n setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(opt ));\n opt = 1;\n setsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(opt ));\n\n addr.sin_family = AF_INET;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n /* It's an alias */\n if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\tif (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n } else {\n\taddr.sin_addr = loopback_addr;\n }\n } else\n addr.sin_addr = so->so_faddr;\n addr.sin_port = so->so_fport;\n\n DEBUG_MISC((dfd, \" connect()ing, addr.sin_port=%d, \"\n\t\t\"addr.sin_addr.s_addr=%.16s\\n\",\n\t\tntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));\n /* We don't care what port we get */\n ret = connect(s,(struct sockaddr *)&addr,sizeof (addr));\n\n /*\n * If it's not in progress, it failed, so we just return 0,\n * without clearing SS_NOFDREF\n */\n soisfconnecting(so);\n }\n\n return(ret);\n}\n\n/*\n * Accept the socket and connect to the local-host\n *\n * We have a problem. The correct thing to do would be\n * to first connect to the local-host, and only if the\n * connection is accepted, then do an accept() here.\n * But, a) we need to know who's trying to connect\n * to the socket to be able to SYN the local-host, and\n * b) we are already connected to the foreign host by\n * the time it gets to accept(), so... We simply accept\n * here and SYN the local-host.\n */\nvoid\ntcp_connect(struct socket *inso)\n{\n\tSlirp *slirp = inso->slirp;\n\tstruct socket *so;\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\tstruct tcpcb *tp;\n\tint s, opt;\n\n\tDEBUG_CALL(\"tcp_connect\");\n\tDEBUG_ARG(\"inso = %lx\", (long)inso);\n\n\t/*\n\t * If it's an SS_ACCEPTONCE socket, no need to socreate()\n\t * another socket, just use the accept() socket.\n\t */\n\tif (inso->so_state & SS_FACCEPTONCE) {\n\t\t/* FACCEPTONCE already have a tcpcb */\n\t\tso = inso;\n\t} else {\n\t\tif ((so = socreate(slirp)) == NULL) {\n\t\t\t/* If it failed, get rid of the pending connection */\n\t\t\tclosesocket(accept(inso->s,(struct sockaddr *)&addr,&addrlen));\n\t\t\treturn;\n\t\t}\n\t\tif (tcp_attach(so) < 0) {\n\t\t\tfree(so); /* NOT sofree */\n\t\t\treturn;\n\t\t}\n\t\tso->so_laddr = inso->so_laddr;\n\t\tso->so_lport = inso->so_lport;\n\t}\n\n\t(void) tcp_mss(sototcpcb(so), 0);\n\n\tif ((s = accept(inso->s,(struct sockaddr *)&addr,&addrlen)) < 0) {\n\t\ttcp_close(sototcpcb(so)); /* This will sofree() as well */\n\t\treturn;\n\t}\n\tfd_nonblock(s);\n\topt = 1;\n\tsetsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\topt = 1;\n\tsetsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\topt = 1;\n\tsetsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&opt,sizeof(int));\n\n\tso->so_fport = addr.sin_port;\n\tso->so_faddr = addr.sin_addr;\n\t/* Translate connections from localhost to the real hostname */\n\tif (so->so_faddr.s_addr == 0 || so->so_faddr.s_addr == loopback_addr.s_addr)\n\t so->so_faddr = slirp->vhost_addr;\n\n\t/* Close the accept() socket, set right state */\n\tif (inso->so_state & SS_FACCEPTONCE) {\n\t\tclosesocket(so->s); /* If we only accept once, close the accept() socket */\n\t\tso->so_state = SS_NOFDREF; /* Don't select it yet, even though we have an FD */\n\t\t\t\t\t /* if it's not FACCEPTONCE, it's already NOFDREF */\n\t}\n\tso->s = s;\n\tso->so_state |= SS_INCOMING;\n\n\tso->so_iptos = tcp_tos(so);\n\ttp = sototcpcb(so);\n\n\ttcp_template(tp);\n\n\ttp->t_state = TCPS_SYN_SENT;\n\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\ttp->iss = slirp->tcp_iss;\n\tslirp->tcp_iss += TCP_ISSINCR/2;\n\ttcp_sendseqinit(tp);\n\ttcp_output(tp);\n}\n\n/*\n * Attach a TCPCB to a socket.\n */\nint\ntcp_attach(struct socket *so)\n{\n\tif ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL)\n\t return -1;\n\n\tinsque(so, &so->slirp->tcb);\n\n\treturn 0;\n}\n\n/*\n * Set the socket's type of service field\n */\nstatic const struct tos_t tcptos[] = {\n\t {0, 20, IPTOS_THROUGHPUT, 0},\t/* ftp data */\n\t {21, 21, IPTOS_LOWDELAY, EMU_FTP},\t/* ftp control */\n\t {0, 23, IPTOS_LOWDELAY, 0},\t/* telnet */\n\t {0, 80, IPTOS_THROUGHPUT, 0},\t/* WWW */\n\t {0, 513, IPTOS_LOWDELAY, EMU_RLOGIN|EMU_NOCONNECT},\t/* rlogin */\n\t {0, 514, IPTOS_LOWDELAY, EMU_RSH|EMU_NOCONNECT},\t/* shell */\n\t {0, 544, IPTOS_LOWDELAY, EMU_KSH},\t\t/* kshell */\n\t {0, 543, IPTOS_LOWDELAY, 0},\t/* klogin */\n\t {0, 6667, IPTOS_THROUGHPUT, EMU_IRC},\t/* IRC */\n\t {0, 6668, IPTOS_THROUGHPUT, EMU_IRC},\t/* IRC undernet */\n\t {0, 7070, IPTOS_LOWDELAY, EMU_REALAUDIO }, /* RealAudio control */\n\t {0, 113, IPTOS_LOWDELAY, EMU_IDENT }, /* identd protocol */\n\t {0, 0, 0, 0}\n};\n\nstatic struct emu_t *tcpemu = NULL;\n\n/*\n * Return TOS according to the above table\n */\nuint8_t\ntcp_tos(struct socket *so)\n{\n\tint i = 0;\n\tstruct emu_t *emup;\n\n\twhile(tcptos[i].tos) {\n\t\tif ((tcptos[i].fport && (ntohs(so->so_fport) == tcptos[i].fport)) ||\n\t\t (tcptos[i].lport && (ntohs(so->so_lport) == tcptos[i].lport))) {\n\t\t\tso->so_emu = tcptos[i].emu;\n\t\t\treturn tcptos[i].tos;\n\t\t}\n\t\ti++;\n\t}\n\n\t/* Nope, lets see if there's a user-added one */\n\tfor (emup = tcpemu; emup; emup = emup->next) {\n\t\tif ((emup->fport && (ntohs(so->so_fport) == emup->fport)) ||\n\t\t (emup->lport && (ntohs(so->so_lport) == emup->lport))) {\n\t\t\tso->so_emu = emup->emu;\n\t\t\treturn emup->tos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/*\n * Emulate programs that try and connect to us\n * This includes ftp (the data connection is\n * initiated by the server) and IRC (DCC CHAT and\n * DCC SEND) for now\n *\n * NOTE: It's possible to crash SLiRP by sending it\n * unstandard strings to emulate... if this is a problem,\n * more checks are needed here\n *\n * XXX Assumes the whole command came in one packet\n *\n * XXX Some ftp clients will have their TOS set to\n * LOWDELAY and so Nagel will kick in. Because of this,\n * we'll get the first letter, followed by the rest, so\n * we simply scan for ORT instead of PORT...\n * DCC doesn't have this problem because there's other stuff\n * in the packet before the DCC command.\n *\n * Return 1 if the mbuf m is still valid and should be\n * sbappend()ed\n *\n * NOTE: if you return 0 you MUST m_free() the mbuf!\n */\nint\ntcp_emu(struct socket *so, struct mbuf *m)\n{\n\tSlirp *slirp = so->slirp;\n\tu_int n1, n2, n3, n4, n5, n6;\n char buff[257];\n\tuint32_t laddr;\n\tu_int lport;\n\tchar *bptr;\n\n\tDEBUG_CALL(\"tcp_emu\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n\tswitch(so->so_emu) {\n\t\tint x, i;\n\n\t case EMU_IDENT:\n\t\t/*\n\t\t * Identification protocol as per rfc-1413\n\t\t */\n\n\t\t{\n\t\t\tstruct socket *tmpso;\n\t\t\tstruct sockaddr_in addr;\n\t\t\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\t\t\tstruct sbuf *so_rcv = &so->so_rcv;\n\n\t\t\tmemcpy(so_rcv->sb_wptr, m->m_data, m->m_len);\n\t\t\tso_rcv->sb_wptr += m->m_len;\n\t\t\tso_rcv->sb_rptr += m->m_len;\n\t\t\tm->m_data[m->m_len] = 0; /* NULL terminate */\n\t\t\tif (strchr(m->m_data, '\\r') || strchr(m->m_data, '\\n')) {\n\t\t\t\tif (sscanf(so_rcv->sb_data, \"%u%*[ ,]%u\", &n1, &n2) == 2) {\n\t\t\t\t\tHTONS(n1);\n\t\t\t\t\tHTONS(n2);\n\t\t\t\t\t/* n2 is the one on our host */\n\t\t\t\t\tfor (tmpso = slirp->tcb.so_next;\n\t\t\t\t\t tmpso != &slirp->tcb;\n\t\t\t\t\t tmpso = tmpso->so_next) {\n\t\t\t\t\t\tif (tmpso->so_laddr.s_addr == so->so_laddr.s_addr &&\n\t\t\t\t\t\t tmpso->so_lport == n2 &&\n\t\t\t\t\t\t tmpso->so_faddr.s_addr == so->so_faddr.s_addr &&\n\t\t\t\t\t\t tmpso->so_fport == n1) {\n\t\t\t\t\t\t\tif (getsockname(tmpso->s,\n\t\t\t\t\t\t\t\t(struct sockaddr *)&addr, &addrlen) == 0)\n\t\t\t\t\t\t\t n2 = ntohs(addr.sin_port);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n so_rcv->sb_cc = snprintf(so_rcv->sb_data,\n so_rcv->sb_datalen,\n \"%d,%d\\r\\n\", n1, n2);\n\t\t\t\tso_rcv->sb_rptr = so_rcv->sb_data;\n\t\t\t\tso_rcv->sb_wptr = so_rcv->sb_data + so_rcv->sb_cc;\n\t\t\t}\n\t\t\tm_free(m);\n\t\t\treturn 0;\n\t\t}\n\n case EMU_FTP: /* ftp */\n *(m->m_data+m->m_len) = 0; /* NUL terminate for strstr */\n\t\tif ((bptr = (char *)strstr(m->m_data, \"ORT\")) != NULL) {\n\t\t\t/*\n\t\t\t * Need to emulate the PORT command\n\t\t\t */\n\t\t\tx = sscanf(bptr, \"ORT %u,%u,%u,%u,%u,%u\\r\\n%256[^\\177]\",\n\t\t\t\t &n1, &n2, &n3, &n4, &n5, &n6, buff);\n\t\t\tif (x < 6)\n\t\t\t return 1;\n\n\t\t\tladdr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));\n\t\t\tlport = htons((n5 << 8) | (n6));\n\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr,\n\t\t\t lport, SS_FACCEPTONCE)) == NULL) {\n\t\t\t return 1;\n\t\t\t}\n\t\t\tn6 = ntohs(so->so_fport);\n\n\t\t\tn5 = (n6 >> 8) & 0xff;\n\t\t\tn6 &= 0xff;\n\n\t\t\tladdr = ntohl(so->so_faddr.s_addr);\n\n\t\t\tn1 = ((laddr >> 24) & 0xff);\n\t\t\tn2 = ((laddr >> 16) & 0xff);\n\t\t\tn3 = ((laddr >> 8) & 0xff);\n\t\t\tn4 = (laddr & 0xff);\n\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size - m->m_len,\n \"ORT %d,%d,%d,%d,%d,%d\\r\\n%s\",\n n1, n2, n3, n4, n5, n6, x==7?buff:\"\");\n\t\t\treturn 1;\n\t\t} else if ((bptr = (char *)strstr(m->m_data, \"27 Entering\")) != NULL) {\n\t\t\t/*\n\t\t\t * Need to emulate the PASV response\n\t\t\t */\n\t\t\tx = sscanf(bptr, \"27 Entering Passive Mode (%u,%u,%u,%u,%u,%u)\\r\\n%256[^\\177]\",\n\t\t\t\t &n1, &n2, &n3, &n4, &n5, &n6, buff);\n\t\t\tif (x < 6)\n\t\t\t return 1;\n\n\t\t\tladdr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));\n\t\t\tlport = htons((n5 << 8) | (n6));\n\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr,\n\t\t\t lport, SS_FACCEPTONCE)) == NULL) {\n\t\t\t return 1;\n\t\t\t}\n\t\t\tn6 = ntohs(so->so_fport);\n\n\t\t\tn5 = (n6 >> 8) & 0xff;\n\t\t\tn6 &= 0xff;\n\n\t\t\tladdr = ntohl(so->so_faddr.s_addr);\n\n\t\t\tn1 = ((laddr >> 24) & 0xff);\n\t\t\tn2 = ((laddr >> 16) & 0xff);\n\t\t\tn3 = ((laddr >> 8) & 0xff);\n\t\t\tn4 = (laddr & 0xff);\n\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n\t\t\tm->m_len += snprintf(bptr, m->m_hdr.mh_size - m->m_len,\n \"27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\\r\\n%s\",\n n1, n2, n3, n4, n5, n6, x==7?buff:\"\");\n\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn 1;\n\n\t case EMU_KSH:\n\t\t/*\n\t\t * The kshell (Kerberos rsh) and shell services both pass\n\t\t * a local port port number to carry signals to the server\n\t\t * and stderr to the client. It is passed at the beginning\n\t\t * of the connection as a NUL-terminated decimal ASCII string.\n\t\t */\n\t\tso->so_emu = 0;\n\t\tfor (lport = 0, i = 0; i < m->m_len-1; ++i) {\n\t\t\tif (m->m_data[i] < '0' || m->m_data[i] > '9')\n\t\t\t\treturn 1; /* invalid number */\n\t\t\tlport *= 10;\n\t\t\tlport += m->m_data[i] - '0';\n\t\t}\n\t\tif (m->m_data[m->m_len-1] == '\\0' && lport != 0 &&\n\t\t (so = tcp_listen(slirp, INADDR_ANY, 0, so->so_laddr.s_addr,\n\t\t htons(lport), SS_FACCEPTONCE)) != NULL)\n m->m_len = snprintf(m->m_data, m->m_hdr.mh_size, \"%d\",\n ntohs(so->so_fport)) + 1;\n\t\treturn 1;\n\n\t case EMU_IRC:\n\t\t/*\n\t\t * Need to emulate DCC CHAT, DCC SEND and DCC MOVE\n\t\t */\n\t\t*(m->m_data+m->m_len) = 0; /* NULL terminate the string for strstr */\n\t\tif ((bptr = (char *)strstr(m->m_data, \"DCC\")) == NULL)\n\t\t\t return 1;\n\n\t\t/* The %256s is for the broken mIRC */\n\t\tif (sscanf(bptr, \"DCC CHAT %256s %u %u\", buff, &laddr, &lport) == 3) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC CHAT chat %lu %u%c\\n\",\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), 1);\n\t\t} else if (sscanf(bptr, \"DCC SEND %256s %u %u %u\", buff, &laddr, &lport, &n1) == 4) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC SEND %s %lu %u %u%c\\n\", buff,\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), n1, 1);\n\t\t} else if (sscanf(bptr, \"DCC MOVE %256s %u %u %u\", buff, &laddr, &lport, &n1) == 4) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC MOVE %s %lu %u %u%c\\n\", buff,\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), n1, 1);\n\t\t}\n\t\treturn 1;\n\n\t case EMU_REALAUDIO:\n /*\n\t\t * RealAudio emulation - JP. We must try to parse the incoming\n\t\t * data and try to find the two characters that contain the\n\t\t * port number. Then we redirect an udp port and replace the\n\t\t * number with the real port we got.\n\t\t *\n\t\t * The 1.0 beta versions of the player are not supported\n\t\t * any more.\n\t\t *\n\t\t * A typical packet for player version 1.0 (release version):\n\t\t *\n\t\t * 0000:50 4E 41 00 05\n\t\t * 0000:00 01 00 02 1B D7 00 00 67 E6 6C DC 63 00 12 50 ........g.l.c..P\n\t\t * 0010:4E 43 4C 49 45 4E 54 20 31 30 31 20 41 4C 50 48 NCLIENT 101 ALPH\n\t\t * 0020:41 6C 00 00 52 00 17 72 61 66 69 6C 65 73 2F 76 Al..R..rafiles/v\n\t\t * 0030:6F 61 2F 65 6E 67 6C 69 73 68 5F 2E 72 61 79 42 oa/english_.rayB\n\t\t *\n\t\t * Now the port number 0x1BD7 is found at offset 0x04 of the\n\t\t * Now the port number 0x1BD7 is found at offset 0x04 of the\n\t\t * second packet. This time we received five bytes first and\n\t\t * then the rest. You never know how many bytes you get.\n\t\t *\n\t\t * A typical packet for player version 2.0 (beta):\n\t\t *\n\t\t * 0000:50 4E 41 00 06 00 02 00 00 00 01 00 02 1B C1 00 PNA.............\n\t\t * 0010:00 67 75 78 F5 63 00 0A 57 69 6E 32 2E 30 2E 30 .gux.c..Win2.0.0\n\t\t * 0020:2E 35 6C 00 00 52 00 1C 72 61 66 69 6C 65 73 2F .5l..R..rafiles/\n\t\t * 0030:77 65 62 73 69 74 65 2F 32 30 72 65 6C 65 61 73 website/20releas\n\t\t * 0040:65 2E 72 61 79 53 00 00 06 36 42 e.rayS...6B\n\t\t *\n\t\t * Port number 0x1BC1 is found at offset 0x0d.\n\t\t *\n\t\t * This is just a horrible switch statement. Variable ra tells\n\t\t * us where we're going.\n\t\t */\n\n\t\tbptr = m->m_data;\n\t\twhile (bptr < m->m_data + m->m_len) {\n\t\t\tu_short p;\n\t\t\tstatic int ra = 0;\n\t\t\tchar ra_tbl[4];\n\n\t\t\tra_tbl[0] = 0x50;\n\t\t\tra_tbl[1] = 0x4e;\n\t\t\tra_tbl[2] = 0x41;\n\t\t\tra_tbl[3] = 0;\n\n\t\t\tswitch (ra) {\n\t\t\t case 0:\n\t\t\t case 2:\n\t\t\t case 3:\n\t\t\t\tif (*bptr++ != ra_tbl[ra]) {\n\t\t\t\t\tra = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t case 1:\n\t\t\t\t/*\n\t\t\t\t * We may get 0x50 several times, ignore them\n\t\t\t\t */\n\t\t\t\tif (*bptr == 0x50) {\n\t\t\t\t\tra = 1;\n\t\t\t\t\tbptr++;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (*bptr++ != ra_tbl[ra]) {\n\t\t\t\t\tra = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t case 4:\n\t\t\t\t/*\n\t\t\t\t * skip version number\n\t\t\t\t */\n\t\t\t\tbptr++;\n\t\t\t\tbreak;\n\n\t\t\t case 5:\n\t\t\t\t/*\n\t\t\t\t * The difference between versions 1.0 and\n\t\t\t\t * 2.0 is here. For future versions of\n\t\t\t\t * the player this may need to be modified.\n\t\t\t\t */\n\t\t\t\tif (*(bptr + 1) == 0x02)\n\t\t\t\t bptr += 8;\n\t\t\t\telse\n\t\t\t\t bptr += 4;\n\t\t\t\tbreak;\n\n\t\t\t case 6:\n\t\t\t\t/* This is the field containing the port\n\t\t\t\t * number that RA-player is listening to.\n\t\t\t\t */\n\t\t\t\tlport = (((u_char*)bptr)[0] << 8)\n\t\t\t\t+ ((u_char *)bptr)[1];\n\t\t\t\tif (lport < 6970)\n\t\t\t\t lport += 256; /* don't know why */\n\t\t\t\tif (lport < 6970 || lport > 7170)\n\t\t\t\t return 1; /* failed */\n\n\t\t\t\t/* try to get udp port between 6970 - 7170 */\n\t\t\t\tfor (p = 6970; p < 7071; p++) {\n\t\t\t\t\tif (udp_listen(slirp, INADDR_ANY,\n\t\t\t\t\t\t htons(p),\n\t\t\t\t\t\t so->so_laddr.s_addr,\n\t\t\t\t\t\t htons(lport),\n\t\t\t\t\t\t SS_FACCEPTONCE)) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (p == 7071)\n\t\t\t\t p = 0;\n\t\t\t\t*(u_char *)bptr++ = (p >> 8) & 0xff;\n *(u_char *)bptr = p & 0xff;\n\t\t\t\tra = 0;\n\t\t\t\treturn 1; /* port redirected, we're done */\n\t\t\t\tbreak;\n\n\t\t\t default:\n\t\t\t\tra = 0;\n\t\t\t}\n\t\t\tra++;\n\t\t}\n\t\treturn 1;\n\n\t default:\n\t\t/* Ooops, not emulated, won't call tcp_emu again */\n\t\tso->so_emu = 0;\n\t\treturn 1;\n\t}\n}\n\n/*\n * Do misc. config of SLiRP while its running.\n * Return 0 if this connections is to be closed, 1 otherwise,\n * return 2 if this is a command-line connection\n */\nint tcp_ctl(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n struct sbuf *sb = &so->so_snd;\n struct ex_list *ex_ptr;\n int do_pty;\n\n DEBUG_CALL(\"tcp_ctl\");\n DEBUG_ARG(\"so = %lx\", (long )so);\n\n if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {\n /* Check if it's pty_exec */\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_fport == so->so_fport &&\n so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {\n if (ex_ptr->ex_pty == 3) {\n so->s = -1;\n so->extra = (void *)ex_ptr->ex_exec;\n return 1;\n }\n do_pty = ex_ptr->ex_pty;\n DEBUG_MISC((dfd, \" executing %s \\n\",ex_ptr->ex_exec));\n return fork_exec(so, ex_ptr->ex_exec, do_pty);\n }\n }\n }\n sb->sb_cc =\n snprintf(sb->sb_wptr, sb->sb_datalen - (sb->sb_wptr - sb->sb_data),\n \"Error: No application configured.\\r\\n\");\n sb->sb_wptr += sb->sb_cc;\n return 0;\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_input.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_input.c\t8.5 (Berkeley) 4/10/94\n * tcp_input.c,v 1.10 1994/10/13 18:36:32 wollman Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n#define\tTCPREXMTTHRESH 3\n\n#define TCP_PAWS_IDLE\t(24 * 24 * 60 * 60 * PR_SLOWHZ)\n\n/* for modulo comparisons of timestamps */\n#define TSTMP_LT(a,b)\t((int)((a)-(b)) < 0)\n#define TSTMP_GEQ(a,b)\t((int)((a)-(b)) >= 0)\n\n/*\n * Insert segment ti into reassembly queue of tcp with\n * control block tp. Return TH_FIN if reassembly now includes\n * a segment with FIN. The macro form does the common case inline\n * (segment is the next to be received on an established connection,\n * and the queue is empty), avoiding linkage into and removal\n * from the queue and repetition of various conversions.\n * Set DELACK for segments received in order, but ack immediately\n * when segments are out of order (so fast retransmit can work).\n */\n#ifdef TCP_ACK_HACK\n#define TCP_REASS(tp, ti, m, so, flags) {\\\n if ((ti)->ti_seq == (tp)->rcv_nxt && \\\n tcpfrag_list_empty(tp) && \\\n (tp)->t_state == TCPS_ESTABLISHED) {\\\n if (ti->ti_flags & TH_PUSH) \\\n tp->t_flags |= TF_ACKNOW; \\\n else \\\n tp->t_flags |= TF_DELACK; \\\n (tp)->rcv_nxt += (ti)->ti_len; \\\n flags = (ti)->ti_flags & TH_FIN; \\\n if (so->so_emu) { \\\n\t\t if (tcp_emu((so),(m))) sbappend((so), (m)); \\\n\t } else \\\n\t \t sbappend((so), (m)); \\\n\t} else {\\\n (flags) = tcp_reass((tp), (ti), (m)); \\\n tp->t_flags |= TF_ACKNOW; \\\n } \\\n}\n#else\n#define\tTCP_REASS(tp, ti, m, so, flags) { \\\n\tif ((ti)->ti_seq == (tp)->rcv_nxt && \\\n tcpfrag_list_empty(tp) && \\\n\t (tp)->t_state == TCPS_ESTABLISHED) { \\\n\t\ttp->t_flags |= TF_DELACK; \\\n\t\t(tp)->rcv_nxt += (ti)->ti_len; \\\n\t\tflags = (ti)->ti_flags & TH_FIN; \\\n\t\tif (so->so_emu) { \\\n\t\t\tif (tcp_emu((so),(m))) sbappend(so, (m)); \\\n\t\t} else \\\n\t\t\tsbappend((so), (m)); \\\n\t} else { \\\n\t\t(flags) = tcp_reass((tp), (ti), (m)); \\\n\t\ttp->t_flags |= TF_ACKNOW; \\\n\t} \\\n}\n#endif\nstatic void tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt,\n struct tcpiphdr *ti);\nstatic void tcp_xmit_timer(register struct tcpcb *tp, int rtt);\n\nstatic int\ntcp_reass(register struct tcpcb *tp, register struct tcpiphdr *ti,\n struct mbuf *m)\n{\n\tregister struct tcpiphdr *q;\n\tstruct socket *so = tp->t_socket;\n\tint flags;\n\n\t/*\n\t * Call with ti==NULL after become established to\n\t * force pre-ESTABLISHED data up to user socket.\n\t */\n if (ti == NULL)\n\t\tgoto present;\n\n\t/*\n\t * Find a segment which begins after this one does.\n\t */\n\tfor (q = tcpfrag_list_first(tp); !tcpfrag_list_end(q, tp);\n q = tcpiphdr_next(q))\n\t\tif (SEQ_GT(q->ti_seq, ti->ti_seq))\n\t\t\tbreak;\n\n\t/*\n\t * If there is a preceding segment, it may provide some of\n\t * our data already. If so, drop the data from the incoming\n\t * segment. If it provides all of our data, drop us.\n\t */\n\tif (!tcpfrag_list_end(tcpiphdr_prev(q), tp)) {\n\t\tregister int i;\n\t\tq = tcpiphdr_prev(q);\n\t\t/* conversion to int (in i) handles seq wraparound */\n\t\ti = q->ti_seq + q->ti_len - ti->ti_seq;\n\t\tif (i > 0) {\n\t\t\tif (i >= ti->ti_len) {\n\t\t\t\tm_freem(m);\n\t\t\t\t/*\n\t\t\t\t * Try to present any queued data\n\t\t\t\t * at the left window edge to the user.\n\t\t\t\t * This is needed after the 3-WHS\n\t\t\t\t * completes.\n\t\t\t\t */\n\t\t\t\tgoto present; /* ??? */\n\t\t\t}\n\t\t\tm_adj(m, i);\n\t\t\tti->ti_len -= i;\n\t\t\tti->ti_seq += i;\n\t\t}\n\t\tq = tcpiphdr_next(q);\n\t}\n\tti->ti_mbuf = m;\n\n\t/*\n\t * While we overlap succeeding segments trim them or,\n\t * if they are completely covered, dequeue them.\n\t */\n\twhile (!tcpfrag_list_end(q, tp)) {\n\t\tregister int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;\n\t\tif (i <= 0)\n\t\t\tbreak;\n\t\tif (i < q->ti_len) {\n\t\t\tq->ti_seq += i;\n\t\t\tq->ti_len -= i;\n\t\t\tm_adj(q->ti_mbuf, i);\n\t\t\tbreak;\n\t\t}\n\t\tq = tcpiphdr_next(q);\n\t\tm = tcpiphdr_prev(q)->ti_mbuf;\n\t\tremque(tcpiphdr2qlink(tcpiphdr_prev(q)));\n\t\tm_freem(m);\n\t}\n\n\t/*\n\t * Stick new segment in its place.\n\t */\n\tinsque(tcpiphdr2qlink(ti), tcpiphdr2qlink(tcpiphdr_prev(q)));\n\npresent:\n\t/*\n\t * Present data to user, advancing rcv_nxt through\n\t * completed sequence space.\n\t */\n\tif (!TCPS_HAVEESTABLISHED(tp->t_state))\n\t\treturn (0);\n\tti = tcpfrag_list_first(tp);\n\tif (tcpfrag_list_end(ti, tp) || ti->ti_seq != tp->rcv_nxt)\n\t\treturn (0);\n\tif (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)\n\t\treturn (0);\n\tdo {\n\t\ttp->rcv_nxt += ti->ti_len;\n\t\tflags = ti->ti_flags & TH_FIN;\n\t\tremque(tcpiphdr2qlink(ti));\n\t\tm = ti->ti_mbuf;\n\t\tti = tcpiphdr_next(ti);\n\t\tif (so->so_state & SS_FCANTSENDMORE)\n\t\t\tm_freem(m);\n\t\telse {\n\t\t\tif (so->so_emu) {\n\t\t\t\tif (tcp_emu(so,m)) sbappend(so, m);\n\t\t\t} else\n\t\t\t\tsbappend(so, m);\n\t\t}\n\t} while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);\n\treturn (flags);\n}\n\n/*\n * TCP input routine, follows pages 65-76 of the\n * protocol specification dated September, 1981 very closely.\n */\nvoid\ntcp_input(struct mbuf *m, int iphlen, struct socket *inso)\n{\n \tstruct ip save_ip, *ip;\n\tregister struct tcpiphdr *ti;\n\tcaddr_t optp = NULL;\n\tint optlen = 0;\n\tint len, tlen, off;\n register struct tcpcb *tp = NULL;\n\tregister int tiflags;\n struct socket *so = NULL;\n\tint todrop, acked, ourfinisacked, needoutput = 0;\n\tint iss = 0;\n\tu_long tiwin;\n\tint ret;\n struct ex_list *ex_ptr;\n Slirp *slirp;\n\n\tDEBUG_CALL(\"tcp_input\");\n\tDEBUG_ARGS((dfd,\" m = %8lx iphlen = %2d inso = %lx\\n\",\n\t\t (long )m, iphlen, (long )inso ));\n\n\t/*\n\t * If called with m == 0, then we're continuing the connect\n\t */\n\tif (m == NULL) {\n\t\tso = inso;\n\t\tslirp = so->slirp;\n\n\t\t/* Re-set a few variables */\n\t\ttp = sototcpcb(so);\n\t\tm = so->so_m;\n so->so_m = NULL;\n\t\tti = so->so_ti;\n\t\ttiwin = ti->ti_win;\n\t\ttiflags = ti->ti_flags;\n\n\t\tgoto cont_conn;\n\t}\n\tslirp = m->slirp;\n\n\t/*\n\t * Get IP and TCP header together in first mbuf.\n\t * Note: IP leaves IP header in first mbuf.\n\t */\n\tti = mtod(m, struct tcpiphdr *);\n\tif (iphlen > sizeof(struct ip )) {\n\t ip_stripoptions(m, (struct mbuf *)0);\n\t iphlen=sizeof(struct ip );\n\t}\n\t/* XXX Check if too short */\n\n\n\t/*\n\t * Save a copy of the IP header in case we want restore it\n\t * for sending an ICMP error message in response.\n\t */\n\tip=mtod(m, struct ip *);\n\tsave_ip = *ip;\n\tsave_ip.ip_len+= iphlen;\n\n\t/*\n\t * Checksum extended TCP header and data.\n\t */\n\ttlen = ((struct ip *)ti)->ip_len;\n tcpiphdr2qlink(ti)->next = tcpiphdr2qlink(ti)->prev = NULL;\n memset(&ti->ti_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));\n\tti->ti_x1 = 0;\n\tti->ti_len = htons((uint16_t)tlen);\n\tlen = sizeof(struct ip ) + tlen;\n\tif(cksum(m, len)) {\n\t goto drop;\n\t}\n\n\t/*\n\t * Check that TCP offset makes sense,\n\t * pull out TCP options and adjust length.\t\tXXX\n\t */\n\toff = ti->ti_off << 2;\n\tif (off < sizeof (struct tcphdr) || off > tlen) {\n\t goto drop;\n\t}\n\ttlen -= off;\n\tti->ti_len = tlen;\n\tif (off > sizeof (struct tcphdr)) {\n\t optlen = off - sizeof (struct tcphdr);\n\t optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);\n\t}\n\ttiflags = ti->ti_flags;\n\n\t/*\n\t * Convert TCP protocol specific fields to host format.\n\t */\n\tNTOHL(ti->ti_seq);\n\tNTOHL(ti->ti_ack);\n\tNTOHS(ti->ti_win);\n\tNTOHS(ti->ti_urp);\n\n\t/*\n\t * Drop TCP, IP headers and TCP options.\n\t */\n\tm->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\tm->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\n if (slirp->restricted) {\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_fport == ti->ti_dport &&\n ti->ti_dst.s_addr == ex_ptr->ex_addr.s_addr) {\n break;\n }\n }\n if (!ex_ptr)\n goto drop;\n }\n\t/*\n\t * Locate pcb for segment.\n\t */\nfindso:\n\tso = slirp->tcp_last_so;\n\tif (so->so_fport != ti->ti_dport ||\n\t so->so_lport != ti->ti_sport ||\n\t so->so_laddr.s_addr != ti->ti_src.s_addr ||\n\t so->so_faddr.s_addr != ti->ti_dst.s_addr) {\n\t\tso = solookup(&slirp->tcb, ti->ti_src, ti->ti_sport,\n\t\t\t ti->ti_dst, ti->ti_dport);\n\t\tif (so)\n\t\t\tslirp->tcp_last_so = so;\n\t}\n\n\t/*\n\t * If the state is CLOSED (i.e., TCB does not exist) then\n\t * all data in the incoming segment is discarded.\n\t * If the TCB exists but is in CLOSED state, it is embryonic,\n\t * but should either do a listen or a connect soon.\n\t *\n\t * state == CLOSED means we've done socreate() but haven't\n\t * attached it to a protocol yet...\n\t *\n\t * XXX If a TCB does not exist, and the TH_SYN flag is\n\t * the only flag set, then create a session, mark it\n\t * as if it was LISTENING, and continue...\n\t */\n if (so == NULL) {\n\t if ((tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) != TH_SYN)\n\t goto dropwithreset;\n\n\t if ((so = socreate(slirp)) == NULL)\n\t goto dropwithreset;\n\t if (tcp_attach(so) < 0) {\n\t free(so); /* Not sofree (if it failed, it's not insqued) */\n\t goto dropwithreset;\n\t }\n\n\t sbreserve(&so->so_snd, TCP_SNDSPACE);\n\t sbreserve(&so->so_rcv, TCP_RCVSPACE);\n\n\t so->so_laddr = ti->ti_src;\n\t so->so_lport = ti->ti_sport;\n\t so->so_faddr = ti->ti_dst;\n\t so->so_fport = ti->ti_dport;\n\n\t if ((so->so_iptos = tcp_tos(so)) == 0)\n\t so->so_iptos = ((struct ip *)ti)->ip_tos;\n\n\t tp = sototcpcb(so);\n\t tp->t_state = TCPS_LISTEN;\n\t}\n\n /*\n * If this is a still-connecting socket, this probably\n * a retransmit of the SYN. Whether it's a retransmit SYN\n\t * or something else, we nuke it.\n */\n if (so->so_state & SS_ISFCONNECTING)\n goto drop;\n\n\ttp = sototcpcb(so);\n\n\t/* XXX Should never fail */\n if (tp == NULL)\n\t\tgoto dropwithreset;\n\tif (tp->t_state == TCPS_CLOSED)\n\t\tgoto drop;\n\n\ttiwin = ti->ti_win;\n\n\t/*\n\t * Segment received on connection.\n\t * Reset idle time and keep-alive timer.\n\t */\n\ttp->t_idle = 0;\n\tif (SO_OPTIONS)\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;\n\telse\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;\n\n\t/*\n\t * Process options if not in LISTEN state,\n\t * else do it below (after getting remote address).\n\t */\n\tif (optp && tp->t_state != TCPS_LISTEN)\n\t\ttcp_dooptions(tp, (u_char *)optp, optlen, ti);\n\n\t/*\n\t * Header prediction: check for the two common cases\n\t * of a uni-directional data xfer. If the packet has\n\t * no control flags, is in-sequence, the window didn't\n\t * change and we're not retransmitting, it's a\n\t * candidate. If the length is zero and the ack moved\n\t * forward, we're the sender side of the xfer. Just\n\t * free the data acked & wake any higher level process\n\t * that was blocked waiting for space. If the length\n\t * is non-zero and the ack didn't move, we're the\n\t * receiver side. If we're getting packets in-order\n\t * (the reassembly queue is empty), add the data to\n\t * the socket buffer and note that we need a delayed ack.\n\t *\n\t * XXX Some of these tests are not needed\n\t * eg: the tiwin == tp->snd_wnd prevents many more\n\t * predictions.. with no *real* advantage..\n\t */\n\tif (tp->t_state == TCPS_ESTABLISHED &&\n\t (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&\n\t ti->ti_seq == tp->rcv_nxt &&\n\t tiwin && tiwin == tp->snd_wnd &&\n\t tp->snd_nxt == tp->snd_max) {\n\t\tif (ti->ti_len == 0) {\n\t\t\tif (SEQ_GT(ti->ti_ack, tp->snd_una) &&\n\t\t\t SEQ_LEQ(ti->ti_ack, tp->snd_max) &&\n\t\t\t tp->snd_cwnd >= tp->snd_wnd) {\n\t\t\t\t/*\n\t\t\t\t * this is a pure ack for outstanding data.\n\t\t\t\t */\n\t\t\t\tif (tp->t_rtt &&\n\t\t\t\t SEQ_GT(ti->ti_ack, tp->t_rtseq))\n\t\t\t\t\ttcp_xmit_timer(tp, tp->t_rtt);\n\t\t\t\tacked = ti->ti_ack - tp->snd_una;\n\t\t\t\tsbdrop(&so->so_snd, acked);\n\t\t\t\ttp->snd_una = ti->ti_ack;\n\t\t\t\tm_freem(m);\n\n\t\t\t\t/*\n\t\t\t\t * If all outstanding data are acked, stop\n\t\t\t\t * retransmit timer, otherwise restart timer\n\t\t\t\t * using current (possibly backed-off) value.\n\t\t\t\t * If process is waiting for space,\n\t\t\t\t * wakeup/selwakeup/signal. If data\n\t\t\t\t * are ready to send, let tcp_output\n\t\t\t\t * decide between more output or persist.\n\t\t\t\t */\n\t\t\t\tif (tp->snd_una == tp->snd_max)\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\t\telse if (tp->t_timer[TCPT_PERSIST] == 0)\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\n\t\t\t\t/*\n\t\t\t\t * This is called because sowwakeup might have\n\t\t\t\t * put data into so_snd. Since we don't so sowwakeup,\n\t\t\t\t * we don't need this.. XXX???\n\t\t\t\t */\n\t\t\t\tif (so->so_snd.sb_cc)\n\t\t\t\t\t(void) tcp_output(tp);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (ti->ti_ack == tp->snd_una &&\n\t\t tcpfrag_list_empty(tp) &&\n\t\t ti->ti_len <= sbspace(&so->so_rcv)) {\n\t\t\t/*\n\t\t\t * this is a pure, in-sequence data packet\n\t\t\t * with nothing on the reassembly queue and\n\t\t\t * we have enough buffer space to take it.\n\t\t\t */\n\t\t\ttp->rcv_nxt += ti->ti_len;\n\t\t\t/*\n\t\t\t * Add data to socket buffer.\n\t\t\t */\n\t\t\tif (so->so_emu) {\n\t\t\t\tif (tcp_emu(so,m)) sbappend(so, m);\n\t\t\t} else\n\t\t\t\tsbappend(so, m);\n\n\t\t\t/*\n\t\t\t * If this is a short packet, then ACK now - with Nagel\n\t\t\t *\tcongestion avoidance sender won't send more until\n\t\t\t *\the gets an ACK.\n\t\t\t *\n\t\t\t * It is better to not delay acks at all to maximize\n\t\t\t * TCP throughput. See RFC 2581.\n\t\t\t */\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttcp_output(tp);\n\t\t\treturn;\n\t\t}\n\t} /* header prediction */\n\t/*\n\t * Calculate amount of space in receive window,\n\t * and then do TCP input processing.\n\t * Receive window is amount of space in rcv queue,\n\t * but not less than advertised window.\n\t */\n\t{ int win;\n win = sbspace(&so->so_rcv);\n\t if (win < 0)\n\t win = 0;\n\t tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));\n\t}\n\n\tswitch (tp->t_state) {\n\n\t/*\n\t * If the state is LISTEN then ignore segment if it contains an RST.\n\t * If the segment contains an ACK then it is bad and send a RST.\n\t * If it does not contain a SYN then it is not interesting; drop it.\n\t * Don't bother responding if the destination was a broadcast.\n\t * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial\n\t * tp->iss, and send a segment:\n\t * \n\t * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.\n\t * Fill in remote peer address fields if not previously specified.\n\t * Enter SYN_RECEIVED state, and process any other fields of this\n\t * segment in this state.\n\t */\n\tcase TCPS_LISTEN: {\n\n\t if (tiflags & TH_RST)\n\t goto drop;\n\t if (tiflags & TH_ACK)\n\t goto dropwithreset;\n\t if ((tiflags & TH_SYN) == 0)\n\t goto drop;\n\n\t /*\n\t * This has way too many gotos...\n\t * But a bit of spaghetti code never hurt anybody :)\n\t */\n\n\t /*\n\t * If this is destined for the control address, then flag to\n\t * tcp_ctl once connected, otherwise connect\n\t */\n\t if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n\t slirp->vnetwork_addr.s_addr) {\n\t if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr &&\n\t\tso->so_faddr.s_addr != slirp->vnameserver_addr.s_addr) {\n\t\t/* May be an add exec */\n\t\tfor (ex_ptr = slirp->exec_list; ex_ptr;\n\t\t ex_ptr = ex_ptr->ex_next) {\n\t\t if(ex_ptr->ex_fport == so->so_fport &&\n\t\t so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {\n\t\t so->so_state |= SS_CTL;\n\t\t break;\n\t\t }\n\t\t}\n\t\tif (so->so_state & SS_CTL) {\n\t\t goto cont_input;\n\t\t}\n\t }\n\t /* CTL_ALIAS: Do nothing, tcp_fconnect will be called on it */\n\t }\n\n\t if (so->so_emu & EMU_NOCONNECT) {\n\t so->so_emu &= ~EMU_NOCONNECT;\n\t goto cont_input;\n\t }\n\n\t if((tcp_fconnect(so) == -1) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK)) {\n\t u_char code=ICMP_UNREACH_NET;\n\t DEBUG_MISC((dfd,\" tcp fconnect errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t if(errno == ECONNREFUSED) {\n\t /* ACK the SYN, send RST to refuse the connection */\n\t tcp_respond(tp, ti, m, ti->ti_seq+1, (tcp_seq)0,\n\t\t\t TH_RST|TH_ACK);\n\t } else {\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t HTONL(ti->ti_seq); /* restore tcp header */\n\t HTONL(ti->ti_ack);\n\t HTONS(ti->ti_win);\n\t HTONS(ti->ti_urp);\n\t m->m_data -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\t m->m_len += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\t *ip=save_ip;\n\t icmp_error(m, ICMP_UNREACH,code, 0,strerror(errno));\n\t }\n tcp_close(tp);\n\t m_free(m);\n\t } else {\n\t /*\n\t * Haven't connected yet, save the current mbuf\n\t * and ti, and return\n\t * XXX Some OS's don't tell us whether the connect()\n\t * succeeded or not. So we must time it out.\n\t */\n\t so->so_m = m;\n\t so->so_ti = ti;\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\t tp->t_state = TCPS_SYN_RECEIVED;\n\t }\n\t return;\n\n\tcont_conn:\n\t /* m==NULL\n\t * Check if the connect succeeded\n\t */\n\t if (so->so_state & SS_NOFDREF) {\n\t tp = tcp_close(tp);\n\t goto dropwithreset;\n\t }\n\tcont_input:\n\t tcp_template(tp);\n\n\t if (optp)\n\t tcp_dooptions(tp, (u_char *)optp, optlen, ti);\n\n\t if (iss)\n\t tp->iss = iss;\n\t else\n\t tp->iss = slirp->tcp_iss;\n\t slirp->tcp_iss += TCP_ISSINCR/2;\n\t tp->irs = ti->ti_seq;\n\t tcp_sendseqinit(tp);\n\t tcp_rcvseqinit(tp);\n\t tp->t_flags |= TF_ACKNOW;\n\t tp->t_state = TCPS_SYN_RECEIVED;\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\t goto trimthenstep6;\n\t} /* case TCPS_LISTEN */\n\n\t/*\n\t * If the state is SYN_SENT:\n\t *\tif seg contains an ACK, but not for our SYN, drop the input.\n\t *\tif seg contains a RST, then drop the connection.\n\t *\tif seg does not contain SYN, then drop it.\n\t * Otherwise this is an acceptable SYN segment\n\t *\tinitialize tp->rcv_nxt and tp->irs\n\t *\tif seg contains ack then advance tp->snd_una\n\t *\tif SYN has been acked change to ESTABLISHED else SYN_RCVD state\n\t *\tarrange for segment to be acked (eventually)\n\t *\tcontinue processing rest of data/controls, beginning with URG\n\t */\n\tcase TCPS_SYN_SENT:\n\t\tif ((tiflags & TH_ACK) &&\n\t\t (SEQ_LEQ(ti->ti_ack, tp->iss) ||\n\t\t SEQ_GT(ti->ti_ack, tp->snd_max)))\n\t\t\tgoto dropwithreset;\n\n\t\tif (tiflags & TH_RST) {\n if (tiflags & TH_ACK) {\n tcp_drop(tp, 0); /* XXX Check t_softerror! */\n }\n\t\t\tgoto drop;\n\t\t}\n\n\t\tif ((tiflags & TH_SYN) == 0)\n\t\t\tgoto drop;\n\t\tif (tiflags & TH_ACK) {\n\t\t\ttp->snd_una = ti->ti_ack;\n\t\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_una))\n\t\t\t\ttp->snd_nxt = tp->snd_una;\n\t\t}\n\n\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\ttp->irs = ti->ti_seq;\n\t\ttcp_rcvseqinit(tp);\n\t\ttp->t_flags |= TF_ACKNOW;\n\t\tif (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {\n\t\t\tsoisfconnected(so);\n\t\t\ttp->t_state = TCPS_ESTABLISHED;\n\n\t\t\t(void) tcp_reass(tp, (struct tcpiphdr *)0,\n\t\t\t\t(struct mbuf *)0);\n\t\t\t/*\n\t\t\t * if we didn't have to retransmit the SYN,\n\t\t\t * use its rtt as our initial srtt & rtt var.\n\t\t\t */\n\t\t\tif (tp->t_rtt)\n\t\t\t\ttcp_xmit_timer(tp, tp->t_rtt);\n\t\t} else\n\t\t\ttp->t_state = TCPS_SYN_RECEIVED;\n\ntrimthenstep6:\n\t\t/*\n\t\t * Advance ti->ti_seq to correspond to first data byte.\n\t\t * If data, trim to stay within window,\n\t\t * dropping FIN if necessary.\n\t\t */\n\t\tti->ti_seq++;\n\t\tif (ti->ti_len > tp->rcv_wnd) {\n\t\t\ttodrop = ti->ti_len - tp->rcv_wnd;\n\t\t\tm_adj(m, -todrop);\n\t\t\tti->ti_len = tp->rcv_wnd;\n\t\t\ttiflags &= ~TH_FIN;\n\t\t}\n\t\ttp->snd_wl1 = ti->ti_seq - 1;\n\t\ttp->rcv_up = ti->ti_seq;\n\t\tgoto step6;\n\t} /* switch tp->t_state */\n\t/*\n\t * States other than LISTEN or SYN_SENT.\n\t * Check that at least some bytes of segment are within\n\t * receive window. If segment begins before rcv_nxt,\n\t * drop leading data (and SYN); if nothing left, just ack.\n\t */\n\ttodrop = tp->rcv_nxt - ti->ti_seq;\n\tif (todrop > 0) {\n\t\tif (tiflags & TH_SYN) {\n\t\t\ttiflags &= ~TH_SYN;\n\t\t\tti->ti_seq++;\n\t\t\tif (ti->ti_urp > 1)\n\t\t\t\tti->ti_urp--;\n\t\t\telse\n\t\t\t\ttiflags &= ~TH_URG;\n\t\t\ttodrop--;\n\t\t}\n\t\t/*\n\t\t * Following if statement from Stevens, vol. 2, p. 960.\n\t\t */\n\t\tif (todrop > ti->ti_len\n\t\t || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {\n\t\t\t/*\n\t\t\t * Any valid FIN must be to the left of the window.\n\t\t\t * At this point the FIN must be a duplicate or out\n\t\t\t * of sequence; drop it.\n\t\t\t */\n\t\t\ttiflags &= ~TH_FIN;\n\n\t\t\t/*\n\t\t\t * Send an ACK to resynchronize and drop any data.\n\t\t\t * But keep on processing for RST or ACK.\n\t\t\t */\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttodrop = ti->ti_len;\n\t\t}\n\t\tm_adj(m, todrop);\n\t\tti->ti_seq += todrop;\n\t\tti->ti_len -= todrop;\n\t\tif (ti->ti_urp > todrop)\n\t\t\tti->ti_urp -= todrop;\n\t\telse {\n\t\t\ttiflags &= ~TH_URG;\n\t\t\tti->ti_urp = 0;\n\t\t}\n\t}\n\t/*\n\t * If new data are received on a connection after the\n\t * user processes are gone, then RST the other end.\n\t */\n\tif ((so->so_state & SS_NOFDREF) &&\n\t tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {\n\t\ttp = tcp_close(tp);\n\t\tgoto dropwithreset;\n\t}\n\n\t/*\n\t * If segment ends after window, drop trailing data\n\t * (and PUSH and FIN); if nothing left, just ACK.\n\t */\n\ttodrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);\n\tif (todrop > 0) {\n\t\tif (todrop >= ti->ti_len) {\n\t\t\t/*\n\t\t\t * If a new connection request is received\n\t\t\t * while in TIME_WAIT, drop the old connection\n\t\t\t * and start over if the sequence numbers\n\t\t\t * are above the previous ones.\n\t\t\t */\n\t\t\tif (tiflags & TH_SYN &&\n\t\t\t tp->t_state == TCPS_TIME_WAIT &&\n\t\t\t SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {\n\t\t\t\tiss = tp->rcv_nxt + TCP_ISSINCR;\n\t\t\t\ttp = tcp_close(tp);\n\t\t\t\tgoto findso;\n\t\t\t}\n\t\t\t/*\n\t\t\t * If window is closed can only take segments at\n\t\t\t * window edge, and have to drop data and PUSH from\n\t\t\t * incoming segments. Continue processing, but\n\t\t\t * remember to ack. Otherwise, drop segment\n\t\t\t * and ack.\n\t\t\t */\n\t\t\tif (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {\n\t\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\t} else {\n\t\t\t\tgoto dropafterack;\n\t\t\t}\n\t\t}\n\t\tm_adj(m, -todrop);\n\t\tti->ti_len -= todrop;\n\t\ttiflags &= ~(TH_PUSH|TH_FIN);\n\t}\n\n\t/*\n\t * If the RST bit is set examine the state:\n\t * SYN_RECEIVED STATE:\n\t *\tIf passive open, return to LISTEN state.\n\t *\tIf active open, inform user that connection was refused.\n\t * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:\n\t *\tInform user that connection was reset, and close tcb.\n\t * CLOSING, LAST_ACK, TIME_WAIT STATES\n\t *\tClose the tcb.\n\t */\n\tif (tiflags&TH_RST) switch (tp->t_state) {\n\n\tcase TCPS_SYN_RECEIVED:\n\tcase TCPS_ESTABLISHED:\n\tcase TCPS_FIN_WAIT_1:\n\tcase TCPS_FIN_WAIT_2:\n\tcase TCPS_CLOSE_WAIT:\n\t\ttp->t_state = TCPS_CLOSED;\n tcp_close(tp);\n\t\tgoto drop;\n\n\tcase TCPS_CLOSING:\n\tcase TCPS_LAST_ACK:\n\tcase TCPS_TIME_WAIT:\n tcp_close(tp);\n\t\tgoto drop;\n\t}\n\n\t/*\n\t * If a SYN is in the window, then this is an\n\t * error and we send an RST and drop the connection.\n\t */\n\tif (tiflags & TH_SYN) {\n\t\ttp = tcp_drop(tp,0);\n\t\tgoto dropwithreset;\n\t}\n\n\t/*\n\t * If the ACK bit is off we drop the segment and return.\n\t */\n\tif ((tiflags & TH_ACK) == 0) goto drop;\n\n\t/*\n\t * Ack processing.\n\t */\n\tswitch (tp->t_state) {\n\t/*\n\t * In SYN_RECEIVED state if the ack ACKs our SYN then enter\n\t * ESTABLISHED state and continue processing, otherwise\n\t * send an RST. una<=ack<=max\n\t */\n\tcase TCPS_SYN_RECEIVED:\n\n\t\tif (SEQ_GT(tp->snd_una, ti->ti_ack) ||\n\t\t SEQ_GT(ti->ti_ack, tp->snd_max))\n\t\t\tgoto dropwithreset;\n\t\ttp->t_state = TCPS_ESTABLISHED;\n\t\t/*\n\t\t * The sent SYN is ack'ed with our sequence number +1\n\t\t * The first data byte already in the buffer will get\n\t\t * lost if no correction is made. This is only needed for\n\t\t * SS_CTL since the buffer is empty otherwise.\n\t\t * tp->snd_una++; or:\n\t\t */\n\t\ttp->snd_una=ti->ti_ack;\n\t\tif (so->so_state & SS_CTL) {\n\t\t /* So tcp_ctl reports the right state */\n\t\t ret = tcp_ctl(so);\n\t\t if (ret == 1) {\n\t\t soisfconnected(so);\n\t\t so->so_state &= ~SS_CTL; /* success XXX */\n\t\t } else if (ret == 2) {\n\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t so->so_state |= SS_NOFDREF; /* CTL_CMD */\n\t\t } else {\n\t\t needoutput = 1;\n\t\t tp->t_state = TCPS_FIN_WAIT_1;\n\t\t }\n\t\t} else {\n\t\t soisfconnected(so);\n\t\t}\n\n\t\t(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);\n\t\ttp->snd_wl1 = ti->ti_seq - 1;\n\t\t/* Avoid ack processing; snd_una==ti_ack => dup ack */\n\t\tgoto synrx_to_est;\n\t\t/* fall into ... */\n\n\t/*\n\t * In ESTABLISHED state: drop duplicate ACKs; ACK out of range\n\t * ACKs. If the ack is in the range\n\t *\ttp->snd_una < ti->ti_ack <= tp->snd_max\n\t * then advance tp->snd_una to ti->ti_ack and drop\n\t * data from the retransmission queue. If this ACK reflects\n\t * more up to date window information we update our window information.\n\t */\n\tcase TCPS_ESTABLISHED:\n\tcase TCPS_FIN_WAIT_1:\n\tcase TCPS_FIN_WAIT_2:\n\tcase TCPS_CLOSE_WAIT:\n\tcase TCPS_CLOSING:\n\tcase TCPS_LAST_ACK:\n\tcase TCPS_TIME_WAIT:\n\n\t\tif (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {\n\t\t\tif (ti->ti_len == 0 && tiwin == tp->snd_wnd) {\n\t\t\t DEBUG_MISC((dfd,\" dup ack m = %lx so = %lx \\n\",\n\t\t\t\t (long )m, (long )so));\n\t\t\t\t/*\n\t\t\t\t * If we have outstanding data (other than\n\t\t\t\t * a window probe), this is a completely\n\t\t\t\t * duplicate ack (ie, window info didn't\n\t\t\t\t * change), the ack is the biggest we've\n\t\t\t\t * seen and we've seen exactly our rexmt\n\t\t\t\t * threshold of them, assume a packet\n\t\t\t\t * has been dropped and retransmit it.\n\t\t\t\t * Kludge snd_nxt & the congestion\n\t\t\t\t * window so we send only this one\n\t\t\t\t * packet.\n\t\t\t\t *\n\t\t\t\t * We know we're losing at the current\n\t\t\t\t * window size so do congestion avoidance\n\t\t\t\t * (set ssthresh to half the current window\n\t\t\t\t * and pull our congestion window back to\n\t\t\t\t * the new ssthresh).\n\t\t\t\t *\n\t\t\t\t * Dup acks mean that packets have left the\n\t\t\t\t * network (they're now cached at the receiver)\n\t\t\t\t * so bump cwnd by the amount in the receiver\n\t\t\t\t * to keep a constant cwnd packets in the\n\t\t\t\t * network.\n\t\t\t\t */\n\t\t\t\tif (tp->t_timer[TCPT_REXMT] == 0 ||\n\t\t\t\t ti->ti_ack != tp->snd_una)\n\t\t\t\t\ttp->t_dupacks = 0;\n\t\t\t\telse if (++tp->t_dupacks == TCPREXMTTHRESH) {\n\t\t\t\t\ttcp_seq onxt = tp->snd_nxt;\n\t\t\t\t\tu_int win =\n\t\t\t\t\t min(tp->snd_wnd, tp->snd_cwnd) / 2 /\n\t\t\t\t\t\ttp->t_maxseg;\n\n\t\t\t\t\tif (win < 2)\n\t\t\t\t\t\twin = 2;\n\t\t\t\t\ttp->snd_ssthresh = win * tp->t_maxseg;\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\t\t\ttp->t_rtt = 0;\n\t\t\t\t\ttp->snd_nxt = ti->ti_ack;\n\t\t\t\t\ttp->snd_cwnd = tp->t_maxseg;\n\t\t\t\t\t(void) tcp_output(tp);\n\t\t\t\t\ttp->snd_cwnd = tp->snd_ssthresh +\n\t\t\t\t\t tp->t_maxseg * tp->t_dupacks;\n\t\t\t\t\tif (SEQ_GT(onxt, tp->snd_nxt))\n\t\t\t\t\t\ttp->snd_nxt = onxt;\n\t\t\t\t\tgoto drop;\n\t\t\t\t} else if (tp->t_dupacks > TCPREXMTTHRESH) {\n\t\t\t\t\ttp->snd_cwnd += tp->t_maxseg;\n\t\t\t\t\t(void) tcp_output(tp);\n\t\t\t\t\tgoto drop;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\ttp->t_dupacks = 0;\n\t\t\tbreak;\n\t\t}\n\tsynrx_to_est:\n\t\t/*\n\t\t * If the congestion window was inflated to account\n\t\t * for the other side's cached packets, retract it.\n\t\t */\n\t\tif (tp->t_dupacks > TCPREXMTTHRESH &&\n\t\t tp->snd_cwnd > tp->snd_ssthresh)\n\t\t\ttp->snd_cwnd = tp->snd_ssthresh;\n\t\ttp->t_dupacks = 0;\n\t\tif (SEQ_GT(ti->ti_ack, tp->snd_max)) {\n\t\t\tgoto dropafterack;\n\t\t}\n\t\tacked = ti->ti_ack - tp->snd_una;\n\n\t\t/*\n\t\t * If transmit timer is running and timed sequence\n\t\t * number was acked, update smoothed round trip time.\n\t\t * Since we now have an rtt measurement, cancel the\n\t\t * timer backoff (cf., Phil Karn's retransmit alg.).\n\t\t * Recompute the initial retransmit timer.\n\t\t */\n\t\tif (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))\n\t\t\ttcp_xmit_timer(tp,tp->t_rtt);\n\n\t\t/*\n\t\t * If all outstanding data is acked, stop retransmit\n\t\t * timer and remember to restart (more output or persist).\n\t\t * If there is more data to be acked, restart retransmit\n\t\t * timer, using current (possibly backed-off) value.\n\t\t */\n\t\tif (ti->ti_ack == tp->snd_max) {\n\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\tneedoutput = 1;\n\t\t} else if (tp->t_timer[TCPT_PERSIST] == 0)\n\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t/*\n\t\t * When new data is acked, open the congestion window.\n\t\t * If the window gives us less than ssthresh packets\n\t\t * in flight, open exponentially (maxseg per packet).\n\t\t * Otherwise open linearly: maxseg per window\n\t\t * (maxseg^2 / cwnd per packet).\n\t\t */\n\t\t{\n\t\t register u_int cw = tp->snd_cwnd;\n\t\t register u_int incr = tp->t_maxseg;\n\n\t\t if (cw > tp->snd_ssthresh)\n\t\t incr = incr * incr / cw;\n\t\t tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<snd_scale);\n\t\t}\n\t\tif (acked > so->so_snd.sb_cc) {\n\t\t\ttp->snd_wnd -= so->so_snd.sb_cc;\n\t\t\tsbdrop(&so->so_snd, (int )so->so_snd.sb_cc);\n\t\t\tourfinisacked = 1;\n\t\t} else {\n\t\t\tsbdrop(&so->so_snd, acked);\n\t\t\ttp->snd_wnd -= acked;\n\t\t\tourfinisacked = 0;\n\t\t}\n\t\ttp->snd_una = ti->ti_ack;\n\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_una))\n\t\t\ttp->snd_nxt = tp->snd_una;\n\n\t\tswitch (tp->t_state) {\n\n\t\t/*\n\t\t * In FIN_WAIT_1 STATE in addition to the processing\n\t\t * for the ESTABLISHED state if our FIN is now acknowledged\n\t\t * then enter FIN_WAIT_2.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_1:\n\t\t\tif (ourfinisacked) {\n\t\t\t\t/*\n\t\t\t\t * If we can't receive any more\n\t\t\t\t * data, then closing user can proceed.\n\t\t\t\t * Starting the timer is contrary to the\n\t\t\t\t * specification, but if we don't get a FIN\n\t\t\t\t * we'll hang forever.\n\t\t\t\t */\n\t\t\t\tif (so->so_state & SS_FCANTRCVMORE) {\n\t\t\t\t\ttp->t_timer[TCPT_2MSL] = TCP_MAXIDLE;\n\t\t\t\t}\n\t\t\t\ttp->t_state = TCPS_FIN_WAIT_2;\n\t\t\t}\n\t\t\tbreak;\n\n\t \t/*\n\t\t * In CLOSING STATE in addition to the processing for\n\t\t * the ESTABLISHED state if the ACK acknowledges our FIN\n\t\t * then enter the TIME-WAIT state, otherwise ignore\n\t\t * the segment.\n\t\t */\n\t\tcase TCPS_CLOSING:\n\t\t\tif (ourfinisacked) {\n\t\t\t\ttp->t_state = TCPS_TIME_WAIT;\n\t\t\t\ttcp_canceltimers(tp);\n\t\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In LAST_ACK, we may still be waiting for data to drain\n\t\t * and/or to be acked, as well as for the ack of our FIN.\n\t\t * If our FIN is now acknowledged, delete the TCB,\n\t\t * enter the closed state and return.\n\t\t */\n\t\tcase TCPS_LAST_ACK:\n\t\t\tif (ourfinisacked) {\n tcp_close(tp);\n\t\t\t\tgoto drop;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In TIME_WAIT state the only thing that should arrive\n\t\t * is a retransmission of the remote FIN. Acknowledge\n\t\t * it and restart the finack timer.\n\t\t */\n\t\tcase TCPS_TIME_WAIT:\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tgoto dropafterack;\n\t\t}\n\t} /* switch(tp->t_state) */\n\nstep6:\n\t/*\n\t * Update window information.\n\t * Don't look at window if no ACK: TAC's send garbage on first SYN.\n\t */\n\tif ((tiflags & TH_ACK) &&\n\t (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||\n\t (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||\n\t (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {\n\t\ttp->snd_wnd = tiwin;\n\t\ttp->snd_wl1 = ti->ti_seq;\n\t\ttp->snd_wl2 = ti->ti_ack;\n\t\tif (tp->snd_wnd > tp->max_sndwnd)\n\t\t\ttp->max_sndwnd = tp->snd_wnd;\n\t\tneedoutput = 1;\n\t}\n\n\t/*\n\t * Process segments with URG.\n\t */\n\tif ((tiflags & TH_URG) && ti->ti_urp &&\n\t TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\t/*\n\t\t * This is a kludge, but if we receive and accept\n\t\t * random urgent pointers, we'll crash in\n\t\t * soreceive. It's hard to imagine someone\n\t\t * actually wanting to send this much urgent data.\n\t\t */\n\t\tif (ti->ti_urp + so->so_rcv.sb_cc > so->so_rcv.sb_datalen) {\n\t\t\tti->ti_urp = 0;\n\t\t\ttiflags &= ~TH_URG;\n\t\t\tgoto dodata;\n\t\t}\n\t\t/*\n\t\t * If this segment advances the known urgent pointer,\n\t\t * then mark the data stream. This should not happen\n\t\t * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since\n\t\t * a FIN has been received from the remote side.\n\t\t * In these states we ignore the URG.\n\t\t *\n\t\t * According to RFC961 (Assigned Protocols),\n\t\t * the urgent pointer points to the last octet\n\t\t * of urgent data. We continue, however,\n\t\t * to consider it to indicate the first octet\n\t\t * of data past the urgent section as the original\n\t\t * spec states (in one of two places).\n\t\t */\n\t\tif (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {\n\t\t\ttp->rcv_up = ti->ti_seq + ti->ti_urp;\n\t\t\tso->so_urgc = so->so_rcv.sb_cc +\n\t\t\t\t(tp->rcv_up - tp->rcv_nxt); /* -1; */\n\t\t\ttp->rcv_up = ti->ti_seq + ti->ti_urp;\n\n\t\t}\n\t} else\n\t\t/*\n\t\t * If no out of band data is expected,\n\t\t * pull receive urgent pointer along\n\t\t * with the receive window.\n\t\t */\n\t\tif (SEQ_GT(tp->rcv_nxt, tp->rcv_up))\n\t\t\ttp->rcv_up = tp->rcv_nxt;\ndodata:\n\n\t/*\n\t * Process the segment text, merging it into the TCP sequencing queue,\n\t * and arranging for acknowledgment of receipt if necessary.\n\t * This process logically involves adjusting tp->rcv_wnd as data\n\t * is presented to the user (this happens in tcp_usrreq.c,\n\t * case PRU_RCVD). If a FIN has already been received on this\n\t * connection then we just ignore the text.\n\t */\n\tif ((ti->ti_len || (tiflags&TH_FIN)) &&\n\t TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\tTCP_REASS(tp, ti, m, so, tiflags);\n\t} else {\n\t\tm_free(m);\n\t\ttiflags &= ~TH_FIN;\n\t}\n\n\t/*\n\t * If FIN is received ACK the FIN and let the user know\n\t * that the connection is closing.\n\t */\n\tif (tiflags & TH_FIN) {\n\t\tif (TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\t\t/*\n\t\t\t * If we receive a FIN we can't send more data,\n\t\t\t * set it SS_FDRAIN\n * Shutdown the socket if there is no rx data in the\n\t\t\t * buffer.\n\t\t\t * soread() is called on completion of shutdown() and\n\t\t\t * will got to TCPS_LAST_ACK, and use tcp_output()\n\t\t\t * to send the FIN.\n\t\t\t */\n\t\t\tsofwdrain(so);\n\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttp->rcv_nxt++;\n\t\t}\n\t\tswitch (tp->t_state) {\n\n\t \t/*\n\t\t * In SYN_RECEIVED and ESTABLISHED STATES\n\t\t * enter the CLOSE_WAIT state.\n\t\t */\n\t\tcase TCPS_SYN_RECEIVED:\n\t\tcase TCPS_ESTABLISHED:\n\t\t if(so->so_emu == EMU_CTL) /* no shutdown on socket */\n\t\t tp->t_state = TCPS_LAST_ACK;\n\t\t else\n\t\t tp->t_state = TCPS_CLOSE_WAIT;\n\t\t break;\n\n\t \t/*\n\t\t * If still in FIN_WAIT_1 STATE FIN has not been acked so\n\t\t * enter the CLOSING state.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_1:\n\t\t\ttp->t_state = TCPS_CLOSING;\n\t\t\tbreak;\n\n\t \t/*\n\t\t * In FIN_WAIT_2 state enter the TIME_WAIT state,\n\t\t * starting the time-wait timer, turning off the other\n\t\t * standard timers.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_2:\n\t\t\ttp->t_state = TCPS_TIME_WAIT;\n\t\t\ttcp_canceltimers(tp);\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In TIME_WAIT state restart the 2 MSL time_wait timer.\n\t\t */\n\t\tcase TCPS_TIME_WAIT:\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/*\n\t * If this is a small packet, then ACK now - with Nagel\n\t * congestion avoidance sender won't send more until\n\t * he gets an ACK.\n\t *\n\t * See above.\n\t */\n\tif (ti->ti_len && (unsigned)ti->ti_len <= 5 &&\n\t ((struct tcpiphdr_2 *)ti)->first_char == (char)27) {\n\t\ttp->t_flags |= TF_ACKNOW;\n\t}\n\n\t/*\n\t * Return any desired output.\n\t */\n\tif (needoutput || (tp->t_flags & TF_ACKNOW)) {\n\t\t(void) tcp_output(tp);\n\t}\n\treturn;\n\ndropafterack:\n\t/*\n\t * Generate an ACK dropping incoming segment if it occupies\n\t * sequence space, where the ACK reflects our state.\n\t */\n\tif (tiflags & TH_RST)\n\t\tgoto drop;\n\tm_freem(m);\n\ttp->t_flags |= TF_ACKNOW;\n\t(void) tcp_output(tp);\n\treturn;\n\ndropwithreset:\n\t/* reuses m if m!=NULL, m_free() unnecessary */\n\tif (tiflags & TH_ACK)\n\t\ttcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);\n\telse {\n\t\tif (tiflags & TH_SYN) ti->ti_len++;\n\t\ttcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,\n\t\t TH_RST|TH_ACK);\n\t}\n\n\treturn;\n\ndrop:\n\t/*\n\t * Drop space held by incoming segment and return.\n\t */\n\tm_free(m);\n\n\treturn;\n}\n\nstatic void\ntcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcpiphdr *ti)\n{\n\tuint16_t mss;\n\tint opt, optlen;\n\n\tDEBUG_CALL(\"tcp_dooptions\");\n\tDEBUG_ARGS((dfd,\" tp = %lx cnt=%i \\n\", (long )tp, cnt));\n\n\tfor (; cnt > 0; cnt -= optlen, cp += optlen) {\n\t\topt = cp[0];\n\t\tif (opt == TCPOPT_EOL)\n\t\t\tbreak;\n\t\tif (opt == TCPOPT_NOP)\n\t\t\toptlen = 1;\n\t\telse {\n\t\t\toptlen = cp[1];\n\t\t\tif (optlen <= 0)\n\t\t\t\tbreak;\n\t\t}\n\t\tswitch (opt) {\n\n\t\tdefault:\n\t\t\tcontinue;\n\n\t\tcase TCPOPT_MAXSEG:\n\t\t\tif (optlen != TCPOLEN_MAXSEG)\n\t\t\t\tcontinue;\n\t\t\tif (!(ti->ti_flags & TH_SYN))\n\t\t\t\tcontinue;\n\t\t\tmemcpy((char *) &mss, (char *) cp + 2, sizeof(mss));\n\t\t\tNTOHS(mss);\n\t\t\t(void) tcp_mss(tp, mss);\t/* sets t_maxseg */\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n/*\n * Pull out of band byte out of a segment so\n * it doesn't appear in the user's data queue.\n * It is still reflected in the segment length for\n * sequencing purposes.\n */\n\n#ifdef notdef\n\nvoid\ntcp_pulloutofband(so, ti, m)\n\tstruct socket *so;\n\tstruct tcpiphdr *ti;\n\tregister struct mbuf *m;\n{\n\tint cnt = ti->ti_urp - 1;\n\n\twhile (cnt >= 0) {\n\t\tif (m->m_len > cnt) {\n\t\t\tchar *cp = mtod(m, caddr_t) + cnt;\n\t\t\tstruct tcpcb *tp = sototcpcb(so);\n\n\t\t\ttp->t_iobc = *cp;\n\t\t\ttp->t_oobflags |= TCPOOB_HAVEDATA;\n\t\t\tmemcpy(sp, cp+1, (unsigned)(m->m_len - cnt - 1));\n\t\t\tm->m_len--;\n\t\t\treturn;\n\t\t}\n\t\tcnt -= m->m_len;\n\t\tm = m->m_next; /* XXX WRONG! Fix it! */\n\t\tif (m == 0)\n\t\t\tbreak;\n\t}\n\tpanic(\"tcp_pulloutofband\");\n}\n\n#endif /* notdef */\n\n/*\n * Collect new round-trip time estimate\n * and update averages and current timeout.\n */\n\nstatic void\ntcp_xmit_timer(register struct tcpcb *tp, int rtt)\n{\n\tregister short delta;\n\n\tDEBUG_CALL(\"tcp_xmit_timer\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"rtt = %d\", rtt);\n\n\tif (tp->t_srtt != 0) {\n\t\t/*\n\t\t * srtt is stored as fixed point with 3 bits after the\n\t\t * binary point (i.e., scaled by 8). The following magic\n\t\t * is equivalent to the smoothing algorithm in rfc793 with\n\t\t * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed\n\t\t * point). Adjust rtt to origin 0.\n\t\t */\n\t\tdelta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);\n\t\tif ((tp->t_srtt += delta) <= 0)\n\t\t\ttp->t_srtt = 1;\n\t\t/*\n\t\t * We accumulate a smoothed rtt variance (actually, a\n\t\t * smoothed mean difference), then set the retransmit\n\t\t * timer to smoothed rtt + 4 times the smoothed variance.\n\t\t * rttvar is stored as fixed point with 2 bits after the\n\t\t * binary point (scaled by 4). The following is\n\t\t * equivalent to rfc793 smoothing with an alpha of .75\n\t\t * (rttvar = rttvar*3/4 + |delta| / 4). This replaces\n\t\t * rfc793's wired-in beta.\n\t\t */\n\t\tif (delta < 0)\n\t\t\tdelta = -delta;\n\t\tdelta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);\n\t\tif ((tp->t_rttvar += delta) <= 0)\n\t\t\ttp->t_rttvar = 1;\n\t} else {\n\t\t/*\n\t\t * No rtt measurement yet - use the unsmoothed rtt.\n\t\t * Set the variance to half the rtt (so our first\n\t\t * retransmit happens at 3*rtt).\n\t\t */\n\t\ttp->t_srtt = rtt << TCP_RTT_SHIFT;\n\t\ttp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);\n\t}\n\ttp->t_rtt = 0;\n\ttp->t_rxtshift = 0;\n\n\t/*\n\t * the retransmit should happen at rtt + 4 * rttvar.\n\t * Because of the way we do the smoothing, srtt and rttvar\n\t * will each average +1/2 tick of bias. When we compute\n\t * the retransmit timer, we want 1/2 tick of rounding and\n\t * 1 extra tick because of +-1/2 tick uncertainty in the\n\t * firing of the timer. The bias will give us exactly the\n\t * 1.5 tick we need. But, because the bias is\n\t * statistical, we have to test that we don't drop below\n\t * the minimum feasible timer (which is 2 ticks).\n\t */\n\tTCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),\n\t (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */\n\n\t/*\n\t * We received an ack for a packet that wasn't retransmitted;\n\t * it is probably safe to discard any error indications we've\n\t * received recently. This isn't quite right, but close enough\n\t * for now (a route might have failed after we sent a segment,\n\t * and the return path might not be symmetrical).\n\t */\n\ttp->t_softerror = 0;\n}\n\n/*\n * Determine a reasonable value for maxseg size.\n * If the route is known, check route for mtu.\n * If none, use an mss that can be handled on the outgoing\n * interface without forcing IP to fragment; if bigger than\n * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES\n * to utilize large mbufs. If no route is found, route has no mtu,\n * or the destination isn't local, use a default, hopefully conservative\n * size (usually 512 or the default IP max size, but no more than the mtu\n * of the interface), as we can't discover anything about intervening\n * gateways or networks. We also initialize the congestion/slow start\n * window to be a single segment if the destination isn't local.\n * While looking at the routing entry, we also initialize other path-dependent\n * parameters from pre-set or cached values in the routing entry.\n */\n\nint\ntcp_mss(struct tcpcb *tp, u_int offer)\n{\n\tstruct socket *so = tp->t_socket;\n\tint mss;\n\n\tDEBUG_CALL(\"tcp_mss\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"offer = %d\", offer);\n\n\tmss = min(IF_MTU, IF_MRU) - sizeof(struct tcpiphdr);\n\tif (offer)\n\t\tmss = min(mss, offer);\n\tmss = max(mss, 32);\n\tif (mss < tp->t_maxseg || offer != 0)\n\t tp->t_maxseg = mss;\n\n\ttp->snd_cwnd = mss;\n\n\tsbreserve(&so->so_snd, TCP_SNDSPACE + ((TCP_SNDSPACE % mss) ?\n (mss - (TCP_SNDSPACE % mss)) :\n 0));\n\tsbreserve(&so->so_rcv, TCP_RCVSPACE + ((TCP_RCVSPACE % mss) ?\n (mss - (TCP_RCVSPACE % mss)) :\n 0));\n\n\tDEBUG_MISC((dfd, \" returning mss = %d\\n\", mss));\n\n\treturn mss;\n}\n"], ["/linuxpdf/tinyemu/slirp/udp.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)udp_usrreq.c\t8.4 (Berkeley) 1/21/94\n * udp_usrreq.c,v 1.4 1994/10/02 17:48:45 phk Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\nstatic uint8_t udp_tos(struct socket *so);\n\nvoid\nudp_init(Slirp *slirp)\n{\n slirp->udb.so_next = slirp->udb.so_prev = &slirp->udb;\n slirp->udp_last_so = &slirp->udb;\n}\n/* m->m_data points at ip packet header\n * m->m_len length ip packet\n * ip->ip_len length data (IPDU)\n */\nvoid\nudp_input(register struct mbuf *m, int iphlen)\n{\n\tSlirp *slirp = m->slirp;\n\tregister struct ip *ip;\n\tregister struct udphdr *uh;\n\tint len;\n\tstruct ip save_ip;\n\tstruct socket *so;\n\n\tDEBUG_CALL(\"udp_input\");\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"iphlen = %d\", iphlen);\n\n\t/*\n\t * Strip IP options, if any; should skip this,\n\t * make available to user, and use on returned packets,\n\t * but we don't yet have a way to check the checksum\n\t * with options still present.\n\t */\n\tif(iphlen > sizeof(struct ip)) {\n\t\tip_stripoptions(m, (struct mbuf *)0);\n\t\tiphlen = sizeof(struct ip);\n\t}\n\n\t/*\n\t * Get IP and UDP header together in first mbuf.\n\t */\n\tip = mtod(m, struct ip *);\n\tuh = (struct udphdr *)((caddr_t)ip + iphlen);\n\n\t/*\n\t * Make mbuf data length reflect UDP length.\n\t * If not enough data to reflect UDP length, drop.\n\t */\n\tlen = ntohs((uint16_t)uh->uh_ulen);\n\n\tif (ip->ip_len != len) {\n\t\tif (len > ip->ip_len) {\n\t\t\tgoto bad;\n\t\t}\n\t\tm_adj(m, len - ip->ip_len);\n\t\tip->ip_len = len;\n\t}\n\n\t/*\n\t * Save a copy of the IP header in case we want restore it\n\t * for sending an ICMP error message in response.\n\t */\n\tsave_ip = *ip;\n\tsave_ip.ip_len+= iphlen; /* tcp_input subtracts this */\n\n\t/*\n\t * Checksum extended UDP header and data.\n\t */\n\tif (uh->uh_sum) {\n memset(&((struct ipovly *)ip)->ih_mbuf, 0, sizeof(struct mbuf_ptr));\n\t ((struct ipovly *)ip)->ih_x1 = 0;\n\t ((struct ipovly *)ip)->ih_len = uh->uh_ulen;\n\t if(cksum(m, len + sizeof(struct ip))) {\n\t goto bad;\n\t }\n\t}\n\n /*\n * handle DHCP/BOOTP\n */\n if (ntohs(uh->uh_dport) == BOOTP_SERVER) {\n bootp_input(m);\n goto bad;\n }\n\n if (slirp->restricted) {\n goto bad;\n }\n\n#if 0\n /*\n * handle TFTP\n */\n if (ntohs(uh->uh_dport) == TFTP_SERVER) {\n tftp_input(m);\n goto bad;\n }\n#endif\n \n\t/*\n\t * Locate pcb for datagram.\n\t */\n\tso = slirp->udp_last_so;\n\tif (so->so_lport != uh->uh_sport ||\n\t so->so_laddr.s_addr != ip->ip_src.s_addr) {\n\t\tstruct socket *tmp;\n\n\t\tfor (tmp = slirp->udb.so_next; tmp != &slirp->udb;\n\t\t tmp = tmp->so_next) {\n\t\t\tif (tmp->so_lport == uh->uh_sport &&\n\t\t\t tmp->so_laddr.s_addr == ip->ip_src.s_addr) {\n\t\t\t\tso = tmp;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (tmp == &slirp->udb) {\n\t\t so = NULL;\n\t\t} else {\n\t\t slirp->udp_last_so = so;\n\t\t}\n\t}\n\n\tif (so == NULL) {\n\t /*\n\t * If there's no socket for this packet,\n\t * create one\n\t */\n\t so = socreate(slirp);\n\t if (!so) {\n\t goto bad;\n\t }\n\t if(udp_attach(so) == -1) {\n\t DEBUG_MISC((dfd,\" udp_attach errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t sofree(so);\n\t goto bad;\n\t }\n\n\t /*\n\t * Setup fields\n\t */\n\t so->so_laddr = ip->ip_src;\n\t so->so_lport = uh->uh_sport;\n\n\t if ((so->so_iptos = udp_tos(so)) == 0)\n\t so->so_iptos = ip->ip_tos;\n\n\t /*\n\t * XXXXX Here, check if it's in udpexec_list,\n\t * and if it is, do the fork_exec() etc.\n\t */\n\t}\n\n so->so_faddr = ip->ip_dst; /* XXX */\n so->so_fport = uh->uh_dport; /* XXX */\n\n\tiphlen += sizeof(struct udphdr);\n\tm->m_len -= iphlen;\n\tm->m_data += iphlen;\n\n\t/*\n\t * Now we sendto() the packet.\n\t */\n\tif(sosendto(so,m) == -1) {\n\t m->m_len += iphlen;\n\t m->m_data -= iphlen;\n\t *ip=save_ip;\n\t DEBUG_MISC((dfd,\"udp tx errno = %d-%s\\n\",errno,strerror(errno)));\n\t icmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));\n\t}\n\n\tm_free(so->so_m); /* used for ICMP if error on sorecvfrom */\n\n\t/* restore the orig mbuf packet */\n\tm->m_len += iphlen;\n\tm->m_data -= iphlen;\n\t*ip=save_ip;\n\tso->so_m=m; /* ICMP backup */\n\n\treturn;\nbad:\n\tm_freem(m);\n\treturn;\n}\n\nint udp_output2(struct socket *so, struct mbuf *m,\n struct sockaddr_in *saddr, struct sockaddr_in *daddr,\n int iptos)\n{\n\tregister struct udpiphdr *ui;\n\tint error = 0;\n\n\tDEBUG_CALL(\"udp_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"saddr = %lx\", (long)saddr->sin_addr.s_addr);\n\tDEBUG_ARG(\"daddr = %lx\", (long)daddr->sin_addr.s_addr);\n\n\t/*\n\t * Adjust for header\n\t */\n\tm->m_data -= sizeof(struct udpiphdr);\n\tm->m_len += sizeof(struct udpiphdr);\n\n\t/*\n\t * Fill in mbuf with extended UDP header\n\t * and addresses and length put into network format.\n\t */\n\tui = mtod(m, struct udpiphdr *);\n memset(&ui->ui_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));\n\tui->ui_x1 = 0;\n\tui->ui_pr = IPPROTO_UDP;\n\tui->ui_len = htons(m->m_len - sizeof(struct ip));\n\t/* XXXXX Check for from-one-location sockets, or from-any-location sockets */\n ui->ui_src = saddr->sin_addr;\n\tui->ui_dst = daddr->sin_addr;\n\tui->ui_sport = saddr->sin_port;\n\tui->ui_dport = daddr->sin_port;\n\tui->ui_ulen = ui->ui_len;\n\n\t/*\n\t * Stuff checksum and output datagram.\n\t */\n\tui->ui_sum = 0;\n\tif ((ui->ui_sum = cksum(m, m->m_len)) == 0)\n\t\tui->ui_sum = 0xffff;\n\t((struct ip *)ui)->ip_len = m->m_len;\n\n\t((struct ip *)ui)->ip_ttl = IPDEFTTL;\n\t((struct ip *)ui)->ip_tos = iptos;\n\n\terror = ip_output(so, m);\n\n\treturn (error);\n}\n\nint udp_output(struct socket *so, struct mbuf *m,\n struct sockaddr_in *addr)\n\n{\n Slirp *slirp = so->slirp;\n struct sockaddr_in saddr, daddr;\n\n saddr = *addr;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n uint32_t inv_mask = ~slirp->vnetwork_mask.s_addr;\n\n if ((so->so_faddr.s_addr & inv_mask) == inv_mask) {\n saddr.sin_addr = slirp->vhost_addr;\n } else if (addr->sin_addr.s_addr == loopback_addr.s_addr ||\n so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {\n saddr.sin_addr = so->so_faddr;\n }\n }\n daddr.sin_addr = so->so_laddr;\n daddr.sin_port = so->so_lport;\n\n return udp_output2(so, m, &saddr, &daddr, so->so_iptos);\n}\n\nint\nudp_attach(struct socket *so)\n{\n if((so->s = os_socket(AF_INET,SOCK_DGRAM,0)) != -1) {\n so->so_expire = curtime + SO_EXPIRE;\n insque(so, &so->slirp->udb);\n }\n return(so->s);\n}\n\nvoid\nudp_detach(struct socket *so)\n{\n\tclosesocket(so->s);\n\tsofree(so);\n}\n\nstatic const struct tos_t udptos[] = {\n\t{0, 53, IPTOS_LOWDELAY, 0},\t\t\t/* DNS */\n\t{0, 0, 0, 0}\n};\n\nstatic uint8_t\nudp_tos(struct socket *so)\n{\n\tint i = 0;\n\n\twhile(udptos[i].tos) {\n\t\tif ((udptos[i].fport && ntohs(so->so_fport) == udptos[i].fport) ||\n\t\t (udptos[i].lport && ntohs(so->so_lport) == udptos[i].lport)) {\n\t\t \tso->so_emu = udptos[i].emu;\n\t\t\treturn udptos[i].tos;\n\t\t}\n\t\ti++;\n\t}\n\n\treturn 0;\n}\n\nstruct socket *\nudp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,\n u_int lport, int flags)\n{\n\tstruct sockaddr_in addr;\n\tstruct socket *so;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in), opt = 1;\n\n\tso = socreate(slirp);\n\tif (!so) {\n\t return NULL;\n\t}\n\tso->s = os_socket(AF_INET,SOCK_DGRAM,0);\n\tso->so_expire = curtime + SO_EXPIRE;\n\tinsque(so, &slirp->udb);\n\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = haddr;\n\taddr.sin_port = hport;\n\n\tif (bind(so->s,(struct sockaddr *)&addr, addrlen) < 0) {\n\t\tudp_detach(so);\n\t\treturn NULL;\n\t}\n\tsetsockopt(so->s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\n\tgetsockname(so->s,(struct sockaddr *)&addr,&addrlen);\n\tso->so_fport = addr.sin_port;\n\tif (addr.sin_addr.s_addr == 0 ||\n\t addr.sin_addr.s_addr == loopback_addr.s_addr) {\n\t so->so_faddr = slirp->vhost_addr;\n\t} else {\n\t so->so_faddr = addr.sin_addr;\n\t}\n\tso->so_lport = lport;\n\tso->so_laddr.s_addr = laddr;\n\tif (flags != SS_FACCEPTONCE)\n\t so->so_expire = 0;\n\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= SS_ISFCONNECTED | flags;\n\n\treturn so;\n}\n"], ["/linuxpdf/tinyemu/slirp/slirp.c", "/*\n * libslirp glue\n *\n * Copyright (c) 2004-2008 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"slirp.h\"\n\n/* host loopback address */\nstruct in_addr loopback_addr;\n\n/* emulated hosts use the MAC addr 52:55:IP:IP:IP:IP */\nstatic const uint8_t special_ethaddr[6] = {\n 0x52, 0x55, 0x00, 0x00, 0x00, 0x00\n};\n\nstatic const uint8_t zero_ethaddr[6] = { 0, 0, 0, 0, 0, 0 };\n\n/* XXX: suppress those select globals */\nfd_set *global_readfds, *global_writefds, *global_xfds;\n\nu_int curtime;\nstatic u_int time_fasttimo, last_slowtimo;\nstatic int do_slowtimo;\n\nstatic struct in_addr dns_addr;\nstatic u_int dns_addr_time;\n\n#ifdef _WIN32\n\nint get_dns_addr(struct in_addr *pdns_addr)\n{\n FIXED_INFO *FixedInfo=NULL;\n ULONG BufLen;\n DWORD ret;\n IP_ADDR_STRING *pIPAddr;\n struct in_addr tmp_addr;\n\n if (dns_addr.s_addr != 0 && (curtime - dns_addr_time) < 1000) {\n *pdns_addr = dns_addr;\n return 0;\n }\n\n FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));\n BufLen = sizeof(FIXED_INFO);\n\n if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen)) {\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n FixedInfo = GlobalAlloc(GPTR, BufLen);\n }\n\n if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS) {\n printf(\"GetNetworkParams failed. ret = %08x\\n\", (u_int)ret );\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n return -1;\n }\n\n pIPAddr = &(FixedInfo->DnsServerList);\n inet_aton(pIPAddr->IpAddress.String, &tmp_addr);\n *pdns_addr = tmp_addr;\n dns_addr = tmp_addr;\n dns_addr_time = curtime;\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n return 0;\n}\n\nstatic void winsock_cleanup(void)\n{\n WSACleanup();\n}\n\n#else\n\nstatic struct stat dns_addr_stat;\n\nint get_dns_addr(struct in_addr *pdns_addr)\n{\n char buff[512];\n char buff2[257];\n FILE *f;\n int found = 0;\n struct in_addr tmp_addr;\n\n if (dns_addr.s_addr != 0) {\n struct stat old_stat;\n if ((curtime - dns_addr_time) < 1000) {\n *pdns_addr = dns_addr;\n return 0;\n }\n old_stat = dns_addr_stat;\n if (stat(\"/etc/resolv.conf\", &dns_addr_stat) != 0)\n return -1;\n if ((dns_addr_stat.st_dev == old_stat.st_dev)\n && (dns_addr_stat.st_ino == old_stat.st_ino)\n && (dns_addr_stat.st_size == old_stat.st_size)\n && (dns_addr_stat.st_mtime == old_stat.st_mtime)) {\n *pdns_addr = dns_addr;\n return 0;\n }\n }\n\n f = fopen(\"/etc/resolv.conf\", \"r\");\n if (!f)\n return -1;\n\n#ifdef DEBUG\n lprint(\"IP address of your DNS(s): \");\n#endif\n while (fgets(buff, 512, f) != NULL) {\n if (sscanf(buff, \"nameserver%*[ \\t]%256s\", buff2) == 1) {\n if (!inet_aton(buff2, &tmp_addr))\n continue;\n /* If it's the first one, set it to dns_addr */\n if (!found) {\n *pdns_addr = tmp_addr;\n dns_addr = tmp_addr;\n dns_addr_time = curtime;\n }\n#ifdef DEBUG\n else\n lprint(\", \");\n#endif\n if (++found > 3) {\n#ifdef DEBUG\n lprint(\"(more)\");\n#endif\n break;\n }\n#ifdef DEBUG\n else\n lprint(\"%s\", inet_ntoa(tmp_addr));\n#endif\n }\n }\n fclose(f);\n if (!found)\n return -1;\n return 0;\n}\n\n#endif\n\nstatic void slirp_init_once(void)\n{\n static int initialized;\n#ifdef _WIN32\n WSADATA Data;\n#endif\n\n if (initialized) {\n return;\n }\n initialized = 1;\n\n#ifdef _WIN32\n WSAStartup(MAKEWORD(2,0), &Data);\n atexit(winsock_cleanup);\n#endif\n\n loopback_addr.s_addr = htonl(INADDR_LOOPBACK);\n}\n\nSlirp *slirp_init(int restricted, struct in_addr vnetwork,\n struct in_addr vnetmask, struct in_addr vhost,\n const char *vhostname, const char *tftp_path,\n const char *bootfile, struct in_addr vdhcp_start,\n struct in_addr vnameserver, void *opaque)\n{\n Slirp *slirp = mallocz(sizeof(Slirp));\n\n slirp_init_once();\n\n slirp->restricted = restricted;\n\n if_init(slirp);\n ip_init(slirp);\n\n /* Initialise mbufs *after* setting the MTU */\n m_init(slirp);\n\n slirp->vnetwork_addr = vnetwork;\n slirp->vnetwork_mask = vnetmask;\n slirp->vhost_addr = vhost;\n if (vhostname) {\n pstrcpy(slirp->client_hostname, sizeof(slirp->client_hostname),\n vhostname);\n }\n if (tftp_path) {\n slirp->tftp_prefix = strdup(tftp_path);\n }\n if (bootfile) {\n slirp->bootp_filename = strdup(bootfile);\n }\n slirp->vdhcp_startaddr = vdhcp_start;\n slirp->vnameserver_addr = vnameserver;\n\n slirp->opaque = opaque;\n\n return slirp;\n}\n\nvoid slirp_cleanup(Slirp *slirp)\n{\n free(slirp->tftp_prefix);\n free(slirp->bootp_filename);\n free(slirp);\n}\n\n#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)\n#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)\n#define UPD_NFDS(x) if (nfds < (x)) nfds = (x)\n\nvoid slirp_select_fill(Slirp *slirp, int *pnfds,\n fd_set *readfds, fd_set *writefds, fd_set *xfds)\n{\n struct socket *so, *so_next;\n int nfds;\n\n /* fail safe */\n global_readfds = NULL;\n global_writefds = NULL;\n global_xfds = NULL;\n\n nfds = *pnfds;\n\t/*\n\t * First, TCP sockets\n\t */\n\tdo_slowtimo = 0;\n\n\t{\n\t\t/*\n\t\t * *_slowtimo needs calling if there are IP fragments\n\t\t * in the fragment queue, or there are TCP connections active\n\t\t */\n\t\tdo_slowtimo |= ((slirp->tcb.so_next != &slirp->tcb) ||\n\t\t (&slirp->ipq.ip_link != slirp->ipq.ip_link.next));\n\n\t\tfor (so = slirp->tcb.so_next; so != &slirp->tcb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * See if we need a tcp_fasttimo\n\t\t\t */\n\t\t\tif (time_fasttimo == 0 && so->so_tcpcb->t_flags & TF_DELACK)\n\t\t\t time_fasttimo = curtime; /* Flag when we want a fasttimo */\n\n\t\t\t/*\n\t\t\t * NOFDREF can include still connecting to local-host,\n\t\t\t * newly socreated() sockets etc. Don't want to select these.\n\t \t\t */\n\t\t\tif (so->so_state & SS_NOFDREF || so->s == -1)\n\t\t\t continue;\n\n\t\t\t/*\n\t\t\t * Set for reading sockets which are accepting\n\t\t\t */\n\t\t\tif (so->so_state & SS_FACCEPTCONN) {\n FD_SET(so->s, readfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for writing sockets which are connecting\n\t\t\t */\n\t\t\tif (so->so_state & SS_ISFCONNECTING) {\n\t\t\t\tFD_SET(so->s, writefds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for writing if we are connected, can send more, and\n\t\t\t * we have something to send\n\t\t\t */\n\t\t\tif (CONN_CANFSEND(so) && so->so_rcv.sb_cc) {\n\t\t\t\tFD_SET(so->s, writefds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for reading (and urgent data) if we are connected, can\n\t\t\t * receive more, and we have room for it XXX /2 ?\n\t\t\t */\n\t\t\tif (CONN_CANFRCV(so) && (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2))) {\n\t\t\t\tFD_SET(so->s, readfds);\n\t\t\t\tFD_SET(so->s, xfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * UDP sockets\n\t\t */\n\t\tfor (so = slirp->udb.so_next; so != &slirp->udb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * See if it's timed out\n\t\t\t */\n\t\t\tif (so->so_expire) {\n\t\t\t\tif (so->so_expire <= curtime) {\n\t\t\t\t\tudp_detach(so);\n\t\t\t\t\tcontinue;\n\t\t\t\t} else\n\t\t\t\t\tdo_slowtimo = 1; /* Let socket expire */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * When UDP packets are received from over the\n\t\t\t * link, they're sendto()'d straight away, so\n\t\t\t * no need for setting for writing\n\t\t\t * Limit the number of packets queued by this session\n\t\t\t * to 4. Note that even though we try and limit this\n\t\t\t * to 4 packets, the session could have more queued\n\t\t\t * if the packets needed to be fragmented\n\t\t\t * (XXX <= 4 ?)\n\t\t\t */\n\t\t\tif ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4) {\n\t\t\t\tFD_SET(so->s, readfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\t\t}\n\t}\n\n *pnfds = nfds;\n}\n\nvoid slirp_select_poll(Slirp *slirp,\n fd_set *readfds, fd_set *writefds, fd_set *xfds,\n int select_error)\n{\n struct socket *so, *so_next;\n int ret;\n\n global_readfds = readfds;\n global_writefds = writefds;\n global_xfds = xfds;\n\n curtime = os_get_time_ms();\n\n {\n\t/*\n\t * See if anything has timed out\n\t */\n\t\tif (time_fasttimo && ((curtime - time_fasttimo) >= 2)) {\n\t\t\ttcp_fasttimo(slirp);\n\t\t\ttime_fasttimo = 0;\n\t\t}\n\t\tif (do_slowtimo && ((curtime - last_slowtimo) >= 499)) {\n\t\t\tip_slowtimo(slirp);\n\t\t\ttcp_slowtimo(slirp);\n\t\t\tlast_slowtimo = curtime;\n\t\t}\n\n\t/*\n\t * Check sockets\n\t */\n\tif (!select_error) {\n\t\t/*\n\t\t * Check TCP sockets\n\t\t */\n\t\tfor (so = slirp->tcb.so_next; so != &slirp->tcb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * FD_ISSET is meaningless on these sockets\n\t\t\t * (and they can crash the program)\n\t\t\t */\n\t\t\tif (so->so_state & SS_NOFDREF || so->s == -1)\n\t\t\t continue;\n\n\t\t\t/*\n\t\t\t * Check for URG data\n\t\t\t * This will soread as well, so no need to\n\t\t\t * test for readfds below if this succeeds\n\t\t\t */\n\t\t\tif (FD_ISSET(so->s, xfds))\n\t\t\t sorecvoob(so);\n\t\t\t/*\n\t\t\t * Check sockets for reading\n\t\t\t */\n\t\t\telse if (FD_ISSET(so->s, readfds)) {\n\t\t\t\t/*\n\t\t\t\t * Check for incoming connections\n\t\t\t\t */\n\t\t\t\tif (so->so_state & SS_FACCEPTCONN) {\n\t\t\t\t\ttcp_connect(so);\n\t\t\t\t\tcontinue;\n\t\t\t\t} /* else */\n\t\t\t\tret = soread(so);\n\n\t\t\t\t/* Output it if we read something */\n\t\t\t\tif (ret > 0)\n\t\t\t\t tcp_output(sototcpcb(so));\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Check sockets for writing\n\t\t\t */\n\t\t\tif (FD_ISSET(so->s, writefds)) {\n\t\t\t /*\n\t\t\t * Check for non-blocking, still-connecting sockets\n\t\t\t */\n\t\t\t if (so->so_state & SS_ISFCONNECTING) {\n\t\t\t /* Connected */\n\t\t\t so->so_state &= ~SS_ISFCONNECTING;\n\n\t\t\t ret = send(so->s, (const void *) &ret, 0, 0);\n\t\t\t if (ret < 0) {\n\t\t\t /* XXXXX Must fix, zero bytes is a NOP */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\t errno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t\tcontinue;\n\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\t\t\t }\n\t\t\t /* else so->so_state &= ~SS_ISFCONNECTING; */\n\n\t\t\t /*\n\t\t\t * Continue tcp_input\n\t\t\t */\n\t\t\t tcp_input((struct mbuf *)NULL, sizeof(struct ip), so);\n\t\t\t /* continue; */\n\t\t\t } else\n\t\t\t ret = sowrite(so);\n\t\t\t /*\n\t\t\t * XXXXX If we wrote something (a lot), there\n\t\t\t * could be a need for a window update.\n\t\t\t * In the worst case, the remote will send\n\t\t\t * a window probe to get things going again\n\t\t\t */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Probe a still-connecting, non-blocking socket\n\t\t\t * to check if it's still alive\n\t \t \t */\n#ifdef PROBE_CONN\n\t\t\tif (so->so_state & SS_ISFCONNECTING) {\n\t\t\t ret = recv(so->s, (char *)&ret, 0,0);\n\n\t\t\t if (ret < 0) {\n\t\t\t /* XXX */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\terrno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t continue; /* Still connecting, continue */\n\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\n\t\t\t /* tcp_input will take care of it */\n\t\t\t } else {\n\t\t\t ret = send(so->s, &ret, 0,0);\n\t\t\t if (ret < 0) {\n\t\t\t /* XXX */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\t errno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t\tcontinue;\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\t\t\t } else\n\t\t\t so->so_state &= ~SS_ISFCONNECTING;\n\n\t\t\t }\n\t\t\t tcp_input((struct mbuf *)NULL, sizeof(struct ip),so);\n\t\t\t} /* SS_ISFCONNECTING */\n#endif\n\t\t}\n\n\t\t/*\n\t\t * Now UDP sockets.\n\t\t * Incoming packets are sent straight away, they're not buffered.\n\t\t * Incoming UDP data isn't buffered either.\n\t\t */\n\t\tfor (so = slirp->udb.so_next; so != &slirp->udb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\tif (so->s != -1 && FD_ISSET(so->s, readfds)) {\n sorecvfrom(so);\n }\n\t\t}\n\t}\n\n\t/*\n\t * See if we can start outputting\n\t */\n\tif (slirp->if_queued) {\n\t if_start(slirp);\n\t}\n }\n\n\t/* clear global file descriptor sets.\n\t * these reside on the stack in vl.c\n\t * so they're unusable if we're not in\n\t * slirp_select_fill or slirp_select_poll.\n\t */\n\t global_readfds = NULL;\n\t global_writefds = NULL;\n\t global_xfds = NULL;\n}\n\n#define ETH_ALEN 6\n#define ETH_HLEN 14\n\n#define ETH_P_IP\t0x0800\t\t/* Internet Protocol packet\t*/\n#define ETH_P_ARP\t0x0806\t\t/* Address Resolution packet\t*/\n\n#define\tARPOP_REQUEST\t1\t\t/* ARP request\t\t\t*/\n#define\tARPOP_REPLY\t2\t\t/* ARP reply\t\t\t*/\n\nstruct ethhdr\n{\n\tunsigned char\th_dest[ETH_ALEN];\t/* destination eth addr\t*/\n\tunsigned char\th_source[ETH_ALEN];\t/* source ether addr\t*/\n\tunsigned short\th_proto;\t\t/* packet type ID field\t*/\n};\n\nstruct arphdr\n{\n\tunsigned short\tar_hrd;\t\t/* format of hardware address\t*/\n\tunsigned short\tar_pro;\t\t/* format of protocol address\t*/\n\tunsigned char\tar_hln;\t\t/* length of hardware address\t*/\n\tunsigned char\tar_pln;\t\t/* length of protocol address\t*/\n\tunsigned short\tar_op;\t\t/* ARP opcode (command)\t\t*/\n\n\t /*\n\t *\t Ethernet looks like this : This bit is variable sized however...\n\t */\n\tunsigned char\t\tar_sha[ETH_ALEN];\t/* sender hardware address\t*/\n\tuint32_t\t\tar_sip;\t\t\t/* sender IP address\t\t*/\n\tunsigned char\t\tar_tha[ETH_ALEN];\t/* target hardware address\t*/\n\tuint32_t\t\tar_tip\t;\t\t/* target IP address\t\t*/\n} __attribute__((packed));\n\nstatic void arp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)\n{\n struct ethhdr *eh = (struct ethhdr *)pkt;\n struct arphdr *ah = (struct arphdr *)(pkt + ETH_HLEN);\n uint8_t arp_reply[max(ETH_HLEN + sizeof(struct arphdr), 64)];\n struct ethhdr *reh = (struct ethhdr *)arp_reply;\n struct arphdr *rah = (struct arphdr *)(arp_reply + ETH_HLEN);\n int ar_op;\n struct ex_list *ex_ptr;\n\n ar_op = ntohs(ah->ar_op);\n switch(ar_op) {\n case ARPOP_REQUEST:\n if ((ah->ar_tip & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n if (ah->ar_tip == slirp->vnameserver_addr.s_addr ||\n ah->ar_tip == slirp->vhost_addr.s_addr)\n goto arp_ok;\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_addr.s_addr == ah->ar_tip)\n goto arp_ok;\n }\n return;\n arp_ok:\n memset(arp_reply, 0, sizeof(arp_reply));\n /* XXX: make an ARP request to have the client address */\n memcpy(slirp->client_ethaddr, eh->h_source, ETH_ALEN);\n\n /* ARP request for alias/dns mac address */\n memcpy(reh->h_dest, pkt + ETH_ALEN, ETH_ALEN);\n memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);\n memcpy(&reh->h_source[2], &ah->ar_tip, 4);\n reh->h_proto = htons(ETH_P_ARP);\n\n rah->ar_hrd = htons(1);\n rah->ar_pro = htons(ETH_P_IP);\n rah->ar_hln = ETH_ALEN;\n rah->ar_pln = 4;\n rah->ar_op = htons(ARPOP_REPLY);\n memcpy(rah->ar_sha, reh->h_source, ETH_ALEN);\n rah->ar_sip = ah->ar_tip;\n memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);\n rah->ar_tip = ah->ar_sip;\n slirp_output(slirp->opaque, arp_reply, sizeof(arp_reply));\n }\n break;\n case ARPOP_REPLY:\n /* reply to request of client mac address ? */\n if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN) &&\n ah->ar_sip == slirp->client_ipaddr.s_addr) {\n memcpy(slirp->client_ethaddr, ah->ar_sha, ETH_ALEN);\n }\n break;\n default:\n break;\n }\n}\n\nvoid slirp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)\n{\n struct mbuf *m;\n int proto;\n\n if (pkt_len < ETH_HLEN)\n return;\n\n proto = ntohs(*(uint16_t *)(pkt + 12));\n switch(proto) {\n case ETH_P_ARP:\n arp_input(slirp, pkt, pkt_len);\n break;\n case ETH_P_IP:\n m = m_get(slirp);\n if (!m)\n return;\n /* Note: we add to align the IP header */\n if (M_FREEROOM(m) < pkt_len + 2) {\n m_inc(m, pkt_len + 2);\n }\n m->m_len = pkt_len + 2;\n memcpy(m->m_data + 2, pkt, pkt_len);\n\n m->m_data += 2 + ETH_HLEN;\n m->m_len -= 2 + ETH_HLEN;\n\n ip_input(m);\n break;\n default:\n break;\n }\n}\n\n/* output the IP packet to the ethernet device */\nvoid if_encap(Slirp *slirp, const uint8_t *ip_data, int ip_data_len)\n{\n uint8_t buf[1600];\n struct ethhdr *eh = (struct ethhdr *)buf;\n\n if (ip_data_len + ETH_HLEN > sizeof(buf))\n return;\n \n if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN)) {\n uint8_t arp_req[ETH_HLEN + sizeof(struct arphdr)];\n struct ethhdr *reh = (struct ethhdr *)arp_req;\n struct arphdr *rah = (struct arphdr *)(arp_req + ETH_HLEN);\n const struct ip *iph = (const struct ip *)ip_data;\n\n /* If the client addr is not known, there is no point in\n sending the packet to it. Normally the sender should have\n done an ARP request to get its MAC address. Here we do it\n in place of sending the packet and we hope that the sender\n will retry sending its packet. */\n memset(reh->h_dest, 0xff, ETH_ALEN);\n memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);\n memcpy(&reh->h_source[2], &slirp->vhost_addr, 4);\n reh->h_proto = htons(ETH_P_ARP);\n rah->ar_hrd = htons(1);\n rah->ar_pro = htons(ETH_P_IP);\n rah->ar_hln = ETH_ALEN;\n rah->ar_pln = 4;\n rah->ar_op = htons(ARPOP_REQUEST);\n /* source hw addr */\n memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN - 4);\n memcpy(&rah->ar_sha[2], &slirp->vhost_addr, 4);\n /* source IP */\n rah->ar_sip = slirp->vhost_addr.s_addr;\n /* target hw addr (none) */\n memset(rah->ar_tha, 0, ETH_ALEN);\n /* target IP */\n rah->ar_tip = iph->ip_dst.s_addr;\n slirp->client_ipaddr = iph->ip_dst;\n slirp_output(slirp->opaque, arp_req, sizeof(arp_req));\n } else {\n memcpy(eh->h_dest, slirp->client_ethaddr, ETH_ALEN);\n memcpy(eh->h_source, special_ethaddr, ETH_ALEN - 4);\n /* XXX: not correct */\n memcpy(&eh->h_source[2], &slirp->vhost_addr, 4);\n eh->h_proto = htons(ETH_P_IP);\n memcpy(buf + sizeof(struct ethhdr), ip_data, ip_data_len);\n slirp_output(slirp->opaque, buf, ip_data_len + ETH_HLEN);\n }\n}\n\n/* Drop host forwarding rule, return 0 if found. */\nint slirp_remove_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,\n int host_port)\n{\n struct socket *so;\n struct socket *head = (is_udp ? &slirp->udb : &slirp->tcb);\n struct sockaddr_in addr;\n int port = htons(host_port);\n socklen_t addr_len;\n\n for (so = head->so_next; so != head; so = so->so_next) {\n addr_len = sizeof(addr);\n if ((so->so_state & SS_HOSTFWD) &&\n getsockname(so->s, (struct sockaddr *)&addr, &addr_len) == 0 &&\n addr.sin_addr.s_addr == host_addr.s_addr &&\n addr.sin_port == port) {\n close(so->s);\n sofree(so);\n return 0;\n }\n }\n\n return -1;\n}\n\nint slirp_add_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,\n int host_port, struct in_addr guest_addr, int guest_port)\n{\n if (!guest_addr.s_addr) {\n guest_addr = slirp->vdhcp_startaddr;\n }\n if (is_udp) {\n if (!udp_listen(slirp, host_addr.s_addr, htons(host_port),\n guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))\n return -1;\n } else {\n if (!tcp_listen(slirp, host_addr.s_addr, htons(host_port),\n guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))\n return -1;\n }\n return 0;\n}\n\nint slirp_add_exec(Slirp *slirp, int do_pty, const void *args,\n struct in_addr *guest_addr, int guest_port)\n{\n if (!guest_addr->s_addr) {\n guest_addr->s_addr = slirp->vnetwork_addr.s_addr |\n (htonl(0x0204) & ~slirp->vnetwork_mask.s_addr);\n }\n if ((guest_addr->s_addr & slirp->vnetwork_mask.s_addr) !=\n slirp->vnetwork_addr.s_addr ||\n guest_addr->s_addr == slirp->vhost_addr.s_addr ||\n guest_addr->s_addr == slirp->vnameserver_addr.s_addr) {\n return -1;\n }\n return add_exec(&slirp->exec_list, do_pty, (char *)args, *guest_addr,\n htons(guest_port));\n}\n\nssize_t slirp_send(struct socket *so, const void *buf, size_t len, int flags)\n{\n#if 0\n if (so->s == -1 && so->extra) {\n\t\tqemu_chr_write(so->extra, buf, len);\n\t\treturn len;\n\t}\n#endif\n\treturn send(so->s, buf, len, flags);\n}\n\nstatic struct socket *\nslirp_find_ctl_socket(Slirp *slirp, struct in_addr guest_addr, int guest_port)\n{\n struct socket *so;\n\n for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {\n if (so->so_faddr.s_addr == guest_addr.s_addr &&\n htons(so->so_fport) == guest_port) {\n return so;\n }\n }\n return NULL;\n}\n\nsize_t slirp_socket_can_recv(Slirp *slirp, struct in_addr guest_addr,\n int guest_port)\n{\n\tstruct iovec iov[2];\n\tstruct socket *so;\n\n\tso = slirp_find_ctl_socket(slirp, guest_addr, guest_port);\n\n\tif (!so || so->so_state & SS_NOFDREF)\n\t\treturn 0;\n\n\tif (!CONN_CANFRCV(so) || so->so_snd.sb_cc >= (so->so_snd.sb_datalen/2))\n\t\treturn 0;\n\n\treturn sopreprbuf(so, iov, NULL);\n}\n\nvoid slirp_socket_recv(Slirp *slirp, struct in_addr guest_addr, int guest_port,\n const uint8_t *buf, int size)\n{\n int ret;\n struct socket *so = slirp_find_ctl_socket(slirp, guest_addr, guest_port);\n\n if (!so)\n return;\n\n ret = soreadbuf(so, (const char *)buf, size);\n\n if (ret > 0)\n tcp_output(sototcpcb(so));\n}\n"], ["/linuxpdf/tinyemu/slirp/sbuf.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\nstatic void sbappendsb(struct sbuf *sb, struct mbuf *m);\n\nvoid\nsbfree(struct sbuf *sb)\n{\n\tfree(sb->sb_data);\n}\n\nvoid\nsbdrop(struct sbuf *sb, int num)\n{\n\t/*\n\t * We can only drop how much we have\n\t * This should never succeed\n\t */\n\tif(num > sb->sb_cc)\n\t\tnum = sb->sb_cc;\n\tsb->sb_cc -= num;\n\tsb->sb_rptr += num;\n\tif(sb->sb_rptr >= sb->sb_data + sb->sb_datalen)\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n}\n\nvoid\nsbreserve(struct sbuf *sb, int size)\n{\n\tif (sb->sb_data) {\n\t\t/* Already alloced, realloc if necessary */\n\t\tif (sb->sb_datalen != size) {\n\t\t\tsb->sb_wptr = sb->sb_rptr = sb->sb_data = (char *)realloc(sb->sb_data, size);\n\t\t\tsb->sb_cc = 0;\n\t\t\tif (sb->sb_wptr)\n\t\t\t sb->sb_datalen = size;\n\t\t\telse\n\t\t\t sb->sb_datalen = 0;\n\t\t}\n\t} else {\n\t\tsb->sb_wptr = sb->sb_rptr = sb->sb_data = (char *)malloc(size);\n\t\tsb->sb_cc = 0;\n\t\tif (sb->sb_wptr)\n\t\t sb->sb_datalen = size;\n\t\telse\n\t\t sb->sb_datalen = 0;\n\t}\n}\n\n/*\n * Try and write() to the socket, whatever doesn't get written\n * append to the buffer... for a host with a fast net connection,\n * this prevents an unnecessary copy of the data\n * (the socket is non-blocking, so we won't hang)\n */\nvoid\nsbappend(struct socket *so, struct mbuf *m)\n{\n\tint ret = 0;\n\n\tDEBUG_CALL(\"sbappend\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"m->m_len = %d\", m->m_len);\n\n\t/* Shouldn't happen, but... e.g. foreign host closes connection */\n\tif (m->m_len <= 0) {\n\t\tm_free(m);\n\t\treturn;\n\t}\n\n\t/*\n\t * If there is urgent data, call sosendoob\n\t * if not all was sent, sowrite will take care of the rest\n\t * (The rest of this function is just an optimisation)\n\t */\n\tif (so->so_urgc) {\n\t\tsbappendsb(&so->so_rcv, m);\n\t\tm_free(m);\n\t\tsosendoob(so);\n\t\treturn;\n\t}\n\n\t/*\n\t * We only write if there's nothing in the buffer,\n\t * ottherwise it'll arrive out of order, and hence corrupt\n\t */\n\tif (!so->so_rcv.sb_cc)\n\t ret = slirp_send(so, m->m_data, m->m_len, 0);\n\n\tif (ret <= 0) {\n\t\t/*\n\t\t * Nothing was written\n\t\t * It's possible that the socket has closed, but\n\t\t * we don't need to check because if it has closed,\n\t\t * it will be detected in the normal way by soread()\n\t\t */\n\t\tsbappendsb(&so->so_rcv, m);\n\t} else if (ret != m->m_len) {\n\t\t/*\n\t\t * Something was written, but not everything..\n\t\t * sbappendsb the rest\n\t\t */\n\t\tm->m_len -= ret;\n\t\tm->m_data += ret;\n\t\tsbappendsb(&so->so_rcv, m);\n\t} /* else */\n\t/* Whatever happened, we free the mbuf */\n\tm_free(m);\n}\n\n/*\n * Copy the data from m into sb\n * The caller is responsible to make sure there's enough room\n */\nstatic void\nsbappendsb(struct sbuf *sb, struct mbuf *m)\n{\n\tint len, n, nn;\n\n\tlen = m->m_len;\n\n\tif (sb->sb_wptr < sb->sb_rptr) {\n\t\tn = sb->sb_rptr - sb->sb_wptr;\n\t\tif (n > len) n = len;\n\t\tmemcpy(sb->sb_wptr, m->m_data, n);\n\t} else {\n\t\t/* Do the right edge first */\n\t\tn = sb->sb_data + sb->sb_datalen - sb->sb_wptr;\n\t\tif (n > len) n = len;\n\t\tmemcpy(sb->sb_wptr, m->m_data, n);\n\t\tlen -= n;\n\t\tif (len) {\n\t\t\t/* Now the left edge */\n\t\t\tnn = sb->sb_rptr - sb->sb_data;\n\t\t\tif (nn > len) nn = len;\n\t\t\tmemcpy(sb->sb_data,m->m_data+n,nn);\n\t\t\tn += nn;\n\t\t}\n\t}\n\n\tsb->sb_cc += n;\n\tsb->sb_wptr += n;\n\tif (sb->sb_wptr >= sb->sb_data + sb->sb_datalen)\n\t\tsb->sb_wptr -= sb->sb_datalen;\n}\n\n/*\n * Copy data from sbuf to a normal, straight buffer\n * Don't update the sbuf rptr, this will be\n * done in sbdrop when the data is acked\n */\nvoid\nsbcopy(struct sbuf *sb, int off, int len, char *to)\n{\n\tchar *from;\n\n\tfrom = sb->sb_rptr + off;\n\tif (from >= sb->sb_data + sb->sb_datalen)\n\t\tfrom -= sb->sb_datalen;\n\n\tif (from < sb->sb_wptr) {\n\t\tif (len > sb->sb_cc) len = sb->sb_cc;\n\t\tmemcpy(to,from,len);\n\t} else {\n\t\t/* re-use off */\n\t\toff = (sb->sb_data + sb->sb_datalen) - from;\n\t\tif (off > len) off = len;\n\t\tmemcpy(to,from,off);\n\t\tlen -= off;\n\t\tif (len)\n\t\t memcpy(to+off,sb->sb_data,len);\n\t}\n}\n"], ["/linuxpdf/tinyemu/slirp/misc.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n#ifdef DEBUG\nint slirp_debug = DBG_CALL|DBG_MISC|DBG_ERROR;\n#endif\n\nstruct quehead {\n\tstruct quehead *qh_link;\n\tstruct quehead *qh_rlink;\n};\n\ninline void\ninsque(void *a, void *b)\n{\n\tregister struct quehead *element = (struct quehead *) a;\n\tregister struct quehead *head = (struct quehead *) b;\n\telement->qh_link = head->qh_link;\n\thead->qh_link = (struct quehead *)element;\n\telement->qh_rlink = (struct quehead *)head;\n\t((struct quehead *)(element->qh_link))->qh_rlink\n\t= (struct quehead *)element;\n}\n\ninline void\nremque(void *a)\n{\n register struct quehead *element = (struct quehead *) a;\n ((struct quehead *)(element->qh_link))->qh_rlink = element->qh_rlink;\n ((struct quehead *)(element->qh_rlink))->qh_link = element->qh_link;\n element->qh_rlink = NULL;\n}\n\nint add_exec(struct ex_list **ex_ptr, int do_pty, char *exec,\n struct in_addr addr, int port)\n{\n\tstruct ex_list *tmp_ptr;\n\n\t/* First, check if the port is \"bound\" */\n\tfor (tmp_ptr = *ex_ptr; tmp_ptr; tmp_ptr = tmp_ptr->ex_next) {\n\t\tif (port == tmp_ptr->ex_fport &&\n\t\t addr.s_addr == tmp_ptr->ex_addr.s_addr)\n\t\t\treturn -1;\n\t}\n\n\ttmp_ptr = *ex_ptr;\n\t*ex_ptr = (struct ex_list *)malloc(sizeof(struct ex_list));\n\t(*ex_ptr)->ex_fport = port;\n\t(*ex_ptr)->ex_addr = addr;\n\t(*ex_ptr)->ex_pty = do_pty;\n\t(*ex_ptr)->ex_exec = (do_pty == 3) ? exec : strdup(exec);\n\t(*ex_ptr)->ex_next = tmp_ptr;\n\treturn 0;\n}\n\n#ifndef HAVE_STRERROR\n\n/*\n * For systems with no strerror\n */\n\nextern int sys_nerr;\nextern char *sys_errlist[];\n\nchar *\nstrerror(error)\n\tint error;\n{\n\tif (error < sys_nerr)\n\t return sys_errlist[error];\n\telse\n\t return \"Unknown error.\";\n}\n\n#endif\n\nint os_socket(int domain, int type, int protocol)\n{\n return socket(domain, type, protocol);\n}\n\nuint32_t os_get_time_ms(void)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return ts.tv_sec * 1000 +\n (ts.tv_nsec / 1000000);\n}\n\n\n#if 1\n\nint\nfork_exec(struct socket *so, const char *ex, int do_pty)\n{\n /* not implemented */\n return 0;\n}\n\n#else\n\n/*\n * XXX This is ugly\n * We create and bind a socket, then fork off to another\n * process, which connects to this socket, after which we\n * exec the wanted program. If something (strange) happens,\n * the accept() call could block us forever.\n *\n * do_pty = 0 Fork/exec inetd style\n * do_pty = 1 Fork/exec using slirp.telnetd\n * do_ptr = 2 Fork/exec using pty\n */\nint\nfork_exec(struct socket *so, const char *ex, int do_pty)\n{\n\tint s;\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(addr);\n\tint opt;\n int master = -1;\n\tconst char *argv[256];\n\t/* don't want to clobber the original */\n\tchar *bptr;\n\tconst char *curarg;\n\tint c, i, ret;\n\n\tDEBUG_CALL(\"fork_exec\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"ex = %lx\", (long)ex);\n\tDEBUG_ARG(\"do_pty = %lx\", (long)do_pty);\n\n\tif (do_pty == 2) {\n return 0;\n\t} else {\n\t\taddr.sin_family = AF_INET;\n\t\taddr.sin_port = 0;\n\t\taddr.sin_addr.s_addr = INADDR_ANY;\n\n\t\tif ((s = os_socket(AF_INET, SOCK_STREAM, 0)) < 0 ||\n\t\t bind(s, (struct sockaddr *)&addr, addrlen) < 0 ||\n\t\t listen(s, 1) < 0) {\n\t\t\tlprint(\"Error: inet socket: %s\\n\", strerror(errno));\n\t\t\tclosesocket(s);\n\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tswitch(fork()) {\n\t case -1:\n\t\tlprint(\"Error: fork failed: %s\\n\", strerror(errno));\n\t\tclose(s);\n\t\tif (do_pty == 2)\n\t\t close(master);\n\t\treturn 0;\n\n\t case 0:\n\t\t/* Set the DISPLAY */\n\t\tif (do_pty == 2) {\n\t\t\t(void) close(master);\n#ifdef TIOCSCTTY /* XXXXX */\n\t\t\t(void) setsid();\n\t\t\tioctl(s, TIOCSCTTY, (char *)NULL);\n#endif\n\t\t} else {\n\t\t\tgetsockname(s, (struct sockaddr *)&addr, &addrlen);\n\t\t\tclose(s);\n\t\t\t/*\n\t\t\t * Connect to the socket\n\t\t\t * XXX If any of these fail, we're in trouble!\n\t \t\t */\n\t\t\ts = os_socket(AF_INET, SOCK_STREAM, 0);\n\t\t\taddr.sin_addr = loopback_addr;\n do {\n ret = connect(s, (struct sockaddr *)&addr, addrlen);\n } while (ret < 0 && errno == EINTR);\n\t\t}\n\n\t\tdup2(s, 0);\n\t\tdup2(s, 1);\n\t\tdup2(s, 2);\n\t\tfor (s = getdtablesize() - 1; s >= 3; s--)\n\t\t close(s);\n\n\t\ti = 0;\n\t\tbptr = qemu_strdup(ex); /* No need to free() this */\n\t\tif (do_pty == 1) {\n\t\t\t/* Setup \"slirp.telnetd -x\" */\n\t\t\targv[i++] = \"slirp.telnetd\";\n\t\t\targv[i++] = \"-x\";\n\t\t\targv[i++] = bptr;\n\t\t} else\n\t\t do {\n\t\t\t/* Change the string into argv[] */\n\t\t\tcurarg = bptr;\n\t\t\twhile (*bptr != ' ' && *bptr != (char)0)\n\t\t\t bptr++;\n\t\t\tc = *bptr;\n\t\t\t*bptr++ = (char)0;\n\t\t\targv[i++] = strdup(curarg);\n\t\t } while (c);\n\n argv[i] = NULL;\n\t\texecvp(argv[0], (char **)argv);\n\n\t\t/* Ooops, failed, let's tell the user why */\n fprintf(stderr, \"Error: execvp of %s failed: %s\\n\",\n argv[0], strerror(errno));\n\t\tclose(0); close(1); close(2); /* XXX */\n\t\texit(1);\n\n\t default:\n\t\tif (do_pty == 2) {\n\t\t\tclose(s);\n\t\t\tso->s = master;\n\t\t} else {\n\t\t\t/*\n\t\t\t * XXX this could block us...\n\t\t\t * XXX Should set a timer here, and if accept() doesn't\n\t\t \t * return after X seconds, declare it a failure\n\t\t \t * The only reason this will block forever is if socket()\n\t\t \t * of connect() fail in the child process\n\t\t \t */\n do {\n so->s = accept(s, (struct sockaddr *)&addr, &addrlen);\n } while (so->s < 0 && errno == EINTR);\n closesocket(s);\n\t\t\topt = 1;\n\t\t\tsetsockopt(so->s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\t\t\topt = 1;\n\t\t\tsetsockopt(so->s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\t\t}\n\t\tfd_nonblock(so->s);\n\n\t\t/* Append the telnet options now */\n if (so->so_m != NULL && do_pty == 1) {\n\t\t\tsbappend(so, so->so_m);\n so->so_m = NULL;\n\t\t}\n\n\t\treturn 1;\n\t}\n}\n#endif\n\n#ifndef HAVE_STRDUP\nchar *\nstrdup(str)\n\tconst char *str;\n{\n\tchar *bptr;\n\n\tbptr = (char *)malloc(strlen(str)+1);\n\tstrcpy(bptr, str);\n\n\treturn bptr;\n}\n#endif\n\nvoid lprint(const char *format, ...)\n{\n va_list args;\n\n va_start(args, format);\n vprintf(format, args);\n va_end(args);\n}\n\n/*\n * Set fd blocking and non-blocking\n */\n\nvoid\nfd_nonblock(int fd)\n{\n#ifdef FIONBIO\n#ifdef _WIN32\n unsigned long opt = 1;\n#else\n int opt = 1;\n#endif\n\n\tioctlsocket(fd, FIONBIO, &opt);\n#else\n\tint opt;\n\n\topt = fcntl(fd, F_GETFL, 0);\n\topt |= O_NONBLOCK;\n\tfcntl(fd, F_SETFL, opt);\n#endif\n}\n\nvoid\nfd_block(int fd)\n{\n#ifdef FIONBIO\n#ifdef _WIN32\n unsigned long opt = 0;\n#else\n\tint opt = 0;\n#endif\n\n\tioctlsocket(fd, FIONBIO, &opt);\n#else\n\tint opt;\n\n\topt = fcntl(fd, F_GETFL, 0);\n\topt &= ~O_NONBLOCK;\n\tfcntl(fd, F_SETFL, opt);\n#endif\n}\n\n#if 0\nvoid slirp_connection_info(Slirp *slirp, Monitor *mon)\n{\n const char * const tcpstates[] = {\n [TCPS_CLOSED] = \"CLOSED\",\n [TCPS_LISTEN] = \"LISTEN\",\n [TCPS_SYN_SENT] = \"SYN_SENT\",\n [TCPS_SYN_RECEIVED] = \"SYN_RCVD\",\n [TCPS_ESTABLISHED] = \"ESTABLISHED\",\n [TCPS_CLOSE_WAIT] = \"CLOSE_WAIT\",\n [TCPS_FIN_WAIT_1] = \"FIN_WAIT_1\",\n [TCPS_CLOSING] = \"CLOSING\",\n [TCPS_LAST_ACK] = \"LAST_ACK\",\n [TCPS_FIN_WAIT_2] = \"FIN_WAIT_2\",\n [TCPS_TIME_WAIT] = \"TIME_WAIT\",\n };\n struct in_addr dst_addr;\n struct sockaddr_in src;\n socklen_t src_len;\n uint16_t dst_port;\n struct socket *so;\n const char *state;\n char buf[20];\n int n;\n\n monitor_printf(mon, \" Protocol[State] FD Source Address Port \"\n \"Dest. Address Port RecvQ SendQ\\n\");\n\n for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {\n if (so->so_state & SS_HOSTFWD) {\n state = \"HOST_FORWARD\";\n } else if (so->so_tcpcb) {\n state = tcpstates[so->so_tcpcb->t_state];\n } else {\n state = \"NONE\";\n }\n if (so->so_state & (SS_HOSTFWD | SS_INCOMING)) {\n src_len = sizeof(src);\n getsockname(so->s, (struct sockaddr *)&src, &src_len);\n dst_addr = so->so_laddr;\n dst_port = so->so_lport;\n } else {\n src.sin_addr = so->so_laddr;\n src.sin_port = so->so_lport;\n dst_addr = so->so_faddr;\n dst_port = so->so_fport;\n }\n n = snprintf(buf, sizeof(buf), \" TCP[%s]\", state);\n memset(&buf[n], ' ', 19 - n);\n buf[19] = 0;\n monitor_printf(mon, \"%s %3d %15s %5d \", buf, so->s,\n src.sin_addr.s_addr ? inet_ntoa(src.sin_addr) : \"*\",\n ntohs(src.sin_port));\n monitor_printf(mon, \"%15s %5d %5d %5d\\n\",\n inet_ntoa(dst_addr), ntohs(dst_port),\n so->so_rcv.sb_cc, so->so_snd.sb_cc);\n }\n\n for (so = slirp->udb.so_next; so != &slirp->udb; so = so->so_next) {\n if (so->so_state & SS_HOSTFWD) {\n n = snprintf(buf, sizeof(buf), \" UDP[HOST_FORWARD]\");\n src_len = sizeof(src);\n getsockname(so->s, (struct sockaddr *)&src, &src_len);\n dst_addr = so->so_laddr;\n dst_port = so->so_lport;\n } else {\n n = snprintf(buf, sizeof(buf), \" UDP[%d sec]\",\n (so->so_expire - curtime) / 1000);\n src.sin_addr = so->so_laddr;\n src.sin_port = so->so_lport;\n dst_addr = so->so_faddr;\n dst_port = so->so_fport;\n }\n memset(&buf[n], ' ', 19 - n);\n buf[19] = 0;\n monitor_printf(mon, \"%s %3d %15s %5d \", buf, so->s,\n src.sin_addr.s_addr ? inet_ntoa(src.sin_addr) : \"*\",\n ntohs(src.sin_port));\n monitor_printf(mon, \"%15s %5d %5d %5d\\n\",\n inet_ntoa(dst_addr), ntohs(dst_port),\n so->so_rcv.sb_cc, so->so_snd.sb_cc);\n }\n}\n#endif\n"], ["/linuxpdf/tinyemu/slirp/ip_icmp.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_icmp.c\t8.2 (Berkeley) 1/4/94\n * ip_icmp.c,v 1.7 1995/05/30 08:09:42 rgrimes Exp\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n/* The message sent when emulating PING */\n/* Be nice and tell them it's just a pseudo-ping packet */\nstatic const char icmp_ping_msg[] = \"This is a pseudo-PING packet used by Slirp to emulate ICMP ECHO-REQUEST packets.\\n\";\n\n/* list of actions for icmp_error() on RX of an icmp message */\nstatic const int icmp_flush[19] = {\n/* ECHO REPLY (0) */ 0,\n\t\t 1,\n\t\t 1,\n/* DEST UNREACH (3) */ 1,\n/* SOURCE QUENCH (4)*/ 1,\n/* REDIRECT (5) */ 1,\n\t\t 1,\n\t\t 1,\n/* ECHO (8) */ 0,\n/* ROUTERADVERT (9) */ 1,\n/* ROUTERSOLICIT (10) */ 1,\n/* TIME EXCEEDED (11) */ 1,\n/* PARAMETER PROBLEM (12) */ 1,\n/* TIMESTAMP (13) */ 0,\n/* TIMESTAMP REPLY (14) */ 0,\n/* INFO (15) */ 0,\n/* INFO REPLY (16) */ 0,\n/* ADDR MASK (17) */ 0,\n/* ADDR MASK REPLY (18) */ 0\n};\n\n/*\n * Process a received ICMP message.\n */\nvoid\nicmp_input(struct mbuf *m, int hlen)\n{\n register struct icmp *icp;\n register struct ip *ip=mtod(m, struct ip *);\n int icmplen=ip->ip_len;\n Slirp *slirp = m->slirp;\n\n DEBUG_CALL(\"icmp_input\");\n DEBUG_ARG(\"m = %lx\", (long )m);\n DEBUG_ARG(\"m_len = %d\", m->m_len);\n\n /*\n * Locate icmp structure in mbuf, and check\n * that its not corrupted and of at least minimum length.\n */\n if (icmplen < ICMP_MINLEN) { /* min 8 bytes payload */\n freeit:\n m_freem(m);\n goto end_error;\n }\n\n m->m_len -= hlen;\n m->m_data += hlen;\n icp = mtod(m, struct icmp *);\n if (cksum(m, icmplen)) {\n goto freeit;\n }\n m->m_len += hlen;\n m->m_data -= hlen;\n\n DEBUG_ARG(\"icmp_type = %d\", icp->icmp_type);\n switch (icp->icmp_type) {\n case ICMP_ECHO:\n icp->icmp_type = ICMP_ECHOREPLY;\n ip->ip_len += hlen;\t /* since ip_input subtracts this */\n if (ip->ip_dst.s_addr == slirp->vhost_addr.s_addr) {\n icmp_reflect(m);\n } else {\n struct socket *so;\n struct sockaddr_in addr;\n if ((so = socreate(slirp)) == NULL) goto freeit;\n if(udp_attach(so) == -1) {\n\tDEBUG_MISC((dfd,\"icmp_input udp_attach errno = %d-%s\\n\",\n\t\t errno,strerror(errno)));\n\tsofree(so);\n\tm_free(m);\n\tgoto end_error;\n }\n so->so_m = m;\n so->so_faddr = ip->ip_dst;\n so->so_fport = htons(7);\n so->so_laddr = ip->ip_src;\n so->so_lport = htons(9);\n so->so_iptos = ip->ip_tos;\n so->so_type = IPPROTO_ICMP;\n so->so_state = SS_ISFCONNECTED;\n\n /* Send the packet */\n addr.sin_family = AF_INET;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n\t/* It's an alias */\n\tif (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\t if (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n\t} else {\n\t addr.sin_addr = loopback_addr;\n\t}\n } else {\n\taddr.sin_addr = so->so_faddr;\n }\n addr.sin_port = so->so_fport;\n if(sendto(so->s, icmp_ping_msg, strlen(icmp_ping_msg), 0,\n\t\t(struct sockaddr *)&addr, sizeof(addr)) == -1) {\n\tDEBUG_MISC((dfd,\"icmp_input udp sendto tx errno = %d-%s\\n\",\n\t\t errno,strerror(errno)));\n\ticmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));\n\tudp_detach(so);\n }\n } /* if ip->ip_dst.s_addr == alias_addr.s_addr */\n break;\n case ICMP_UNREACH:\n /* XXX? report error? close socket? */\n case ICMP_TIMXCEED:\n case ICMP_PARAMPROB:\n case ICMP_SOURCEQUENCH:\n case ICMP_TSTAMP:\n case ICMP_MASKREQ:\n case ICMP_REDIRECT:\n m_freem(m);\n break;\n\n default:\n m_freem(m);\n } /* swith */\n\nend_error:\n /* m is m_free()'d xor put in a socket xor or given to ip_send */\n return;\n}\n\n\n/*\n *\tSend an ICMP message in response to a situation\n *\n *\tRFC 1122: 3.2.2\tMUST send at least the IP header and 8 bytes of header. MAY send more (we do).\n *\t\t\tMUST NOT change this header information.\n *\t\t\tMUST NOT reply to a multicast/broadcast IP address.\n *\t\t\tMUST NOT reply to a multicast/broadcast MAC address.\n *\t\t\tMUST reply to only the first fragment.\n */\n/*\n * Send ICMP_UNREACH back to the source regarding msrc.\n * mbuf *msrc is used as a template, but is NOT m_free()'d.\n * It is reported as the bad ip packet. The header should\n * be fully correct and in host byte order.\n * ICMP fragmentation is illegal. All machines must accept 576 bytes in one\n * packet. The maximum payload is 576-20(ip hdr)-8(icmp hdr)=548\n */\n\n#define ICMP_MAXDATALEN (IP_MSS-28)\nvoid\nicmp_error(struct mbuf *msrc, u_char type, u_char code, int minsize,\n const char *message)\n{\n unsigned hlen, shlen, s_ip_len;\n register struct ip *ip;\n register struct icmp *icp;\n register struct mbuf *m;\n\n DEBUG_CALL(\"icmp_error\");\n DEBUG_ARG(\"msrc = %lx\", (long )msrc);\n DEBUG_ARG(\"msrc_len = %d\", msrc->m_len);\n\n if(type!=ICMP_UNREACH && type!=ICMP_TIMXCEED) goto end_error;\n\n /* check msrc */\n if(!msrc) goto end_error;\n ip = mtod(msrc, struct ip *);\n#ifdef DEBUG\n { char bufa[20], bufb[20];\n strcpy(bufa, inet_ntoa(ip->ip_src));\n strcpy(bufb, inet_ntoa(ip->ip_dst));\n DEBUG_MISC((dfd, \" %.16s to %.16s\\n\", bufa, bufb));\n }\n#endif\n if(ip->ip_off & IP_OFFMASK) goto end_error; /* Only reply to fragment 0 */\n\n shlen=ip->ip_hl << 2;\n s_ip_len=ip->ip_len;\n if(ip->ip_p == IPPROTO_ICMP) {\n icp = (struct icmp *)((char *)ip + shlen);\n /*\n *\tAssume any unknown ICMP type is an error. This isn't\n *\tspecified by the RFC, but think about it..\n */\n if(icp->icmp_type>18 || icmp_flush[icp->icmp_type]) goto end_error;\n }\n\n /* make a copy */\n m = m_get(msrc->slirp);\n if (!m) {\n goto end_error;\n }\n\n { int new_m_size;\n new_m_size=sizeof(struct ip )+ICMP_MINLEN+msrc->m_len+ICMP_MAXDATALEN;\n if(new_m_size>m->m_size) m_inc(m, new_m_size);\n }\n memcpy(m->m_data, msrc->m_data, msrc->m_len);\n m->m_len = msrc->m_len; /* copy msrc to m */\n\n /* make the header of the reply packet */\n ip = mtod(m, struct ip *);\n hlen= sizeof(struct ip ); /* no options in reply */\n\n /* fill in icmp */\n m->m_data += hlen;\n m->m_len -= hlen;\n\n icp = mtod(m, struct icmp *);\n\n if(minsize) s_ip_len=shlen+ICMP_MINLEN; /* return header+8b only */\n else if(s_ip_len>ICMP_MAXDATALEN) /* maximum size */\n s_ip_len=ICMP_MAXDATALEN;\n\n m->m_len=ICMP_MINLEN+s_ip_len; /* 8 bytes ICMP header */\n\n /* min. size = 8+sizeof(struct ip)+8 */\n\n icp->icmp_type = type;\n icp->icmp_code = code;\n icp->icmp_id = 0;\n icp->icmp_seq = 0;\n\n memcpy(&icp->icmp_ip, msrc->m_data, s_ip_len); /* report the ip packet */\n HTONS(icp->icmp_ip.ip_len);\n HTONS(icp->icmp_ip.ip_id);\n HTONS(icp->icmp_ip.ip_off);\n\n#ifdef DEBUG\n if(message) { /* DEBUG : append message to ICMP packet */\n int message_len;\n char *cpnt;\n message_len=strlen(message);\n if(message_len>ICMP_MAXDATALEN) message_len=ICMP_MAXDATALEN;\n cpnt=(char *)m->m_data+m->m_len;\n memcpy(cpnt, message, message_len);\n m->m_len+=message_len;\n }\n#endif\n\n icp->icmp_cksum = 0;\n icp->icmp_cksum = cksum(m, m->m_len);\n\n m->m_data -= hlen;\n m->m_len += hlen;\n\n /* fill in ip */\n ip->ip_hl = hlen >> 2;\n ip->ip_len = m->m_len;\n\n ip->ip_tos=((ip->ip_tos & 0x1E) | 0xC0); /* high priority for errors */\n\n ip->ip_ttl = MAXTTL;\n ip->ip_p = IPPROTO_ICMP;\n ip->ip_dst = ip->ip_src; /* ip adresses */\n ip->ip_src = m->slirp->vhost_addr;\n\n (void ) ip_output((struct socket *)NULL, m);\n\nend_error:\n return;\n}\n#undef ICMP_MAXDATALEN\n\n/*\n * Reflect the ip packet back to the source\n */\nvoid\nicmp_reflect(struct mbuf *m)\n{\n register struct ip *ip = mtod(m, struct ip *);\n int hlen = ip->ip_hl << 2;\n int optlen = hlen - sizeof(struct ip );\n register struct icmp *icp;\n\n /*\n * Send an icmp packet back to the ip level,\n * after supplying a checksum.\n */\n m->m_data += hlen;\n m->m_len -= hlen;\n icp = mtod(m, struct icmp *);\n\n icp->icmp_cksum = 0;\n icp->icmp_cksum = cksum(m, ip->ip_len - hlen);\n\n m->m_data -= hlen;\n m->m_len += hlen;\n\n /* fill in ip */\n if (optlen > 0) {\n /*\n * Strip out original options by copying rest of first\n * mbuf's data back, and adjust the IP length.\n */\n memmove((caddr_t)(ip + 1), (caddr_t)ip + hlen,\n\t (unsigned )(m->m_len - hlen));\n hlen -= optlen;\n ip->ip_hl = hlen >> 2;\n ip->ip_len -= optlen;\n m->m_len -= optlen;\n }\n\n ip->ip_ttl = MAXTTL;\n { /* swap */\n struct in_addr icmp_dst;\n icmp_dst = ip->ip_dst;\n ip->ip_dst = ip->ip_src;\n ip->ip_src = icmp_dst;\n }\n\n (void ) ip_output((struct socket *)NULL, m);\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_output.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_output.c\t8.3 (Berkeley) 12/30/93\n * tcp_output.c,v 1.3 1994/09/15 10:36:55 davidg Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\nstatic const u_char tcp_outflags[TCP_NSTATES] = {\n\tTH_RST|TH_ACK, 0, TH_SYN, TH_SYN|TH_ACK,\n\tTH_ACK, TH_ACK, TH_FIN|TH_ACK, TH_FIN|TH_ACK,\n\tTH_FIN|TH_ACK, TH_ACK, TH_ACK,\n};\n\n\n#define MAX_TCPOPTLEN\t32\t/* max # bytes that go in options */\n\n/*\n * Tcp output routine: figure out what should be sent and send it.\n */\nint\ntcp_output(struct tcpcb *tp)\n{\n\tregister struct socket *so = tp->t_socket;\n\tregister long len, win;\n\tint off, flags, error;\n\tregister struct mbuf *m;\n\tregister struct tcpiphdr *ti;\n\tu_char opt[MAX_TCPOPTLEN];\n\tunsigned optlen, hdrlen;\n\tint idle, sendalot;\n\n\tDEBUG_CALL(\"tcp_output\");\n\tDEBUG_ARG(\"tp = %lx\", (long )tp);\n\n\t/*\n\t * Determine length of data that should be transmitted,\n\t * and flags that will be used.\n\t * If there is some data or critical controls (SYN, RST)\n\t * to send, then transmit; otherwise, investigate further.\n\t */\n\tidle = (tp->snd_max == tp->snd_una);\n\tif (idle && tp->t_idle >= tp->t_rxtcur)\n\t\t/*\n\t\t * We have been idle for \"a while\" and no acks are\n\t\t * expected to clock out any data we send --\n\t\t * slow start to get ack \"clock\" running again.\n\t\t */\n\t\ttp->snd_cwnd = tp->t_maxseg;\nagain:\n\tsendalot = 0;\n\toff = tp->snd_nxt - tp->snd_una;\n\twin = min(tp->snd_wnd, tp->snd_cwnd);\n\n\tflags = tcp_outflags[tp->t_state];\n\n\tDEBUG_MISC((dfd, \" --- tcp_output flags = 0x%x\\n\",flags));\n\n\t/*\n\t * If in persist timeout with window of 0, send 1 byte.\n\t * Otherwise, if window is small but nonzero\n\t * and timer expired, we will send what we can\n\t * and go to transmit state.\n\t */\n\tif (tp->t_force) {\n\t\tif (win == 0) {\n\t\t\t/*\n\t\t\t * If we still have some data to send, then\n\t\t\t * clear the FIN bit. Usually this would\n\t\t\t * happen below when it realizes that we\n\t\t\t * aren't sending all the data. However,\n\t\t\t * if we have exactly 1 byte of unset data,\n\t\t\t * then it won't clear the FIN bit below,\n\t\t\t * and if we are in persist state, we wind\n\t\t\t * up sending the packet without recording\n\t\t\t * that we sent the FIN bit.\n\t\t\t *\n\t\t\t * We can't just blindly clear the FIN bit,\n\t\t\t * because if we don't have any more data\n\t\t\t * to send then the probe will be the FIN\n\t\t\t * itself.\n\t\t\t */\n\t\t\tif (off < so->so_snd.sb_cc)\n\t\t\t\tflags &= ~TH_FIN;\n\t\t\twin = 1;\n\t\t} else {\n\t\t\ttp->t_timer[TCPT_PERSIST] = 0;\n\t\t\ttp->t_rxtshift = 0;\n\t\t}\n\t}\n\n\tlen = min(so->so_snd.sb_cc, win) - off;\n\n\tif (len < 0) {\n\t\t/*\n\t\t * If FIN has been sent but not acked,\n\t\t * but we haven't been called to retransmit,\n\t\t * len will be -1. Otherwise, window shrank\n\t\t * after we sent into it. If window shrank to 0,\n\t\t * cancel pending retransmit and pull snd_nxt\n\t\t * back to (closed) window. We will enter persist\n\t\t * state below. If the window didn't close completely,\n\t\t * just wait for an ACK.\n\t\t */\n\t\tlen = 0;\n\t\tif (win == 0) {\n\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\ttp->snd_nxt = tp->snd_una;\n\t\t}\n\t}\n\n\tif (len > tp->t_maxseg) {\n\t\tlen = tp->t_maxseg;\n\t\tsendalot = 1;\n\t}\n\tif (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc))\n\t\tflags &= ~TH_FIN;\n\n\twin = sbspace(&so->so_rcv);\n\n\t/*\n\t * Sender silly window avoidance. If connection is idle\n\t * and can send all data, a maximum segment,\n\t * at least a maximum default-size segment do it,\n\t * or are forced, do it; otherwise don't bother.\n\t * If peer's buffer is tiny, then send\n\t * when window is at least half open.\n\t * If retransmitting (possibly after persist timer forced us\n\t * to send into a small window), then must resend.\n\t */\n\tif (len) {\n\t\tif (len == tp->t_maxseg)\n\t\t\tgoto send;\n\t\tif ((1 || idle || tp->t_flags & TF_NODELAY) &&\n\t\t len + off >= so->so_snd.sb_cc)\n\t\t\tgoto send;\n\t\tif (tp->t_force)\n\t\t\tgoto send;\n\t\tif (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)\n\t\t\tgoto send;\n\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_max))\n\t\t\tgoto send;\n\t}\n\n\t/*\n\t * Compare available window to amount of window\n\t * known to peer (as advertised window less\n\t * next expected input). If the difference is at least two\n\t * max size segments, or at least 50% of the maximum possible\n\t * window, then want to send a window update to peer.\n\t */\n\tif (win > 0) {\n\t\t/*\n\t\t * \"adv\" is the amount we can increase the window,\n\t\t * taking into account that we are limited by\n\t\t * TCP_MAXWIN << tp->rcv_scale.\n\t\t */\n\t\tlong adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -\n\t\t\t(tp->rcv_adv - tp->rcv_nxt);\n\n\t\tif (adv >= (long) (2 * tp->t_maxseg))\n\t\t\tgoto send;\n\t\tif (2 * adv >= (long) so->so_rcv.sb_datalen)\n\t\t\tgoto send;\n\t}\n\n\t/*\n\t * Send if we owe peer an ACK.\n\t */\n\tif (tp->t_flags & TF_ACKNOW)\n\t\tgoto send;\n\tif (flags & (TH_SYN|TH_RST))\n\t\tgoto send;\n\tif (SEQ_GT(tp->snd_up, tp->snd_una))\n\t\tgoto send;\n\t/*\n\t * If our state indicates that FIN should be sent\n\t * and we have not yet done so, or we're retransmitting the FIN,\n\t * then we need to send.\n\t */\n\tif (flags & TH_FIN &&\n\t ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))\n\t\tgoto send;\n\n\t/*\n\t * TCP window updates are not reliable, rather a polling protocol\n\t * using ``persist'' packets is used to insure receipt of window\n\t * updates. The three ``states'' for the output side are:\n\t *\tidle\t\t\tnot doing retransmits or persists\n\t *\tpersisting\t\tto move a small or zero window\n\t *\t(re)transmitting\tand thereby not persisting\n\t *\n\t * tp->t_timer[TCPT_PERSIST]\n\t *\tis set when we are in persist state.\n\t * tp->t_force\n\t *\tis set when we are called to send a persist packet.\n\t * tp->t_timer[TCPT_REXMT]\n\t *\tis set when we are retransmitting\n\t * The output side is idle when both timers are zero.\n\t *\n\t * If send window is too small, there is data to transmit, and no\n\t * retransmit or persist is pending, then go to persist state.\n\t * If nothing happens soon, send when timer expires:\n\t * if window is nonzero, transmit what we can,\n\t * otherwise force out a byte.\n\t */\n\tif (so->so_snd.sb_cc && tp->t_timer[TCPT_REXMT] == 0 &&\n\t tp->t_timer[TCPT_PERSIST] == 0) {\n\t\ttp->t_rxtshift = 0;\n\t\ttcp_setpersist(tp);\n\t}\n\n\t/*\n\t * No reason to send a segment, just return.\n\t */\n\treturn (0);\n\nsend:\n\t/*\n\t * Before ESTABLISHED, force sending of initial options\n\t * unless TCP set not to do any options.\n\t * NOTE: we assume that the IP/TCP header plus TCP options\n\t * always fit in a single mbuf, leaving room for a maximum\n\t * link header, i.e.\n\t *\tmax_linkhdr + sizeof (struct tcpiphdr) + optlen <= MHLEN\n\t */\n\toptlen = 0;\n\thdrlen = sizeof (struct tcpiphdr);\n\tif (flags & TH_SYN) {\n\t\ttp->snd_nxt = tp->iss;\n\t\tif ((tp->t_flags & TF_NOOPT) == 0) {\n\t\t\tuint16_t mss;\n\n\t\t\topt[0] = TCPOPT_MAXSEG;\n\t\t\topt[1] = 4;\n\t\t\tmss = htons((uint16_t) tcp_mss(tp, 0));\n\t\t\tmemcpy((caddr_t)(opt + 2), (caddr_t)&mss, sizeof(mss));\n\t\t\toptlen = 4;\n\t\t}\n \t}\n\n \thdrlen += optlen;\n\n\t/*\n\t * Adjust data length if insertion of options will\n\t * bump the packet length beyond the t_maxseg length.\n\t */\n\t if (len > tp->t_maxseg - optlen) {\n\t\tlen = tp->t_maxseg - optlen;\n\t\tsendalot = 1;\n\t }\n\n\t/*\n\t * Grab a header mbuf, attaching a copy of data to\n\t * be transmitted, and initialize the header from\n\t * the template for sends on this connection.\n\t */\n\tif (len) {\n\t\tm = m_get(so->slirp);\n\t\tif (m == NULL) {\n\t\t\terror = 1;\n\t\t\tgoto out;\n\t\t}\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\tm->m_len = hdrlen;\n\n\t\tsbcopy(&so->so_snd, off, (int) len, mtod(m, caddr_t) + hdrlen);\n\t\tm->m_len += len;\n\n\t\t/*\n\t\t * If we're sending everything we've got, set PUSH.\n\t\t * (This will keep happy those implementations which only\n\t\t * give data to the user when a buffer fills or\n\t\t * a PUSH comes in.)\n\t\t */\n\t\tif (off + len == so->so_snd.sb_cc)\n\t\t\tflags |= TH_PUSH;\n\t} else {\n\t\tm = m_get(so->slirp);\n\t\tif (m == NULL) {\n\t\t\terror = 1;\n\t\t\tgoto out;\n\t\t}\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\tm->m_len = hdrlen;\n\t}\n\n\tti = mtod(m, struct tcpiphdr *);\n\n\tmemcpy((caddr_t)ti, &tp->t_template, sizeof (struct tcpiphdr));\n\n\t/*\n\t * Fill in fields, remembering maximum advertised\n\t * window for use in delaying messages about window sizes.\n\t * If resending a FIN, be sure not to use a new sequence number.\n\t */\n\tif (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&\n\t tp->snd_nxt == tp->snd_max)\n\t\ttp->snd_nxt--;\n\t/*\n\t * If we are doing retransmissions, then snd_nxt will\n\t * not reflect the first unsent octet. For ACK only\n\t * packets, we do not want the sequence number of the\n\t * retransmitted packet, we want the sequence number\n\t * of the next unsent octet. So, if there is no data\n\t * (and no SYN or FIN), use snd_max instead of snd_nxt\n\t * when filling in ti_seq. But if we are in persist\n\t * state, snd_max might reflect one byte beyond the\n\t * right edge of the window, so use snd_nxt in that\n\t * case, since we know we aren't doing a retransmission.\n\t * (retransmit and persist are mutually exclusive...)\n\t */\n\tif (len || (flags & (TH_SYN|TH_FIN)) || tp->t_timer[TCPT_PERSIST])\n\t\tti->ti_seq = htonl(tp->snd_nxt);\n\telse\n\t\tti->ti_seq = htonl(tp->snd_max);\n\tti->ti_ack = htonl(tp->rcv_nxt);\n\tif (optlen) {\n\t\tmemcpy((caddr_t)(ti + 1), (caddr_t)opt, optlen);\n\t\tti->ti_off = (sizeof (struct tcphdr) + optlen) >> 2;\n\t}\n\tti->ti_flags = flags;\n\t/*\n\t * Calculate receive window. Don't shrink window,\n\t * but avoid silly window syndrome.\n\t */\n\tif (win < (long)(so->so_rcv.sb_datalen / 4) && win < (long)tp->t_maxseg)\n\t\twin = 0;\n\tif (win > (long)TCP_MAXWIN << tp->rcv_scale)\n\t\twin = (long)TCP_MAXWIN << tp->rcv_scale;\n\tif (win < (long)(tp->rcv_adv - tp->rcv_nxt))\n\t\twin = (long)(tp->rcv_adv - tp->rcv_nxt);\n\tti->ti_win = htons((uint16_t) (win>>tp->rcv_scale));\n\n\tif (SEQ_GT(tp->snd_up, tp->snd_una)) {\n\t\tti->ti_urp = htons((uint16_t)(tp->snd_up - ntohl(ti->ti_seq)));\n\t\tti->ti_flags |= TH_URG;\n\t} else\n\t\t/*\n\t\t * If no urgent pointer to send, then we pull\n\t\t * the urgent pointer to the left edge of the send window\n\t\t * so that it doesn't drift into the send window on sequence\n\t\t * number wraparound.\n\t\t */\n\t\ttp->snd_up = tp->snd_una;\t\t/* drag it along */\n\n\t/*\n\t * Put TCP length in extended header, and then\n\t * checksum extended header and data.\n\t */\n\tif (len + optlen)\n\t\tti->ti_len = htons((uint16_t)(sizeof (struct tcphdr) +\n\t\t optlen + len));\n\tti->ti_sum = cksum(m, (int)(hdrlen + len));\n\n\t/*\n\t * In transmit state, time the transmission and arrange for\n\t * the retransmit. In persist state, just set snd_max.\n\t */\n\tif (tp->t_force == 0 || tp->t_timer[TCPT_PERSIST] == 0) {\n\t\ttcp_seq startseq = tp->snd_nxt;\n\n\t\t/*\n\t\t * Advance snd_nxt over sequence space of this segment.\n\t\t */\n\t\tif (flags & (TH_SYN|TH_FIN)) {\n\t\t\tif (flags & TH_SYN)\n\t\t\t\ttp->snd_nxt++;\n\t\t\tif (flags & TH_FIN) {\n\t\t\t\ttp->snd_nxt++;\n\t\t\t\ttp->t_flags |= TF_SENTFIN;\n\t\t\t}\n\t\t}\n\t\ttp->snd_nxt += len;\n\t\tif (SEQ_GT(tp->snd_nxt, tp->snd_max)) {\n\t\t\ttp->snd_max = tp->snd_nxt;\n\t\t\t/*\n\t\t\t * Time this transmission if not a retransmission and\n\t\t\t * not currently timing anything.\n\t\t\t */\n\t\t\tif (tp->t_rtt == 0) {\n\t\t\t\ttp->t_rtt = 1;\n\t\t\t\ttp->t_rtseq = startseq;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Set retransmit timer if not currently set,\n\t\t * and not doing an ack or a keep-alive probe.\n\t\t * Initial value for retransmit timer is smoothed\n\t\t * round-trip time + 2 * round-trip time variance.\n\t\t * Initialize shift counter which is used for backoff\n\t\t * of retransmit time.\n\t\t */\n\t\tif (tp->t_timer[TCPT_REXMT] == 0 &&\n\t\t tp->snd_nxt != tp->snd_una) {\n\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t\tif (tp->t_timer[TCPT_PERSIST]) {\n\t\t\t\ttp->t_timer[TCPT_PERSIST] = 0;\n\t\t\t\ttp->t_rxtshift = 0;\n\t\t\t}\n\t\t}\n\t} else\n\t\tif (SEQ_GT(tp->snd_nxt + len, tp->snd_max))\n\t\t\ttp->snd_max = tp->snd_nxt + len;\n\n\t/*\n\t * Fill in IP length and desired time to live and\n\t * send to IP level. There should be a better way\n\t * to handle ttl and tos; we could keep them in\n\t * the template, but need a way to checksum without them.\n\t */\n\tm->m_len = hdrlen + len; /* XXX Needed? m_len should be correct */\n\n {\n\n\t((struct ip *)ti)->ip_len = m->m_len;\n\n\t((struct ip *)ti)->ip_ttl = IPDEFTTL;\n\t((struct ip *)ti)->ip_tos = so->so_iptos;\n\n\terror = ip_output(so, m);\n }\n\tif (error) {\nout:\n\t\treturn (error);\n\t}\n\n\t/*\n\t * Data sent (as far as we can tell).\n\t * If this advertises a larger window than any other segment,\n\t * then remember the size of the advertised window.\n\t * Any pending ACK has now been sent.\n\t */\n\tif (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))\n\t\ttp->rcv_adv = tp->rcv_nxt + win;\n\ttp->last_ack_sent = tp->rcv_nxt;\n\ttp->t_flags &= ~(TF_ACKNOW|TF_DELACK);\n\tif (sendalot)\n\t\tgoto again;\n\n\treturn (0);\n}\n\nvoid\ntcp_setpersist(struct tcpcb *tp)\n{\n int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;\n\n\t/*\n\t * Start/restart persistence timer.\n\t */\n\tTCPT_RANGESET(tp->t_timer[TCPT_PERSIST],\n\t t * tcp_backoff[tp->t_rxtshift],\n\t TCPTV_PERSMIN, TCPTV_PERSMAX);\n\tif (tp->t_rxtshift < TCP_MAXRXTSHIFT)\n\t\ttp->t_rxtshift++;\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_input.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_input.c\t8.2 (Berkeley) 1/4/94\n * ip_input.c,v 1.11 1994/11/16 10:17:08 jkh Exp\n */\n\n/*\n * Changes and additions relating to SLiRP are\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n#define container_of(ptr, type, member) ({ \\\n const typeof( ((type *)0)->member ) *__mptr = (ptr); \\\n (type *)( (char *)__mptr - offsetof(type,member) );})\n\nstatic struct ip *ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp);\nstatic void ip_freef(Slirp *slirp, struct ipq *fp);\nstatic void ip_enq(register struct ipasfrag *p,\n register struct ipasfrag *prev);\nstatic void ip_deq(register struct ipasfrag *p);\n\n/*\n * IP initialization: fill in IP protocol switch table.\n * All protocols not implemented in kernel go to raw IP protocol handler.\n */\nvoid\nip_init(Slirp *slirp)\n{\n slirp->ipq.ip_link.next = slirp->ipq.ip_link.prev = &slirp->ipq.ip_link;\n udp_init(slirp);\n tcp_init(slirp);\n}\n\n/*\n * Ip input routine. Checksum and byte swap header. If fragmented\n * try to reassemble. Process options. Pass to next level.\n */\nvoid\nip_input(struct mbuf *m)\n{\n\tSlirp *slirp = m->slirp;\n\tregister struct ip *ip;\n\tint hlen;\n\n\tDEBUG_CALL(\"ip_input\");\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"m_len = %d\", m->m_len);\n\n\tif (m->m_len < sizeof (struct ip)) {\n\t\treturn;\n\t}\n\n\tip = mtod(m, struct ip *);\n\n\tif (ip->ip_v != IPVERSION) {\n\t\tgoto bad;\n\t}\n\n\thlen = ip->ip_hl << 2;\n\tif (hlenm->m_len) {/* min header length */\n\t goto bad; /* or packet too short */\n\t}\n\n /* keep ip header intact for ICMP reply\n\t * ip->ip_sum = cksum(m, hlen);\n\t * if (ip->ip_sum) {\n\t */\n\tif(cksum(m,hlen)) {\n\t goto bad;\n\t}\n\n\t/*\n\t * Convert fields to host representation.\n\t */\n\tNTOHS(ip->ip_len);\n\tif (ip->ip_len < hlen) {\n\t\tgoto bad;\n\t}\n\tNTOHS(ip->ip_id);\n\tNTOHS(ip->ip_off);\n\n\t/*\n\t * Check that the amount of data in the buffers\n\t * is as at least much as the IP header would have us expect.\n\t * Trim mbufs if longer than we expect.\n\t * Drop packet if shorter than we expect.\n\t */\n\tif (m->m_len < ip->ip_len) {\n\t\tgoto bad;\n\t}\n\n if (slirp->restricted) {\n if ((ip->ip_dst.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n if (ip->ip_dst.s_addr == 0xffffffff && ip->ip_p != IPPROTO_UDP)\n goto bad;\n } else {\n uint32_t inv_mask = ~slirp->vnetwork_mask.s_addr;\n struct ex_list *ex_ptr;\n\n if ((ip->ip_dst.s_addr & inv_mask) == inv_mask) {\n goto bad;\n }\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)\n if (ex_ptr->ex_addr.s_addr == ip->ip_dst.s_addr)\n break;\n\n if (!ex_ptr)\n goto bad;\n }\n }\n\n\t/* Should drop packet if mbuf too long? hmmm... */\n\tif (m->m_len > ip->ip_len)\n\t m_adj(m, ip->ip_len - m->m_len);\n\n\t/* check ip_ttl for a correct ICMP reply */\n\tif(ip->ip_ttl==0) {\n\t icmp_error(m, ICMP_TIMXCEED,ICMP_TIMXCEED_INTRANS, 0,\"ttl\");\n\t goto bad;\n\t}\n\n\t/*\n\t * If offset or IP_MF are set, must reassemble.\n\t * Otherwise, nothing need be done.\n\t * (We could look in the reassembly queue to see\n\t * if the packet was previously fragmented,\n\t * but it's not worth the time; just let them time out.)\n\t *\n\t * XXX This should fail, don't fragment yet\n\t */\n\tif (ip->ip_off &~ IP_DF) {\n\t register struct ipq *fp;\n struct qlink *l;\n\t\t/*\n\t\t * Look for queue of fragments\n\t\t * of this datagram.\n\t\t */\n\t\tfor (l = slirp->ipq.ip_link.next; l != &slirp->ipq.ip_link;\n\t\t l = l->next) {\n fp = container_of(l, struct ipq, ip_link);\n if (ip->ip_id == fp->ipq_id &&\n ip->ip_src.s_addr == fp->ipq_src.s_addr &&\n ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&\n ip->ip_p == fp->ipq_p)\n\t\t goto found;\n }\n fp = NULL;\n\tfound:\n\n\t\t/*\n\t\t * Adjust ip_len to not reflect header,\n\t\t * set ip_mff if more fragments are expected,\n\t\t * convert offset of this to bytes.\n\t\t */\n\t\tip->ip_len -= hlen;\n\t\tif (ip->ip_off & IP_MF)\n\t\t ip->ip_tos |= 1;\n\t\telse\n\t\t ip->ip_tos &= ~1;\n\n\t\tip->ip_off <<= 3;\n\n\t\t/*\n\t\t * If datagram marked as having more fragments\n\t\t * or if this is not the first fragment,\n\t\t * attempt reassembly; if it succeeds, proceed.\n\t\t */\n\t\tif (ip->ip_tos & 1 || ip->ip_off) {\n\t\t\tip = ip_reass(slirp, ip, fp);\n if (ip == NULL)\n\t\t\t\treturn;\n\t\t\tm = dtom(slirp, ip);\n\t\t} else\n\t\t\tif (fp)\n\t\t \t ip_freef(slirp, fp);\n\n\t} else\n\t\tip->ip_len -= hlen;\n\n\t/*\n\t * Switch out to protocol's input routine.\n\t */\n\tswitch (ip->ip_p) {\n\t case IPPROTO_TCP:\n\t\ttcp_input(m, hlen, (struct socket *)NULL);\n\t\tbreak;\n\t case IPPROTO_UDP:\n\t\tudp_input(m, hlen);\n\t\tbreak;\n\t case IPPROTO_ICMP:\n\t\ticmp_input(m, hlen);\n\t\tbreak;\n\t default:\n\t\tm_free(m);\n\t}\n\treturn;\nbad:\n\tm_freem(m);\n\treturn;\n}\n\n#define iptofrag(P) ((struct ipasfrag *)(((char*)(P)) - sizeof(struct qlink)))\n#define fragtoip(P) ((struct ip*)(((char*)(P)) + sizeof(struct qlink)))\n/*\n * Take incoming datagram fragment and try to\n * reassemble it into whole datagram. If a chain for\n * reassembly of this datagram already exists, then it\n * is given as fp; otherwise have to make a chain.\n */\nstatic struct ip *\nip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)\n{\n\tregister struct mbuf *m = dtom(slirp, ip);\n\tregister struct ipasfrag *q;\n\tint hlen = ip->ip_hl << 2;\n\tint i, next;\n\n\tDEBUG_CALL(\"ip_reass\");\n\tDEBUG_ARG(\"ip = %lx\", (long)ip);\n\tDEBUG_ARG(\"fp = %lx\", (long)fp);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n\t/*\n\t * Presence of header sizes in mbufs\n\t * would confuse code below.\n * Fragment m_data is concatenated.\n\t */\n\tm->m_data += hlen;\n\tm->m_len -= hlen;\n\n\t/*\n\t * If first fragment to arrive, create a reassembly queue.\n\t */\n if (fp == NULL) {\n\t struct mbuf *t = m_get(slirp);\n\n\t if (t == NULL) {\n\t goto dropfrag;\n\t }\n\t fp = mtod(t, struct ipq *);\n\t insque(&fp->ip_link, &slirp->ipq.ip_link);\n\t fp->ipq_ttl = IPFRAGTTL;\n\t fp->ipq_p = ip->ip_p;\n\t fp->ipq_id = ip->ip_id;\n\t fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;\n\t fp->ipq_src = ip->ip_src;\n\t fp->ipq_dst = ip->ip_dst;\n\t q = (struct ipasfrag *)fp;\n\t goto insert;\n\t}\n\n\t/*\n\t * Find a segment which begins after this one does.\n\t */\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next)\n\t\tif (q->ipf_off > ip->ip_off)\n\t\t\tbreak;\n\n\t/*\n\t * If there is a preceding segment, it may provide some of\n\t * our data already. If so, drop the data from the incoming\n\t * segment. If it provides all of our data, drop us.\n\t */\n\tif (q->ipf_prev != &fp->frag_link) {\n struct ipasfrag *pq = q->ipf_prev;\n\t\ti = pq->ipf_off + pq->ipf_len - ip->ip_off;\n\t\tif (i > 0) {\n\t\t\tif (i >= ip->ip_len)\n\t\t\t\tgoto dropfrag;\n\t\t\tm_adj(dtom(slirp, ip), i);\n\t\t\tip->ip_off += i;\n\t\t\tip->ip_len -= i;\n\t\t}\n\t}\n\n\t/*\n\t * While we overlap succeeding segments trim them or,\n\t * if they are completely covered, dequeue them.\n\t */\n\twhile (q != (struct ipasfrag*)&fp->frag_link &&\n ip->ip_off + ip->ip_len > q->ipf_off) {\n\t\ti = (ip->ip_off + ip->ip_len) - q->ipf_off;\n\t\tif (i < q->ipf_len) {\n\t\t\tq->ipf_len -= i;\n\t\t\tq->ipf_off += i;\n\t\t\tm_adj(dtom(slirp, q), i);\n\t\t\tbreak;\n\t\t}\n\t\tq = q->ipf_next;\n\t\tm_freem(dtom(slirp, q->ipf_prev));\n\t\tip_deq(q->ipf_prev);\n\t}\n\ninsert:\n\t/*\n\t * Stick new segment in its place;\n\t * check for complete reassembly.\n\t */\n\tip_enq(iptofrag(ip), q->ipf_prev);\n\tnext = 0;\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link;\n q = q->ipf_next) {\n\t\tif (q->ipf_off != next)\n return NULL;\n\t\tnext += q->ipf_len;\n\t}\n\tif (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)\n return NULL;\n\n\t/*\n\t * Reassembly is complete; concatenate fragments.\n\t */\n q = fp->frag_link.next;\n\tm = dtom(slirp, q);\n\n\tq = (struct ipasfrag *) q->ipf_next;\n\twhile (q != (struct ipasfrag*)&fp->frag_link) {\n\t struct mbuf *t = dtom(slirp, q);\n\t q = (struct ipasfrag *) q->ipf_next;\n\t m_cat(m, t);\n\t}\n\n\t/*\n\t * Create header for new ip packet by\n\t * modifying header of first packet;\n\t * dequeue and discard fragment reassembly header.\n\t * Make header visible.\n\t */\n\tq = fp->frag_link.next;\n\n\t/*\n\t * If the fragments concatenated to an mbuf that's\n\t * bigger than the total size of the fragment, then and\n\t * m_ext buffer was alloced. But fp->ipq_next points to\n\t * the old buffer (in the mbuf), so we must point ip\n\t * into the new buffer.\n\t */\n\tif (m->m_flags & M_EXT) {\n\t int delta = (char *)q - m->m_dat;\n\t q = (struct ipasfrag *)(m->m_ext + delta);\n\t}\n\n ip = fragtoip(q);\n\tip->ip_len = next;\n\tip->ip_tos &= ~1;\n\tip->ip_src = fp->ipq_src;\n\tip->ip_dst = fp->ipq_dst;\n\tremque(&fp->ip_link);\n\t(void) m_free(dtom(slirp, fp));\n\tm->m_len += (ip->ip_hl << 2);\n\tm->m_data -= (ip->ip_hl << 2);\n\n\treturn ip;\n\ndropfrag:\n\tm_freem(m);\n return NULL;\n}\n\n/*\n * Free a fragment reassembly header and all\n * associated datagrams.\n */\nstatic void\nip_freef(Slirp *slirp, struct ipq *fp)\n{\n\tregister struct ipasfrag *q, *p;\n\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link; q = p) {\n\t\tp = q->ipf_next;\n\t\tip_deq(q);\n\t\tm_freem(dtom(slirp, q));\n\t}\n\tremque(&fp->ip_link);\n\t(void) m_free(dtom(slirp, fp));\n}\n\n/*\n * Put an ip fragment on a reassembly chain.\n * Like insque, but pointers in middle of structure.\n */\nstatic void\nip_enq(register struct ipasfrag *p, register struct ipasfrag *prev)\n{\n\tDEBUG_CALL(\"ip_enq\");\n\tDEBUG_ARG(\"prev = %lx\", (long)prev);\n\tp->ipf_prev = prev;\n\tp->ipf_next = prev->ipf_next;\n\t((struct ipasfrag *)(prev->ipf_next))->ipf_prev = p;\n\tprev->ipf_next = p;\n}\n\n/*\n * To ip_enq as remque is to insque.\n */\nstatic void\nip_deq(register struct ipasfrag *p)\n{\n\t((struct ipasfrag *)(p->ipf_prev))->ipf_next = p->ipf_next;\n\t((struct ipasfrag *)(p->ipf_next))->ipf_prev = p->ipf_prev;\n}\n\n/*\n * IP timer processing;\n * if a timer expires on a reassembly\n * queue, discard it.\n */\nvoid\nip_slowtimo(Slirp *slirp)\n{\n struct qlink *l;\n\n\tDEBUG_CALL(\"ip_slowtimo\");\n\n l = slirp->ipq.ip_link.next;\n\n if (l == NULL)\n\t return;\n\n while (l != &slirp->ipq.ip_link) {\n struct ipq *fp = container_of(l, struct ipq, ip_link);\n l = l->next;\n\t\tif (--fp->ipq_ttl == 0) {\n\t\t\tip_freef(slirp, fp);\n\t\t}\n }\n}\n\n/*\n * Do option processing on a datagram,\n * possibly discarding it if bad options are encountered,\n * or forwarding it if source-routed.\n * Returns 1 if packet has been forwarded/freed,\n * 0 if the packet should be processed further.\n */\n\n#ifdef notdef\n\nint\nip_dooptions(m)\n\tstruct mbuf *m;\n{\n\tregister struct ip *ip = mtod(m, struct ip *);\n\tregister u_char *cp;\n\tregister struct ip_timestamp *ipt;\n\tregister struct in_ifaddr *ia;\n\tint opt, optlen, cnt, off, code, type, forward = 0;\n\tstruct in_addr *sin, dst;\ntypedef uint32_t n_time;\n\tn_time ntime;\n\n\tdst = ip->ip_dst;\n\tcp = (u_char *)(ip + 1);\n\tcnt = (ip->ip_hl << 2) - sizeof (struct ip);\n\tfor (; cnt > 0; cnt -= optlen, cp += optlen) {\n\t\topt = cp[IPOPT_OPTVAL];\n\t\tif (opt == IPOPT_EOL)\n\t\t\tbreak;\n\t\tif (opt == IPOPT_NOP)\n\t\t\toptlen = 1;\n\t\telse {\n\t\t\toptlen = cp[IPOPT_OLEN];\n\t\t\tif (optlen <= 0 || optlen > cnt) {\n\t\t\t\tcode = &cp[IPOPT_OLEN] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t}\n\t\tswitch (opt) {\n\n\t\tdefault:\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Source routing with record.\n\t\t * Find interface with current destination address.\n\t\t * If none on this machine then drop if strictly routed,\n\t\t * or do nothing if loosely routed.\n\t\t * Record interface address and bring up next address\n\t\t * component. If strictly routed make sure next\n\t\t * address is on directly accessible net.\n\t\t */\n\t\tcase IPOPT_LSRR:\n\t\tcase IPOPT_SSRR:\n\t\t\tif ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {\n\t\t\t\tcode = &cp[IPOPT_OFFSET] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tipaddr.sin_addr = ip->ip_dst;\n\t\t\tia = (struct in_ifaddr *)\n\t\t\t\tifa_ifwithaddr((struct sockaddr *)&ipaddr);\n\t\t\tif (ia == 0) {\n\t\t\t\tif (opt == IPOPT_SSRR) {\n\t\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\t\tcode = ICMP_UNREACH_SRCFAIL;\n\t\t\t\t\tgoto bad;\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Loose routing, and not at next destination\n\t\t\t\t * yet; nothing to do except forward.\n\t\t\t\t */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toff--;\t\t\t/ * 0 origin * /\n\t\t\tif (off > optlen - sizeof(struct in_addr)) {\n\t\t\t\t/*\n\t\t\t\t * End of source route. Should be for us.\n\t\t\t\t */\n\t\t\t\tsave_rte(cp, ip->ip_src);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/*\n\t\t\t * locate outgoing interface\n\t\t\t */\n\t\t\tbcopy((caddr_t)(cp + off), (caddr_t)&ipaddr.sin_addr,\n\t\t\t sizeof(ipaddr.sin_addr));\n\t\t\tif (opt == IPOPT_SSRR) {\n#define\tINA\tstruct in_ifaddr *\n#define\tSA\tstruct sockaddr *\n \t\t\t if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)\n\t\t\t\tia = (INA)ifa_ifwithnet((SA)&ipaddr);\n\t\t\t} else\n\t\t\t\tia = ip_rtaddr(ipaddr.sin_addr);\n\t\t\tif (ia == 0) {\n\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\tcode = ICMP_UNREACH_SRCFAIL;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tip->ip_dst = ipaddr.sin_addr;\n\t\t\tbcopy((caddr_t)&(IA_SIN(ia)->sin_addr),\n\t\t\t (caddr_t)(cp + off), sizeof(struct in_addr));\n\t\t\tcp[IPOPT_OFFSET] += sizeof(struct in_addr);\n\t\t\t/*\n\t\t\t * Let ip_intr's mcast routing check handle mcast pkts\n\t\t\t */\n\t\t\tforward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));\n\t\t\tbreak;\n\n\t\tcase IPOPT_RR:\n\t\t\tif ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {\n\t\t\t\tcode = &cp[IPOPT_OFFSET] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\t/*\n\t\t\t * If no space remains, ignore.\n\t\t\t */\n\t\t\toff--;\t\t\t * 0 origin *\n\t\t\tif (off > optlen - sizeof(struct in_addr))\n\t\t\t\tbreak;\n\t\t\tbcopy((caddr_t)(&ip->ip_dst), (caddr_t)&ipaddr.sin_addr,\n\t\t\t sizeof(ipaddr.sin_addr));\n\t\t\t/*\n\t\t\t * locate outgoing interface; if we're the destination,\n\t\t\t * use the incoming interface (should be same).\n\t\t\t */\n\t\t\tif ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&\n\t\t\t (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {\n\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\tcode = ICMP_UNREACH_HOST;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tbcopy((caddr_t)&(IA_SIN(ia)->sin_addr),\n\t\t\t (caddr_t)(cp + off), sizeof(struct in_addr));\n\t\t\tcp[IPOPT_OFFSET] += sizeof(struct in_addr);\n\t\t\tbreak;\n\n\t\tcase IPOPT_TS:\n\t\t\tcode = cp - (u_char *)ip;\n\t\t\tipt = (struct ip_timestamp *)cp;\n\t\t\tif (ipt->ipt_len < 5)\n\t\t\t\tgoto bad;\n\t\t\tif (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {\n\t\t\t\tif (++ipt->ipt_oflw == 0)\n\t\t\t\t\tgoto bad;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);\n\t\t\tswitch (ipt->ipt_flg) {\n\n\t\t\tcase IPOPT_TS_TSONLY:\n\t\t\t\tbreak;\n\n\t\t\tcase IPOPT_TS_TSANDADDR:\n\t\t\t\tif (ipt->ipt_ptr + sizeof(n_time) +\n\t\t\t\t sizeof(struct in_addr) > ipt->ipt_len)\n\t\t\t\t\tgoto bad;\n\t\t\t\tipaddr.sin_addr = dst;\n\t\t\t\tia = (INA)ifaof_ i f p foraddr((SA)&ipaddr,\n\t\t\t\t\t\t\t m->m_pkthdr.rcvif);\n\t\t\t\tif (ia == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tbcopy((caddr_t)&IA_SIN(ia)->sin_addr,\n\t\t\t\t (caddr_t)sin, sizeof(struct in_addr));\n\t\t\t\tipt->ipt_ptr += sizeof(struct in_addr);\n\t\t\t\tbreak;\n\n\t\t\tcase IPOPT_TS_PRESPEC:\n\t\t\t\tif (ipt->ipt_ptr + sizeof(n_time) +\n\t\t\t\t sizeof(struct in_addr) > ipt->ipt_len)\n\t\t\t\t\tgoto bad;\n\t\t\t\tbcopy((caddr_t)sin, (caddr_t)&ipaddr.sin_addr,\n\t\t\t\t sizeof(struct in_addr));\n\t\t\t\tif (ifa_ifwithaddr((SA)&ipaddr) == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tipt->ipt_ptr += sizeof(struct in_addr);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tntime = iptime();\n\t\t\tbcopy((caddr_t)&ntime, (caddr_t)cp + ipt->ipt_ptr - 1,\n\t\t\t sizeof(n_time));\n\t\t\tipt->ipt_ptr += sizeof(n_time);\n\t\t}\n\t}\n\tif (forward) {\n\t\tip_forward(m, 1);\n\t\treturn (1);\n\t}\n\treturn (0);\nbad:\n \ticmp_error(m, type, code, 0, 0);\n\n\treturn (1);\n}\n\n#endif /* notdef */\n\n/*\n * Strip out IP options, at higher\n * level protocol in the kernel.\n * Second argument is buffer to which options\n * will be moved, and return value is their length.\n * (XXX) should be deleted; last arg currently ignored.\n */\nvoid\nip_stripoptions(register struct mbuf *m, struct mbuf *mopt)\n{\n\tregister int i;\n\tstruct ip *ip = mtod(m, struct ip *);\n\tregister caddr_t opts;\n\tint olen;\n\n\tolen = (ip->ip_hl<<2) - sizeof (struct ip);\n\topts = (caddr_t)(ip + 1);\n\ti = m->m_len - (sizeof (struct ip) + olen);\n\tmemcpy(opts, opts + olen, (unsigned)i);\n\tm->m_len -= olen;\n\n\tip->ip_hl = sizeof(struct ip) >> 2;\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_timer.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_timer.c\t8.1 (Berkeley) 6/10/93\n * tcp_timer.c,v 1.2 1994/08/02 07:49:10 davidg Exp\n */\n\n#include \"slirp.h\"\n\nstatic struct tcpcb *tcp_timers(register struct tcpcb *tp, int timer);\n\n/*\n * Fast timeout routine for processing delayed acks\n */\nvoid\ntcp_fasttimo(Slirp *slirp)\n{\n\tregister struct socket *so;\n\tregister struct tcpcb *tp;\n\n\tDEBUG_CALL(\"tcp_fasttimo\");\n\n\tso = slirp->tcb.so_next;\n\tif (so)\n\tfor (; so != &slirp->tcb; so = so->so_next)\n\t\tif ((tp = (struct tcpcb *)so->so_tcpcb) &&\n\t\t (tp->t_flags & TF_DELACK)) {\n\t\t\ttp->t_flags &= ~TF_DELACK;\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\t(void) tcp_output(tp);\n\t\t}\n}\n\n/*\n * Tcp protocol timeout routine called every 500 ms.\n * Updates the timers in all active tcb's and\n * causes finite state machine actions if timers expire.\n */\nvoid\ntcp_slowtimo(Slirp *slirp)\n{\n\tregister struct socket *ip, *ipnxt;\n\tregister struct tcpcb *tp;\n\tregister int i;\n\n\tDEBUG_CALL(\"tcp_slowtimo\");\n\n\t/*\n\t * Search through tcb's and update active timers.\n\t */\n\tip = slirp->tcb.so_next;\n if (ip == NULL) {\n return;\n }\n\tfor (; ip != &slirp->tcb; ip = ipnxt) {\n\t\tipnxt = ip->so_next;\n\t\ttp = sototcpcb(ip);\n if (tp == NULL) {\n continue;\n }\n\t\tfor (i = 0; i < TCPT_NTIMERS; i++) {\n\t\t\tif (tp->t_timer[i] && --tp->t_timer[i] == 0) {\n\t\t\t\ttcp_timers(tp,i);\n\t\t\t\tif (ipnxt->so_prev != ip)\n\t\t\t\t\tgoto tpgone;\n\t\t\t}\n\t\t}\n\t\ttp->t_idle++;\n\t\tif (tp->t_rtt)\n\t\t tp->t_rtt++;\ntpgone:\n\t\t;\n\t}\n\tslirp->tcp_iss += TCP_ISSINCR/PR_SLOWHZ;\t/* increment iss */\n\tslirp->tcp_now++;\t\t\t\t/* for timestamps */\n}\n\n/*\n * Cancel all timers for TCP tp.\n */\nvoid\ntcp_canceltimers(struct tcpcb *tp)\n{\n\tregister int i;\n\n\tfor (i = 0; i < TCPT_NTIMERS; i++)\n\t\ttp->t_timer[i] = 0;\n}\n\nconst int tcp_backoff[TCP_MAXRXTSHIFT + 1] =\n { 1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64 };\n\n/*\n * TCP timer processing.\n */\nstatic struct tcpcb *\ntcp_timers(register struct tcpcb *tp, int timer)\n{\n\tregister int rexmt;\n\n\tDEBUG_CALL(\"tcp_timers\");\n\n\tswitch (timer) {\n\n\t/*\n\t * 2 MSL timeout in shutdown went off. If we're closed but\n\t * still waiting for peer to close and connection has been idle\n\t * too long, or if 2MSL time is up from TIME_WAIT, delete connection\n\t * control block. Otherwise, check again in a bit.\n\t */\n\tcase TCPT_2MSL:\n\t\tif (tp->t_state != TCPS_TIME_WAIT &&\n\t\t tp->t_idle <= TCP_MAXIDLE)\n\t\t\ttp->t_timer[TCPT_2MSL] = TCPTV_KEEPINTVL;\n\t\telse\n\t\t\ttp = tcp_close(tp);\n\t\tbreak;\n\n\t/*\n\t * Retransmission timer went off. Message has not\n\t * been acked within retransmit interval. Back off\n\t * to a longer retransmit interval and retransmit one segment.\n\t */\n\tcase TCPT_REXMT:\n\n\t\t/*\n\t\t * XXXXX If a packet has timed out, then remove all the queued\n\t\t * packets for that session.\n\t\t */\n\n\t\tif (++tp->t_rxtshift > TCP_MAXRXTSHIFT) {\n\t\t\t/*\n\t\t\t * This is a hack to suit our terminal server here at the uni of canberra\n\t\t\t * since they have trouble with zeroes... It usually lets them through\n\t\t\t * unharmed, but under some conditions, it'll eat the zeros. If we\n\t\t\t * keep retransmitting it, it'll keep eating the zeroes, so we keep\n\t\t\t * retransmitting, and eventually the connection dies...\n\t\t\t * (this only happens on incoming data)\n\t\t\t *\n\t\t\t * So, if we were gonna drop the connection from too many retransmits,\n\t\t\t * don't... instead halve the t_maxseg, which might break up the NULLs and\n\t\t\t * let them through\n\t\t\t *\n\t\t\t * *sigh*\n\t\t\t */\n\n\t\t\ttp->t_maxseg >>= 1;\n\t\t\tif (tp->t_maxseg < 32) {\n\t\t\t\t/*\n\t\t\t\t * We tried our best, now the connection must die!\n\t\t\t\t */\n\t\t\t\ttp->t_rxtshift = TCP_MAXRXTSHIFT;\n\t\t\t\ttp = tcp_drop(tp, tp->t_softerror);\n\t\t\t\t/* tp->t_softerror : ETIMEDOUT); */ /* XXX */\n\t\t\t\treturn (tp); /* XXX */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set rxtshift to 6, which is still at the maximum\n\t\t\t * backoff time\n\t\t\t */\n\t\t\ttp->t_rxtshift = 6;\n\t\t}\n\t\trexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];\n\t\tTCPT_RANGESET(tp->t_rxtcur, rexmt,\n\t\t (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */\n\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t/*\n\t\t * If losing, let the lower level know and try for\n\t\t * a better route. Also, if we backed off this far,\n\t\t * our srtt estimate is probably bogus. Clobber it\n\t\t * so we'll take the next rtt measurement as our srtt;\n\t\t * move the current srtt into rttvar to keep the current\n\t\t * retransmit times until then.\n\t\t */\n\t\tif (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {\n\t\t\ttp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);\n\t\t\ttp->t_srtt = 0;\n\t\t}\n\t\ttp->snd_nxt = tp->snd_una;\n\t\t/*\n\t\t * If timing a segment in this window, stop the timer.\n\t\t */\n\t\ttp->t_rtt = 0;\n\t\t/*\n\t\t * Close the congestion window down to one segment\n\t\t * (we'll open it by one segment for each ack we get).\n\t\t * Since we probably have a window's worth of unacked\n\t\t * data accumulated, this \"slow start\" keeps us from\n\t\t * dumping all that data as back-to-back packets (which\n\t\t * might overwhelm an intermediate gateway).\n\t\t *\n\t\t * There are two phases to the opening: Initially we\n\t\t * open by one mss on each ack. This makes the window\n\t\t * size increase exponentially with time. If the\n\t\t * window is larger than the path can handle, this\n\t\t * exponential growth results in dropped packet(s)\n\t\t * almost immediately. To get more time between\n\t\t * drops but still \"push\" the network to take advantage\n\t\t * of improving conditions, we switch from exponential\n\t\t * to linear window opening at some threshold size.\n\t\t * For a threshold, we use half the current window\n\t\t * size, truncated to a multiple of the mss.\n\t\t *\n\t\t * (the minimum cwnd that will give us exponential\n\t\t * growth is 2 mss. We don't allow the threshold\n\t\t * to go below this.)\n\t\t */\n\t\t{\n\t\tu_int win = min(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg;\n\t\tif (win < 2)\n\t\t\twin = 2;\n\t\ttp->snd_cwnd = tp->t_maxseg;\n\t\ttp->snd_ssthresh = win * tp->t_maxseg;\n\t\ttp->t_dupacks = 0;\n\t\t}\n\t\t(void) tcp_output(tp);\n\t\tbreak;\n\n\t/*\n\t * Persistence timer into zero window.\n\t * Force a byte to be output, if possible.\n\t */\n\tcase TCPT_PERSIST:\n\t\ttcp_setpersist(tp);\n\t\ttp->t_force = 1;\n\t\t(void) tcp_output(tp);\n\t\ttp->t_force = 0;\n\t\tbreak;\n\n\t/*\n\t * Keep-alive timer went off; send something\n\t * or drop connection if idle for too long.\n\t */\n\tcase TCPT_KEEP:\n\t\tif (tp->t_state < TCPS_ESTABLISHED)\n\t\t\tgoto dropit;\n\n\t\tif ((SO_OPTIONS) && tp->t_state <= TCPS_CLOSE_WAIT) {\n\t\t \tif (tp->t_idle >= TCPTV_KEEP_IDLE + TCP_MAXIDLE)\n\t\t\t\tgoto dropit;\n\t\t\t/*\n\t\t\t * Send a packet designed to force a response\n\t\t\t * if the peer is up and reachable:\n\t\t\t * either an ACK if the connection is still alive,\n\t\t\t * or an RST if the peer has closed the connection\n\t\t\t * due to timeout or reboot.\n\t\t\t * Using sequence number tp->snd_una-1\n\t\t\t * causes the transmitted zero-length segment\n\t\t\t * to lie outside the receive window;\n\t\t\t * by the protocol spec, this requires the\n\t\t\t * correspondent TCP to respond.\n\t\t\t */\n\t\t\ttcp_respond(tp, &tp->t_template, (struct mbuf *)NULL,\n\t\t\t tp->rcv_nxt, tp->snd_una - 1, 0);\n\t\t\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;\n\t\t} else\n\t\t\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;\n\t\tbreak;\n\n\tdropit:\n\t\ttp = tcp_drop(tp, 0);\n\t\tbreak;\n\t}\n\n\treturn (tp);\n}\n"], ["/linuxpdf/tinyemu/slirp/if.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n#define ifs_init(ifm) ((ifm)->ifs_next = (ifm)->ifs_prev = (ifm))\n\nstatic void\nifs_insque(struct mbuf *ifm, struct mbuf *ifmhead)\n{\n\tifm->ifs_next = ifmhead->ifs_next;\n\tifmhead->ifs_next = ifm;\n\tifm->ifs_prev = ifmhead;\n\tifm->ifs_next->ifs_prev = ifm;\n}\n\nstatic void\nifs_remque(struct mbuf *ifm)\n{\n\tifm->ifs_prev->ifs_next = ifm->ifs_next;\n\tifm->ifs_next->ifs_prev = ifm->ifs_prev;\n}\n\nvoid\nif_init(Slirp *slirp)\n{\n slirp->if_fastq.ifq_next = slirp->if_fastq.ifq_prev = &slirp->if_fastq;\n slirp->if_batchq.ifq_next = slirp->if_batchq.ifq_prev = &slirp->if_batchq;\n slirp->next_m = &slirp->if_batchq;\n}\n\n/*\n * if_output: Queue packet into an output queue.\n * There are 2 output queue's, if_fastq and if_batchq.\n * Each output queue is a doubly linked list of double linked lists\n * of mbufs, each list belonging to one \"session\" (socket). This\n * way, we can output packets fairly by sending one packet from each\n * session, instead of all the packets from one session, then all packets\n * from the next session, etc. Packets on the if_fastq get absolute\n * priority, but if one session hogs the link, it gets \"downgraded\"\n * to the batchq until it runs out of packets, then it'll return\n * to the fastq (eg. if the user does an ls -alR in a telnet session,\n * it'll temporarily get downgraded to the batchq)\n */\nvoid\nif_output(struct socket *so, struct mbuf *ifm)\n{\n\tSlirp *slirp = ifm->slirp;\n\tstruct mbuf *ifq;\n\tint on_fastq = 1;\n\n\tDEBUG_CALL(\"if_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"ifm = %lx\", (long)ifm);\n\n\t/*\n\t * First remove the mbuf from m_usedlist,\n\t * since we're gonna use m_next and m_prev ourselves\n\t * XXX Shouldn't need this, gotta change dtom() etc.\n\t */\n\tif (ifm->m_flags & M_USEDLIST) {\n\t\tremque(ifm);\n\t\tifm->m_flags &= ~M_USEDLIST;\n\t}\n\n\t/*\n\t * See if there's already a batchq list for this session.\n\t * This can include an interactive session, which should go on fastq,\n\t * but gets too greedy... hence it'll be downgraded from fastq to batchq.\n\t * We mustn't put this packet back on the fastq (or we'll send it out of order)\n\t * XXX add cache here?\n\t */\n\tfor (ifq = slirp->if_batchq.ifq_prev; ifq != &slirp->if_batchq;\n\t ifq = ifq->ifq_prev) {\n\t\tif (so == ifq->ifq_so) {\n\t\t\t/* A match! */\n\t\t\tifm->ifq_so = so;\n\t\t\tifs_insque(ifm, ifq->ifs_prev);\n\t\t\tgoto diddit;\n\t\t}\n\t}\n\n\t/* No match, check which queue to put it on */\n\tif (so && (so->so_iptos & IPTOS_LOWDELAY)) {\n\t\tifq = slirp->if_fastq.ifq_prev;\n\t\ton_fastq = 1;\n\t\t/*\n\t\t * Check if this packet is a part of the last\n\t\t * packet's session\n\t\t */\n\t\tif (ifq->ifq_so == so) {\n\t\t\tifm->ifq_so = so;\n\t\t\tifs_insque(ifm, ifq->ifs_prev);\n\t\t\tgoto diddit;\n\t\t}\n\t} else\n\t\tifq = slirp->if_batchq.ifq_prev;\n\n\t/* Create a new doubly linked list for this session */\n\tifm->ifq_so = so;\n\tifs_init(ifm);\n\tinsque(ifm, ifq);\n\ndiddit:\n\tslirp->if_queued++;\n\n\tif (so) {\n\t\t/* Update *_queued */\n\t\tso->so_queued++;\n\t\tso->so_nqueued++;\n\t\t/*\n\t\t * Check if the interactive session should be downgraded to\n\t\t * the batchq. A session is downgraded if it has queued 6\n\t\t * packets without pausing, and at least 3 of those packets\n\t\t * have been sent over the link\n\t\t * (XXX These are arbitrary numbers, probably not optimal..)\n\t\t */\n\t\tif (on_fastq && ((so->so_nqueued >= 6) &&\n\t\t\t\t (so->so_nqueued - so->so_queued) >= 3)) {\n\n\t\t\t/* Remove from current queue... */\n\t\t\tremque(ifm->ifs_next);\n\n\t\t\t/* ...And insert in the new. That'll teach ya! */\n\t\t\tinsque(ifm->ifs_next, &slirp->if_batchq);\n\t\t}\n\t}\n\n#ifndef FULL_BOLT\n\t/*\n\t * This prevents us from malloc()ing too many mbufs\n\t */\n\tif_start(ifm->slirp);\n#endif\n}\n\n/*\n * Send a packet\n * We choose a packet based on it's position in the output queues;\n * If there are packets on the fastq, they are sent FIFO, before\n * everything else. Otherwise we choose the first packet from the\n * batchq and send it. the next packet chosen will be from the session\n * after this one, then the session after that one, and so on.. So,\n * for example, if there are 3 ftp session's fighting for bandwidth,\n * one packet will be sent from the first session, then one packet\n * from the second session, then one packet from the third, then back\n * to the first, etc. etc.\n */\nvoid\nif_start(Slirp *slirp)\n{\n\tstruct mbuf *ifm, *ifqt;\n\n\tDEBUG_CALL(\"if_start\");\n\n\tif (slirp->if_queued == 0)\n\t return; /* Nothing to do */\n\n again:\n /* check if we can really output */\n if (!slirp_can_output(slirp->opaque))\n return;\n\n\t/*\n\t * See which queue to get next packet from\n\t * If there's something in the fastq, select it immediately\n\t */\n\tif (slirp->if_fastq.ifq_next != &slirp->if_fastq) {\n\t\tifm = slirp->if_fastq.ifq_next;\n\t} else {\n\t\t/* Nothing on fastq, see if next_m is valid */\n\t\tif (slirp->next_m != &slirp->if_batchq)\n\t\t ifm = slirp->next_m;\n\t\telse\n\t\t ifm = slirp->if_batchq.ifq_next;\n\n\t\t/* Set which packet to send on next iteration */\n\t\tslirp->next_m = ifm->ifq_next;\n\t}\n\t/* Remove it from the queue */\n\tifqt = ifm->ifq_prev;\n\tremque(ifm);\n\tslirp->if_queued--;\n\n\t/* If there are more packets for this session, re-queue them */\n\tif (ifm->ifs_next != /* ifm->ifs_prev != */ ifm) {\n\t\tinsque(ifm->ifs_next, ifqt);\n\t\tifs_remque(ifm);\n\t}\n\n\t/* Update so_queued */\n\tif (ifm->ifq_so) {\n\t\tif (--ifm->ifq_so->so_queued == 0)\n\t\t /* If there's no more queued, reset nqueued */\n\t\t ifm->ifq_so->so_nqueued = 0;\n\t}\n\n\t/* Encapsulate the packet for sending */\n if_encap(slirp, (uint8_t *)ifm->m_data, ifm->m_len);\n\n m_free(ifm);\n\n\tif (slirp->if_queued)\n\t goto again;\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_output.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_output.c\t8.3 (Berkeley) 1/21/94\n * ip_output.c,v 1.9 1994/11/16 10:17:10 jkh Exp\n */\n\n/*\n * Changes and additions relating to SLiRP are\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n/* Number of packets queued before we start sending\n * (to prevent allocing too many mbufs) */\n#define IF_THRESH 10\n\n/*\n * IP output. The packet in mbuf chain m contains a skeletal IP\n * header (with len, off, ttl, proto, tos, src, dst).\n * The mbuf chain containing the packet will be freed.\n * The mbuf opt, if present, will not be freed.\n */\nint\nip_output(struct socket *so, struct mbuf *m0)\n{\n\tSlirp *slirp = m0->slirp;\n\tregister struct ip *ip;\n\tregister struct mbuf *m = m0;\n\tregister int hlen = sizeof(struct ip );\n\tint len, off, error = 0;\n\n\tDEBUG_CALL(\"ip_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m0 = %lx\", (long)m0);\n\n\tip = mtod(m, struct ip *);\n\t/*\n\t * Fill in IP header.\n\t */\n\tip->ip_v = IPVERSION;\n\tip->ip_off &= IP_DF;\n\tip->ip_id = htons(slirp->ip_id++);\n\tip->ip_hl = hlen >> 2;\n\n\t/*\n\t * If small enough for interface, can just send directly.\n\t */\n\tif ((uint16_t)ip->ip_len <= IF_MTU) {\n\t\tip->ip_len = htons((uint16_t)ip->ip_len);\n\t\tip->ip_off = htons((uint16_t)ip->ip_off);\n\t\tip->ip_sum = 0;\n\t\tip->ip_sum = cksum(m, hlen);\n\n\t\tif_output(so, m);\n\t\tgoto done;\n\t}\n\n\t/*\n\t * Too large for interface; fragment if possible.\n\t * Must be able to put at least 8 bytes per fragment.\n\t */\n\tif (ip->ip_off & IP_DF) {\n\t\terror = -1;\n\t\tgoto bad;\n\t}\n\n\tlen = (IF_MTU - hlen) &~ 7; /* ip databytes per packet */\n\tif (len < 8) {\n\t\terror = -1;\n\t\tgoto bad;\n\t}\n\n {\n\tint mhlen, firstlen = len;\n\tstruct mbuf **mnext = &m->m_nextpkt;\n\n\t/*\n\t * Loop through length of segment after first fragment,\n\t * make new header and copy data of each part and link onto chain.\n\t */\n\tm0 = m;\n\tmhlen = sizeof (struct ip);\n\tfor (off = hlen + len; off < (uint16_t)ip->ip_len; off += len) {\n\t register struct ip *mhip;\n\t m = m_get(slirp);\n if (m == NULL) {\n\t error = -1;\n\t goto sendorfree;\n\t }\n\t m->m_data += IF_MAXLINKHDR;\n\t mhip = mtod(m, struct ip *);\n\t *mhip = *ip;\n\n\t m->m_len = mhlen;\n\t mhip->ip_off = ((off - hlen) >> 3) + (ip->ip_off & ~IP_MF);\n\t if (ip->ip_off & IP_MF)\n\t mhip->ip_off |= IP_MF;\n\t if (off + len >= (uint16_t)ip->ip_len)\n\t len = (uint16_t)ip->ip_len - off;\n\t else\n\t mhip->ip_off |= IP_MF;\n\t mhip->ip_len = htons((uint16_t)(len + mhlen));\n\n\t if (m_copy(m, m0, off, len) < 0) {\n\t error = -1;\n\t goto sendorfree;\n\t }\n\n\t mhip->ip_off = htons((uint16_t)mhip->ip_off);\n\t mhip->ip_sum = 0;\n\t mhip->ip_sum = cksum(m, mhlen);\n\t *mnext = m;\n\t mnext = &m->m_nextpkt;\n\t}\n\t/*\n\t * Update first fragment by trimming what's been copied out\n\t * and updating header, then send each fragment (in order).\n\t */\n\tm = m0;\n\tm_adj(m, hlen + firstlen - (uint16_t)ip->ip_len);\n\tip->ip_len = htons((uint16_t)m->m_len);\n\tip->ip_off = htons((uint16_t)(ip->ip_off | IP_MF));\n\tip->ip_sum = 0;\n\tip->ip_sum = cksum(m, hlen);\nsendorfree:\n\tfor (m = m0; m; m = m0) {\n\t\tm0 = m->m_nextpkt;\n m->m_nextpkt = NULL;\n\t\tif (error == 0)\n\t\t\tif_output(so, m);\n\t\telse\n\t\t\tm_freem(m);\n\t}\n }\n\ndone:\n\treturn (error);\n\nbad:\n\tm_freem(m0);\n\tgoto done;\n}\n"], ["/linuxpdf/tinyemu/slirp/mbuf.c", "/*\n * Copyright (c) 1995 Danny Gasparovski\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n/*\n * mbuf's in SLiRP are much simpler than the real mbufs in\n * FreeBSD. They are fixed size, determined by the MTU,\n * so that one whole packet can fit. Mbuf's cannot be\n * chained together. If there's more data than the mbuf\n * could hold, an external malloced buffer is pointed to\n * by m_ext (and the data pointers) and M_EXT is set in\n * the flags\n */\n\n#include \"slirp.h\"\n\n#define MBUF_THRESH 30\n\n/*\n * Find a nice value for msize\n * XXX if_maxlinkhdr already in mtu\n */\n#define SLIRP_MSIZE (IF_MTU + IF_MAXLINKHDR + offsetof(struct mbuf, m_dat) + 6)\n\nvoid\nm_init(Slirp *slirp)\n{\n slirp->m_freelist.m_next = slirp->m_freelist.m_prev = &slirp->m_freelist;\n slirp->m_usedlist.m_next = slirp->m_usedlist.m_prev = &slirp->m_usedlist;\n}\n\n/*\n * Get an mbuf from the free list, if there are none\n * malloc one\n *\n * Because fragmentation can occur if we alloc new mbufs and\n * free old mbufs, we mark all mbufs above mbuf_thresh as M_DOFREE,\n * which tells m_free to actually free() it\n */\nstruct mbuf *\nm_get(Slirp *slirp)\n{\n\tregister struct mbuf *m;\n\tint flags = 0;\n\n\tDEBUG_CALL(\"m_get\");\n\n\tif (slirp->m_freelist.m_next == &slirp->m_freelist) {\n\t\tm = (struct mbuf *)malloc(SLIRP_MSIZE);\n\t\tif (m == NULL) goto end_error;\n\t\tslirp->mbuf_alloced++;\n\t\tif (slirp->mbuf_alloced > MBUF_THRESH)\n\t\t\tflags = M_DOFREE;\n\t\tm->slirp = slirp;\n\t} else {\n\t\tm = slirp->m_freelist.m_next;\n\t\tremque(m);\n\t}\n\n\t/* Insert it in the used list */\n\tinsque(m,&slirp->m_usedlist);\n\tm->m_flags = (flags | M_USEDLIST);\n\n\t/* Initialise it */\n\tm->m_size = SLIRP_MSIZE - offsetof(struct mbuf, m_dat);\n\tm->m_data = m->m_dat;\n\tm->m_len = 0;\n m->m_nextpkt = NULL;\n m->m_prevpkt = NULL;\nend_error:\n\tDEBUG_ARG(\"m = %lx\", (long )m);\n\treturn m;\n}\n\nvoid\nm_free(struct mbuf *m)\n{\n\n DEBUG_CALL(\"m_free\");\n DEBUG_ARG(\"m = %lx\", (long )m);\n\n if(m) {\n\t/* Remove from m_usedlist */\n\tif (m->m_flags & M_USEDLIST)\n\t remque(m);\n\n\t/* If it's M_EXT, free() it */\n\tif (m->m_flags & M_EXT)\n\t free(m->m_ext);\n\n\t/*\n\t * Either free() it or put it on the free list\n\t */\n\tif (m->m_flags & M_DOFREE) {\n\t\tm->slirp->mbuf_alloced--;\n\t\tfree(m);\n\t} else if ((m->m_flags & M_FREELIST) == 0) {\n\t\tinsque(m,&m->slirp->m_freelist);\n\t\tm->m_flags = M_FREELIST; /* Clobber other flags */\n\t}\n } /* if(m) */\n}\n\n/*\n * Copy data from one mbuf to the end of\n * the other.. if result is too big for one mbuf, malloc()\n * an M_EXT data segment\n */\nvoid\nm_cat(struct mbuf *m, struct mbuf *n)\n{\n\t/*\n\t * If there's no room, realloc\n\t */\n\tif (M_FREEROOM(m) < n->m_len)\n\t\tm_inc(m,m->m_size+MINCSIZE);\n\n\tmemcpy(m->m_data+m->m_len, n->m_data, n->m_len);\n\tm->m_len += n->m_len;\n\n\tm_free(n);\n}\n\n\n/* make m size bytes large */\nvoid\nm_inc(struct mbuf *m, int size)\n{\n\tint datasize;\n\n\t/* some compiles throw up on gotos. This one we can fake. */\n if(m->m_size>size) return;\n\n if (m->m_flags & M_EXT) {\n\t datasize = m->m_data - m->m_ext;\n\t m->m_ext = (char *)realloc(m->m_ext,size);\n\t m->m_data = m->m_ext + datasize;\n } else {\n\t char *dat;\n\t datasize = m->m_data - m->m_dat;\n\t dat = (char *)malloc(size);\n\t memcpy(dat, m->m_dat, m->m_size);\n\n\t m->m_ext = dat;\n\t m->m_data = m->m_ext + datasize;\n\t m->m_flags |= M_EXT;\n }\n\n m->m_size = size;\n\n}\n\n\n\nvoid\nm_adj(struct mbuf *m, int len)\n{\n\tif (m == NULL)\n\t\treturn;\n\tif (len >= 0) {\n\t\t/* Trim from head */\n\t\tm->m_data += len;\n\t\tm->m_len -= len;\n\t} else {\n\t\t/* Trim from tail */\n\t\tlen = -len;\n\t\tm->m_len -= len;\n\t}\n}\n\n\n/*\n * Copy len bytes from m, starting off bytes into n\n */\nint\nm_copy(struct mbuf *n, struct mbuf *m, int off, int len)\n{\n\tif (len > M_FREEROOM(n))\n\t\treturn -1;\n\n\tmemcpy((n->m_data + n->m_len), (m->m_data + off), len);\n\tn->m_len += len;\n\treturn 0;\n}\n\n\n/*\n * Given a pointer into an mbuf, return the mbuf\n * XXX This is a kludge, I should eliminate the need for it\n * Fortunately, it's not used often\n */\nstruct mbuf *\ndtom(Slirp *slirp, void *dat)\n{\n\tstruct mbuf *m;\n\n\tDEBUG_CALL(\"dtom\");\n\tDEBUG_ARG(\"dat = %lx\", (long )dat);\n\n\t/* bug corrected for M_EXT buffers */\n\tfor (m = slirp->m_usedlist.m_next; m != &slirp->m_usedlist;\n\t m = m->m_next) {\n\t if (m->m_flags & M_EXT) {\n\t if( (char *)dat>=m->m_ext && (char *)dat<(m->m_ext + m->m_size) )\n\t return m;\n\t } else {\n\t if( (char *)dat >= m->m_dat && (char *)dat<(m->m_dat + m->m_size) )\n\t return m;\n\t }\n\t}\n\n\tDEBUG_ERROR((dfd, \"dtom failed\"));\n\n\treturn (struct mbuf *)0;\n}\n"], ["/linuxpdf/tinyemu/x86_machine.c", "/*\n * PC emulator\n * \n * Copyright (c) 2011-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"x86_cpu.h\"\n#include \"machine.h\"\n#include \"pci.h\"\n#include \"ide.h\"\n#include \"ps2.h\"\n\n#if defined(__linux__) && (defined(__i386__) || defined(__x86_64__))\n#define USE_KVM\n#endif\n\n#ifdef USE_KVM\n#include \n#include \n#include \n#include \n#include \n#endif\n\n//#define DEBUG_BIOS\n//#define DUMP_IOPORT\n\n/***********************************************************/\n/* cmos emulation */\n\n//#define DEBUG_CMOS\n\n#define RTC_SECONDS 0\n#define RTC_SECONDS_ALARM 1\n#define RTC_MINUTES 2\n#define RTC_MINUTES_ALARM 3\n#define RTC_HOURS 4\n#define RTC_HOURS_ALARM 5\n#define RTC_ALARM_DONT_CARE 0xC0\n\n#define RTC_DAY_OF_WEEK 6\n#define RTC_DAY_OF_MONTH 7\n#define RTC_MONTH 8\n#define RTC_YEAR 9\n\n#define RTC_REG_A 10\n#define RTC_REG_B 11\n#define RTC_REG_C 12\n#define RTC_REG_D 13\n\n#define REG_A_UIP 0x80\n\n#define REG_B_SET 0x80\n#define REG_B_PIE 0x40\n#define REG_B_AIE 0x20\n#define REG_B_UIE 0x10\n\ntypedef struct {\n uint8_t cmos_index;\n uint8_t cmos_data[128];\n IRQSignal *irq;\n BOOL use_local_time;\n /* used for the periodic irq */\n uint32_t irq_timeout;\n uint32_t irq_period;\n} CMOSState;\n\nstatic void cmos_write(void *opaque, uint32_t offset,\n uint32_t data, int size_log2);\nstatic uint32_t cmos_read(void *opaque, uint32_t offset, int size_log2);\n\nstatic int to_bcd(CMOSState *s, unsigned int a)\n{\n if (s->cmos_data[RTC_REG_B] & 0x04) {\n return a;\n } else {\n return ((a / 10) << 4) | (a % 10);\n }\n}\n\nstatic void cmos_update_time(CMOSState *s, BOOL set_century)\n{\n struct timeval tv;\n struct tm tm;\n time_t ti;\n int val;\n \n gettimeofday(&tv, NULL);\n ti = tv.tv_sec;\n if (s->use_local_time) {\n localtime_r(&ti, &tm);\n } else {\n gmtime_r(&ti, &tm);\n }\n \n s->cmos_data[RTC_SECONDS] = to_bcd(s, tm.tm_sec);\n s->cmos_data[RTC_MINUTES] = to_bcd(s, tm.tm_min);\n if (s->cmos_data[RTC_REG_B] & 0x02) {\n s->cmos_data[RTC_HOURS] = to_bcd(s, tm.tm_hour);\n } else {\n s->cmos_data[RTC_HOURS] = to_bcd(s, tm.tm_hour % 12);\n if (tm.tm_hour >= 12)\n s->cmos_data[RTC_HOURS] |= 0x80;\n }\n s->cmos_data[RTC_DAY_OF_WEEK] = to_bcd(s, tm.tm_wday);\n s->cmos_data[RTC_DAY_OF_MONTH] = to_bcd(s, tm.tm_mday);\n s->cmos_data[RTC_MONTH] = to_bcd(s, tm.tm_mon + 1);\n s->cmos_data[RTC_YEAR] = to_bcd(s, tm.tm_year % 100);\n\n if (set_century) {\n /* not set by the hardware, but easier to do it here */\n val = to_bcd(s, (tm.tm_year / 100) + 19);\n s->cmos_data[0x32] = val;\n s->cmos_data[0x37] = val;\n }\n \n /* update in progress flag: 8/32768 seconds after change */\n if (tv.tv_usec < 244) {\n s->cmos_data[RTC_REG_A] |= REG_A_UIP;\n } else {\n s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;\n }\n}\n\nCMOSState *cmos_init(PhysMemoryMap *port_map, int addr,\n IRQSignal *irq, BOOL use_local_time)\n{\n CMOSState *s;\n \n s = mallocz(sizeof(*s));\n s->use_local_time = use_local_time;\n \n s->cmos_index = 0;\n\n s->cmos_data[RTC_REG_A] = 0x26;\n s->cmos_data[RTC_REG_B] = 0x02;\n s->cmos_data[RTC_REG_C] = 0x00;\n s->cmos_data[RTC_REG_D] = 0x80;\n\n cmos_update_time(s, TRUE);\n \n s->irq = irq;\n \n cpu_register_device(port_map, addr, 2, s, cmos_read, cmos_write, \n DEVIO_SIZE8);\n return s;\n}\n\n#define CMOS_FREQ 32768\n\nstatic uint32_t cmos_get_timer(CMOSState *s)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint32_t)ts.tv_sec * CMOS_FREQ +\n ((uint64_t)ts.tv_nsec * CMOS_FREQ / 1000000000);\n}\n\nstatic void cmos_update_timer(CMOSState *s)\n{\n int period_code;\n\n period_code = s->cmos_data[RTC_REG_A] & 0x0f;\n if ((s->cmos_data[RTC_REG_B] & REG_B_PIE) &&\n period_code != 0) {\n if (period_code <= 2)\n period_code += 7;\n s->irq_period = 1 << (period_code - 1);\n s->irq_timeout = (cmos_get_timer(s) + s->irq_period) &\n ~(s->irq_period - 1);\n }\n}\n\n/* XXX: could return a delay, but we don't need high precision\n (Windows 2000 uses it for delay calibration) */\nstatic void cmos_update_irq(CMOSState *s)\n{\n uint32_t d;\n if (s->cmos_data[RTC_REG_B] & REG_B_PIE) {\n d = cmos_get_timer(s) - s->irq_timeout;\n if ((int32_t)d >= 0) {\n /* this is not what the real RTC does. Here we sent the IRQ\n immediately */\n s->cmos_data[RTC_REG_C] |= 0xc0;\n set_irq(s->irq, 1);\n /* update for the next irq */\n s->irq_timeout += s->irq_period;\n }\n }\n}\n\nstatic void cmos_write(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n CMOSState *s = opaque;\n\n if (offset == 0) {\n s->cmos_index = data & 0x7f;\n } else {\n#ifdef DEBUG_CMOS\n printf(\"cmos_write: reg=0x%02x val=0x%02x\\n\", s->cmos_index, data);\n#endif\n switch(s->cmos_index) {\n case RTC_REG_A:\n s->cmos_data[RTC_REG_A] = (data & ~REG_A_UIP) |\n (s->cmos_data[RTC_REG_A] & REG_A_UIP);\n cmos_update_timer(s);\n break;\n case RTC_REG_B:\n s->cmos_data[s->cmos_index] = data;\n cmos_update_timer(s);\n break;\n default:\n s->cmos_data[s->cmos_index] = data;\n break;\n }\n }\n}\n\nstatic uint32_t cmos_read(void *opaque, uint32_t offset, int size_log2)\n{\n CMOSState *s = opaque;\n int ret;\n\n if (offset == 0) {\n return 0xff;\n } else {\n switch(s->cmos_index) {\n case RTC_SECONDS:\n case RTC_MINUTES:\n case RTC_HOURS:\n case RTC_DAY_OF_WEEK:\n case RTC_DAY_OF_MONTH:\n case RTC_MONTH:\n case RTC_YEAR:\n case RTC_REG_A:\n cmos_update_time(s, FALSE);\n ret = s->cmos_data[s->cmos_index];\n break;\n case RTC_REG_C:\n ret = s->cmos_data[s->cmos_index];\n s->cmos_data[RTC_REG_C] = 0x00;\n set_irq(s->irq, 0);\n break;\n default:\n ret = s->cmos_data[s->cmos_index];\n }\n#ifdef DEBUG_CMOS\n printf(\"cmos_read: reg=0x%02x val=0x%02x\\n\", s->cmos_index, ret);\n#endif\n return ret;\n }\n}\n\n/***********************************************************/\n/* 8259 pic emulation */\n\n//#define DEBUG_PIC\n\ntypedef void PICUpdateIRQFunc(void *opaque);\n\ntypedef struct {\n uint8_t last_irr; /* edge detection */\n uint8_t irr; /* interrupt request register */\n uint8_t imr; /* interrupt mask register */\n uint8_t isr; /* interrupt service register */\n uint8_t priority_add; /* used to compute irq priority */\n uint8_t irq_base;\n uint8_t read_reg_select;\n uint8_t special_mask;\n uint8_t init_state;\n uint8_t auto_eoi;\n uint8_t rotate_on_autoeoi;\n uint8_t init4; /* true if 4 byte init */\n uint8_t elcr; /* PIIX edge/trigger selection*/\n uint8_t elcr_mask;\n PICUpdateIRQFunc *update_irq;\n void *opaque;\n} PICState;\n\nstatic void pic_reset(PICState *s);\nstatic void pic_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pic_read(void *opaque, uint32_t offset, int size_log2);\nstatic void pic_elcr_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pic_elcr_read(void *opaque, uint32_t offset, int size_log2);\n\nPICState *pic_init(PhysMemoryMap *port_map, int port, int elcr_port,\n int elcr_mask,\n PICUpdateIRQFunc *update_irq, void *opaque)\n{\n PICState *s;\n\n s = mallocz(sizeof(*s));\n s->elcr_mask = elcr_mask;\n s->update_irq = update_irq;\n s->opaque = opaque;\n cpu_register_device(port_map, port, 2, s,\n pic_read, pic_write, DEVIO_SIZE8);\n cpu_register_device(port_map, elcr_port, 1, s,\n pic_elcr_read, pic_elcr_write, DEVIO_SIZE8);\n pic_reset(s);\n return s;\n}\n\nstatic void pic_reset(PICState *s)\n{\n /* all 8 bit registers */\n s->last_irr = 0; /* edge detection */\n s->irr = 0; /* interrupt request register */\n s->imr = 0; /* interrupt mask register */\n s->isr = 0; /* interrupt service register */\n s->priority_add = 0; /* used to compute irq priority */\n s->irq_base = 0;\n s->read_reg_select = 0;\n s->special_mask = 0;\n s->init_state = 0;\n s->auto_eoi = 0;\n s->rotate_on_autoeoi = 0;\n s->init4 = 0; /* true if 4 byte init */\n}\n\n/* set irq level. If an edge is detected, then the IRR is set to 1 */\nstatic void pic_set_irq1(PICState *s, int irq, int level)\n{\n int mask;\n mask = 1 << irq;\n if (s->elcr & mask) {\n /* level triggered */\n if (level) {\n s->irr |= mask;\n s->last_irr |= mask;\n } else {\n s->irr &= ~mask;\n s->last_irr &= ~mask;\n }\n } else {\n /* edge triggered */\n if (level) {\n if ((s->last_irr & mask) == 0)\n s->irr |= mask;\n s->last_irr |= mask;\n } else {\n s->last_irr &= ~mask;\n }\n }\n}\n \nstatic int pic_get_priority(PICState *s, int mask)\n{\n int priority;\n if (mask == 0)\n return -1;\n priority = 7;\n while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)\n priority--;\n return priority;\n}\n\n/* return the pic wanted interrupt. return -1 if none */\nstatic int pic_get_irq(PICState *s)\n{\n int mask, cur_priority, priority;\n\n mask = s->irr & ~s->imr;\n priority = pic_get_priority(s, mask);\n if (priority < 0)\n return -1;\n /* compute current priority */\n cur_priority = pic_get_priority(s, s->isr);\n if (priority > cur_priority) {\n /* higher priority found: an irq should be generated */\n return priority;\n } else {\n return -1;\n }\n}\n \n/* acknowledge interrupt 'irq' */\nstatic void pic_intack(PICState *s, int irq)\n{\n if (s->auto_eoi) {\n if (s->rotate_on_autoeoi)\n s->priority_add = (irq + 1) & 7;\n } else {\n s->isr |= (1 << irq);\n }\n /* We don't clear a level sensitive interrupt here */\n if (!(s->elcr & (1 << irq)))\n s->irr &= ~(1 << irq);\n}\n\nstatic void pic_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PICState *s = opaque;\n int priority, addr;\n \n addr = offset & 1;\n#ifdef DEBUG_PIC\n console.log(\"pic_write: addr=\" + toHex2(addr) + \" val=\" + toHex2(val));\n#endif\n if (addr == 0) {\n if (val & 0x10) {\n /* init */\n pic_reset(s);\n s->init_state = 1;\n s->init4 = val & 1;\n if (val & 0x02)\n abort(); /* \"single mode not supported\" */\n if (val & 0x08)\n abort(); /* \"level sensitive irq not supported\" */\n } else if (val & 0x08) {\n if (val & 0x02)\n s->read_reg_select = val & 1;\n if (val & 0x40)\n s->special_mask = (val >> 5) & 1;\n } else {\n switch(val) {\n case 0x00:\n case 0x80:\n s->rotate_on_autoeoi = val >> 7;\n break;\n case 0x20: /* end of interrupt */\n case 0xa0:\n priority = pic_get_priority(s, s->isr);\n if (priority >= 0) {\n s->isr &= ~(1 << ((priority + s->priority_add) & 7));\n }\n if (val == 0xa0)\n s->priority_add = (s->priority_add + 1) & 7;\n break;\n case 0x60:\n case 0x61:\n case 0x62:\n case 0x63:\n case 0x64:\n case 0x65:\n case 0x66:\n case 0x67:\n priority = val & 7;\n s->isr &= ~(1 << priority);\n break;\n case 0xc0:\n case 0xc1:\n case 0xc2:\n case 0xc3:\n case 0xc4:\n case 0xc5:\n case 0xc6:\n case 0xc7:\n s->priority_add = (val + 1) & 7;\n break;\n case 0xe0:\n case 0xe1:\n case 0xe2:\n case 0xe3:\n case 0xe4:\n case 0xe5:\n case 0xe6:\n case 0xe7:\n priority = val & 7;\n s->isr &= ~(1 << priority);\n s->priority_add = (priority + 1) & 7;\n break;\n }\n }\n } else {\n switch(s->init_state) {\n case 0:\n /* normal mode */\n s->imr = val;\n s->update_irq(s->opaque);\n break;\n case 1:\n s->irq_base = val & 0xf8;\n s->init_state = 2;\n break;\n case 2:\n if (s->init4) {\n s->init_state = 3;\n } else {\n s->init_state = 0;\n }\n break;\n case 3:\n s->auto_eoi = (val >> 1) & 1;\n s->init_state = 0;\n break;\n }\n }\n}\n\nstatic uint32_t pic_read(void *opaque, uint32_t offset, int size_log2)\n{\n PICState *s = opaque;\n int addr, ret;\n\n addr = offset & 1;\n if (addr == 0) {\n if (s->read_reg_select)\n ret = s->isr;\n else\n ret = s->irr;\n } else {\n ret = s->imr;\n }\n#ifdef DEBUG_PIC\n console.log(\"pic_read: addr=\" + toHex2(addr1) + \" val=\" + toHex2(ret));\n#endif\n return ret;\n}\n\nstatic void pic_elcr_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PICState *s = opaque;\n s->elcr = val & s->elcr_mask;\n}\n\nstatic uint32_t pic_elcr_read(void *opaque, uint32_t offset, int size_log2)\n{\n PICState *s = opaque;\n return s->elcr;\n}\n\ntypedef struct {\n PICState *pics[2];\n int irq_requested;\n void (*cpu_set_irq)(void *opaque, int level);\n void *opaque;\n#if defined(DEBUG_PIC)\n uint8_t irq_level[16];\n#endif\n IRQSignal *irqs;\n} PIC2State;\n\nstatic void pic2_update_irq(void *opaque);\nstatic void pic2_set_irq(void *opaque, int irq, int level);\n\nPIC2State *pic2_init(PhysMemoryMap *port_map, uint32_t addr0, uint32_t addr1,\n uint32_t elcr_addr0, uint32_t elcr_addr1, \n void (*cpu_set_irq)(void *opaque, int level),\n void *opaque, IRQSignal *irqs)\n{\n PIC2State *s;\n int i;\n \n s = mallocz(sizeof(*s));\n\n for(i = 0; i < 16; i++) {\n irq_init(&irqs[i], pic2_set_irq, s, i);\n }\n s->cpu_set_irq = cpu_set_irq;\n s->opaque = opaque;\n s->pics[0] = pic_init(port_map, addr0, elcr_addr0, 0xf8, pic2_update_irq, s);\n s->pics[1] = pic_init(port_map, addr1, elcr_addr1, 0xde, pic2_update_irq, s);\n s->irq_requested = 0;\n return s;\n}\n\nvoid pic2_set_elcr(PIC2State *s, const uint8_t *elcr)\n{\n int i;\n for(i = 0; i < 2; i++) {\n s->pics[i]->elcr = elcr[i] & s->pics[i]->elcr_mask;\n }\n}\n\n/* raise irq to CPU if necessary. must be called every time the active\n irq may change */\nstatic void pic2_update_irq(void *opaque)\n{\n PIC2State *s = opaque;\n int irq2, irq;\n\n /* first look at slave pic */\n irq2 = pic_get_irq(s->pics[1]);\n if (irq2 >= 0) {\n /* if irq request by slave pic, signal master PIC */\n pic_set_irq1(s->pics[0], 2, 1);\n pic_set_irq1(s->pics[0], 2, 0);\n }\n /* look at requested irq */\n irq = pic_get_irq(s->pics[0]);\n#if 0\n console.log(\"irr=\" + toHex2(s->pics[0].irr) + \" imr=\" + toHex2(s->pics[0].imr) + \" isr=\" + toHex2(s->pics[0].isr) + \" irq=\"+ irq);\n#endif\n if (irq >= 0) {\n /* raise IRQ request on the CPU */\n s->cpu_set_irq(s->opaque, 1);\n } else {\n /* lower irq */\n s->cpu_set_irq(s->opaque, 0);\n }\n}\n\nstatic void pic2_set_irq(void *opaque, int irq, int level)\n{\n PIC2State *s = opaque;\n#if defined(DEBUG_PIC)\n if (irq != 0 && level != s->irq_level[irq]) {\n console.log(\"pic_set_irq: irq=\" + irq + \" level=\" + level);\n s->irq_level[irq] = level;\n }\n#endif\n pic_set_irq1(s->pics[irq >> 3], irq & 7, level);\n pic2_update_irq(s);\n}\n\n/* called from the CPU to get the hardware interrupt number */\nstatic int pic2_get_hard_intno(PIC2State *s)\n{\n int irq, irq2, intno;\n\n irq = pic_get_irq(s->pics[0]);\n if (irq >= 0) {\n pic_intack(s->pics[0], irq);\n if (irq == 2) {\n irq2 = pic_get_irq(s->pics[1]);\n if (irq2 >= 0) {\n pic_intack(s->pics[1], irq2);\n } else {\n /* spurious IRQ on slave controller */\n irq2 = 7;\n }\n intno = s->pics[1]->irq_base + irq2;\n irq = irq2 + 8;\n } else {\n intno = s->pics[0]->irq_base + irq;\n }\n } else {\n /* spurious IRQ on host controller */\n irq = 7;\n intno = s->pics[0]->irq_base + irq;\n }\n pic2_update_irq(s);\n\n#if defined(DEBUG_PIC)\n if (irq != 0 && irq != 14)\n printf(\"pic_interrupt: irq=%d\\n\", irq);\n#endif\n return intno;\n}\n\n/***********************************************************/\n/* 8253 PIT emulation */\n\n#define PIT_FREQ 1193182\n\n#define RW_STATE_LSB 0\n#define RW_STATE_MSB 1\n#define RW_STATE_WORD0 2\n#define RW_STATE_WORD1 3\n#define RW_STATE_LATCHED_WORD0 4\n#define RW_STATE_LATCHED_WORD1 5\n\n//#define DEBUG_PIT\n\ntypedef int64_t PITGetTicksFunc(void *opaque);\n\ntypedef struct PITState PITState;\n\ntypedef struct {\n PITState *pit_state;\n uint32_t count;\n uint32_t latched_count;\n uint8_t rw_state;\n uint8_t mode;\n uint8_t bcd;\n uint8_t gate;\n int64_t count_load_time;\n int64_t last_irq_time;\n} PITChannel;\n\nstruct PITState {\n PITChannel pit_channels[3];\n uint8_t speaker_data_on;\n PITGetTicksFunc *get_ticks;\n IRQSignal *irq;\n void *opaque;\n};\n\nstatic void pit_load_count(PITChannel *pc, int val);\nstatic void pit_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pit_read(void *opaque, uint32_t offset, int size_log2);\nstatic void speaker_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t speaker_read(void *opaque, uint32_t offset, int size_log2);\n\nPITState *pit_init(PhysMemoryMap *port_map, int addr0, int addr1,\n IRQSignal *irq,\n PITGetTicksFunc *get_ticks, void *opaque)\n{\n PITState *s;\n PITChannel *pc;\n int i;\n\n s = mallocz(sizeof(*s));\n\n s->irq = irq;\n s->get_ticks = get_ticks;\n s->opaque = opaque;\n \n for(i = 0; i < 3; i++) {\n pc = &s->pit_channels[i];\n pc->pit_state = s;\n pc->mode = 3;\n pc->gate = (i != 2) >> 0;\n pit_load_count(pc, 0);\n }\n s->speaker_data_on = 0;\n\n cpu_register_device(port_map, addr0, 4, s, pit_read, pit_write, \n DEVIO_SIZE8);\n\n cpu_register_device(port_map, addr1, 1, s, speaker_read, speaker_write, \n DEVIO_SIZE8);\n return s;\n}\n\n/* unit = PIT frequency */\nstatic int64_t pit_get_time(PITChannel *pc)\n{\n PITState *s = pc->pit_state;\n return s->get_ticks(s->opaque);\n}\n\nstatic uint32_t pit_get_count(PITChannel *pc)\n{\n uint32_t counter;\n uint64_t d;\n \n d = pit_get_time(pc) - pc->count_load_time;\n switch(pc->mode) {\n case 0:\n case 1:\n case 4:\n case 5:\n counter = (pc->count - d) & 0xffff;\n break;\n default:\n counter = pc->count - (d % pc->count);\n break;\n }\n return counter;\n}\n\n/* get pit output bit */\nstatic int pit_get_out(PITChannel *pc)\n{\n int out;\n int64_t d;\n \n d = pit_get_time(pc) - pc->count_load_time;\n switch(pc->mode) {\n default:\n case 0:\n out = (d >= pc->count) >> 0;\n break;\n case 1:\n out = (d < pc->count) >> 0;\n break;\n case 2:\n /* mode used by Linux */\n if ((d % pc->count) == 0 && d != 0)\n out = 1;\n else\n out = 0;\n break;\n case 3:\n out = ((d % pc->count) < (pc->count >> 1)) >> 0;\n break;\n case 4:\n case 5:\n out = (d == pc->count) >> 0;\n break;\n }\n return out;\n}\n\nstatic void pit_load_count(PITChannel *s, int val)\n{\n if (val == 0)\n val = 0x10000;\n s->count_load_time = pit_get_time(s);\n s->last_irq_time = 0;\n s->count = val;\n}\n\nstatic void pit_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PITState *pit = opaque;\n int channel, access, addr;\n PITChannel *s;\n\n addr = offset & 3;\n#ifdef DEBUG_PIT\n printf(\"pit_write: off=%d val=0x%02x\\n\", addr, val);\n#endif\n if (addr == 3) {\n channel = val >> 6;\n if (channel == 3)\n return;\n s = &pit->pit_channels[channel];\n access = (val >> 4) & 3;\n switch(access) {\n case 0:\n s->latched_count = pit_get_count(s);\n s->rw_state = RW_STATE_LATCHED_WORD0;\n break;\n default:\n s->mode = (val >> 1) & 7;\n s->bcd = val & 1;\n s->rw_state = access - 1 + RW_STATE_LSB;\n break;\n }\n } else {\n s = &pit->pit_channels[addr];\n switch(s->rw_state) {\n case RW_STATE_LSB:\n pit_load_count(s, val);\n break;\n case RW_STATE_MSB:\n pit_load_count(s, val << 8);\n break;\n case RW_STATE_WORD0:\n case RW_STATE_WORD1:\n if (s->rw_state & 1) {\n pit_load_count(s, (s->latched_count & 0xff) | (val << 8));\n } else {\n s->latched_count = val;\n }\n s->rw_state ^= 1;\n break;\n }\n }\n}\n\nstatic uint32_t pit_read(void *opaque, uint32_t offset, int size_log2)\n{\n PITState *pit = opaque;\n PITChannel *s;\n int ret, count, addr;\n \n addr = offset & 3;\n if (addr == 3)\n return 0xff;\n\n s = &pit->pit_channels[addr];\n switch(s->rw_state) {\n case RW_STATE_LSB:\n case RW_STATE_MSB:\n case RW_STATE_WORD0:\n case RW_STATE_WORD1:\n count = pit_get_count(s);\n if (s->rw_state & 1)\n ret = (count >> 8) & 0xff;\n else\n ret = count & 0xff;\n if (s->rw_state & 2)\n s->rw_state ^= 1;\n break;\n default:\n case RW_STATE_LATCHED_WORD0:\n case RW_STATE_LATCHED_WORD1:\n if (s->rw_state & 1)\n ret = s->latched_count >> 8;\n else\n ret = s->latched_count & 0xff;\n s->rw_state ^= 1;\n break;\n }\n#ifdef DEBUG_PIT\n printf(\"pit_read: off=%d val=0x%02x\\n\", addr, ret);\n#endif\n return ret;\n}\n\nstatic void speaker_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PITState *pit = opaque;\n pit->speaker_data_on = (val >> 1) & 1;\n pit->pit_channels[2].gate = val & 1;\n}\n\nstatic uint32_t speaker_read(void *opaque, uint32_t offset, int size_log2)\n{\n PITState *pit = opaque;\n PITChannel *s;\n int out, val;\n\n s = &pit->pit_channels[2];\n out = pit_get_out(s);\n val = (pit->speaker_data_on << 1) | s->gate | (out << 5);\n#ifdef DEBUG_PIT\n // console.log(\"speaker_read: addr=\" + toHex2(addr) + \" val=\" + toHex2(val));\n#endif\n return val;\n}\n\n/* set the IRQ if necessary and return the delay in ms until the next\n IRQ. Note: The code does not handle all the PIT configurations. */\nstatic int pit_update_irq(PITState *pit)\n{\n PITChannel *s;\n int64_t d, delay;\n \n s = &pit->pit_channels[0];\n \n delay = PIT_FREQ; /* could be infinity delay */\n \n d = pit_get_time(s) - s->count_load_time;\n switch(s->mode) {\n default:\n case 0:\n case 1:\n case 4:\n case 5:\n if (s->last_irq_time == 0) {\n delay = s->count - d;\n if (delay <= 0) {\n set_irq(pit->irq, 1);\n set_irq(pit->irq, 0);\n s->last_irq_time = d;\n }\n }\n break;\n case 2: /* mode used by Linux */\n case 3:\n delay = s->last_irq_time + s->count - d;\n if (delay <= 0) {\n set_irq(pit->irq, 1);\n set_irq(pit->irq, 0);\n s->last_irq_time += s->count;\n }\n break;\n }\n\n if (delay <= 0)\n return 0;\n else\n return delay / (PIT_FREQ / 1000);\n}\n \n/***********************************************************/\n/* serial port emulation */\n\n#define UART_LCR_DLAB\t0x80\t/* Divisor latch access bit */\n\n#define UART_IER_MSI\t0x08\t/* Enable Modem status interrupt */\n#define UART_IER_RLSI\t0x04\t/* Enable receiver line status interrupt */\n#define UART_IER_THRI\t0x02\t/* Enable Transmitter holding register int. */\n#define UART_IER_RDI\t0x01\t/* Enable receiver data interrupt */\n\n#define UART_IIR_NO_INT\t0x01\t/* No interrupts pending */\n#define UART_IIR_ID\t0x06\t/* Mask for the interrupt ID */\n\n#define UART_IIR_MSI\t0x00\t/* Modem status interrupt */\n#define UART_IIR_THRI\t0x02\t/* Transmitter holding register empty */\n#define UART_IIR_RDI\t0x04\t/* Receiver data interrupt */\n#define UART_IIR_RLSI\t0x06\t/* Receiver line status interrupt */\n#define UART_IIR_FE 0xC0 /* Fifo enabled */\n\n#define UART_LSR_TEMT\t0x40\t/* Transmitter empty */\n#define UART_LSR_THRE\t0x20\t/* Transmit-hold-register empty */\n#define UART_LSR_BI\t0x10\t/* Break interrupt indicator */\n#define UART_LSR_FE\t0x08\t/* Frame error indicator */\n#define UART_LSR_PE\t0x04\t/* Parity error indicator */\n#define UART_LSR_OE\t0x02\t/* Overrun error indicator */\n#define UART_LSR_DR\t0x01\t/* Receiver data ready */\n\n#define UART_FCR_XFR 0x04 /* XMIT Fifo Reset */\n#define UART_FCR_RFR 0x02 /* RCVR Fifo Reset */\n#define UART_FCR_FE 0x01 /* FIFO Enable */\n\n#define UART_FIFO_LENGTH 16 /* 16550A Fifo Length */\n\ntypedef struct {\n uint8_t divider; \n uint8_t rbr; /* receive register */\n uint8_t ier;\n uint8_t iir; /* read only */\n uint8_t lcr;\n uint8_t mcr;\n uint8_t lsr; /* read only */\n uint8_t msr;\n uint8_t scr;\n uint8_t fcr;\n IRQSignal *irq;\n void (*write_func)(void *opaque, const uint8_t *buf, int buf_len);\n void *opaque;\n} SerialState;\n\nstatic void serial_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t serial_read(void *opaque, uint32_t offset, int size_log2);\n\nSerialState *serial_init(PhysMemoryMap *port_map, int addr,\n IRQSignal *irq,\n void (*write_func)(void *opaque, const uint8_t *buf, int buf_len), void *opaque)\n{\n SerialState *s;\n s = mallocz(sizeof(*s));\n \n /* all 8 bit registers */\n s->divider = 0; \n s->rbr = 0; /* receive register */\n s->ier = 0;\n s->iir = UART_IIR_NO_INT; /* read only */\n s->lcr = 0;\n s->mcr = 0;\n s->lsr = UART_LSR_TEMT | UART_LSR_THRE; /* read only */\n s->msr = 0;\n s->scr = 0;\n s->fcr = 0;\n\n s->irq = irq;\n s->write_func = write_func;\n s->opaque = opaque;\n\n cpu_register_device(port_map, addr, 8, s, serial_read, serial_write, \n DEVIO_SIZE8);\n return s;\n}\n\nstatic void serial_update_irq(SerialState *s)\n{\n if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {\n s->iir = UART_IIR_RDI;\n } else if ((s->lsr & UART_LSR_THRE) && (s->ier & UART_IER_THRI)) {\n s->iir = UART_IIR_THRI;\n } else {\n s->iir = UART_IIR_NO_INT;\n }\n if (s->iir != UART_IIR_NO_INT) {\n set_irq(s->irq, 1);\n } else {\n set_irq(s->irq, 0);\n }\n}\n\n#if 0\n/* send remainining chars in fifo */\nSerial.prototype.write_tx_fifo = function()\n{\n if (s->tx_fifo != \"\") {\n s->write_func(s->tx_fifo);\n s->tx_fifo = \"\";\n \n s->lsr |= UART_LSR_THRE;\n s->lsr |= UART_LSR_TEMT;\n s->update_irq();\n }\n}\n#endif\n \nstatic void serial_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n SerialState *s = opaque;\n int addr;\n\n addr = offset & 7;\n switch(addr) {\n default:\n case 0:\n if (s->lcr & UART_LCR_DLAB) {\n s->divider = (s->divider & 0xff00) | val;\n } else {\n#if 0\n if (s->fcr & UART_FCR_FE) {\n s->tx_fifo += String.fromCharCode(val);\n s->lsr &= ~UART_LSR_THRE;\n serial_update_irq(s);\n if (s->tx_fifo.length >= UART_FIFO_LENGTH) {\n /* write to the terminal */\n s->write_tx_fifo();\n }\n } else\n#endif\n {\n uint8_t ch;\n s->lsr &= ~UART_LSR_THRE;\n serial_update_irq(s);\n \n /* write to the terminal */\n ch = val;\n s->write_func(s->opaque, &ch, 1);\n s->lsr |= UART_LSR_THRE;\n s->lsr |= UART_LSR_TEMT;\n serial_update_irq(s);\n }\n }\n break;\n case 1:\n if (s->lcr & UART_LCR_DLAB) {\n s->divider = (s->divider & 0x00ff) | (val << 8);\n } else {\n s->ier = val;\n serial_update_irq(s);\n }\n break;\n case 2:\n#if 0\n if ((s->fcr ^ val) & UART_FCR_FE) {\n /* clear fifos */\n val |= UART_FCR_XFR | UART_FCR_RFR;\n }\n if (val & UART_FCR_XFR)\n s->tx_fifo = \"\";\n if (val & UART_FCR_RFR)\n s->rx_fifo = \"\";\n s->fcr = val & UART_FCR_FE;\n#endif\n break;\n case 3:\n s->lcr = val;\n break;\n case 4:\n s->mcr = val;\n break;\n case 5:\n break;\n case 6:\n s->msr = val;\n break;\n case 7:\n s->scr = val;\n break;\n }\n}\n\nstatic uint32_t serial_read(void *opaque, uint32_t offset, int size_log2)\n{\n SerialState *s = opaque;\n int ret, addr;\n\n addr = offset & 7;\n switch(addr) {\n default:\n case 0:\n if (s->lcr & UART_LCR_DLAB) {\n ret = s->divider & 0xff; \n } else {\n ret = s->rbr;\n s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);\n serial_update_irq(s);\n#if 0\n /* try to receive next chars */\n s->send_char_from_fifo();\n#endif\n }\n break;\n case 1:\n if (s->lcr & UART_LCR_DLAB) {\n ret = (s->divider >> 8) & 0xff;\n } else {\n ret = s->ier;\n }\n break;\n case 2:\n ret = s->iir;\n if (s->fcr & UART_FCR_FE)\n ret |= UART_IIR_FE;\n break;\n case 3:\n ret = s->lcr;\n break;\n case 4:\n ret = s->mcr;\n break;\n case 5:\n ret = s->lsr;\n break;\n case 6:\n ret = s->msr;\n break;\n case 7:\n ret = s->scr;\n break;\n }\n return ret;\n}\n\nvoid serial_send_break(SerialState *s)\n{\n s->rbr = 0;\n s->lsr |= UART_LSR_BI | UART_LSR_DR;\n serial_update_irq(s);\n}\n\n#if 0\nstatic void serial_send_char(SerialState *s, int ch)\n{\n s->rbr = ch;\n s->lsr |= UART_LSR_DR;\n serial_update_irq(s);\n}\n\nSerial.prototype.send_char_from_fifo = function()\n{\n var fifo;\n\n fifo = s->rx_fifo;\n if (fifo != \"\" && !(s->lsr & UART_LSR_DR)) {\n s->send_char(fifo.charCodeAt(0));\n s->rx_fifo = fifo.substr(1, fifo.length - 1);\n }\n}\n\n/* queue the string in the UART receive fifo and send it ASAP */\nSerial.prototype.send_chars = function(str)\n{\n s->rx_fifo += str;\n s->send_char_from_fifo();\n}\n \n#endif\n\n#ifdef DEBUG_BIOS\nstatic void bios_debug_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n#ifdef EMSCRIPTEN\n static char line_buf[256];\n static int line_buf_index;\n line_buf[line_buf_index++] = val;\n if (val == '\\n' || line_buf_index >= sizeof(line_buf) - 1) {\n line_buf[line_buf_index] = '\\0';\n printf(\"%s\", line_buf);\n line_buf_index = 0;\n }\n#else\n putchar(val & 0xff);\n#endif\n}\n\nstatic uint32_t bios_debug_read(void *opaque, uint32_t offset, int size_log2)\n{\n return 0;\n}\n#endif\n\ntypedef struct PCMachine {\n VirtMachine common;\n uint64_t ram_size;\n PhysMemoryMap *mem_map;\n PhysMemoryMap *port_map;\n \n X86CPUState *cpu_state;\n PIC2State *pic_state;\n IRQSignal pic_irq[16];\n PITState *pit_state;\n I440FXState *i440fx_state;\n CMOSState *cmos_state;\n SerialState *serial_state;\n\n /* input */\n VIRTIODevice *keyboard_dev;\n VIRTIODevice *mouse_dev;\n KBDState *kbd_state;\n PS2MouseState *ps2_mouse;\n VMMouseState *vm_mouse;\n PS2KbdState *ps2_kbd;\n\n#ifdef USE_KVM\n BOOL kvm_enabled;\n int kvm_fd;\n int vm_fd;\n int vcpu_fd;\n int kvm_run_size;\n struct kvm_run *kvm_run;\n#endif\n} PCMachine;\n\nstatic void copy_kernel(PCMachine *s, const uint8_t *buf, int buf_len,\n const char *cmd_line);\n\nstatic void port80_write(void *opaque, uint32_t offset,\n uint32_t val64, int size_log2)\n{\n}\n\nstatic uint32_t port80_read(void *opaque, uint32_t offset, int size_log2)\n{\n return 0xff;\n}\n\nstatic void port92_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n}\n\nstatic uint32_t port92_read(void *opaque, uint32_t offset, int size_log2)\n{\n int a20 = 1; /* A20=0 is not supported */\n return a20 << 1;\n}\n\n#define VMPORT_MAGIC 0x564D5868\n#define REG_EAX 0\n#define REG_EBX 1\n#define REG_ECX 2\n#define REG_EDX 3\n#define REG_ESI 4\n#define REG_EDI 5\n\nstatic uint32_t vmport_read(void *opaque, uint32_t addr, int size_log2)\n{\n PCMachine *s = opaque;\n uint32_t regs[6];\n\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n struct kvm_regs r;\n\n ioctl(s->vcpu_fd, KVM_GET_REGS, &r);\n regs[REG_EAX] = r.rax;\n regs[REG_EBX] = r.rbx;\n regs[REG_ECX] = r.rcx;\n regs[REG_EDX] = r.rdx;\n regs[REG_ESI] = r.rsi;\n regs[REG_EDI] = r.rdi;\n\n if (regs[REG_EAX] == VMPORT_MAGIC) {\n \n vmmouse_handler(s->vm_mouse, regs);\n \n /* Note: in 64 bits the high parts are reset to zero\n in all cases. */\n r.rax = regs[REG_EAX];\n r.rbx = regs[REG_EBX];\n r.rcx = regs[REG_ECX];\n r.rdx = regs[REG_EDX];\n r.rsi = regs[REG_ESI];\n r.rdi = regs[REG_EDI];\n ioctl(s->vcpu_fd, KVM_SET_REGS, &r);\n }\n } else\n#endif\n {\n regs[REG_EAX] = x86_cpu_get_reg(s->cpu_state, 0);\n regs[REG_EBX] = x86_cpu_get_reg(s->cpu_state, 3);\n regs[REG_ECX] = x86_cpu_get_reg(s->cpu_state, 1);\n regs[REG_EDX] = x86_cpu_get_reg(s->cpu_state, 2);\n regs[REG_ESI] = x86_cpu_get_reg(s->cpu_state, 6);\n regs[REG_EDI] = x86_cpu_get_reg(s->cpu_state, 7);\n\n if (regs[REG_EAX] == VMPORT_MAGIC) {\n vmmouse_handler(s->vm_mouse, regs);\n\n x86_cpu_set_reg(s->cpu_state, 0, regs[REG_EAX]);\n x86_cpu_set_reg(s->cpu_state, 3, regs[REG_EBX]);\n x86_cpu_set_reg(s->cpu_state, 1, regs[REG_ECX]);\n x86_cpu_set_reg(s->cpu_state, 2, regs[REG_EDX]);\n x86_cpu_set_reg(s->cpu_state, 6, regs[REG_ESI]);\n x86_cpu_set_reg(s->cpu_state, 7, regs[REG_EDI]);\n }\n }\n return regs[REG_EAX];\n}\n\nstatic void vmport_write(void *opaque, uint32_t addr, uint32_t val,\n int size_log2)\n{\n}\n\nstatic void pic_set_irq_cb(void *opaque, int level)\n{\n PCMachine *s = opaque;\n x86_cpu_set_irq(s->cpu_state, level);\n}\n\nstatic void serial_write_cb(void *opaque, const uint8_t *buf, int buf_len)\n{\n PCMachine *s = opaque;\n if (s->common.console) {\n s->common.console->write_data(s->common.console->opaque, buf, buf_len);\n }\n}\n\nstatic int get_hard_intno_cb(void *opaque)\n{\n PCMachine *s = opaque;\n return pic2_get_hard_intno(s->pic_state);\n}\n\nstatic int64_t pit_get_ticks_cb(void *opaque)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * PIT_FREQ +\n ((uint64_t)ts.tv_nsec * PIT_FREQ / 1000000000);\n}\n\n#define FRAMEBUFFER_BASE_ADDR 0xf0400000\n\nstatic uint8_t *get_ram_ptr(PCMachine *s, uint64_t paddr)\n{\n PhysMemoryRange *pr;\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr || !pr->is_ram)\n return NULL;\n return pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n}\n\n#ifdef DUMP_IOPORT\nstatic BOOL dump_port(int port)\n{\n return !((port >= 0x1f0 && port <= 0x1f7) ||\n (port >= 0x20 && port <= 0x21) ||\n (port >= 0xa0 && port <= 0xa1));\n}\n#endif\n\nstatic void st_port(void *opaque, uint32_t port, uint32_t val, int size_log2)\n{\n PCMachine *s = opaque;\n PhysMemoryRange *pr;\n#ifdef DUMP_IOPORT\n if (dump_port(port))\n printf(\"write port=0x%x val=0x%x s=%d\\n\", port, val, 1 << size_log2);\n#endif\n pr = get_phys_mem_range(s->port_map, port);\n if (!pr) {\n return;\n }\n port -= pr->addr;\n if ((pr->devio_flags >> size_log2) & 1) {\n pr->write_func(pr->opaque, port, (uint32_t)val, size_log2);\n } else if (size_log2 == 1 && (pr->devio_flags & DEVIO_SIZE8)) {\n pr->write_func(pr->opaque, port, val & 0xff, 0);\n pr->write_func(pr->opaque, port + 1, (val >> 8) & 0xff, 0);\n }\n}\n\nstatic uint32_t ld_port(void *opaque, uint32_t port1, int size_log2)\n{\n PCMachine *s = opaque;\n PhysMemoryRange *pr;\n uint32_t val, port;\n \n port = port1;\n pr = get_phys_mem_range(s->port_map, port);\n if (!pr) {\n val = -1;\n } else {\n port -= pr->addr;\n if ((pr->devio_flags >> size_log2) & 1) {\n val = pr->read_func(pr->opaque, port, size_log2);\n } else if (size_log2 == 1 && (pr->devio_flags & DEVIO_SIZE8)) {\n val = pr->read_func(pr->opaque, port, 0) & 0xff;\n val |= (pr->read_func(pr->opaque, port + 1, 0) & 0xff) << 8;\n } else {\n val = -1;\n }\n }\n#ifdef DUMP_IOPORT\n if (dump_port(port1))\n printf(\"read port=0x%x val=0x%x s=%d\\n\", port1, val, 1 << size_log2);\n#endif\n return val;\n}\n\nstatic void pc_machine_set_defaults(VirtMachineParams *p)\n{\n p->accel_enable = TRUE;\n}\n\n#ifdef USE_KVM\n\nstatic void sigalrm_handler(int sig)\n{\n}\n\n#define CPUID_APIC (1 << 9)\n#define CPUID_ACPI (1 << 22)\n\nstatic void kvm_set_cpuid(PCMachine *s)\n{\n struct kvm_cpuid2 *kvm_cpuid;\n int n_ent_max, i;\n struct kvm_cpuid_entry2 *ent;\n \n n_ent_max = 128;\n kvm_cpuid = mallocz(sizeof(struct kvm_cpuid2) + n_ent_max * sizeof(kvm_cpuid->entries[0]));\n \n kvm_cpuid->nent = n_ent_max;\n if (ioctl(s->kvm_fd, KVM_GET_SUPPORTED_CPUID, kvm_cpuid) < 0) {\n perror(\"KVM_GET_SUPPORTED_CPUID\");\n exit(1);\n }\n\n for(i = 0; i < kvm_cpuid->nent; i++) {\n ent = &kvm_cpuid->entries[i];\n /* remove the APIC & ACPI to be in sync with the emulator */\n if (ent->function == 1 || ent->function == 0x80000001) {\n ent->edx &= ~(CPUID_APIC | CPUID_ACPI);\n }\n }\n \n if (ioctl(s->vcpu_fd, KVM_SET_CPUID2, kvm_cpuid) < 0) {\n perror(\"KVM_SET_CPUID2\");\n exit(1);\n }\n free(kvm_cpuid);\n}\n\n/* XXX: should check overlapping mappings */\nstatic void kvm_map_ram(PhysMemoryMap *mem_map, PhysMemoryRange *pr)\n{\n PCMachine *s = mem_map->opaque;\n struct kvm_userspace_memory_region region;\n int flags;\n\n region.slot = pr - mem_map->phys_mem_range;\n flags = 0;\n if (pr->devram_flags & DEVRAM_FLAG_ROM)\n flags |= KVM_MEM_READONLY;\n if (pr->devram_flags & DEVRAM_FLAG_DIRTY_BITS)\n flags |= KVM_MEM_LOG_DIRTY_PAGES;\n region.flags = flags;\n region.guest_phys_addr = pr->addr;\n region.memory_size = pr->size;\n#if 0\n printf(\"map slot %d: %08lx %08lx\\n\",\n region.slot, pr->addr, pr->size);\n#endif\n region.userspace_addr = (uintptr_t)pr->phys_mem;\n if (ioctl(s->vm_fd, KVM_SET_USER_MEMORY_REGION, ®ion) < 0) {\n perror(\"KVM_SET_USER_MEMORY_REGION\");\n exit(1);\n }\n}\n\n/* XXX: just for one region */\nstatic PhysMemoryRange *kvm_register_ram(PhysMemoryMap *mem_map, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n uint8_t *phys_mem;\n \n pr = register_ram_entry(mem_map, addr, size, devram_flags);\n\n phys_mem = mmap(NULL, size, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n if (!phys_mem)\n return NULL;\n pr->phys_mem = phys_mem;\n if (devram_flags & DEVRAM_FLAG_DIRTY_BITS) {\n int n_pages = size >> 12;\n pr->dirty_bits_size = ((n_pages + 63) / 64) * 8;\n pr->dirty_bits = mallocz(pr->dirty_bits_size);\n }\n\n if (pr->size != 0) {\n kvm_map_ram(mem_map, pr);\n }\n return pr;\n}\n\nstatic void kvm_set_ram_addr(PhysMemoryMap *mem_map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n if (enabled) {\n if (pr->size == 0 || addr != pr->addr) {\n /* move or create the region */\n pr->size = pr->org_size;\n pr->addr = addr;\n kvm_map_ram(mem_map, pr);\n }\n } else {\n if (pr->size != 0) {\n pr->addr = 0;\n pr->size = 0;\n /* map a zero size region to disable */\n kvm_map_ram(mem_map, pr);\n }\n }\n}\n\nstatic const uint32_t *kvm_get_dirty_bits(PhysMemoryMap *mem_map,\n PhysMemoryRange *pr)\n{\n PCMachine *s = mem_map->opaque;\n struct kvm_dirty_log dlog;\n \n if (pr->size == 0) {\n /* not mapped: we assume no modification was made */\n memset(pr->dirty_bits, 0, pr->dirty_bits_size);\n } else {\n dlog.slot = pr - mem_map->phys_mem_range;\n dlog.dirty_bitmap = pr->dirty_bits;\n if (ioctl(s->vm_fd, KVM_GET_DIRTY_LOG, &dlog) < 0) {\n perror(\"KVM_GET_DIRTY_LOG\");\n exit(1);\n }\n }\n return pr->dirty_bits;\n}\n\nstatic void kvm_free_ram(PhysMemoryMap *mem_map, PhysMemoryRange *pr)\n{\n /* XXX: do it */\n munmap(pr->phys_mem, pr->org_size);\n free(pr->dirty_bits);\n}\n\nstatic void kvm_pic_set_irq(void *opaque, int irq_num, int level)\n{\n PCMachine *s = opaque;\n struct kvm_irq_level irq_level;\n irq_level.irq = irq_num;\n irq_level.level = level;\n if (ioctl(s->vm_fd, KVM_IRQ_LINE, &irq_level) < 0) {\n perror(\"KVM_IRQ_LINE\");\n exit(1);\n }\n}\n\nstatic void kvm_init(PCMachine *s)\n{\n int ret, i;\n struct sigaction act;\n struct kvm_pit_config pit_config;\n uint64_t base_addr;\n \n s->kvm_enabled = FALSE;\n s->kvm_fd = open(\"/dev/kvm\", O_RDWR);\n if (s->kvm_fd < 0) {\n fprintf(stderr, \"KVM not available\\n\");\n return;\n }\n ret = ioctl(s->kvm_fd, KVM_GET_API_VERSION, 0);\n if (ret < 0) {\n perror(\"KVM_GET_API_VERSION\");\n exit(1);\n }\n if (ret != 12) {\n fprintf(stderr, \"Unsupported KVM version\\n\");\n close(s->kvm_fd);\n s->kvm_fd = -1;\n return;\n }\n s->vm_fd = ioctl(s->kvm_fd, KVM_CREATE_VM, 0);\n if (s->vm_fd < 0) {\n perror(\"KVM_CREATE_VM\");\n exit(1);\n }\n\n /* just before the BIOS */\n base_addr = 0xfffbc000;\n if (ioctl(s->vm_fd, KVM_SET_IDENTITY_MAP_ADDR, &base_addr) < 0) {\n perror(\"KVM_SET_IDENTITY_MAP_ADDR\");\n exit(1);\n }\n \n if (ioctl(s->vm_fd, KVM_SET_TSS_ADDR, (long)(base_addr + 0x1000)) < 0) {\n perror(\"KVM_SET_TSS_ADDR\");\n exit(1);\n }\n \n if (ioctl(s->vm_fd, KVM_CREATE_IRQCHIP, 0) < 0) {\n perror(\"KVM_CREATE_IRQCHIP\");\n exit(1);\n }\n\n memset(&pit_config, 0, sizeof(pit_config));\n pit_config.flags = KVM_PIT_SPEAKER_DUMMY;\n if (ioctl(s->vm_fd, KVM_CREATE_PIT2, &pit_config)) {\n perror(\"KVM_CREATE_PIT2\");\n exit(1);\n }\n \n s->vcpu_fd = ioctl(s->vm_fd, KVM_CREATE_VCPU, 0);\n if (s->vcpu_fd < 0) {\n perror(\"KVM_CREATE_VCPU\");\n exit(1);\n }\n\n kvm_set_cpuid(s);\n \n /* map the kvm_run structure */\n s->kvm_run_size = ioctl(s->kvm_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);\n if (s->kvm_run_size < 0) {\n perror(\"KVM_GET_VCPU_MMAP_SIZE\");\n exit(1);\n }\n\n s->kvm_run = mmap(NULL, s->kvm_run_size, PROT_READ | PROT_WRITE,\n MAP_SHARED, s->vcpu_fd, 0);\n if (!s->kvm_run) {\n perror(\"mmap kvm_run\");\n exit(1);\n }\n\n for(i = 0; i < 16; i++) {\n irq_init(&s->pic_irq[i], kvm_pic_set_irq, s, i);\n }\n\n act.sa_handler = sigalrm_handler;\n sigemptyset(&act.sa_mask);\n act.sa_flags = 0;\n sigaction(SIGALRM, &act, NULL);\n\n s->kvm_enabled = TRUE;\n\n s->mem_map->register_ram = kvm_register_ram;\n s->mem_map->free_ram = kvm_free_ram;\n s->mem_map->get_dirty_bits = kvm_get_dirty_bits;\n s->mem_map->set_ram_addr = kvm_set_ram_addr;\n s->mem_map->opaque = s;\n}\n\nstatic void kvm_exit_io(PCMachine *s, struct kvm_run *run)\n{\n uint8_t *ptr;\n int i;\n \n ptr = (uint8_t *)run + run->io.data_offset;\n // printf(\"port: addr=%04x\\n\", run->io.port);\n \n for(i = 0; i < run->io.count; i++) {\n if (run->io.direction == KVM_EXIT_IO_OUT) {\n switch(run->io.size) {\n case 1:\n st_port(s, run->io.port, *(uint8_t *)ptr, 0);\n break;\n case 2:\n st_port(s, run->io.port, *(uint16_t *)ptr, 1);\n break;\n case 4:\n st_port(s, run->io.port, *(uint32_t *)ptr, 2);\n break;\n default:\n abort();\n }\n } else {\n switch(run->io.size) {\n case 1:\n *(uint8_t *)ptr = ld_port(s, run->io.port, 0);\n break;\n case 2:\n *(uint16_t *)ptr = ld_port(s, run->io.port, 1);\n break;\n case 4:\n *(uint32_t *)ptr = ld_port(s, run->io.port, 2);\n break;\n default:\n abort();\n }\n }\n ptr += run->io.size;\n }\n}\n\nstatic void kvm_exit_mmio(PCMachine *s, struct kvm_run *run)\n{\n uint8_t *data = run->mmio.data;\n PhysMemoryRange *pr;\n uint64_t addr;\n \n pr = get_phys_mem_range(s->mem_map, run->mmio.phys_addr);\n if (run->mmio.is_write) {\n if (!pr || pr->is_ram)\n return;\n addr = run->mmio.phys_addr - pr->addr;\n switch(run->mmio.len) {\n case 1:\n if (pr->devio_flags & DEVIO_SIZE8) {\n pr->write_func(pr->opaque, addr, *(uint8_t *)data, 0);\n }\n break;\n case 2:\n if (pr->devio_flags & DEVIO_SIZE16) {\n pr->write_func(pr->opaque, addr, *(uint16_t *)data, 1);\n }\n break;\n case 4:\n if (pr->devio_flags & DEVIO_SIZE32) {\n pr->write_func(pr->opaque, addr, *(uint32_t *)data, 2);\n }\n break;\n case 8:\n if (pr->devio_flags & DEVIO_SIZE32) {\n pr->write_func(pr->opaque, addr, *(uint32_t *)data, 2);\n pr->write_func(pr->opaque, addr + 4, *(uint32_t *)(data + 4), 2);\n }\n break;\n default:\n abort();\n }\n } else {\n if (!pr || pr->is_ram)\n goto no_dev;\n addr = run->mmio.phys_addr - pr->addr;\n switch(run->mmio.len) {\n case 1:\n if (!(pr->devio_flags & DEVIO_SIZE8))\n goto no_dev;\n *(uint8_t *)data = pr->read_func(pr->opaque, addr, 0);\n break;\n case 2:\n if (!(pr->devio_flags & DEVIO_SIZE16))\n goto no_dev;\n *(uint16_t *)data = pr->read_func(pr->opaque, addr, 1);\n break;\n case 4:\n if (!(pr->devio_flags & DEVIO_SIZE32))\n goto no_dev;\n *(uint32_t *)data = pr->read_func(pr->opaque, addr, 2);\n break;\n case 8:\n if (pr->devio_flags & DEVIO_SIZE32) {\n *(uint32_t *)data =\n pr->read_func(pr->opaque, addr, 2);\n *(uint32_t *)(data + 4) =\n pr->read_func(pr->opaque, addr + 4, 2);\n } else {\n no_dev:\n memset(run->mmio.data, 0, run->mmio.len);\n }\n break;\n default:\n abort();\n }\n \n }\n}\n\nstatic void kvm_exec(PCMachine *s)\n{\n struct kvm_run *run = s->kvm_run;\n struct itimerval ival;\n int ret;\n \n /* Not efficient but simple: we use a timer to interrupt the\n execution after a given time */\n ival.it_interval.tv_sec = 0;\n ival.it_interval.tv_usec = 0;\n ival.it_value.tv_sec = 0;\n ival.it_value.tv_usec = 10 * 1000; /* 10 ms max */\n setitimer(ITIMER_REAL, &ival, NULL);\n\n ret = ioctl(s->vcpu_fd, KVM_RUN, 0);\n if (ret < 0) {\n if (errno == EINTR || errno == EAGAIN) {\n /* timeout */\n return;\n }\n perror(\"KVM_RUN\");\n exit(1);\n }\n // printf(\"exit=%d\\n\", run->exit_reason);\n switch(run->exit_reason) {\n case KVM_EXIT_HLT:\n break;\n case KVM_EXIT_IO:\n kvm_exit_io(s, run);\n break;\n case KVM_EXIT_MMIO:\n kvm_exit_mmio(s, run);\n break;\n case KVM_EXIT_FAIL_ENTRY:\n fprintf(stderr, \"KVM_EXIT_FAIL_ENTRY: reason=0x%\" PRIx64 \"\\n\",\n (uint64_t)run->fail_entry.hardware_entry_failure_reason);\n#if 0\n {\n struct kvm_regs regs;\n if (ioctl(s->vcpu_fd, KVM_GET_REGS, ®s) < 0) {\n perror(\"KVM_SET_REGS\");\n exit(1);\n }\n printf(\"RIP=%016\" PRIx64 \"\\n\", (uint64_t)regs.rip);\n }\n#endif\n exit(1);\n case KVM_EXIT_INTERNAL_ERROR:\n fprintf(stderr, \"KVM_EXIT_INTERNAL_ERROR: suberror=0x%x\\n\",\n (uint32_t)run->internal.suberror);\n exit(1);\n default:\n fprintf(stderr, \"KVM: unsupported exit_reason=%d\\n\", run->exit_reason);\n exit(1);\n }\n}\n#endif\n\n#if defined(EMSCRIPTEN)\n/* with Javascript clock_gettime() is not enough precise enough to\n have a reliable TSC counter. XXX: increment the cycles during the\n power down time */\nstatic uint64_t cpu_get_tsc(void *opaque)\n{\n PCMachine *s = opaque;\n uint64_t c;\n c = x86_cpu_get_cycles(s->cpu_state);\n return c;\n}\n#else\n\n#define TSC_FREQ 100000000\n\nstatic uint64_t cpu_get_tsc(void *opaque)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * TSC_FREQ +\n (ts.tv_nsec / (1000000000 / TSC_FREQ));\n}\n#endif\n\nstatic void pc_flush_tlb_write_range(void *opaque, uint8_t *ram_addr,\n size_t ram_size)\n{\n PCMachine *s = opaque;\n x86_cpu_flush_tlb_write_range_ram(s->cpu_state, ram_addr, ram_size);\n}\n\nstatic VirtMachine *pc_machine_init(const VirtMachineParams *p)\n{\n PCMachine *s;\n int i, piix3_devfn;\n PCIBus *pci_bus;\n VIRTIOBusDef vbus_s, *vbus = &vbus_s;\n \n if (strcmp(p->machine_name, \"pc\") != 0) {\n vm_error(\"unsupported machine: %s\\n\", p->machine_name);\n return NULL;\n }\n\n assert(p->ram_size >= (1 << 20));\n\n s = mallocz(sizeof(*s));\n s->common.vmc = p->vmc;\n s->ram_size = p->ram_size;\n \n s->port_map = phys_mem_map_init();\n s->mem_map = phys_mem_map_init();\n\n#ifdef USE_KVM\n if (p->accel_enable) {\n kvm_init(s);\n }\n#endif\n\n#ifdef USE_KVM\n if (!s->kvm_enabled)\n#endif\n {\n s->cpu_state = x86_cpu_init(s->mem_map);\n x86_cpu_set_get_tsc(s->cpu_state, cpu_get_tsc, s);\n x86_cpu_set_port_io(s->cpu_state, ld_port, st_port, s);\n \n /* needed to handle the RAM dirty bits */\n s->mem_map->opaque = s;\n s->mem_map->flush_tlb_write_range = pc_flush_tlb_write_range;\n }\n\n /* set the RAM mapping and leave the VGA addresses empty */\n cpu_register_ram(s->mem_map, 0xc0000, p->ram_size - 0xc0000, 0);\n cpu_register_ram(s->mem_map, 0, 0xa0000, 0);\n \n /* devices */\n cpu_register_device(s->port_map, 0x80, 2, s, port80_read, port80_write, \n DEVIO_SIZE8);\n cpu_register_device(s->port_map, 0x92, 2, s, port92_read, port92_write, \n DEVIO_SIZE8);\n \n /* setup the bios */\n if (p->files[VM_FILE_BIOS].len > 0) {\n int bios_size, bios_size1;\n uint8_t *bios_buf, *ptr;\n uint32_t bios_addr;\n \n bios_size = p->files[VM_FILE_BIOS].len;\n bios_buf = p->files[VM_FILE_BIOS].buf;\n assert((bios_size % 65536) == 0 && bios_size != 0);\n bios_addr = -bios_size;\n /* at the top of the 4GB memory */\n cpu_register_ram(s->mem_map, bios_addr, bios_size, DEVRAM_FLAG_ROM);\n ptr = get_ram_ptr(s, bios_addr);\n memcpy(ptr, bios_buf, bios_size);\n /* in the lower 1MB memory (currently set as RAM) */\n bios_size1 = min_int(bios_size, 128 * 1024);\n ptr = get_ram_ptr(s, 0x100000 - bios_size1);\n memcpy(ptr, bios_buf + bios_size - bios_size1, bios_size1);\n#ifdef DEBUG_BIOS\n cpu_register_device(s->port_map, 0x402, 2, s,\n bios_debug_read, bios_debug_write, \n DEVIO_SIZE8);\n#endif\n }\n\n#ifdef USE_KVM\n if (!s->kvm_enabled)\n#endif\n {\n s->pic_state = pic2_init(s->port_map, 0x20, 0xa0,\n 0x4d0, 0x4d1,\n pic_set_irq_cb, s,\n s->pic_irq);\n x86_cpu_set_get_hard_intno(s->cpu_state, get_hard_intno_cb, s);\n s->pit_state = pit_init(s->port_map, 0x40, 0x61, &s->pic_irq[0],\n pit_get_ticks_cb, s);\n }\n\n s->cmos_state = cmos_init(s->port_map, 0x70, &s->pic_irq[8],\n p->rtc_local_time);\n\n /* various cmos data */\n {\n int size;\n /* memory size */\n size = min_int((s->ram_size - (1 << 20)) >> 10, 65535);\n put_le16(s->cmos_state->cmos_data + 0x30, size);\n if (s->ram_size >= (16 << 20)) {\n size = min_int((s->ram_size - (16 << 20)) >> 16, 65535);\n put_le16(s->cmos_state->cmos_data + 0x34, size);\n }\n s->cmos_state->cmos_data[0x14] = 0x06; /* mouse + FPU present */\n }\n \n s->i440fx_state = i440fx_init(&pci_bus, &piix3_devfn, s->mem_map,\n s->port_map, s->pic_irq);\n \n s->common.console = p->console;\n /* serial console */\n if (0) {\n s->serial_state = serial_init(s->port_map, 0x3f8, &s->pic_irq[4],\n serial_write_cb, s);\n }\n \n memset(vbus, 0, sizeof(*vbus));\n vbus->pci_bus = pci_bus;\n\n if (p->console) {\n /* virtio console */\n s->common.console_dev = virtio_console_init(vbus, p->console);\n }\n \n /* block devices */\n for(i = 0; i < p->drive_count;) {\n const VMDriveEntry *de = &p->tab_drive[i];\n\n if (!de->device || !strcmp(de->device, \"virtio\")) {\n virtio_block_init(vbus, p->tab_drive[i].block_dev);\n i++;\n } else if (!strcmp(de->device, \"ide\")) {\n BlockDevice *tab_bs[2];\n \n tab_bs[0] = p->tab_drive[i++].block_dev;\n tab_bs[1] = NULL;\n if (i < p->drive_count)\n tab_bs[1] = p->tab_drive[i++].block_dev;\n ide_init(s->port_map, 0x1f0, 0x3f6, &s->pic_irq[14], tab_bs);\n piix3_ide_init(pci_bus, piix3_devfn + 1);\n }\n }\n \n /* virtio filesystem */\n for(i = 0; i < p->fs_count; i++) {\n virtio_9p_init(vbus, p->tab_fs[i].fs_dev,\n p->tab_fs[i].tag);\n }\n\n if (p->display_device) {\n FBDevice *fb_dev;\n\n fb_dev = mallocz(sizeof(*fb_dev));\n s->common.fb_dev = fb_dev;\n if (!strcmp(p->display_device, \"vga\")) {\n int bios_size;\n uint8_t *bios_buf;\n bios_size = p->files[VM_FILE_VGA_BIOS].len;\n bios_buf = p->files[VM_FILE_VGA_BIOS].buf;\n pci_vga_init(pci_bus, fb_dev, p->width, p->height,\n bios_buf, bios_size);\n } else if (!strcmp(p->display_device, \"simplefb\")) {\n simplefb_init(s->mem_map,\n FRAMEBUFFER_BASE_ADDR,\n fb_dev, p->width, p->height);\n } else {\n vm_error(\"unsupported display device: %s\\n\", p->display_device);\n exit(1);\n }\n }\n\n if (p->input_device) {\n if (!strcmp(p->input_device, \"virtio\")) {\n s->keyboard_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_KEYBOARD);\n \n s->mouse_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_TABLET);\n } else if (!strcmp(p->input_device, \"ps2\")) {\n s->kbd_state = i8042_init(&s->ps2_kbd, &s->ps2_mouse,\n s->port_map,\n &s->pic_irq[1], &s->pic_irq[12], 0x60);\n /* vmmouse */\n cpu_register_device(s->port_map, 0x5658, 1, s,\n vmport_read, vmport_write, \n DEVIO_SIZE32);\n s->vm_mouse = vmmouse_init(s->ps2_mouse);\n } else {\n vm_error(\"unsupported input device: %s\\n\", p->input_device);\n exit(1);\n }\n }\n \n /* virtio net device */\n for(i = 0; i < p->eth_count; i++) {\n virtio_net_init(vbus, p->tab_eth[i].net);\n s->common.net = p->tab_eth[i].net;\n }\n\n if (p->files[VM_FILE_KERNEL].buf) {\n copy_kernel(s, p->files[VM_FILE_KERNEL].buf,\n p->files[VM_FILE_KERNEL].len,\n p->cmdline ? p->cmdline : \"\");\n }\n\n return (VirtMachine *)s;\n}\n\nstatic void pc_machine_end(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n /* XXX: free all */\n if (s->cpu_state) {\n x86_cpu_end(s->cpu_state);\n }\n phys_mem_map_end(s->mem_map);\n phys_mem_map_end(s->port_map);\n free(s);\n}\n\nstatic void pc_vm_send_key_event(VirtMachine *s1, BOOL is_down, uint16_t key_code)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->keyboard_dev) {\n virtio_input_send_key_event(s->keyboard_dev, is_down, key_code);\n } else if (s->ps2_kbd) {\n ps2_put_keycode(s->ps2_kbd, is_down, key_code);\n }\n}\n\nstatic BOOL pc_vm_mouse_is_absolute(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->mouse_dev) {\n return TRUE;\n } else if (s->vm_mouse) {\n return vmmouse_is_absolute(s->vm_mouse);\n } else {\n return FALSE;\n }\n}\n\nstatic void pc_vm_send_mouse_event(VirtMachine *s1, int dx, int dy, int dz,\n unsigned int buttons)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->mouse_dev) {\n virtio_input_send_mouse_event(s->mouse_dev, dx, dy, dz, buttons);\n } else if (s->vm_mouse) {\n vmmouse_send_mouse_event(s->vm_mouse, dx, dy, dz, buttons);\n }\n}\n\nstruct screen_info {\n} __attribute__((packed));\n\n/* from plex86 (BSD license) */\nstruct __attribute__ ((packed)) linux_params {\n /* screen_info structure */\n uint8_t orig_x;\t\t/* 0x00 */\n uint8_t orig_y;\t\t/* 0x01 */\n uint16_t ext_mem_k;\t/* 0x02 */\n uint16_t orig_video_page;\t/* 0x04 */\n uint8_t orig_video_mode;\t/* 0x06 */\n uint8_t orig_video_cols;\t/* 0x07 */\n uint8_t flags;\t\t/* 0x08 */\n uint8_t unused2;\t\t/* 0x09 */\n uint16_t orig_video_ega_bx;/* 0x0a */\n uint16_t unused3;\t\t/* 0x0c */\n uint8_t orig_video_lines;\t/* 0x0e */\n uint8_t orig_video_isVGA;\t/* 0x0f */\n uint16_t orig_video_points;/* 0x10 */\n \n /* VESA graphic mode -- linear frame buffer */\n uint16_t lfb_width;\t/* 0x12 */\n uint16_t lfb_height;\t/* 0x14 */\n uint16_t lfb_depth;\t/* 0x16 */\n uint32_t lfb_base;\t\t/* 0x18 */\n uint32_t lfb_size;\t\t/* 0x1c */\n uint16_t cl_magic, cl_offset; /* 0x20 */\n uint16_t lfb_linelength;\t/* 0x24 */\n uint8_t red_size;\t\t/* 0x26 */\n uint8_t red_pos;\t\t/* 0x27 */\n uint8_t green_size;\t/* 0x28 */\n uint8_t green_pos;\t/* 0x29 */\n uint8_t blue_size;\t/* 0x2a */\n uint8_t blue_pos;\t\t/* 0x2b */\n uint8_t rsvd_size;\t/* 0x2c */\n uint8_t rsvd_pos;\t\t/* 0x2d */\n uint16_t vesapm_seg;\t/* 0x2e */\n uint16_t vesapm_off;\t/* 0x30 */\n uint16_t pages;\t\t/* 0x32 */\n uint16_t vesa_attributes;\t/* 0x34 */\n uint32_t capabilities; /* 0x36 */\n uint32_t ext_lfb_base;\t/* 0x3a */\n uint8_t _reserved[2];\t/* 0x3e */\n \n /* 0x040 */ uint8_t apm_bios_info[20]; // struct apm_bios_info\n /* 0x054 */ uint8_t pad2[0x80 - 0x54];\n\n // Following 2 from 'struct drive_info_struct' in drivers/block/cciss.h.\n // Might be truncated?\n /* 0x080 */ uint8_t hd0_info[16]; // hd0-disk-parameter from intvector 0x41\n /* 0x090 */ uint8_t hd1_info[16]; // hd1-disk-parameter from intvector 0x46\n\n // System description table truncated to 16 bytes\n // From 'struct sys_desc_table_struct' in linux/arch/i386/kernel/setup.c.\n /* 0x0a0 */ uint16_t sys_description_len;\n /* 0x0a2 */ uint8_t sys_description_table[14];\n // [0] machine id\n // [1] machine submodel id\n // [2] BIOS revision\n // [3] bit1: MCA bus\n\n /* 0x0b0 */ uint8_t pad3[0x1e0 - 0xb0];\n /* 0x1e0 */ uint32_t alt_mem_k;\n /* 0x1e4 */ uint8_t pad4[4];\n /* 0x1e8 */ uint8_t e820map_entries;\n /* 0x1e9 */ uint8_t eddbuf_entries; // EDD_NR\n /* 0x1ea */ uint8_t pad5[0x1f1 - 0x1ea];\n /* 0x1f1 */ uint8_t setup_sects; // size of setup.S, number of sectors\n /* 0x1f2 */ uint16_t mount_root_rdonly; // MOUNT_ROOT_RDONLY (if !=0)\n /* 0x1f4 */ uint16_t sys_size; // size of compressed kernel-part in the\n // (b)zImage-file (in 16 byte units, rounded up)\n /* 0x1f6 */ uint16_t swap_dev; // (unused AFAIK)\n /* 0x1f8 */ uint16_t ramdisk_flags;\n /* 0x1fa */ uint16_t vga_mode; // (old one)\n /* 0x1fc */ uint16_t orig_root_dev; // (high=Major, low=minor)\n /* 0x1fe */ uint8_t pad6[1];\n /* 0x1ff */ uint8_t aux_device_info;\n /* 0x200 */ uint16_t jump_setup; // Jump to start of setup code,\n // aka \"reserved\" field.\n /* 0x202 */ uint8_t setup_signature[4]; // Signature for SETUP-header, =\"HdrS\"\n /* 0x206 */ uint16_t header_format_version; // Version number of header format;\n /* 0x208 */ uint8_t setup_S_temp0[8]; // Used by setup.S for communication with\n // boot loaders, look there.\n /* 0x210 */ uint8_t loader_type;\n // 0 for old one.\n // else 0xTV:\n // T=0: LILO\n // T=1: Loadlin\n // T=2: bootsect-loader\n // T=3: SYSLINUX\n // T=4: ETHERBOOT\n // V=version\n /* 0x211 */ uint8_t loadflags;\n // bit0 = 1: kernel is loaded high (bzImage)\n // bit7 = 1: Heap and pointer (see below) set by boot\n // loader.\n /* 0x212 */ uint16_t setup_S_temp1;\n /* 0x214 */ uint32_t kernel_start;\n /* 0x218 */ uint32_t initrd_start;\n /* 0x21c */ uint32_t initrd_size;\n /* 0x220 */ uint8_t setup_S_temp2[4];\n /* 0x224 */ uint16_t setup_S_heap_end_pointer;\n /* 0x226 */ uint16_t pad70;\n /* 0x228 */ uint32_t cmd_line_ptr;\n /* 0x22c */ uint8_t pad7[0x2d0 - 0x22c];\n\n /* 0x2d0 : Int 15, ax=e820 memory map. */\n // (linux/include/asm-i386/e820.h, 'struct e820entry')\n#define E820MAX 32\n#define E820_RAM 1\n#define E820_RESERVED 2\n#define E820_ACPI 3 /* usable as RAM once ACPI tables have been read */\n#define E820_NVS 4\n struct {\n uint64_t addr;\n uint64_t size;\n uint32_t type;\n } e820map[E820MAX];\n\n /* 0x550 */ uint8_t pad8[0x600 - 0x550];\n\n // BIOS Enhanced Disk Drive Services.\n // (From linux/include/asm-i386/edd.h, 'struct edd_info')\n // Each 'struct edd_info is 78 bytes, times a max of 6 structs in array.\n /* 0x600 */ uint8_t eddbuf[0x7d4 - 0x600];\n\n /* 0x7d4 */ uint8_t pad9[0x800 - 0x7d4];\n /* 0x800 */ uint8_t commandline[0x800];\n\n uint64_t gdt_table[4];\n};\n\n#define KERNEL_PARAMS_ADDR 0x00090000\n\nstatic void copy_kernel(PCMachine *s, const uint8_t *buf, int buf_len,\n const char *cmd_line)\n{\n uint8_t *ram_ptr;\n int setup_sects, header_len, copy_len, setup_hdr_start, setup_hdr_end;\n uint32_t load_address;\n struct linux_params *params;\n FBDevice *fb_dev;\n \n if (buf_len < 1024) {\n too_small:\n fprintf(stderr, \"Kernel too small\\n\");\n exit(1);\n }\n if (buf[0x1fe] != 0x55 || buf[0x1ff] != 0xaa) {\n fprintf(stderr, \"Invalid kernel magic\\n\");\n exit(1);\n }\n setup_sects = buf[0x1f1];\n if (setup_sects == 0)\n setup_sects = 4;\n header_len = (setup_sects + 1) * 512;\n if (buf_len < header_len)\n goto too_small;\n if (memcmp(buf + 0x202, \"HdrS\", 4) != 0) {\n fprintf(stderr, \"Kernel too old\\n\");\n exit(1);\n }\n load_address = 0x100000; /* we don't support older protocols */\n\n ram_ptr = get_ram_ptr(s, load_address);\n copy_len = buf_len - header_len;\n if (copy_len > (s->ram_size - load_address)) {\n fprintf(stderr, \"Not enough RAM\\n\");\n exit(1);\n }\n memcpy(ram_ptr, buf + header_len, copy_len);\n\n params = (void *)get_ram_ptr(s, KERNEL_PARAMS_ADDR);\n \n memset(params, 0, sizeof(struct linux_params));\n\n /* copy the setup header */\n setup_hdr_start = 0x1f1;\n setup_hdr_end = 0x202 + buf[0x201];\n memcpy((uint8_t *)params + setup_hdr_start, buf + setup_hdr_start,\n setup_hdr_end - setup_hdr_start);\n\n strcpy((char *)params->commandline, cmd_line);\n\n params->mount_root_rdonly = 0;\n params->cmd_line_ptr = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, commandline);\n params->alt_mem_k = (s->ram_size / 1024) - 1024;\n params->loader_type = 0x01;\n#if 0\n if (initrd_size > 0) {\n params->initrd_start = INITRD_LOAD_ADDR;\n params->initrd_size = initrd_size;\n }\n#endif\n params->orig_video_lines = 0;\n params->orig_video_cols = 0;\n\n fb_dev = s->common.fb_dev;\n if (fb_dev) {\n \n params->orig_video_isVGA = 0x23; /* VIDEO_TYPE_VLFB */\n\n params->lfb_depth = 32;\n params->red_size = 8;\n params->red_pos = 16;\n params->green_size = 8;\n params->green_pos = 8;\n params->blue_size = 8;\n params->blue_pos = 0;\n params->rsvd_size = 8;\n params->rsvd_pos = 24;\n\n params->lfb_width = fb_dev->width;\n params->lfb_height = fb_dev->height;\n params->lfb_linelength = fb_dev->stride;\n params->lfb_size = fb_dev->fb_size;\n params->lfb_base = FRAMEBUFFER_BASE_ADDR;\n }\n \n params->gdt_table[2] = 0x00cf9b000000ffffLL; /* CS */\n params->gdt_table[3] = 0x00cf93000000ffffLL; /* DS */\n \n#ifdef USE_KVM\n if (s->kvm_enabled) {\n struct kvm_sregs sregs;\n struct kvm_segment seg;\n struct kvm_regs regs;\n \n /* init flat protected mode */\n\n if (ioctl(s->vcpu_fd, KVM_GET_SREGS, &sregs) < 0) {\n perror(\"KVM_GET_SREGS\");\n exit(1);\n }\n\n sregs.cr0 |= (1 << 0); /* CR0_PE */\n sregs.gdt.base = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, gdt_table);\n sregs.gdt.limit = sizeof(params->gdt_table) - 1;\n \n memset(&seg, 0, sizeof(seg));\n seg.limit = 0xffffffff;\n seg.present = 1;\n seg.db = 1;\n seg.s = 1; /* code/data */\n seg.g = 1; /* 4KB granularity */\n\n seg.type = 0xb; /* code */\n seg.selector = 2 << 3;\n sregs.cs = seg;\n\n seg.type = 0x3; /* data */\n seg.selector = 3 << 3;\n sregs.ds = seg;\n sregs.es = seg;\n sregs.ss = seg;\n sregs.fs = seg;\n sregs.gs = seg;\n \n if (ioctl(s->vcpu_fd, KVM_SET_SREGS, &sregs) < 0) {\n perror(\"KVM_SET_SREGS\");\n exit(1);\n }\n \n memset(®s, 0, sizeof(regs));\n regs.rip = load_address;\n regs.rsi = KERNEL_PARAMS_ADDR;\n regs.rflags = 0x2;\n if (ioctl(s->vcpu_fd, KVM_SET_REGS, ®s) < 0) {\n perror(\"KVM_SET_REGS\");\n exit(1);\n }\n } else\n#endif\n {\n int i;\n X86CPUSeg sd;\n uint32_t val;\n val = x86_cpu_get_reg(s->cpu_state, X86_CPU_REG_CR0);\n x86_cpu_set_reg(s->cpu_state, X86_CPU_REG_CR0, val | (1 << 0));\n \n sd.base = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, gdt_table);\n sd.limit = sizeof(params->gdt_table) - 1;\n x86_cpu_set_seg(s->cpu_state, X86_CPU_SEG_GDT, &sd);\n sd.sel = 2 << 3;\n sd.base = 0;\n sd.limit = 0xffffffff;\n sd.flags = 0xc09b;\n x86_cpu_set_seg(s->cpu_state, X86_CPU_SEG_CS, &sd);\n sd.sel = 3 << 3;\n sd.flags = 0xc093;\n for(i = 0; i < 6; i++) {\n if (i != X86_CPU_SEG_CS) {\n x86_cpu_set_seg(s->cpu_state, i, &sd);\n }\n }\n \n x86_cpu_set_reg(s->cpu_state, X86_CPU_REG_EIP, load_address);\n x86_cpu_set_reg(s->cpu_state, 6, KERNEL_PARAMS_ADDR); /* esi */\n }\n\n /* map PCI interrupts (no BIOS, so we must do it) */\n {\n uint8_t elcr[2];\n static const uint8_t pci_irqs[4] = { 9, 10, 11, 12 };\n\n i440fx_map_interrupts(s->i440fx_state, elcr, pci_irqs);\n /* XXX: KVM support */\n if (s->pic_state) {\n pic2_set_elcr(s->pic_state, elcr);\n }\n }\n}\n\n/* in ms */\nstatic int pc_machine_get_sleep_duration(VirtMachine *s1, int delay)\n{\n PCMachine *s = (PCMachine *)s1;\n\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n /* XXX: improve */\n cmos_update_irq(s->cmos_state);\n delay = 0;\n } else\n#endif\n {\n cmos_update_irq(s->cmos_state);\n delay = min_int(delay, pit_update_irq(s->pit_state));\n if (!x86_cpu_get_power_down(s->cpu_state))\n delay = 0;\n }\n return delay;\n}\n\nstatic void pc_machine_interp(VirtMachine *s1, int max_exec_cycles)\n{\n PCMachine *s = (PCMachine *)s1;\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n kvm_exec(s);\n } else \n#endif\n {\n x86_cpu_interp(s->cpu_state, max_exec_cycles);\n }\n}\n\nconst VirtMachineClass pc_machine_class = {\n \"pc\",\n pc_machine_set_defaults,\n pc_machine_init,\n pc_machine_end,\n pc_machine_get_sleep_duration,\n pc_machine_interp,\n pc_vm_mouse_is_absolute,\n pc_vm_send_mouse_event,\n pc_vm_send_key_event,\n};\n"], ["/linuxpdf/tinyemu/virtio.c", "/*\n * VIRTIO driver\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"virtio.h\"\n\n//#define DEBUG_VIRTIO\n\n/* MMIO addresses - from the Linux kernel */\n#define VIRTIO_MMIO_MAGIC_VALUE\t\t0x000\n#define VIRTIO_MMIO_VERSION\t\t0x004\n#define VIRTIO_MMIO_DEVICE_ID\t\t0x008\n#define VIRTIO_MMIO_VENDOR_ID\t\t0x00c\n#define VIRTIO_MMIO_DEVICE_FEATURES\t0x010\n#define VIRTIO_MMIO_DEVICE_FEATURES_SEL\t0x014\n#define VIRTIO_MMIO_DRIVER_FEATURES\t0x020\n#define VIRTIO_MMIO_DRIVER_FEATURES_SEL\t0x024\n#define VIRTIO_MMIO_GUEST_PAGE_SIZE\t0x028 /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_SEL\t\t0x030\n#define VIRTIO_MMIO_QUEUE_NUM_MAX\t0x034\n#define VIRTIO_MMIO_QUEUE_NUM\t\t0x038\n#define VIRTIO_MMIO_QUEUE_ALIGN\t\t0x03c /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_PFN\t\t0x040 /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_READY\t\t0x044\n#define VIRTIO_MMIO_QUEUE_NOTIFY\t0x050\n#define VIRTIO_MMIO_INTERRUPT_STATUS\t0x060\n#define VIRTIO_MMIO_INTERRUPT_ACK\t0x064\n#define VIRTIO_MMIO_STATUS\t\t0x070\n#define VIRTIO_MMIO_QUEUE_DESC_LOW\t0x080\n#define VIRTIO_MMIO_QUEUE_DESC_HIGH\t0x084\n#define VIRTIO_MMIO_QUEUE_AVAIL_LOW\t0x090\n#define VIRTIO_MMIO_QUEUE_AVAIL_HIGH\t0x094\n#define VIRTIO_MMIO_QUEUE_USED_LOW\t0x0a0\n#define VIRTIO_MMIO_QUEUE_USED_HIGH\t0x0a4\n#define VIRTIO_MMIO_CONFIG_GENERATION\t0x0fc\n#define VIRTIO_MMIO_CONFIG\t\t0x100\n\n/* PCI registers */\n#define VIRTIO_PCI_DEVICE_FEATURE_SEL\t0x000\n#define VIRTIO_PCI_DEVICE_FEATURE\t0x004\n#define VIRTIO_PCI_GUEST_FEATURE_SEL\t0x008\n#define VIRTIO_PCI_GUEST_FEATURE\t0x00c\n#define VIRTIO_PCI_MSIX_CONFIG 0x010\n#define VIRTIO_PCI_NUM_QUEUES 0x012\n#define VIRTIO_PCI_DEVICE_STATUS 0x014\n#define VIRTIO_PCI_CONFIG_GENERATION 0x015\n#define VIRTIO_PCI_QUEUE_SEL\t\t0x016\n#define VIRTIO_PCI_QUEUE_SIZE\t 0x018\n#define VIRTIO_PCI_QUEUE_MSIX_VECTOR 0x01a\n#define VIRTIO_PCI_QUEUE_ENABLE 0x01c\n#define VIRTIO_PCI_QUEUE_NOTIFY_OFF 0x01e\n#define VIRTIO_PCI_QUEUE_DESC_LOW\t0x020\n#define VIRTIO_PCI_QUEUE_DESC_HIGH\t0x024\n#define VIRTIO_PCI_QUEUE_AVAIL_LOW\t0x028\n#define VIRTIO_PCI_QUEUE_AVAIL_HIGH\t0x02c\n#define VIRTIO_PCI_QUEUE_USED_LOW\t0x030\n#define VIRTIO_PCI_QUEUE_USED_HIGH\t0x034\n\n#define VIRTIO_PCI_CFG_OFFSET 0x0000\n#define VIRTIO_PCI_ISR_OFFSET 0x1000\n#define VIRTIO_PCI_CONFIG_OFFSET 0x2000\n#define VIRTIO_PCI_NOTIFY_OFFSET 0x3000\n\n#define VIRTIO_PCI_CAP_LEN 16\n\n#define MAX_QUEUE 8\n#define MAX_CONFIG_SPACE_SIZE 256\n#define MAX_QUEUE_NUM 16\n\ntypedef struct {\n uint32_t ready; /* 0 or 1 */\n uint32_t num;\n uint16_t last_avail_idx;\n virtio_phys_addr_t desc_addr;\n virtio_phys_addr_t avail_addr;\n virtio_phys_addr_t used_addr;\n BOOL manual_recv; /* if TRUE, the device_recv() callback is not called */\n} QueueState;\n\n#define VRING_DESC_F_NEXT\t1\n#define VRING_DESC_F_WRITE\t2\n#define VRING_DESC_F_INDIRECT\t4\n\ntypedef struct {\n uint64_t addr;\n uint32_t len;\n uint16_t flags; /* VRING_DESC_F_x */\n uint16_t next;\n} VIRTIODesc;\n\n/* return < 0 to stop the notification (it must be manually restarted\n later), 0 if OK */\ntypedef int VIRTIODeviceRecvFunc(VIRTIODevice *s1, int queue_idx,\n int desc_idx, int read_size,\n int write_size);\n\n/* return NULL if no RAM at this address. The mapping is valid for one page */\ntypedef uint8_t *VIRTIOGetRAMPtrFunc(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw);\n\nstruct VIRTIODevice {\n PhysMemoryMap *mem_map;\n PhysMemoryRange *mem_range;\n /* PCI only */\n PCIDevice *pci_dev;\n /* MMIO only */\n IRQSignal *irq;\n VIRTIOGetRAMPtrFunc *get_ram_ptr;\n int debug;\n\n uint32_t int_status;\n uint32_t status;\n uint32_t device_features_sel;\n uint32_t queue_sel; /* currently selected queue */\n QueueState queue[MAX_QUEUE];\n\n /* device specific */\n uint32_t device_id;\n uint32_t vendor_id;\n uint32_t device_features;\n VIRTIODeviceRecvFunc *device_recv;\n void (*config_write)(VIRTIODevice *s); /* called after the config\n is written */\n uint32_t config_space_size; /* in bytes, must be multiple of 4 */\n uint8_t config_space[MAX_CONFIG_SPACE_SIZE];\n};\n\nstatic uint32_t virtio_mmio_read(void *opaque, uint32_t offset1, int size_log2);\nstatic void virtio_mmio_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t virtio_pci_read(void *opaque, uint32_t offset, int size_log2);\nstatic void virtio_pci_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\n\nstatic void virtio_reset(VIRTIODevice *s)\n{\n int i;\n\n s->status = 0;\n s->queue_sel = 0;\n s->device_features_sel = 0;\n s->int_status = 0;\n for(i = 0; i < MAX_QUEUE; i++) {\n QueueState *qs = &s->queue[i];\n qs->ready = 0;\n qs->num = MAX_QUEUE_NUM;\n qs->desc_addr = 0;\n qs->avail_addr = 0;\n qs->used_addr = 0;\n qs->last_avail_idx = 0;\n }\n}\n\nstatic uint8_t *virtio_pci_get_ram_ptr(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw)\n{\n return pci_device_get_dma_ptr(s->pci_dev, paddr, is_rw);\n}\n\nstatic uint8_t *virtio_mmio_get_ram_ptr(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(s->mem_map, paddr, is_rw);\n}\n\nstatic void virtio_add_pci_capability(VIRTIODevice *s, int cfg_type,\n int bar, uint32_t offset, uint32_t len,\n uint32_t mult)\n{\n uint8_t cap[20];\n int cap_len;\n if (cfg_type == 2)\n cap_len = 20;\n else\n cap_len = 16;\n memset(cap, 0, cap_len);\n cap[0] = 0x09; /* vendor specific */\n cap[2] = cap_len; /* set by pci_add_capability() */\n cap[3] = cfg_type;\n cap[4] = bar;\n put_le32(cap + 8, offset);\n put_le32(cap + 12, len);\n if (cfg_type == 2)\n put_le32(cap + 16, mult);\n pci_add_capability(s->pci_dev, cap, cap_len);\n}\n\nstatic void virtio_pci_bar_set(void *opaque, int bar_num,\n uint32_t addr, BOOL enabled)\n{\n VIRTIODevice *s = opaque;\n phys_mem_set_addr(s->mem_range, addr, enabled);\n}\n\nstatic void virtio_init(VIRTIODevice *s, VIRTIOBusDef *bus,\n uint32_t device_id, int config_space_size,\n VIRTIODeviceRecvFunc *device_recv)\n{\n memset(s, 0, sizeof(*s));\n\n if (bus->pci_bus) {\n uint16_t pci_device_id, class_id;\n char name[32];\n int bar_num;\n \n switch(device_id) {\n case 1:\n pci_device_id = 0x1000; /* net */\n class_id = 0x0200;\n break;\n case 2:\n pci_device_id = 0x1001; /* block */\n class_id = 0x0100; /* XXX: check it */\n break;\n case 3:\n pci_device_id = 0x1003; /* console */\n class_id = 0x0780;\n break;\n case 9:\n pci_device_id = 0x1040 + device_id; /* use new device ID */\n class_id = 0x2;\n break;\n case 18:\n pci_device_id = 0x1040 + device_id; /* use new device ID */\n class_id = 0x0980;\n break;\n default:\n abort();\n }\n snprintf(name, sizeof(name), \"virtio_%04x\", pci_device_id);\n s->pci_dev = pci_register_device(bus->pci_bus, name, -1,\n 0x1af4, pci_device_id, 0x00,\n class_id);\n pci_device_set_config16(s->pci_dev, 0x2c, 0x1af4);\n pci_device_set_config16(s->pci_dev, 0x2e, device_id);\n pci_device_set_config8(s->pci_dev, PCI_INTERRUPT_PIN, 1);\n\n bar_num = 4;\n virtio_add_pci_capability(s, 1, bar_num,\n VIRTIO_PCI_CFG_OFFSET, 0x1000, 0); /* common */\n virtio_add_pci_capability(s, 3, bar_num,\n VIRTIO_PCI_ISR_OFFSET, 0x1000, 0); /* isr */\n virtio_add_pci_capability(s, 4, bar_num,\n VIRTIO_PCI_CONFIG_OFFSET, 0x1000, 0); /* config */\n virtio_add_pci_capability(s, 2, bar_num,\n VIRTIO_PCI_NOTIFY_OFFSET, 0x1000, 0); /* notify */\n \n s->get_ram_ptr = virtio_pci_get_ram_ptr;\n s->irq = pci_device_get_irq(s->pci_dev, 0);\n s->mem_map = pci_device_get_mem_map(s->pci_dev);\n s->mem_range = cpu_register_device(s->mem_map, 0, 0x4000, s,\n virtio_pci_read, virtio_pci_write,\n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32 | DEVIO_DISABLED);\n pci_register_bar(s->pci_dev, bar_num, 0x4000, PCI_ADDRESS_SPACE_MEM,\n s, virtio_pci_bar_set);\n } else {\n /* MMIO case */\n s->mem_map = bus->mem_map;\n s->irq = bus->irq;\n s->mem_range = cpu_register_device(s->mem_map, bus->addr, VIRTIO_PAGE_SIZE,\n s, virtio_mmio_read, virtio_mmio_write,\n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32);\n s->get_ram_ptr = virtio_mmio_get_ram_ptr;\n }\n\n s->device_id = device_id;\n s->vendor_id = 0xffff;\n s->config_space_size = config_space_size;\n s->device_recv = device_recv;\n virtio_reset(s);\n}\n\nstatic uint16_t virtio_read16(VIRTIODevice *s, virtio_phys_addr_t addr)\n{\n uint8_t *ptr;\n if (addr & 1)\n return 0; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, FALSE);\n if (!ptr)\n return 0;\n return *(uint16_t *)ptr;\n}\n\nstatic void virtio_write16(VIRTIODevice *s, virtio_phys_addr_t addr,\n uint16_t val)\n{\n uint8_t *ptr;\n if (addr & 1)\n return; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return;\n *(uint16_t *)ptr = val;\n}\n\nstatic void virtio_write32(VIRTIODevice *s, virtio_phys_addr_t addr,\n uint32_t val)\n{\n uint8_t *ptr;\n if (addr & 3)\n return; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return;\n *(uint32_t *)ptr = val;\n}\n\nstatic int virtio_memcpy_from_ram(VIRTIODevice *s, uint8_t *buf,\n virtio_phys_addr_t addr, int count)\n{\n uint8_t *ptr;\n int l;\n\n while (count > 0) {\n l = min_int(count, VIRTIO_PAGE_SIZE - (addr & (VIRTIO_PAGE_SIZE - 1)));\n ptr = s->get_ram_ptr(s, addr, FALSE);\n if (!ptr)\n return -1;\n memcpy(buf, ptr, l);\n addr += l;\n buf += l;\n count -= l;\n }\n return 0;\n}\n\nstatic int virtio_memcpy_to_ram(VIRTIODevice *s, virtio_phys_addr_t addr, \n const uint8_t *buf, int count)\n{\n uint8_t *ptr;\n int l;\n\n while (count > 0) {\n l = min_int(count, VIRTIO_PAGE_SIZE - (addr & (VIRTIO_PAGE_SIZE - 1)));\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return -1;\n memcpy(ptr, buf, l);\n addr += l;\n buf += l;\n count -= l;\n }\n return 0;\n}\n\nstatic int get_desc(VIRTIODevice *s, VIRTIODesc *desc, \n int queue_idx, int desc_idx)\n{\n QueueState *qs = &s->queue[queue_idx];\n return virtio_memcpy_from_ram(s, (void *)desc, qs->desc_addr +\n desc_idx * sizeof(VIRTIODesc),\n sizeof(VIRTIODesc));\n}\n\nstatic int memcpy_to_from_queue(VIRTIODevice *s, uint8_t *buf,\n int queue_idx, int desc_idx,\n int offset, int count, BOOL to_queue)\n{\n VIRTIODesc desc;\n int l, f_write_flag;\n\n if (count == 0)\n return 0;\n\n get_desc(s, &desc, queue_idx, desc_idx);\n\n if (to_queue) {\n f_write_flag = VRING_DESC_F_WRITE;\n /* find the first write descriptor */\n for(;;) {\n if ((desc.flags & VRING_DESC_F_WRITE) == f_write_flag)\n break;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n } else {\n f_write_flag = 0;\n }\n\n /* find the descriptor at offset */\n for(;;) {\n if ((desc.flags & VRING_DESC_F_WRITE) != f_write_flag)\n return -1;\n if (offset < desc.len)\n break;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n offset -= desc.len;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n\n for(;;) {\n l = min_int(count, desc.len - offset);\n if (to_queue)\n virtio_memcpy_to_ram(s, desc.addr + offset, buf, l);\n else\n virtio_memcpy_from_ram(s, buf, desc.addr + offset, l);\n count -= l;\n if (count == 0)\n break;\n offset += l;\n buf += l;\n if (offset == desc.len) {\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n if ((desc.flags & VRING_DESC_F_WRITE) != f_write_flag)\n return -1;\n offset = 0;\n }\n }\n return 0;\n}\n\nstatic int memcpy_from_queue(VIRTIODevice *s, void *buf,\n int queue_idx, int desc_idx,\n int offset, int count)\n{\n return memcpy_to_from_queue(s, buf, queue_idx, desc_idx, offset, count,\n FALSE);\n}\n\nstatic int memcpy_to_queue(VIRTIODevice *s,\n int queue_idx, int desc_idx,\n int offset, const void *buf, int count)\n{\n return memcpy_to_from_queue(s, (void *)buf, queue_idx, desc_idx, offset,\n count, TRUE);\n}\n\n/* signal that the descriptor has been consumed */\nstatic void virtio_consume_desc(VIRTIODevice *s,\n int queue_idx, int desc_idx, int desc_len)\n{\n QueueState *qs = &s->queue[queue_idx];\n virtio_phys_addr_t addr;\n uint32_t index;\n\n addr = qs->used_addr + 2;\n index = virtio_read16(s, addr);\n virtio_write16(s, addr, index + 1);\n\n addr = qs->used_addr + 4 + (index & (qs->num - 1)) * 8;\n virtio_write32(s, addr, desc_idx);\n virtio_write32(s, addr + 4, desc_len);\n\n s->int_status |= 1;\n set_irq(s->irq, 1);\n}\n\nstatic int get_desc_rw_size(VIRTIODevice *s, \n int *pread_size, int *pwrite_size,\n int queue_idx, int desc_idx)\n{\n VIRTIODesc desc;\n int read_size, write_size;\n\n read_size = 0;\n write_size = 0;\n get_desc(s, &desc, queue_idx, desc_idx);\n\n for(;;) {\n if (desc.flags & VRING_DESC_F_WRITE)\n break;\n read_size += desc.len;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n goto done;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n \n for(;;) {\n if (!(desc.flags & VRING_DESC_F_WRITE))\n return -1;\n write_size += desc.len;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n break;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n\n done:\n *pread_size = read_size;\n *pwrite_size = write_size;\n return 0;\n}\n\n/* XXX: test if the queue is ready ? */\nstatic void queue_notify(VIRTIODevice *s, int queue_idx)\n{\n QueueState *qs = &s->queue[queue_idx];\n uint16_t avail_idx;\n int desc_idx, read_size, write_size;\n\n if (qs->manual_recv)\n return;\n\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n while (qs->last_avail_idx != avail_idx) {\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (!get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx)) {\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"queue_notify: idx=%d read_size=%d write_size=%d\\n\",\n queue_idx, read_size, write_size);\n }\n#endif\n if (s->device_recv(s, queue_idx, desc_idx,\n read_size, write_size) < 0)\n break;\n }\n qs->last_avail_idx++;\n }\n}\n\nstatic uint32_t virtio_config_read(VIRTIODevice *s, uint32_t offset,\n int size_log2)\n{\n uint32_t val;\n switch(size_log2) {\n case 0:\n if (offset < s->config_space_size) {\n val = s->config_space[offset];\n } else {\n val = 0;\n }\n break;\n case 1:\n if (offset < (s->config_space_size - 1)) {\n val = get_le16(&s->config_space[offset]);\n } else {\n val = 0;\n }\n break;\n case 2:\n if (offset < (s->config_space_size - 3)) {\n val = get_le32(s->config_space + offset);\n } else {\n val = 0;\n }\n break;\n default:\n abort();\n }\n return val;\n}\n\nstatic void virtio_config_write(VIRTIODevice *s, uint32_t offset,\n uint32_t val, int size_log2)\n{\n switch(size_log2) {\n case 0:\n if (offset < s->config_space_size) {\n s->config_space[offset] = val;\n if (s->config_write)\n s->config_write(s);\n }\n break;\n case 1:\n if (offset < s->config_space_size - 1) {\n put_le16(s->config_space + offset, val);\n if (s->config_write)\n s->config_write(s);\n }\n break;\n case 2:\n if (offset < s->config_space_size - 3) {\n put_le32(s->config_space + offset, val);\n if (s->config_write)\n s->config_write(s);\n }\n break;\n }\n}\n\nstatic uint32_t virtio_mmio_read(void *opaque, uint32_t offset, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t val;\n\n if (offset >= VIRTIO_MMIO_CONFIG) {\n return virtio_config_read(s, offset - VIRTIO_MMIO_CONFIG, size_log2);\n }\n\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_MMIO_MAGIC_VALUE:\n val = 0x74726976;\n break;\n case VIRTIO_MMIO_VERSION:\n val = 2;\n break;\n case VIRTIO_MMIO_DEVICE_ID:\n val = s->device_id;\n break;\n case VIRTIO_MMIO_VENDOR_ID:\n val = s->vendor_id;\n break;\n case VIRTIO_MMIO_DEVICE_FEATURES:\n switch(s->device_features_sel) {\n case 0:\n val = s->device_features;\n break;\n case 1:\n val = 1; /* version 1 */\n break;\n default:\n val = 0;\n break;\n }\n break;\n case VIRTIO_MMIO_DEVICE_FEATURES_SEL:\n val = s->device_features_sel;\n break;\n case VIRTIO_MMIO_QUEUE_SEL:\n val = s->queue_sel;\n break;\n case VIRTIO_MMIO_QUEUE_NUM_MAX:\n val = MAX_QUEUE_NUM;\n break;\n case VIRTIO_MMIO_QUEUE_NUM:\n val = s->queue[s->queue_sel].num;\n break;\n case VIRTIO_MMIO_QUEUE_DESC_LOW:\n val = s->queue[s->queue_sel].desc_addr;\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_LOW:\n val = s->queue[s->queue_sel].avail_addr;\n break;\n case VIRTIO_MMIO_QUEUE_USED_LOW:\n val = s->queue[s->queue_sel].used_addr;\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_MMIO_QUEUE_DESC_HIGH:\n val = s->queue[s->queue_sel].desc_addr >> 32;\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_HIGH:\n val = s->queue[s->queue_sel].avail_addr >> 32;\n break;\n case VIRTIO_MMIO_QUEUE_USED_HIGH:\n val = s->queue[s->queue_sel].used_addr >> 32;\n break;\n#endif\n case VIRTIO_MMIO_QUEUE_READY:\n val = s->queue[s->queue_sel].ready;\n break;\n case VIRTIO_MMIO_INTERRUPT_STATUS:\n val = s->int_status;\n break;\n case VIRTIO_MMIO_STATUS:\n val = s->status;\n break;\n case VIRTIO_MMIO_CONFIG_GENERATION:\n val = 0;\n break;\n default:\n val = 0;\n break;\n }\n } else {\n val = 0;\n }\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_mmio_read: offset=0x%x val=0x%x size=%d\\n\", \n offset, val, 1 << size_log2);\n }\n#endif\n return val;\n}\n\n#if VIRTIO_ADDR_BITS == 64\nstatic void set_low32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = (*paddr & ~(virtio_phys_addr_t)0xffffffff) | val;\n}\n\nstatic void set_high32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = (*paddr & 0xffffffff) | ((virtio_phys_addr_t)val << 32);\n}\n#else\nstatic void set_low32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = val;\n}\n#endif\n\nstatic void virtio_mmio_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n VIRTIODevice *s = opaque;\n \n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_mmio_write: offset=0x%x val=0x%x size=%d\\n\",\n offset, val, 1 << size_log2);\n }\n#endif\n\n if (offset >= VIRTIO_MMIO_CONFIG) {\n virtio_config_write(s, offset - VIRTIO_MMIO_CONFIG, val, size_log2);\n return;\n }\n\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_MMIO_DEVICE_FEATURES_SEL:\n s->device_features_sel = val;\n break;\n case VIRTIO_MMIO_QUEUE_SEL:\n if (val < MAX_QUEUE)\n s->queue_sel = val;\n break;\n case VIRTIO_MMIO_QUEUE_NUM:\n if ((val & (val - 1)) == 0 && val > 0) {\n s->queue[s->queue_sel].num = val;\n }\n break;\n case VIRTIO_MMIO_QUEUE_DESC_LOW:\n set_low32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_LOW:\n set_low32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_USED_LOW:\n set_low32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_MMIO_QUEUE_DESC_HIGH:\n set_high32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_HIGH:\n set_high32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_USED_HIGH:\n set_high32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#endif\n case VIRTIO_MMIO_STATUS:\n s->status = val;\n if (val == 0) {\n /* reset */\n set_irq(s->irq, 0);\n virtio_reset(s);\n }\n break;\n case VIRTIO_MMIO_QUEUE_READY:\n s->queue[s->queue_sel].ready = val & 1;\n break;\n case VIRTIO_MMIO_QUEUE_NOTIFY:\n if (val < MAX_QUEUE)\n queue_notify(s, val);\n break;\n case VIRTIO_MMIO_INTERRUPT_ACK:\n s->int_status &= ~val;\n if (s->int_status == 0) {\n set_irq(s->irq, 0);\n }\n break;\n }\n }\n}\n\nstatic uint32_t virtio_pci_read(void *opaque, uint32_t offset1, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t offset;\n uint32_t val = 0;\n\n offset = offset1 & 0xfff;\n switch(offset1 >> 12) {\n case VIRTIO_PCI_CFG_OFFSET >> 12:\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_FEATURE:\n switch(s->device_features_sel) {\n case 0:\n val = s->device_features;\n break;\n case 1:\n val = 1; /* version 1 */\n break;\n default:\n val = 0;\n break;\n }\n break;\n case VIRTIO_PCI_DEVICE_FEATURE_SEL:\n val = s->device_features_sel;\n break;\n case VIRTIO_PCI_QUEUE_DESC_LOW:\n val = s->queue[s->queue_sel].desc_addr;\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_LOW:\n val = s->queue[s->queue_sel].avail_addr;\n break;\n case VIRTIO_PCI_QUEUE_USED_LOW:\n val = s->queue[s->queue_sel].used_addr;\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_PCI_QUEUE_DESC_HIGH:\n val = s->queue[s->queue_sel].desc_addr >> 32;\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_HIGH:\n val = s->queue[s->queue_sel].avail_addr >> 32;\n break;\n case VIRTIO_PCI_QUEUE_USED_HIGH:\n val = s->queue[s->queue_sel].used_addr >> 32;\n break;\n#endif\n }\n } else if (size_log2 == 1) {\n switch(offset) {\n case VIRTIO_PCI_NUM_QUEUES:\n val = MAX_QUEUE_NUM;\n break;\n case VIRTIO_PCI_QUEUE_SEL:\n val = s->queue_sel;\n break;\n case VIRTIO_PCI_QUEUE_SIZE:\n val = s->queue[s->queue_sel].num;\n break;\n case VIRTIO_PCI_QUEUE_ENABLE:\n val = s->queue[s->queue_sel].ready;\n break;\n case VIRTIO_PCI_QUEUE_NOTIFY_OFF:\n val = 0;\n break;\n }\n } else if (size_log2 == 0) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_STATUS:\n val = s->status;\n break;\n }\n }\n break;\n case VIRTIO_PCI_ISR_OFFSET >> 12:\n if (offset == 0 && size_log2 == 0) {\n val = s->int_status;\n s->int_status = 0;\n set_irq(s->irq, 0);\n }\n break;\n case VIRTIO_PCI_CONFIG_OFFSET >> 12:\n val = virtio_config_read(s, offset, size_log2);\n break;\n }\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_pci_read: offset=0x%x val=0x%x size=%d\\n\", \n offset1, val, 1 << size_log2);\n }\n#endif\n return val;\n}\n\nstatic void virtio_pci_write(void *opaque, uint32_t offset1,\n uint32_t val, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t offset;\n \n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_pci_write: offset=0x%x val=0x%x size=%d\\n\",\n offset1, val, 1 << size_log2);\n }\n#endif\n offset = offset1 & 0xfff;\n switch(offset1 >> 12) {\n case VIRTIO_PCI_CFG_OFFSET >> 12:\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_FEATURE_SEL:\n s->device_features_sel = val;\n break;\n case VIRTIO_PCI_QUEUE_DESC_LOW:\n set_low32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_LOW:\n set_low32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_USED_LOW:\n set_low32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_PCI_QUEUE_DESC_HIGH:\n set_high32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_HIGH:\n set_high32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_USED_HIGH:\n set_high32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#endif\n }\n } else if (size_log2 == 1) {\n switch(offset) {\n case VIRTIO_PCI_QUEUE_SEL:\n if (val < MAX_QUEUE)\n s->queue_sel = val;\n break;\n case VIRTIO_PCI_QUEUE_SIZE:\n if ((val & (val - 1)) == 0 && val > 0) {\n s->queue[s->queue_sel].num = val;\n }\n break;\n case VIRTIO_PCI_QUEUE_ENABLE:\n s->queue[s->queue_sel].ready = val & 1;\n break;\n }\n } else if (size_log2 == 0) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_STATUS:\n s->status = val;\n if (val == 0) {\n /* reset */\n set_irq(s->irq, 0);\n virtio_reset(s);\n }\n break;\n }\n }\n break;\n case VIRTIO_PCI_CONFIG_OFFSET >> 12:\n virtio_config_write(s, offset, val, size_log2);\n break;\n case VIRTIO_PCI_NOTIFY_OFFSET >> 12:\n if (val < MAX_QUEUE)\n queue_notify(s, val);\n break;\n }\n}\n\nvoid virtio_set_debug(VIRTIODevice *s, int debug)\n{\n s->debug = debug;\n}\n\nstatic void virtio_config_change_notify(VIRTIODevice *s)\n{\n /* INT_CONFIG interrupt */\n s->int_status |= 2;\n set_irq(s->irq, 1);\n}\n\n/*********************************************************************/\n/* block device */\n\ntypedef struct {\n uint32_t type;\n uint8_t *buf;\n int write_size;\n int queue_idx;\n int desc_idx;\n} BlockRequest;\n\ntypedef struct VIRTIOBlockDevice {\n VIRTIODevice common;\n BlockDevice *bs;\n\n BOOL req_in_progress;\n BlockRequest req; /* request in progress */\n} VIRTIOBlockDevice;\n\ntypedef struct {\n uint32_t type;\n uint32_t ioprio;\n uint64_t sector_num;\n} BlockRequestHeader;\n\n#define VIRTIO_BLK_T_IN 0\n#define VIRTIO_BLK_T_OUT 1\n#define VIRTIO_BLK_T_FLUSH 4\n#define VIRTIO_BLK_T_FLUSH_OUT 5\n\n#define VIRTIO_BLK_S_OK 0\n#define VIRTIO_BLK_S_IOERR 1\n#define VIRTIO_BLK_S_UNSUPP 2\n\n#define SECTOR_SIZE 512\n\nstatic void virtio_block_req_end(VIRTIODevice *s, int ret)\n{\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n int write_size;\n int queue_idx = s1->req.queue_idx;\n int desc_idx = s1->req.desc_idx;\n uint8_t *buf, buf1[1];\n\n switch(s1->req.type) {\n case VIRTIO_BLK_T_IN:\n write_size = s1->req.write_size;\n buf = s1->req.buf;\n if (ret < 0) {\n buf[write_size - 1] = VIRTIO_BLK_S_IOERR;\n } else {\n buf[write_size - 1] = VIRTIO_BLK_S_OK;\n }\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, write_size);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, write_size);\n break;\n case VIRTIO_BLK_T_OUT:\n if (ret < 0)\n buf1[0] = VIRTIO_BLK_S_IOERR;\n else\n buf1[0] = VIRTIO_BLK_S_OK;\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf1, sizeof(buf1));\n virtio_consume_desc(s, queue_idx, desc_idx, 1);\n break;\n default:\n abort();\n }\n}\n\nstatic void virtio_block_req_cb(void *opaque, int ret)\n{\n VIRTIODevice *s = opaque;\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n\n virtio_block_req_end(s, ret);\n \n s1->req_in_progress = FALSE;\n\n /* handle next requests */\n queue_notify((VIRTIODevice *)s, s1->req.queue_idx);\n}\n\n/* XXX: handle async I/O */\nstatic int virtio_block_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n BlockDevice *bs = s1->bs;\n BlockRequestHeader h;\n uint8_t *buf;\n int len, ret;\n\n if (s1->req_in_progress)\n return -1;\n \n if (memcpy_from_queue(s, &h, queue_idx, desc_idx, 0, sizeof(h)) < 0)\n return 0;\n s1->req.type = h.type;\n s1->req.queue_idx = queue_idx;\n s1->req.desc_idx = desc_idx;\n switch(h.type) {\n case VIRTIO_BLK_T_IN:\n s1->req.buf = malloc(write_size);\n s1->req.write_size = write_size;\n ret = bs->read_async(bs, h.sector_num, s1->req.buf, \n (write_size - 1) / SECTOR_SIZE,\n virtio_block_req_cb, s);\n if (ret > 0) {\n /* asyncronous read */\n s1->req_in_progress = TRUE;\n } else {\n virtio_block_req_end(s, ret);\n }\n break;\n case VIRTIO_BLK_T_OUT:\n assert(write_size >= 1);\n len = read_size - sizeof(h);\n buf = malloc(len);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, sizeof(h), len);\n ret = bs->write_async(bs, h.sector_num, buf, len / SECTOR_SIZE,\n virtio_block_req_cb, s);\n free(buf);\n if (ret > 0) {\n /* asyncronous write */\n s1->req_in_progress = TRUE;\n } else {\n virtio_block_req_end(s, ret);\n }\n break;\n default:\n break;\n }\n return 0;\n}\n\nVIRTIODevice *virtio_block_init(VIRTIOBusDef *bus, BlockDevice *bs)\n{\n VIRTIOBlockDevice *s;\n uint64_t nb_sectors;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 2, 8, virtio_block_recv_request);\n s->bs = bs;\n \n nb_sectors = bs->get_sector_count(bs);\n put_le32(s->common.config_space, nb_sectors);\n put_le32(s->common.config_space + 4, nb_sectors >> 32);\n\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* network device */\n\ntypedef struct VIRTIONetDevice {\n VIRTIODevice common;\n EthernetDevice *es;\n int header_size;\n} VIRTIONetDevice;\n\ntypedef struct {\n uint8_t flags;\n uint8_t gso_type;\n uint16_t hdr_len;\n uint16_t gso_size;\n uint16_t csum_start;\n uint16_t csum_offset;\n uint16_t num_buffers;\n} VIRTIONetHeader;\n\nstatic int virtio_net_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIONetDevice *s1 = (VIRTIONetDevice *)s;\n EthernetDevice *es = s1->es;\n VIRTIONetHeader h;\n uint8_t *buf;\n int len;\n\n if (queue_idx == 1) {\n /* send to network */\n if (memcpy_from_queue(s, &h, queue_idx, desc_idx, 0, s1->header_size) < 0)\n return 0;\n len = read_size - s1->header_size;\n buf = malloc(len);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, s1->header_size, len);\n es->write_packet(es, buf, len);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\nstatic BOOL virtio_net_can_write_packet(EthernetDevice *es)\n{\n VIRTIODevice *s = es->device_opaque;\n QueueState *qs = &s->queue[0];\n uint16_t avail_idx;\n\n if (!qs->ready)\n return FALSE;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n return qs->last_avail_idx != avail_idx;\n}\n\nstatic void virtio_net_write_packet(EthernetDevice *es, const uint8_t *buf, int buf_len)\n{\n VIRTIODevice *s = es->device_opaque;\n VIRTIONetDevice *s1 = (VIRTIONetDevice *)s;\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n VIRTIONetHeader h;\n int len, read_size, write_size;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx))\n return;\n len = s1->header_size + buf_len; \n if (len > write_size)\n return;\n memset(&h, 0, s1->header_size);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, &h, s1->header_size);\n memcpy_to_queue(s, queue_idx, desc_idx, s1->header_size, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, len);\n qs->last_avail_idx++;\n}\n\nstatic void virtio_net_set_carrier(EthernetDevice *es, BOOL carrier_state)\n{\n#if 0\n VIRTIODevice *s1 = es->device_opaque;\n VIRTIONetDevice *s = (VIRTIONetDevice *)s1;\n int cur_carrier_state;\n\n // printf(\"virtio_net_set_carrier: %d\\n\", carrier_state);\n cur_carrier_state = s->common.config_space[6] & 1;\n if (cur_carrier_state != carrier_state) {\n s->common.config_space[6] = (carrier_state << 0);\n virtio_config_change_notify(s1);\n }\n#endif\n}\n\nVIRTIODevice *virtio_net_init(VIRTIOBusDef *bus, EthernetDevice *es)\n{\n VIRTIONetDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 1, 6 + 2, virtio_net_recv_request);\n /* VIRTIO_NET_F_MAC, VIRTIO_NET_F_STATUS */\n s->common.device_features = (1 << 5) /* | (1 << 16) */;\n s->common.queue[0].manual_recv = TRUE;\n s->es = es;\n memcpy(s->common.config_space, es->mac_addr, 6);\n /* status */\n s->common.config_space[6] = 0;\n s->common.config_space[7] = 0;\n\n s->header_size = sizeof(VIRTIONetHeader);\n \n es->device_opaque = s;\n es->device_can_write_packet = virtio_net_can_write_packet;\n es->device_write_packet = virtio_net_write_packet;\n es->device_set_carrier = virtio_net_set_carrier;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* console device */\n\ntypedef struct VIRTIOConsoleDevice {\n VIRTIODevice common;\n CharacterDevice *cs;\n} VIRTIOConsoleDevice;\n\nstatic int virtio_console_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIOConsoleDevice *s1 = (VIRTIOConsoleDevice *)s;\n CharacterDevice *cs = s1->cs;\n uint8_t *buf;\n\n if (queue_idx == 1) {\n /* send to console */\n buf = malloc(read_size);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, 0, read_size);\n cs->write_data(cs->opaque, buf, read_size);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\nBOOL virtio_console_can_write_data(VIRTIODevice *s)\n{\n QueueState *qs = &s->queue[0];\n uint16_t avail_idx;\n\n if (!qs->ready)\n return FALSE;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n return qs->last_avail_idx != avail_idx;\n}\n\nint virtio_console_get_write_len(VIRTIODevice *s)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n int read_size, write_size;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return 0;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return 0;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx))\n return 0;\n return write_size;\n}\n\nint virtio_console_write_data(VIRTIODevice *s, const uint8_t *buf, int buf_len)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return 0;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return 0;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, buf_len);\n qs->last_avail_idx++;\n return buf_len;\n}\n\n/* send a resize event */\nvoid virtio_console_resize_event(VIRTIODevice *s, int width, int height)\n{\n /* indicate the console size */\n put_le16(s->config_space + 0, width);\n put_le16(s->config_space + 2, height);\n\n virtio_config_change_notify(s);\n}\n\nVIRTIODevice *virtio_console_init(VIRTIOBusDef *bus, CharacterDevice *cs)\n{\n VIRTIOConsoleDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 3, 4, virtio_console_recv_request);\n s->common.device_features = (1 << 0); /* VIRTIO_CONSOLE_F_SIZE */\n s->common.queue[0].manual_recv = TRUE;\n \n s->cs = cs;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* input device */\n\nenum {\n VIRTIO_INPUT_CFG_UNSET = 0x00,\n VIRTIO_INPUT_CFG_ID_NAME = 0x01,\n VIRTIO_INPUT_CFG_ID_SERIAL = 0x02,\n VIRTIO_INPUT_CFG_ID_DEVIDS = 0x03,\n VIRTIO_INPUT_CFG_PROP_BITS = 0x10,\n VIRTIO_INPUT_CFG_EV_BITS = 0x11,\n VIRTIO_INPUT_CFG_ABS_INFO = 0x12,\n};\n\n#define VIRTIO_INPUT_EV_SYN 0x00\n#define VIRTIO_INPUT_EV_KEY 0x01\n#define VIRTIO_INPUT_EV_REL 0x02\n#define VIRTIO_INPUT_EV_ABS 0x03\n#define VIRTIO_INPUT_EV_REP 0x14\n\n#define BTN_LEFT 0x110\n#define BTN_RIGHT 0x111\n#define BTN_MIDDLE 0x112\n#define BTN_GEAR_DOWN 0x150\n#define BTN_GEAR_UP 0x151\n\n#define REL_X 0x00\n#define REL_Y 0x01\n#define REL_Z 0x02\n#define REL_WHEEL 0x08\n\n#define ABS_X 0x00\n#define ABS_Y 0x01\n#define ABS_Z 0x02\n\ntypedef struct VIRTIOInputDevice {\n VIRTIODevice common;\n VirtioInputTypeEnum type;\n uint32_t buttons_state;\n} VIRTIOInputDevice;\n\nstatic const uint16_t buttons_list[] = {\n BTN_LEFT, BTN_RIGHT, BTN_MIDDLE\n};\n\nstatic int virtio_input_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n if (queue_idx == 1) {\n /* led & keyboard updates */\n // printf(\"%s: write_size=%d\\n\", __func__, write_size);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\n/* return < 0 if could not send key event */\nstatic int virtio_input_queue_event(VIRTIODevice *s,\n uint16_t type, uint16_t code,\n uint32_t value)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx, buf_len;\n uint16_t avail_idx;\n uint8_t buf[8];\n\n if (!qs->ready)\n return -1;\n\n put_le16(buf, type);\n put_le16(buf + 2, code);\n put_le32(buf + 4, value);\n buf_len = 8;\n \n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return -1;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n // printf(\"send: queue_idx=%d desc_idx=%d\\n\", queue_idx, desc_idx);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, buf_len);\n qs->last_avail_idx++;\n return 0;\n}\n\nint virtio_input_send_key_event(VIRTIODevice *s, BOOL is_down,\n uint16_t key_code)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n int ret;\n \n if (s1->type != VIRTIO_INPUT_TYPE_KEYBOARD)\n return -1;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_KEY, key_code, is_down);\n if (ret)\n return ret;\n return virtio_input_queue_event(s, VIRTIO_INPUT_EV_SYN, 0, 0);\n}\n\n/* also used for the tablet */\nint virtio_input_send_mouse_event(VIRTIODevice *s, int dx, int dy, int dz,\n unsigned int buttons)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n int ret, i, b, last_b;\n\n if (s1->type != VIRTIO_INPUT_TYPE_MOUSE &&\n s1->type != VIRTIO_INPUT_TYPE_TABLET)\n return -1;\n if (s1->type == VIRTIO_INPUT_TYPE_MOUSE) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_X, dx);\n if (ret != 0)\n return ret;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_Y, dy);\n if (ret != 0)\n return ret;\n } else {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_ABS, ABS_X, dx);\n if (ret != 0)\n return ret;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_ABS, ABS_Y, dy);\n if (ret != 0)\n return ret;\n }\n if (dz != 0) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_WHEEL, dz);\n if (ret != 0)\n return ret;\n }\n\n if (buttons != s1->buttons_state) {\n for(i = 0; i < countof(buttons_list); i++) {\n b = (buttons >> i) & 1;\n last_b = (s1->buttons_state >> i) & 1;\n if (b != last_b) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_KEY,\n buttons_list[i], b);\n if (ret != 0)\n return ret;\n }\n }\n s1->buttons_state = buttons;\n }\n\n return virtio_input_queue_event(s, VIRTIO_INPUT_EV_SYN, 0, 0);\n}\n\nstatic void set_bit(uint8_t *tab, int k)\n{\n tab[k >> 3] |= 1 << (k & 7);\n}\n\nstatic void virtio_input_config_write(VIRTIODevice *s)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n uint8_t *config = s->config_space;\n int i;\n \n // printf(\"config_write: %02x %02x\\n\", config[0], config[1]);\n switch(config[0]) {\n case VIRTIO_INPUT_CFG_UNSET:\n break;\n case VIRTIO_INPUT_CFG_ID_NAME:\n {\n const char *name;\n int len;\n switch(s1->type) {\n case VIRTIO_INPUT_TYPE_KEYBOARD:\n name = \"virtio_keyboard\";\n break;\n case VIRTIO_INPUT_TYPE_MOUSE:\n name = \"virtio_mouse\";\n break;\n case VIRTIO_INPUT_TYPE_TABLET:\n name = \"virtio_tablet\";\n break;\n default:\n abort();\n }\n len = strlen(name);\n config[2] = len;\n memcpy(config + 8, name, len);\n }\n break;\n default:\n case VIRTIO_INPUT_CFG_ID_SERIAL:\n case VIRTIO_INPUT_CFG_ID_DEVIDS:\n case VIRTIO_INPUT_CFG_PROP_BITS:\n config[2] = 0; /* size of reply */\n break;\n case VIRTIO_INPUT_CFG_EV_BITS:\n config[2] = 0;\n switch(s1->type) {\n case VIRTIO_INPUT_TYPE_KEYBOARD:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 128 / 8;\n memset(config + 8, 0xff, 128 / 8); /* bitmap */\n break;\n case VIRTIO_INPUT_EV_REP: /* allow key repetition */\n config[2] = 1;\n break;\n default:\n break;\n }\n break;\n case VIRTIO_INPUT_TYPE_MOUSE:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 512 / 8;\n memset(config + 8, 0, 512 / 8); /* bitmap */\n for(i = 0; i < countof(buttons_list); i++)\n set_bit(config + 8, buttons_list[i]);\n break;\n case VIRTIO_INPUT_EV_REL:\n config[2] = 2;\n config[8] = 0;\n config[9] = 0;\n set_bit(config + 8, REL_X);\n set_bit(config + 8, REL_Y);\n set_bit(config + 8, REL_WHEEL);\n break;\n default:\n break;\n }\n break;\n case VIRTIO_INPUT_TYPE_TABLET:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 512 / 8;\n memset(config + 8, 0, 512 / 8); /* bitmap */\n for(i = 0; i < countof(buttons_list); i++)\n set_bit(config + 8, buttons_list[i]);\n break;\n case VIRTIO_INPUT_EV_REL:\n config[2] = 2;\n config[8] = 0;\n config[9] = 0;\n set_bit(config + 8, REL_WHEEL);\n break;\n case VIRTIO_INPUT_EV_ABS:\n config[2] = 1;\n config[8] = 0;\n set_bit(config + 8, ABS_X);\n set_bit(config + 8, ABS_Y);\n break;\n default:\n break;\n }\n break;\n default:\n abort();\n }\n break;\n case VIRTIO_INPUT_CFG_ABS_INFO:\n if (s1->type == VIRTIO_INPUT_TYPE_TABLET && config[1] <= 1) {\n /* for ABS_X and ABS_Y */\n config[2] = 5 * 4;\n put_le32(config + 8, 0); /* min */\n put_le32(config + 12, VIRTIO_INPUT_ABS_SCALE - 1) ; /* max */\n put_le32(config + 16, 0); /* fuzz */\n put_le32(config + 20, 0); /* flat */\n put_le32(config + 24, 0); /* res */\n }\n break;\n }\n}\n\nVIRTIODevice *virtio_input_init(VIRTIOBusDef *bus, VirtioInputTypeEnum type)\n{\n VIRTIOInputDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 18, 256, virtio_input_recv_request);\n s->common.queue[0].manual_recv = TRUE;\n s->common.device_features = 0;\n s->common.config_write = virtio_input_config_write;\n s->type = type;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* 9p filesystem device */\n\ntypedef struct {\n struct list_head link;\n uint32_t fid;\n FSFile *fd;\n} FIDDesc;\n\ntypedef struct VIRTIO9PDevice {\n VIRTIODevice common;\n FSDevice *fs;\n int msize; /* maximum message size */\n struct list_head fid_list; /* list of FIDDesc */\n BOOL req_in_progress;\n} VIRTIO9PDevice;\n\nstatic FIDDesc *fid_find1(VIRTIO9PDevice *s, uint32_t fid)\n{\n struct list_head *el;\n FIDDesc *f;\n\n list_for_each(el, &s->fid_list) {\n f = list_entry(el, FIDDesc, link);\n if (f->fid == fid)\n return f;\n }\n return NULL;\n}\n\nstatic FSFile *fid_find(VIRTIO9PDevice *s, uint32_t fid)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (!f)\n return NULL;\n return f->fd;\n}\n\nstatic void fid_delete(VIRTIO9PDevice *s, uint32_t fid)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (f) {\n s->fs->fs_delete(s->fs, f->fd);\n list_del(&f->link);\n free(f);\n }\n}\n\nstatic void fid_set(VIRTIO9PDevice *s, uint32_t fid, FSFile *fd)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (f) {\n s->fs->fs_delete(s->fs, f->fd);\n f->fd = fd;\n } else {\n f = malloc(sizeof(*f));\n f->fid = fid;\n f->fd = fd;\n list_add(&f->link, &s->fid_list);\n }\n}\n\n#ifdef DEBUG_VIRTIO\n\ntypedef struct {\n uint8_t tag;\n const char *name;\n} Virtio9POPName;\n\nstatic const Virtio9POPName virtio_9p_op_names[] = {\n { 8, \"statfs\" },\n { 12, \"lopen\" },\n { 14, \"lcreate\" },\n { 16, \"symlink\" },\n { 18, \"mknod\" },\n { 22, \"readlink\" },\n { 24, \"getattr\" },\n { 26, \"setattr\" },\n { 30, \"xattrwalk\" },\n { 40, \"readdir\" },\n { 50, \"fsync\" },\n { 52, \"lock\" },\n { 54, \"getlock\" },\n { 70, \"link\" },\n { 72, \"mkdir\" },\n { 74, \"renameat\" },\n { 76, \"unlinkat\" },\n { 100, \"version\" },\n { 104, \"attach\" },\n { 108, \"flush\" },\n { 110, \"walk\" },\n { 116, \"read\" },\n { 118, \"write\" },\n { 120, \"clunk\" },\n { 0, NULL },\n};\n\nstatic const char *get_9p_op_name(int tag)\n{\n const Virtio9POPName *p;\n for(p = virtio_9p_op_names; p->name != NULL; p++) {\n if (p->tag == tag)\n return p->name;\n }\n return NULL;\n}\n\n#endif /* DEBUG_VIRTIO */\n\nstatic int marshall(VIRTIO9PDevice *s, \n uint8_t *buf1, int max_len, const char *fmt, ...)\n{\n va_list ap;\n int c;\n uint32_t val;\n uint64_t val64;\n uint8_t *buf, *buf_end;\n\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" ->\");\n#endif\n va_start(ap, fmt);\n buf = buf1;\n buf_end = buf1 + max_len;\n for(;;) {\n c = *fmt++;\n if (c == '\\0')\n break;\n switch(c) {\n case 'b':\n assert(buf + 1 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" b=%d\", val);\n#endif\n buf[0] = val;\n buf += 1;\n break;\n case 'h':\n assert(buf + 2 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" h=%d\", val);\n#endif\n put_le16(buf, val);\n buf += 2;\n break;\n case 'w':\n assert(buf + 4 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" w=%d\", val);\n#endif\n put_le32(buf, val);\n buf += 4;\n break;\n case 'd':\n assert(buf + 8 <= buf_end);\n val64 = va_arg(ap, uint64_t);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" d=%\" PRId64, val64);\n#endif\n put_le64(buf, val64);\n buf += 8;\n break;\n case 's':\n {\n char *str;\n int len;\n str = va_arg(ap, char *);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" s=\\\"%s\\\"\", str);\n#endif\n len = strlen(str);\n assert(len <= 65535);\n assert(buf + 2 + len <= buf_end);\n put_le16(buf, len);\n buf += 2;\n memcpy(buf, str, len);\n buf += len;\n }\n break;\n case 'Q':\n {\n FSQID *qid;\n assert(buf + 13 <= buf_end);\n qid = va_arg(ap, FSQID *);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" Q=%d:%d:%\" PRIu64, qid->type, qid->version, qid->path);\n#endif\n buf[0] = qid->type;\n put_le32(buf + 1, qid->version);\n put_le64(buf + 5, qid->path);\n buf += 13;\n }\n break;\n default:\n abort();\n }\n }\n va_end(ap);\n return buf - buf1;\n}\n\n/* return < 0 if error */\n/* XXX: free allocated strings in case of error */\nstatic int unmarshall(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, int *poffset, const char *fmt, ...)\n{\n VIRTIODevice *s1 = (VIRTIODevice *)s;\n va_list ap;\n int offset, c;\n uint8_t buf[16];\n\n offset = *poffset;\n va_start(ap, fmt);\n for(;;) {\n c = *fmt++;\n if (c == '\\0')\n break;\n switch(c) {\n case 'b':\n {\n uint8_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 1))\n return -1;\n ptr = va_arg(ap, uint8_t *);\n *ptr = buf[0];\n offset += 1;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" b=%d\", *ptr);\n#endif\n }\n break;\n case 'h':\n {\n uint16_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 2))\n return -1;\n ptr = va_arg(ap, uint16_t *);\n *ptr = get_le16(buf);\n offset += 2;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" h=%d\", *ptr);\n#endif\n }\n break;\n case 'w':\n {\n uint32_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 4))\n return -1;\n ptr = va_arg(ap, uint32_t *);\n *ptr = get_le32(buf);\n offset += 4;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" w=%d\", *ptr);\n#endif\n }\n break;\n case 'd':\n {\n uint64_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 8))\n return -1;\n ptr = va_arg(ap, uint64_t *);\n *ptr = get_le64(buf);\n offset += 8;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" d=%\" PRId64, *ptr);\n#endif\n }\n break;\n case 's':\n {\n char *str, **ptr;\n int len;\n\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 2))\n return -1;\n len = get_le16(buf);\n offset += 2;\n str = malloc(len + 1);\n if (memcpy_from_queue(s1, str, queue_idx, desc_idx, offset, len))\n return -1;\n str[len] = '\\0';\n offset += len;\n ptr = va_arg(ap, char **);\n *ptr = str;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" s=\\\"%s\\\"\", *ptr);\n#endif\n }\n break;\n default:\n abort();\n }\n }\n va_end(ap);\n *poffset = offset;\n return 0;\n}\n\nstatic void virtio_9p_send_reply(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, uint8_t id, uint16_t tag, \n uint8_t *buf, int buf_len)\n{\n uint8_t *buf1;\n int len;\n\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P) {\n if (id == 6)\n printf(\" (error)\");\n printf(\"\\n\");\n }\n#endif\n len = buf_len + 7;\n buf1 = malloc(len);\n put_le32(buf1, len);\n buf1[4] = id + 1;\n put_le16(buf1 + 5, tag);\n memcpy(buf1 + 7, buf, buf_len);\n memcpy_to_queue((VIRTIODevice *)s, queue_idx, desc_idx, 0, buf1, len);\n virtio_consume_desc((VIRTIODevice *)s, queue_idx, desc_idx, len);\n free(buf1);\n}\n\nstatic void virtio_9p_send_error(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, uint16_t tag, uint32_t error)\n{\n uint8_t buf[4];\n int buf_len;\n\n buf_len = marshall(s, buf, sizeof(buf), \"w\", -error);\n virtio_9p_send_reply(s, queue_idx, desc_idx, 6, tag, buf, buf_len);\n}\n\ntypedef struct {\n VIRTIO9PDevice *dev;\n int queue_idx;\n int desc_idx;\n uint16_t tag;\n} P9OpenInfo;\n\nstatic void virtio_9p_open_reply(FSDevice *fs, FSQID *qid, int err,\n P9OpenInfo *oi)\n{\n VIRTIO9PDevice *s = oi->dev;\n uint8_t buf[32];\n int buf_len;\n \n if (err < 0) {\n virtio_9p_send_error(s, oi->queue_idx, oi->desc_idx, oi->tag, err);\n } else {\n buf_len = marshall(s, buf, sizeof(buf),\n \"Qw\", qid, s->msize - 24);\n virtio_9p_send_reply(s, oi->queue_idx, oi->desc_idx, 12, oi->tag,\n buf, buf_len);\n }\n free(oi);\n}\n\nstatic void virtio_9p_open_cb(FSDevice *fs, FSQID *qid, int err,\n void *opaque)\n{\n P9OpenInfo *oi = opaque;\n VIRTIO9PDevice *s = oi->dev;\n int queue_idx = oi->queue_idx;\n \n virtio_9p_open_reply(fs, qid, err, oi);\n\n s->req_in_progress = FALSE;\n\n /* handle next requests */\n queue_notify((VIRTIODevice *)s, queue_idx);\n}\n\nstatic int virtio_9p_recv_request(VIRTIODevice *s1, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIO9PDevice *s = (VIRTIO9PDevice *)s1;\n int offset, header_len;\n uint8_t id;\n uint16_t tag;\n uint8_t buf[1024];\n int buf_len, err;\n FSDevice *fs = s->fs;\n\n if (queue_idx != 0)\n return 0;\n \n if (s->req_in_progress)\n return -1;\n \n offset = 0;\n header_len = 4 + 1 + 2;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, header_len)) {\n tag = 0;\n goto protocol_error;\n }\n //size = get_le32(buf);\n id = buf[4];\n tag = get_le16(buf + 5);\n offset += header_len;\n \n#ifdef DEBUG_VIRTIO\n if (s1->debug & VIRTIO_DEBUG_9P) {\n const char *name;\n name = get_9p_op_name(id);\n printf(\"9p: op=\");\n if (name)\n printf(\"%s\", name);\n else\n printf(\"%d\", id);\n }\n#endif\n /* Note: same subset as JOR1K */\n switch(id) {\n case 8: /* statfs */\n {\n FSStatFS st;\n\n fs->fs_statfs(fs, &st);\n buf_len = marshall(s, buf, sizeof(buf),\n \"wwddddddw\", \n 0,\n st.f_bsize,\n st.f_blocks,\n st.f_bfree,\n st.f_bavail,\n st.f_files,\n st.f_ffree,\n 0, /* id */\n 256 /* max filename length */\n );\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 12: /* lopen */\n {\n uint32_t fid, flags;\n FSFile *f;\n FSQID qid;\n P9OpenInfo *oi;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"ww\", &fid, &flags))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n oi = malloc(sizeof(*oi));\n oi->dev = s;\n oi->queue_idx = queue_idx;\n oi->desc_idx = desc_idx;\n oi->tag = tag;\n err = fs->fs_open(fs, &qid, f, flags, virtio_9p_open_cb, oi);\n if (err <= 0) {\n virtio_9p_open_reply(fs, &qid, err, oi);\n } else {\n s->req_in_progress = TRUE;\n }\n }\n break;\n case 14: /* lcreate */\n {\n uint32_t fid, flags, mode, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wswww\", &fid, &name, &flags, &mode, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_create(fs, &qid, f, name, flags, mode, gid);\n }\n free(name);\n if (err) \n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Qw\", &qid, s->msize - 24);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 16: /* symlink */\n {\n uint32_t fid, gid;\n char *name, *symgt;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wssw\", &fid, &name, &symgt, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_symlink(fs, &qid, f, name, symgt, gid);\n }\n free(name);\n free(symgt);\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 18: /* mknod */\n {\n uint32_t fid, mode, major, minor, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wswwww\", &fid, &name, &mode, &major, &minor, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_mknod(fs, &qid, f, name, mode, major, minor, gid);\n }\n free(name);\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 22: /* readlink */\n {\n uint32_t fid;\n char buf1[1024];\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"w\", &fid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_readlink(fs, buf1, sizeof(buf1), f);\n }\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"s\", buf1);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 24: /* getattr */\n {\n uint32_t fid;\n uint64_t mask;\n FSFile *f;\n FSStat st;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wd\", &fid, &mask))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_stat(fs, f, &st);\n if (err)\n goto error;\n\n buf_len = marshall(s, buf, sizeof(buf),\n \"dQwwwddddddddddddddd\", \n mask, &st.qid,\n st.st_mode, st.st_uid, st.st_gid,\n st.st_nlink, st.st_rdev, st.st_size,\n st.st_blksize, st.st_blocks,\n st.st_atime_sec, (uint64_t)st.st_atime_nsec,\n st.st_mtime_sec, (uint64_t)st.st_mtime_nsec,\n st.st_ctime_sec, (uint64_t)st.st_ctime_nsec,\n (uint64_t)0, (uint64_t)0,\n (uint64_t)0, (uint64_t)0);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 26: /* setattr */\n {\n uint32_t fid, mask, mode, uid, gid;\n uint64_t size, atime_sec, atime_nsec, mtime_sec, mtime_nsec;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wwwwwddddd\", &fid, &mask, &mode, &uid, &gid,\n &size, &atime_sec, &atime_nsec, \n &mtime_sec, &mtime_nsec))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_setattr(fs, f, mask, mode, uid, gid, size, atime_sec,\n atime_nsec, mtime_sec, mtime_nsec);\n if (err)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 30: /* xattrwalk */\n {\n /* not supported yet */\n err = -P9_ENOTSUP;\n goto error;\n }\n break;\n case 40: /* readdir */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf = malloc(count + 4);\n n = fs->fs_readdir(fs, f, offs, buf + 4, count);\n if (n < 0) {\n err = n;\n goto error;\n }\n put_le32(buf, n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, n + 4);\n free(buf);\n }\n break;\n case 50: /* fsync */\n {\n uint32_t fid;\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"w\", &fid))\n goto protocol_error;\n /* ignored */\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 52: /* lock */\n {\n uint32_t fid;\n FSFile *f;\n FSLock lock;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wbwddws\", &fid, &lock.type, &lock.flags,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n err = -P9_EPROTO;\n else\n err = fs->fs_lock(fs, f, &lock);\n free(lock.client_id);\n if (err < 0)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"b\", err);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 54: /* getlock */\n {\n uint32_t fid;\n FSFile *f;\n FSLock lock;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wbddws\", &fid, &lock.type,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n err = -P9_EPROTO;\n else\n err = fs->fs_getlock(fs, f, &lock);\n if (err < 0) {\n free(lock.client_id);\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"bddws\",\n &lock.type,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id);\n free(lock.client_id);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 70: /* link */\n {\n uint32_t dfid, fid;\n char *name;\n FSFile *f, *df;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wws\", &dfid, &fid, &name))\n goto protocol_error;\n df = fid_find(s, dfid);\n f = fid_find(s, fid);\n if (!df || !f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_link(fs, df, f, name);\n }\n free(name);\n if (err)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 72: /* mkdir */\n {\n uint32_t fid, mode, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsww\", &fid, &name, &mode, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_mkdir(fs, &qid, f, name, mode, gid);\n if (err != 0)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 74: /* renameat */\n {\n uint32_t fid, new_fid;\n char *name, *new_name;\n FSFile *f, *new_f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsws\", &fid, &name, &new_fid, &new_name))\n goto protocol_error;\n f = fid_find(s, fid);\n new_f = fid_find(s, new_fid);\n if (!f || !new_f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_renameat(fs, f, name, new_f, new_name);\n }\n free(name);\n free(new_name);\n if (err != 0)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 76: /* unlinkat */\n {\n uint32_t fid, flags;\n char *name;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsw\", &fid, &name, &flags))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_unlinkat(fs, f, name);\n }\n free(name);\n if (err != 0)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 100: /* version */\n {\n uint32_t msize;\n char *version;\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"ws\", &msize, &version))\n goto protocol_error;\n s->msize = msize;\n // printf(\"version: msize=%d version=%s\\n\", msize, version);\n free(version);\n buf_len = marshall(s, buf, sizeof(buf), \"ws\", s->msize, \"9P2000.L\");\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 104: /* attach */\n {\n uint32_t fid, afid, uid;\n char *uname, *aname;\n FSQID qid;\n FSFile *f;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"wwssw\", &fid, &afid, &uname, &aname, &uid))\n goto protocol_error;\n err = fs->fs_attach(fs, &f, &qid, uid, uname, aname);\n if (err != 0)\n goto error;\n fid_set(s, fid, f);\n free(uname);\n free(aname);\n buf_len = marshall(s, buf, sizeof(buf), \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 108: /* flush */\n {\n uint16_t oldtag;\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"h\", &oldtag))\n goto protocol_error;\n /* ignored */\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 110: /* walk */\n {\n uint32_t fid, newfid;\n uint16_t nwname;\n FSQID *qids;\n char **names;\n FSFile *f;\n int i;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"wwh\", &fid, &newfid, &nwname))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n names = mallocz(sizeof(names[0]) * nwname);\n qids = malloc(sizeof(qids[0]) * nwname);\n for(i = 0; i < nwname; i++) {\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"s\", &names[i])) {\n err = -P9_EPROTO;\n goto walk_done;\n }\n }\n err = fs->fs_walk(fs, &f, qids, f, nwname, names);\n walk_done:\n for(i = 0; i < nwname; i++) {\n free(names[i]);\n }\n free(names);\n if (err < 0) {\n free(qids);\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"h\", err);\n for(i = 0; i < err; i++) {\n buf_len += marshall(s, buf + buf_len, sizeof(buf) - buf_len,\n \"Q\", &qids[i]);\n }\n free(qids);\n fid_set(s, newfid, f);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 116: /* read */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf = malloc(count + 4);\n n = fs->fs_read(fs, f, offs, buf + 4, count);\n if (n < 0) {\n err = n;\n free(buf);\n goto error;\n }\n put_le32(buf, n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, n + 4);\n free(buf);\n }\n break;\n case 118: /* write */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf1;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf1 = malloc(count);\n if (memcpy_from_queue(s1, buf1, queue_idx, desc_idx, offset,\n count)) {\n free(buf1);\n goto protocol_error;\n }\n n = fs->fs_write(fs, f, offs, buf1, count);\n free(buf1);\n if (n < 0) {\n err = n;\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"w\", n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 120: /* clunk */\n {\n uint32_t fid;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"w\", &fid))\n goto protocol_error;\n fid_delete(s, fid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n default:\n printf(\"9p: unsupported operation id=%d\\n\", id);\n goto protocol_error;\n }\n return 0;\n error:\n virtio_9p_send_error(s, queue_idx, desc_idx, tag, err);\n return 0;\n protocol_error:\n fid_not_found:\n err = -P9_EPROTO;\n goto error;\n}\n\nVIRTIODevice *virtio_9p_init(VIRTIOBusDef *bus, FSDevice *fs,\n const char *mount_tag)\n\n{\n VIRTIO9PDevice *s;\n int len;\n uint8_t *cfg;\n\n len = strlen(mount_tag);\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 9, 2 + len, virtio_9p_recv_request);\n s->common.device_features = 1 << 0;\n\n /* set the mount tag */\n cfg = s->common.config_space;\n cfg[0] = len;\n cfg[1] = len >> 8;\n memcpy(cfg + 2, mount_tag, len);\n\n s->fs = fs;\n s->msize = 8192;\n init_list_head(&s->fid_list);\n \n return (VIRTIODevice *)s;\n}\n\n"], ["/linuxpdf/tinyemu/riscv_machine.c", "/*\n * RISCV machine\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"riscv_cpu.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n/* RISCV machine */\n\ntypedef struct RISCVMachine {\n VirtMachine common;\n PhysMemoryMap *mem_map;\n int max_xlen;\n RISCVCPUState *cpu_state;\n uint64_t ram_size;\n /* RTC */\n BOOL rtc_real_time;\n uint64_t rtc_start_time;\n uint64_t timecmp;\n /* PLIC */\n uint32_t plic_pending_irq, plic_served_irq;\n IRQSignal plic_irq[32]; /* IRQ 0 is not used */\n /* HTIF */\n uint64_t htif_tohost, htif_fromhost;\n\n VIRTIODevice *keyboard_dev;\n VIRTIODevice *mouse_dev;\n\n int virtio_count;\n} RISCVMachine;\n\n#define LOW_RAM_SIZE 0x00010000 /* 64KB */\n#define RAM_BASE_ADDR 0x80000000\n#define CLINT_BASE_ADDR 0x02000000\n#define CLINT_SIZE 0x000c0000\n#define HTIF_BASE_ADDR 0x40008000\n#define IDE_BASE_ADDR 0x40009000\n#define VIRTIO_BASE_ADDR 0x40010000\n#define VIRTIO_SIZE 0x1000\n#define VIRTIO_IRQ 1\n#define PLIC_BASE_ADDR 0x40100000\n#define PLIC_SIZE 0x00400000\n#define FRAMEBUFFER_BASE_ADDR 0x41000000\n\n#define RTC_FREQ 10000000\n#define RTC_FREQ_DIV 16 /* arbitrary, relative to CPU freq to have a\n 10 MHz frequency */\n\nstatic uint64_t rtc_get_real_time(RISCVMachine *s)\n{\n struct timespec ts;\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * RTC_FREQ +\n (ts.tv_nsec / (1000000000 / RTC_FREQ));\n}\n\nstatic uint64_t rtc_get_time(RISCVMachine *m)\n{\n uint64_t val;\n if (m->rtc_real_time) {\n val = rtc_get_real_time(m) - m->rtc_start_time;\n } else {\n val = riscv_cpu_get_cycles(m->cpu_state) / RTC_FREQ_DIV;\n }\n // printf(\"rtc_time=%\" PRId64 \"\\n\", val);\n return val;\n}\n\nstatic uint32_t htif_read(void *opaque, uint32_t offset,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n uint32_t val;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0:\n val = s->htif_tohost;\n break;\n case 4:\n val = s->htif_tohost >> 32;\n break;\n case 8:\n val = s->htif_fromhost;\n break;\n case 12:\n val = s->htif_fromhost >> 32;\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n\nstatic void htif_handle_cmd(RISCVMachine *s)\n{\n uint32_t device, cmd;\n\n device = s->htif_tohost >> 56;\n cmd = (s->htif_tohost >> 48) & 0xff;\n if (s->htif_tohost == 1) {\n /* shuthost */\n printf(\"\\nPower off.\\n\");\n exit(0);\n } else if (device == 1 && cmd == 1) {\n uint8_t buf[1];\n buf[0] = s->htif_tohost & 0xff;\n s->common.console->write_data(s->common.console->opaque, buf, 1);\n s->htif_tohost = 0;\n s->htif_fromhost = ((uint64_t)device << 56) | ((uint64_t)cmd << 48);\n } else if (device == 1 && cmd == 0) {\n /* request keyboard interrupt */\n s->htif_tohost = 0;\n } else {\n printf(\"HTIF: unsupported tohost=0x%016\" PRIx64 \"\\n\", s->htif_tohost);\n }\n}\n\nstatic void htif_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0:\n s->htif_tohost = (s->htif_tohost & ~0xffffffff) | val;\n break;\n case 4:\n s->htif_tohost = (s->htif_tohost & 0xffffffff) | ((uint64_t)val << 32);\n htif_handle_cmd(s);\n break;\n case 8:\n s->htif_fromhost = (s->htif_fromhost & ~0xffffffff) | val;\n break;\n case 12:\n s->htif_fromhost = (s->htif_fromhost & 0xffffffff) |\n (uint64_t)val << 32;\n break;\n default:\n break;\n }\n}\n\n#if 0\nstatic void htif_poll(RISCVMachine *s)\n{\n uint8_t buf[1];\n int ret;\n\n if (s->htif_fromhost == 0) {\n ret = s->console->read_data(s->console->opaque, buf, 1);\n if (ret == 1) {\n s->htif_fromhost = ((uint64_t)1 << 56) | ((uint64_t)0 << 48) |\n buf[0];\n }\n }\n}\n#endif\n\nstatic uint32_t clint_read(void *opaque, uint32_t offset, int size_log2)\n{\n RISCVMachine *m = opaque;\n uint32_t val;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0xbff8:\n val = rtc_get_time(m);\n break;\n case 0xbffc:\n val = rtc_get_time(m) >> 32;\n break;\n case 0x4000:\n val = m->timecmp;\n break;\n case 0x4004:\n val = m->timecmp >> 32;\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n \nstatic void clint_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *m = opaque;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0x4000:\n m->timecmp = (m->timecmp & ~0xffffffff) | val;\n riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP);\n break;\n case 0x4004:\n m->timecmp = (m->timecmp & 0xffffffff) | ((uint64_t)val << 32);\n riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP);\n break;\n default:\n break;\n }\n}\n\nstatic void plic_update_mip(RISCVMachine *s)\n{\n RISCVCPUState *cpu = s->cpu_state;\n uint32_t mask;\n mask = s->plic_pending_irq & ~s->plic_served_irq;\n if (mask) {\n riscv_cpu_set_mip(cpu, MIP_MEIP | MIP_SEIP);\n } else {\n riscv_cpu_reset_mip(cpu, MIP_MEIP | MIP_SEIP);\n }\n}\n\n#define PLIC_HART_BASE 0x200000\n#define PLIC_HART_SIZE 0x1000\n\nstatic uint32_t plic_read(void *opaque, uint32_t offset, int size_log2)\n{\n RISCVMachine *s = opaque;\n uint32_t val, mask;\n int i;\n assert(size_log2 == 2);\n switch(offset) {\n case PLIC_HART_BASE:\n val = 0;\n break;\n case PLIC_HART_BASE + 4:\n mask = s->plic_pending_irq & ~s->plic_served_irq;\n if (mask != 0) {\n i = ctz32(mask);\n s->plic_served_irq |= 1 << i;\n plic_update_mip(s);\n val = i + 1;\n } else {\n val = 0;\n }\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n\nstatic void plic_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n \n assert(size_log2 == 2);\n switch(offset) {\n case PLIC_HART_BASE + 4:\n val--;\n if (val < 32) {\n s->plic_served_irq &= ~(1 << val);\n plic_update_mip(s);\n }\n break;\n default:\n break;\n }\n}\n\nstatic void plic_set_irq(void *opaque, int irq_num, int state)\n{\n RISCVMachine *s = opaque;\n uint32_t mask;\n\n mask = 1 << (irq_num - 1);\n if (state) \n s->plic_pending_irq |= mask;\n else\n s->plic_pending_irq &= ~mask;\n plic_update_mip(s);\n}\n\nstatic uint8_t *get_ram_ptr(RISCVMachine *s, uint64_t paddr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(s->mem_map, paddr, is_rw);\n}\n\n/* FDT machine description */\n\n#define FDT_MAGIC\t0xd00dfeed\n#define FDT_VERSION\t17\n\nstruct fdt_header {\n uint32_t magic;\n uint32_t totalsize;\n uint32_t off_dt_struct;\n uint32_t off_dt_strings;\n uint32_t off_mem_rsvmap;\n uint32_t version;\n uint32_t last_comp_version; /* <= 17 */\n uint32_t boot_cpuid_phys;\n uint32_t size_dt_strings;\n uint32_t size_dt_struct;\n};\n\nstruct fdt_reserve_entry {\n uint64_t address;\n uint64_t size;\n};\n\n#define FDT_BEGIN_NODE\t1\n#define FDT_END_NODE\t2\n#define FDT_PROP\t3\n#define FDT_NOP\t\t4\n#define FDT_END\t\t9\n\ntypedef struct {\n uint32_t *tab;\n int tab_len;\n int tab_size;\n int open_node_count;\n \n char *string_table;\n int string_table_len;\n int string_table_size;\n} FDTState;\n\nstatic FDTState *fdt_init(void)\n{\n FDTState *s;\n s = mallocz(sizeof(*s));\n return s;\n}\n\nstatic void fdt_alloc_len(FDTState *s, int len)\n{\n int new_size;\n if (unlikely(len > s->tab_size)) {\n new_size = max_int(len, s->tab_size * 3 / 2);\n s->tab = realloc(s->tab, new_size * sizeof(uint32_t));\n s->tab_size = new_size;\n }\n}\n\nstatic void fdt_put32(FDTState *s, int v)\n{\n fdt_alloc_len(s, s->tab_len + 1);\n s->tab[s->tab_len++] = cpu_to_be32(v);\n}\n\n/* the data is zero padded */\nstatic void fdt_put_data(FDTState *s, const uint8_t *data, int len)\n{\n int len1;\n \n len1 = (len + 3) / 4;\n fdt_alloc_len(s, s->tab_len + len1);\n memcpy(s->tab + s->tab_len, data, len);\n memset((uint8_t *)(s->tab + s->tab_len) + len, 0, -len & 3);\n s->tab_len += len1;\n}\n\nstatic void fdt_begin_node(FDTState *s, const char *name)\n{\n fdt_put32(s, FDT_BEGIN_NODE);\n fdt_put_data(s, (uint8_t *)name, strlen(name) + 1);\n s->open_node_count++;\n}\n\nstatic void fdt_begin_node_num(FDTState *s, const char *name, uint64_t n)\n{\n char buf[256];\n snprintf(buf, sizeof(buf), \"%s@%\" PRIx64, name, n);\n fdt_begin_node(s, buf);\n}\n\nstatic void fdt_end_node(FDTState *s)\n{\n fdt_put32(s, FDT_END_NODE);\n s->open_node_count--;\n}\n\nstatic int fdt_get_string_offset(FDTState *s, const char *name)\n{\n int pos, new_size, name_size, new_len;\n\n pos = 0;\n while (pos < s->string_table_len) {\n if (!strcmp(s->string_table + pos, name))\n return pos;\n pos += strlen(s->string_table + pos) + 1;\n }\n /* add a new string */\n name_size = strlen(name) + 1;\n new_len = s->string_table_len + name_size;\n if (new_len > s->string_table_size) {\n new_size = max_int(new_len, s->string_table_size * 3 / 2);\n s->string_table = realloc(s->string_table, new_size);\n s->string_table_size = new_size;\n }\n pos = s->string_table_len;\n memcpy(s->string_table + pos, name, name_size);\n s->string_table_len = new_len;\n return pos;\n}\n\nstatic void fdt_prop(FDTState *s, const char *prop_name,\n const void *data, int data_len)\n{\n fdt_put32(s, FDT_PROP);\n fdt_put32(s, data_len);\n fdt_put32(s, fdt_get_string_offset(s, prop_name));\n fdt_put_data(s, data, data_len);\n}\n\nstatic void fdt_prop_tab_u32(FDTState *s, const char *prop_name,\n uint32_t *tab, int tab_len)\n{\n int i;\n fdt_put32(s, FDT_PROP);\n fdt_put32(s, tab_len * sizeof(uint32_t));\n fdt_put32(s, fdt_get_string_offset(s, prop_name));\n for(i = 0; i < tab_len; i++)\n fdt_put32(s, tab[i]);\n}\n\nstatic void fdt_prop_u32(FDTState *s, const char *prop_name, uint32_t val)\n{\n fdt_prop_tab_u32(s, prop_name, &val, 1);\n}\n\nstatic void fdt_prop_tab_u64(FDTState *s, const char *prop_name,\n uint64_t v0)\n{\n uint32_t tab[2];\n tab[0] = v0 >> 32;\n tab[1] = v0;\n fdt_prop_tab_u32(s, prop_name, tab, 2);\n}\n\nstatic void fdt_prop_tab_u64_2(FDTState *s, const char *prop_name,\n uint64_t v0, uint64_t v1)\n{\n uint32_t tab[4];\n tab[0] = v0 >> 32;\n tab[1] = v0;\n tab[2] = v1 >> 32;\n tab[3] = v1;\n fdt_prop_tab_u32(s, prop_name, tab, 4);\n}\n\nstatic void fdt_prop_str(FDTState *s, const char *prop_name,\n const char *str)\n{\n fdt_prop(s, prop_name, str, strlen(str) + 1);\n}\n\n/* NULL terminated string list */\nstatic void fdt_prop_tab_str(FDTState *s, const char *prop_name,\n ...)\n{\n va_list ap;\n int size, str_size;\n char *ptr, *tab;\n\n va_start(ap, prop_name);\n size = 0;\n for(;;) {\n ptr = va_arg(ap, char *);\n if (!ptr)\n break;\n str_size = strlen(ptr) + 1;\n size += str_size;\n }\n va_end(ap);\n \n tab = malloc(size);\n va_start(ap, prop_name);\n size = 0;\n for(;;) {\n ptr = va_arg(ap, char *);\n if (!ptr)\n break;\n str_size = strlen(ptr) + 1;\n memcpy(tab + size, ptr, str_size);\n size += str_size;\n }\n va_end(ap);\n \n fdt_prop(s, prop_name, tab, size);\n free(tab);\n}\n\n/* write the FDT to 'dst1'. return the FDT size in bytes */\nint fdt_output(FDTState *s, uint8_t *dst)\n{\n struct fdt_header *h;\n struct fdt_reserve_entry *re;\n int dt_struct_size;\n int dt_strings_size;\n int pos;\n\n assert(s->open_node_count == 0);\n \n fdt_put32(s, FDT_END);\n \n dt_struct_size = s->tab_len * sizeof(uint32_t);\n dt_strings_size = s->string_table_len;\n\n h = (struct fdt_header *)dst;\n h->magic = cpu_to_be32(FDT_MAGIC);\n h->version = cpu_to_be32(FDT_VERSION);\n h->last_comp_version = cpu_to_be32(16);\n h->boot_cpuid_phys = cpu_to_be32(0);\n h->size_dt_strings = cpu_to_be32(dt_strings_size);\n h->size_dt_struct = cpu_to_be32(dt_struct_size);\n\n pos = sizeof(struct fdt_header);\n\n h->off_dt_struct = cpu_to_be32(pos);\n memcpy(dst + pos, s->tab, dt_struct_size);\n pos += dt_struct_size;\n\n /* align to 8 */\n while ((pos & 7) != 0) {\n dst[pos++] = 0;\n }\n h->off_mem_rsvmap = cpu_to_be32(pos);\n re = (struct fdt_reserve_entry *)(dst + pos);\n re->address = 0; /* no reserved entry */\n re->size = 0;\n pos += sizeof(struct fdt_reserve_entry);\n\n h->off_dt_strings = cpu_to_be32(pos);\n memcpy(dst + pos, s->string_table, dt_strings_size);\n pos += dt_strings_size;\n\n /* align to 8, just in case */\n while ((pos & 7) != 0) {\n dst[pos++] = 0;\n }\n\n h->totalsize = cpu_to_be32(pos);\n return pos;\n}\n\nvoid fdt_end(FDTState *s)\n{\n free(s->tab);\n free(s->string_table);\n free(s);\n}\n\nstatic int riscv_build_fdt(RISCVMachine *m, uint8_t *dst,\n uint64_t kernel_start, uint64_t kernel_size,\n uint64_t initrd_start, uint64_t initrd_size,\n const char *cmd_line)\n{\n FDTState *s;\n int size, max_xlen, i, cur_phandle, intc_phandle, plic_phandle;\n char isa_string[128], *q;\n uint32_t misa;\n uint32_t tab[4];\n FBDevice *fb_dev;\n \n s = fdt_init();\n\n cur_phandle = 1;\n \n fdt_begin_node(s, \"\");\n fdt_prop_u32(s, \"#address-cells\", 2);\n fdt_prop_u32(s, \"#size-cells\", 2);\n fdt_prop_str(s, \"compatible\", \"ucbbar,riscvemu-bar_dev\");\n fdt_prop_str(s, \"model\", \"ucbbar,riscvemu-bare\");\n\n /* CPU list */\n fdt_begin_node(s, \"cpus\");\n fdt_prop_u32(s, \"#address-cells\", 1);\n fdt_prop_u32(s, \"#size-cells\", 0);\n fdt_prop_u32(s, \"timebase-frequency\", RTC_FREQ);\n\n /* cpu */\n fdt_begin_node_num(s, \"cpu\", 0);\n fdt_prop_str(s, \"device_type\", \"cpu\");\n fdt_prop_u32(s, \"reg\", 0);\n fdt_prop_str(s, \"status\", \"okay\");\n fdt_prop_str(s, \"compatible\", \"riscv\");\n\n max_xlen = m->max_xlen;\n misa = riscv_cpu_get_misa(m->cpu_state);\n q = isa_string;\n q += snprintf(isa_string, sizeof(isa_string), \"rv%d\", max_xlen);\n for(i = 0; i < 26; i++) {\n if (misa & (1 << i))\n *q++ = 'a' + i;\n }\n *q = '\\0';\n fdt_prop_str(s, \"riscv,isa\", isa_string);\n \n fdt_prop_str(s, \"mmu-type\", max_xlen <= 32 ? \"riscv,sv32\" : \"riscv,sv48\");\n fdt_prop_u32(s, \"clock-frequency\", 2000000000);\n\n fdt_begin_node(s, \"interrupt-controller\");\n fdt_prop_u32(s, \"#interrupt-cells\", 1);\n fdt_prop(s, \"interrupt-controller\", NULL, 0);\n fdt_prop_str(s, \"compatible\", \"riscv,cpu-intc\");\n intc_phandle = cur_phandle++;\n fdt_prop_u32(s, \"phandle\", intc_phandle);\n fdt_end_node(s); /* interrupt-controller */\n \n fdt_end_node(s); /* cpu */\n \n fdt_end_node(s); /* cpus */\n\n fdt_begin_node_num(s, \"memory\", RAM_BASE_ADDR);\n fdt_prop_str(s, \"device_type\", \"memory\");\n tab[0] = (uint64_t)RAM_BASE_ADDR >> 32;\n tab[1] = RAM_BASE_ADDR;\n tab[2] = m->ram_size >> 32;\n tab[3] = m->ram_size;\n fdt_prop_tab_u32(s, \"reg\", tab, 4);\n \n fdt_end_node(s); /* memory */\n\n fdt_begin_node(s, \"htif\");\n fdt_prop_str(s, \"compatible\", \"ucb,htif0\");\n fdt_end_node(s); /* htif */\n\n fdt_begin_node(s, \"soc\");\n fdt_prop_u32(s, \"#address-cells\", 2);\n fdt_prop_u32(s, \"#size-cells\", 2);\n fdt_prop_tab_str(s, \"compatible\",\n \"ucbbar,riscvemu-bar-soc\", \"simple-bus\", NULL);\n fdt_prop(s, \"ranges\", NULL, 0);\n\n fdt_begin_node_num(s, \"clint\", CLINT_BASE_ADDR);\n fdt_prop_str(s, \"compatible\", \"riscv,clint0\");\n\n tab[0] = intc_phandle;\n tab[1] = 3; /* M IPI irq */\n tab[2] = intc_phandle;\n tab[3] = 7; /* M timer irq */\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 4);\n\n fdt_prop_tab_u64_2(s, \"reg\", CLINT_BASE_ADDR, CLINT_SIZE);\n \n fdt_end_node(s); /* clint */\n\n fdt_begin_node_num(s, \"plic\", PLIC_BASE_ADDR);\n fdt_prop_u32(s, \"#interrupt-cells\", 1);\n fdt_prop(s, \"interrupt-controller\", NULL, 0);\n fdt_prop_str(s, \"compatible\", \"riscv,plic0\");\n fdt_prop_u32(s, \"riscv,ndev\", 31);\n fdt_prop_tab_u64_2(s, \"reg\", PLIC_BASE_ADDR, PLIC_SIZE);\n\n tab[0] = intc_phandle;\n tab[1] = 9; /* S ext irq */\n tab[2] = intc_phandle;\n tab[3] = 11; /* M ext irq */\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 4);\n\n plic_phandle = cur_phandle++;\n fdt_prop_u32(s, \"phandle\", plic_phandle);\n\n fdt_end_node(s); /* plic */\n \n for(i = 0; i < m->virtio_count; i++) {\n fdt_begin_node_num(s, \"virtio\", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE);\n fdt_prop_str(s, \"compatible\", \"virtio,mmio\");\n fdt_prop_tab_u64_2(s, \"reg\", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE,\n VIRTIO_SIZE);\n tab[0] = plic_phandle;\n tab[1] = VIRTIO_IRQ + i;\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 2);\n fdt_end_node(s); /* virtio */\n }\n\n fb_dev = m->common.fb_dev;\n if (fb_dev) {\n fdt_begin_node_num(s, \"framebuffer\", FRAMEBUFFER_BASE_ADDR);\n fdt_prop_str(s, \"compatible\", \"simple-framebuffer\");\n fdt_prop_tab_u64_2(s, \"reg\", FRAMEBUFFER_BASE_ADDR, fb_dev->fb_size);\n fdt_prop_u32(s, \"width\", fb_dev->width);\n fdt_prop_u32(s, \"height\", fb_dev->height);\n fdt_prop_u32(s, \"stride\", fb_dev->stride);\n fdt_prop_str(s, \"format\", \"a8r8g8b8\");\n fdt_end_node(s); /* framebuffer */\n }\n \n fdt_end_node(s); /* soc */\n\n fdt_begin_node(s, \"chosen\");\n fdt_prop_str(s, \"bootargs\", cmd_line ? cmd_line : \"\");\n if (kernel_size > 0) {\n fdt_prop_tab_u64(s, \"riscv,kernel-start\", kernel_start);\n fdt_prop_tab_u64(s, \"riscv,kernel-end\", kernel_start + kernel_size);\n }\n if (initrd_size > 0) {\n fdt_prop_tab_u64(s, \"linux,initrd-start\", initrd_start);\n fdt_prop_tab_u64(s, \"linux,initrd-end\", initrd_start + initrd_size);\n }\n \n\n fdt_end_node(s); /* chosen */\n \n fdt_end_node(s); /* / */\n\n size = fdt_output(s, dst);\n#if 0\n {\n FILE *f;\n f = fopen(\"/tmp/riscvemu.dtb\", \"wb\");\n fwrite(dst, 1, size, f);\n fclose(f);\n }\n#endif\n fdt_end(s);\n return size;\n}\n\nstatic void copy_bios(RISCVMachine *s, const uint8_t *buf, int buf_len,\n const uint8_t *kernel_buf, int kernel_buf_len,\n const uint8_t *initrd_buf, int initrd_buf_len,\n const char *cmd_line)\n{\n uint32_t fdt_addr, align, kernel_base, initrd_base;\n uint8_t *ram_ptr;\n uint32_t *q;\n\n if (buf_len > s->ram_size) {\n vm_error(\"BIOS too big\\n\");\n exit(1);\n }\n\n ram_ptr = get_ram_ptr(s, RAM_BASE_ADDR, TRUE);\n memcpy(ram_ptr, buf, buf_len);\n\n kernel_base = 0;\n if (kernel_buf_len > 0) {\n /* copy the kernel if present */\n if (s->max_xlen == 32)\n align = 4 << 20; /* 4 MB page align */\n else\n align = 2 << 20; /* 2 MB page align */\n kernel_base = (buf_len + align - 1) & ~(align - 1);\n memcpy(ram_ptr + kernel_base, kernel_buf, kernel_buf_len);\n if (kernel_buf_len + kernel_base > s->ram_size) {\n vm_error(\"kernel too big\");\n exit(1);\n }\n }\n\n initrd_base = 0;\n if (initrd_buf_len > 0) {\n /* same allocation as QEMU */\n initrd_base = s->ram_size / 2;\n if (initrd_base > (128 << 20))\n initrd_base = 128 << 20;\n memcpy(ram_ptr + initrd_base, initrd_buf, initrd_buf_len);\n if (initrd_buf_len + initrd_base > s->ram_size) {\n vm_error(\"initrd too big\");\n exit(1);\n }\n }\n \n ram_ptr = get_ram_ptr(s, 0, TRUE);\n \n fdt_addr = 0x1000 + 8 * 8;\n\n riscv_build_fdt(s, ram_ptr + fdt_addr,\n RAM_BASE_ADDR + kernel_base, kernel_buf_len,\n RAM_BASE_ADDR + initrd_base, initrd_buf_len,\n cmd_line);\n\n /* jump_addr = 0x80000000 */\n \n q = (uint32_t *)(ram_ptr + 0x1000);\n q[0] = 0x297 + 0x80000000 - 0x1000; /* auipc t0, jump_addr */\n q[1] = 0x597; /* auipc a1, dtb */\n q[2] = 0x58593 + ((fdt_addr - 4) << 20); /* addi a1, a1, dtb */\n q[3] = 0xf1402573; /* csrr a0, mhartid */\n q[4] = 0x00028067; /* jalr zero, t0, jump_addr */\n}\n\nstatic void riscv_flush_tlb_write_range(void *opaque, uint8_t *ram_addr,\n size_t ram_size)\n{\n RISCVMachine *s = opaque;\n riscv_cpu_flush_tlb_write_range_ram(s->cpu_state, ram_addr, ram_size);\n}\n\nstatic void riscv_machine_set_defaults(VirtMachineParams *p)\n{\n}\n\nstatic VirtMachine *riscv_machine_init(const VirtMachineParams *p)\n{\n RISCVMachine *s;\n VIRTIODevice *blk_dev;\n int irq_num, i, max_xlen, ram_flags;\n VIRTIOBusDef vbus_s, *vbus = &vbus_s;\n\n\n if (!strcmp(p->machine_name, \"riscv32\")) {\n max_xlen = 32;\n } else if (!strcmp(p->machine_name, \"riscv64\")) {\n max_xlen = 64;\n } else if (!strcmp(p->machine_name, \"riscv128\")) {\n max_xlen = 128;\n } else {\n vm_error(\"unsupported machine: %s\\n\", p->machine_name);\n return NULL;\n }\n \n s = mallocz(sizeof(*s));\n s->common.vmc = p->vmc;\n s->ram_size = p->ram_size;\n s->max_xlen = max_xlen;\n s->mem_map = phys_mem_map_init();\n /* needed to handle the RAM dirty bits */\n s->mem_map->opaque = s;\n s->mem_map->flush_tlb_write_range = riscv_flush_tlb_write_range;\n\n s->cpu_state = riscv_cpu_init(s->mem_map, max_xlen);\n if (!s->cpu_state) {\n vm_error(\"unsupported max_xlen=%d\\n\", max_xlen);\n /* XXX: should free resources */\n return NULL;\n }\n /* RAM */\n ram_flags = 0;\n cpu_register_ram(s->mem_map, RAM_BASE_ADDR, p->ram_size, ram_flags);\n cpu_register_ram(s->mem_map, 0x00000000, LOW_RAM_SIZE, 0);\n s->rtc_real_time = p->rtc_real_time;\n if (p->rtc_real_time) {\n s->rtc_start_time = rtc_get_real_time(s);\n }\n \n cpu_register_device(s->mem_map, CLINT_BASE_ADDR, CLINT_SIZE, s,\n clint_read, clint_write, DEVIO_SIZE32);\n cpu_register_device(s->mem_map, PLIC_BASE_ADDR, PLIC_SIZE, s,\n plic_read, plic_write, DEVIO_SIZE32);\n for(i = 1; i < 32; i++) {\n irq_init(&s->plic_irq[i], plic_set_irq, s, i);\n }\n\n cpu_register_device(s->mem_map, HTIF_BASE_ADDR, 16,\n s, htif_read, htif_write, DEVIO_SIZE32);\n s->common.console = p->console;\n\n memset(vbus, 0, sizeof(*vbus));\n vbus->mem_map = s->mem_map;\n vbus->addr = VIRTIO_BASE_ADDR;\n irq_num = VIRTIO_IRQ;\n \n /* virtio console */\n if (p->console) {\n vbus->irq = &s->plic_irq[irq_num];\n s->common.console_dev = virtio_console_init(vbus, p->console);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n \n /* virtio net device */\n for(i = 0; i < p->eth_count; i++) {\n vbus->irq = &s->plic_irq[irq_num];\n virtio_net_init(vbus, p->tab_eth[i].net);\n s->common.net = p->tab_eth[i].net;\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n /* virtio block device */\n for(i = 0; i < p->drive_count; i++) {\n vbus->irq = &s->plic_irq[irq_num];\n blk_dev = virtio_block_init(vbus, p->tab_drive[i].block_dev);\n (void)blk_dev;\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n /* virtio filesystem */\n for(i = 0; i < p->fs_count; i++) {\n VIRTIODevice *fs_dev;\n vbus->irq = &s->plic_irq[irq_num];\n fs_dev = virtio_9p_init(vbus, p->tab_fs[i].fs_dev,\n p->tab_fs[i].tag);\n (void)fs_dev;\n // virtio_set_debug(fs_dev, VIRTIO_DEBUG_9P);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n if (p->display_device) {\n FBDevice *fb_dev;\n fb_dev = mallocz(sizeof(*fb_dev));\n s->common.fb_dev = fb_dev;\n if (!strcmp(p->display_device, \"simplefb\")) {\n simplefb_init(s->mem_map,\n FRAMEBUFFER_BASE_ADDR,\n fb_dev,\n p->width, p->height);\n \n } else {\n vm_error(\"unsupported display device: %s\\n\", p->display_device);\n exit(1);\n }\n }\n\n if (p->input_device) {\n if (!strcmp(p->input_device, \"virtio\")) {\n vbus->irq = &s->plic_irq[irq_num];\n s->keyboard_dev = virtio_input_init(vbus,\n VIRTIO_INPUT_TYPE_KEYBOARD);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n\n vbus->irq = &s->plic_irq[irq_num];\n s->mouse_dev = virtio_input_init(vbus,\n VIRTIO_INPUT_TYPE_TABLET);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n } else {\n vm_error(\"unsupported input device: %s\\n\", p->input_device);\n exit(1);\n }\n }\n \n if (!p->files[VM_FILE_BIOS].buf) {\n vm_error(\"No bios found\");\n }\n\n copy_bios(s, p->files[VM_FILE_BIOS].buf, p->files[VM_FILE_BIOS].len,\n p->files[VM_FILE_KERNEL].buf, p->files[VM_FILE_KERNEL].len,\n p->files[VM_FILE_INITRD].buf, p->files[VM_FILE_INITRD].len,\n p->cmdline);\n \n return (VirtMachine *)s;\n}\n\nstatic void riscv_machine_end(VirtMachine *s1)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n /* XXX: stop all */\n riscv_cpu_end(s->cpu_state);\n phys_mem_map_end(s->mem_map);\n free(s);\n}\n\n/* in ms */\nstatic int riscv_machine_get_sleep_duration(VirtMachine *s1, int delay)\n{\n RISCVMachine *m = (RISCVMachine *)s1;\n RISCVCPUState *s = m->cpu_state;\n int64_t delay1;\n \n /* wait for an event: the only asynchronous event is the RTC timer */\n if (!(riscv_cpu_get_mip(s) & MIP_MTIP)) {\n delay1 = m->timecmp - rtc_get_time(m);\n if (delay1 <= 0) {\n riscv_cpu_set_mip(s, MIP_MTIP);\n delay = 0;\n } else {\n /* convert delay to ms */\n delay1 = delay1 / (RTC_FREQ / 1000);\n if (delay1 < delay)\n delay = delay1;\n }\n }\n if (!riscv_cpu_get_power_down(s))\n delay = 0;\n return delay;\n}\n\nstatic void riscv_machine_interp(VirtMachine *s1, int max_exec_cycle)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n riscv_cpu_interp(s->cpu_state, max_exec_cycle);\n}\n\nstatic void riscv_vm_send_key_event(VirtMachine *s1, BOOL is_down,\n uint16_t key_code)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n if (s->keyboard_dev) {\n virtio_input_send_key_event(s->keyboard_dev, is_down, key_code);\n }\n}\n\nstatic BOOL riscv_vm_mouse_is_absolute(VirtMachine *s)\n{\n return TRUE;\n}\n\nstatic void riscv_vm_send_mouse_event(VirtMachine *s1, int dx, int dy, int dz,\n unsigned int buttons)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n if (s->mouse_dev) {\n virtio_input_send_mouse_event(s->mouse_dev, dx, dy, dz, buttons);\n }\n}\n\nconst VirtMachineClass riscv_machine_class = {\n \"riscv32,riscv64,riscv128\",\n riscv_machine_set_defaults,\n riscv_machine_init,\n riscv_machine_end,\n riscv_machine_get_sleep_duration,\n riscv_machine_interp,\n riscv_vm_mouse_is_absolute,\n riscv_vm_send_mouse_event,\n riscv_vm_send_key_event,\n};\n"], ["/linuxpdf/tinyemu/slirp/cksum.c", "/*\n * Copyright (c) 1988, 1992, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)in_cksum.c\t8.1 (Berkeley) 6/10/93\n * in_cksum.c,v 1.2 1994/08/02 07:48:16 davidg Exp\n */\n\n#include \"slirp.h\"\n\n/*\n * Checksum routine for Internet Protocol family headers (Portable Version).\n *\n * This routine is very heavily used in the network\n * code and should be modified for each CPU to be as fast as possible.\n *\n * XXX Since we will never span more than 1 mbuf, we can optimise this\n */\n\n#define ADDCARRY(x) (x > 65535 ? x -= 65535 : x)\n#define REDUCE {l_util.l = sum; sum = l_util.s[0] + l_util.s[1]; \\\n (void)ADDCARRY(sum);}\n\nint cksum(struct mbuf *m, int len)\n{\n\tregister uint16_t *w;\n\tregister int sum = 0;\n\tregister int mlen = 0;\n\tint byte_swapped = 0;\n\n\tunion {\n\t\tuint8_t c[2];\n\t\tuint16_t s;\n\t} s_util;\n\tunion {\n\t\tuint16_t s[2];\n\t\tuint32_t l;\n\t} l_util;\n\n\tif (m->m_len == 0)\n\t goto cont;\n\tw = mtod(m, uint16_t *);\n\n\tmlen = m->m_len;\n\n\tif (len < mlen)\n\t mlen = len;\n#ifdef DEBUG\n\tlen -= mlen;\n#endif\n\t/*\n\t * Force to even boundary.\n\t */\n\tif ((1 & (long) w) && (mlen > 0)) {\n\t\tREDUCE;\n\t\tsum <<= 8;\n\t\ts_util.c[0] = *(uint8_t *)w;\n\t\tw = (uint16_t *)((int8_t *)w + 1);\n\t\tmlen--;\n\t\tbyte_swapped = 1;\n\t}\n\t/*\n\t * Unroll the loop to make overhead from\n\t * branches &c small.\n\t */\n\twhile ((mlen -= 32) >= 0) {\n\t\tsum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];\n\t\tsum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];\n\t\tsum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];\n\t\tsum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];\n\t\tw += 16;\n\t}\n\tmlen += 32;\n\twhile ((mlen -= 8) >= 0) {\n\t\tsum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];\n\t\tw += 4;\n\t}\n\tmlen += 8;\n\tif (mlen == 0 && byte_swapped == 0)\n\t goto cont;\n\tREDUCE;\n\twhile ((mlen -= 2) >= 0) {\n\t\tsum += *w++;\n\t}\n\n\tif (byte_swapped) {\n\t\tREDUCE;\n\t\tsum <<= 8;\n\t\tif (mlen == -1) {\n\t\t\ts_util.c[1] = *(uint8_t *)w;\n\t\t\tsum += s_util.s;\n\t\t\tmlen = 0;\n\t\t} else\n\n\t\t mlen = -1;\n\t} else if (mlen == -1)\n\t s_util.c[0] = *(uint8_t *)w;\n\ncont:\n#ifdef DEBUG\n\tif (len) {\n\t\tDEBUG_ERROR((dfd, \"cksum: out of data\\n\"));\n\t\tDEBUG_ERROR((dfd, \" len = %d\\n\", len));\n\t}\n#endif\n\tif (mlen == -1) {\n\t\t/* The last mbuf has odd # of bytes. Follow the\n\t\t standard (the odd byte may be shifted left by 8 bits\n\t\t\t or not as determined by endian-ness of the machine) */\n\t\ts_util.c[1] = 0;\n\t\tsum += s_util.s;\n\t}\n\tREDUCE;\n\treturn (~sum & 0xffff);\n}\n"], ["/linuxpdf/tinyemu/temu.c", "/*\n * TinyEMU\n * \n * Copyright (c) 2016-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifndef _WIN32\n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#ifdef CONFIG_FS_NET\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n#endif\n#ifdef CONFIG_SLIRP\n#include \"slirp/libslirp.h\"\n#endif\n\n#ifndef _WIN32\n\ntypedef struct {\n int stdin_fd;\n int console_esc_state;\n BOOL resize_pending;\n} STDIODevice;\n\nstatic struct termios oldtty;\nstatic int old_fd0_flags;\nstatic STDIODevice *global_stdio_device;\n\nstatic void term_exit(void)\n{\n tcsetattr (0, TCSANOW, &oldtty);\n fcntl(0, F_SETFL, old_fd0_flags);\n}\n\nstatic void term_init(BOOL allow_ctrlc)\n{\n struct termios tty;\n\n memset(&tty, 0, sizeof(tty));\n tcgetattr (0, &tty);\n oldtty = tty;\n old_fd0_flags = fcntl(0, F_GETFL);\n\n tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP\n |INLCR|IGNCR|ICRNL|IXON);\n tty.c_oflag |= OPOST;\n tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);\n if (!allow_ctrlc)\n tty.c_lflag &= ~ISIG;\n tty.c_cflag &= ~(CSIZE|PARENB);\n tty.c_cflag |= CS8;\n tty.c_cc[VMIN] = 1;\n tty.c_cc[VTIME] = 0;\n\n tcsetattr (0, TCSANOW, &tty);\n\n atexit(term_exit);\n}\n\nstatic void console_write(void *opaque, const uint8_t *buf, int len)\n{\n fwrite(buf, 1, len, stdout);\n fflush(stdout);\n}\n\nstatic int console_read(void *opaque, uint8_t *buf, int len)\n{\n STDIODevice *s = opaque;\n int ret, i, j;\n uint8_t ch;\n \n if (len <= 0)\n return 0;\n\n ret = read(s->stdin_fd, buf, len);\n if (ret < 0)\n return 0;\n if (ret == 0) {\n /* EOF */\n exit(1);\n }\n\n j = 0;\n for(i = 0; i < ret; i++) {\n ch = buf[i];\n if (s->console_esc_state) {\n s->console_esc_state = 0;\n switch(ch) {\n case 'x':\n printf(\"Terminated\\n\");\n exit(0);\n case 'h':\n printf(\"\\n\"\n \"C-a h print this help\\n\"\n \"C-a x exit emulator\\n\"\n \"C-a C-a send C-a\\n\"\n );\n break;\n case 1:\n goto output_char;\n default:\n break;\n }\n } else {\n if (ch == 1) {\n s->console_esc_state = 1;\n } else {\n output_char:\n buf[j++] = ch;\n }\n }\n }\n return j;\n}\n\nstatic void term_resize_handler(int sig)\n{\n if (global_stdio_device)\n global_stdio_device->resize_pending = TRUE;\n}\n\nstatic void console_get_size(STDIODevice *s, int *pw, int *ph)\n{\n struct winsize ws;\n int width, height;\n /* default values */\n width = 80;\n height = 25;\n if (ioctl(s->stdin_fd, TIOCGWINSZ, &ws) == 0 &&\n ws.ws_col >= 4 && ws.ws_row >= 4) {\n width = ws.ws_col;\n height = ws.ws_row;\n }\n *pw = width;\n *ph = height;\n}\n\nCharacterDevice *console_init(BOOL allow_ctrlc)\n{\n CharacterDevice *dev;\n STDIODevice *s;\n struct sigaction sig;\n\n term_init(allow_ctrlc);\n\n dev = mallocz(sizeof(*dev));\n s = mallocz(sizeof(*s));\n s->stdin_fd = 0;\n /* Note: the glibc does not properly tests the return value of\n write() in printf, so some messages on stdout may be lost */\n fcntl(s->stdin_fd, F_SETFL, O_NONBLOCK);\n\n s->resize_pending = TRUE;\n global_stdio_device = s;\n \n /* use a signal to get the host terminal resize events */\n sig.sa_handler = term_resize_handler;\n sigemptyset(&sig.sa_mask);\n sig.sa_flags = 0;\n sigaction(SIGWINCH, &sig, NULL);\n \n dev->opaque = s;\n dev->write_data = console_write;\n dev->read_data = console_read;\n return dev;\n}\n\n#endif /* !_WIN32 */\n\ntypedef enum {\n BF_MODE_RO,\n BF_MODE_RW,\n BF_MODE_SNAPSHOT,\n} BlockDeviceModeEnum;\n\n#define SECTOR_SIZE 512\n\ntypedef struct BlockDeviceFile {\n FILE *f;\n int64_t nb_sectors;\n BlockDeviceModeEnum mode;\n uint8_t **sector_table;\n} BlockDeviceFile;\n\nstatic int64_t bf_get_sector_count(BlockDevice *bs)\n{\n BlockDeviceFile *bf = bs->opaque;\n return bf->nb_sectors;\n}\n\n//#define DUMP_BLOCK_READ\n\nstatic int bf_read_async(BlockDevice *bs,\n uint64_t sector_num, uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceFile *bf = bs->opaque;\n // printf(\"bf_read_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n#ifdef DUMP_BLOCK_READ\n {\n static FILE *f;\n if (!f)\n f = fopen(\"/tmp/read_sect.txt\", \"wb\");\n fprintf(f, \"%\" PRId64 \" %d\\n\", sector_num, n);\n }\n#endif\n if (!bf->f)\n return -1;\n if (bf->mode == BF_MODE_SNAPSHOT) {\n int i;\n for(i = 0; i < n; i++) {\n if (!bf->sector_table[sector_num]) {\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fread(buf, 1, SECTOR_SIZE, bf->f);\n } else {\n memcpy(buf, bf->sector_table[sector_num], SECTOR_SIZE);\n }\n sector_num++;\n buf += SECTOR_SIZE;\n }\n } else {\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fread(buf, 1, n * SECTOR_SIZE, bf->f);\n }\n /* synchronous read */\n return 0;\n}\n\nstatic int bf_write_async(BlockDevice *bs,\n uint64_t sector_num, const uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceFile *bf = bs->opaque;\n int ret;\n\n switch(bf->mode) {\n case BF_MODE_RO:\n ret = -1; /* error */\n break;\n case BF_MODE_RW:\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fwrite(buf, 1, n * SECTOR_SIZE, bf->f);\n ret = 0;\n break;\n case BF_MODE_SNAPSHOT:\n {\n int i;\n if ((sector_num + n) > bf->nb_sectors)\n return -1;\n for(i = 0; i < n; i++) {\n if (!bf->sector_table[sector_num]) {\n bf->sector_table[sector_num] = malloc(SECTOR_SIZE);\n }\n memcpy(bf->sector_table[sector_num], buf, SECTOR_SIZE);\n sector_num++;\n buf += SECTOR_SIZE;\n }\n ret = 0;\n }\n break;\n default:\n abort();\n }\n\n return ret;\n}\n\nstatic BlockDevice *block_device_init(const char *filename,\n BlockDeviceModeEnum mode)\n{\n BlockDevice *bs;\n BlockDeviceFile *bf;\n int64_t file_size;\n FILE *f;\n const char *mode_str;\n\n if (mode == BF_MODE_RW) {\n mode_str = \"r+b\";\n } else {\n mode_str = \"rb\";\n }\n \n f = fopen(filename, mode_str);\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n file_size = ftello(f);\n\n bs = mallocz(sizeof(*bs));\n bf = mallocz(sizeof(*bf));\n\n bf->mode = mode;\n bf->nb_sectors = file_size / 512;\n bf->f = f;\n\n if (mode == BF_MODE_SNAPSHOT) {\n bf->sector_table = mallocz(sizeof(bf->sector_table[0]) *\n bf->nb_sectors);\n }\n \n bs->opaque = bf;\n bs->get_sector_count = bf_get_sector_count;\n bs->read_async = bf_read_async;\n bs->write_async = bf_write_async;\n return bs;\n}\n\n#ifndef _WIN32\n\ntypedef struct {\n int fd;\n BOOL select_filled;\n} TunState;\n\nstatic void tun_write_packet(EthernetDevice *net,\n const uint8_t *buf, int len)\n{\n TunState *s = net->opaque;\n write(s->fd, buf, len);\n}\n\nstatic void tun_select_fill(EthernetDevice *net, int *pfd_max,\n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *pdelay)\n{\n TunState *s = net->opaque;\n int net_fd = s->fd;\n\n s->select_filled = net->device_can_write_packet(net);\n if (s->select_filled) {\n FD_SET(net_fd, rfds);\n *pfd_max = max_int(*pfd_max, net_fd);\n }\n}\n\nstatic void tun_select_poll(EthernetDevice *net, \n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int select_ret)\n{\n TunState *s = net->opaque;\n int net_fd = s->fd;\n uint8_t buf[2048];\n int ret;\n \n if (select_ret <= 0)\n return;\n if (s->select_filled && FD_ISSET(net_fd, rfds)) {\n ret = read(net_fd, buf, sizeof(buf));\n if (ret > 0)\n net->device_write_packet(net, buf, ret);\n }\n \n}\n\n/* configure with:\n# bridge configuration (connect tap0 to bridge interface br0)\n ip link add br0 type bridge\n ip tuntap add dev tap0 mode tap [user x] [group x]\n ip link set tap0 master br0\n ip link set dev br0 up\n ip link set dev tap0 up\n\n# NAT configuration (eth1 is the interface connected to internet)\n ifconfig br0 192.168.3.1\n echo 1 > /proc/sys/net/ipv4/ip_forward\n iptables -D FORWARD 1\n iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE\n\n In the VM:\n ifconfig eth0 192.168.3.2\n route add -net 0.0.0.0 netmask 0.0.0.0 gw 192.168.3.1\n*/\nstatic EthernetDevice *tun_open(const char *ifname)\n{\n struct ifreq ifr;\n int fd, ret;\n EthernetDevice *net;\n TunState *s;\n \n fd = open(\"/dev/net/tun\", O_RDWR);\n if (fd < 0) {\n fprintf(stderr, \"Error: could not open /dev/net/tun\\n\");\n return NULL;\n }\n memset(&ifr, 0, sizeof(ifr));\n ifr.ifr_flags = IFF_TAP | IFF_NO_PI;\n pstrcpy(ifr.ifr_name, sizeof(ifr.ifr_name), ifname);\n ret = ioctl(fd, TUNSETIFF, (void *) &ifr);\n if (ret != 0) {\n fprintf(stderr, \"Error: could not configure /dev/net/tun\\n\");\n close(fd);\n return NULL;\n }\n fcntl(fd, F_SETFL, O_NONBLOCK);\n\n net = mallocz(sizeof(*net));\n net->mac_addr[0] = 0x02;\n net->mac_addr[1] = 0x00;\n net->mac_addr[2] = 0x00;\n net->mac_addr[3] = 0x00;\n net->mac_addr[4] = 0x00;\n net->mac_addr[5] = 0x01;\n s = mallocz(sizeof(*s));\n s->fd = fd;\n net->opaque = s;\n net->write_packet = tun_write_packet;\n net->select_fill = tun_select_fill;\n net->select_poll = tun_select_poll;\n return net;\n}\n\n#endif /* !_WIN32 */\n\n#ifdef CONFIG_SLIRP\n\n/*******************************************************/\n/* slirp */\n\nstatic Slirp *slirp_state;\n\nstatic void slirp_write_packet(EthernetDevice *net,\n const uint8_t *buf, int len)\n{\n Slirp *slirp_state = net->opaque;\n slirp_input(slirp_state, buf, len);\n}\n\nint slirp_can_output(void *opaque)\n{\n EthernetDevice *net = opaque;\n return net->device_can_write_packet(net);\n}\n\nvoid slirp_output(void *opaque, const uint8_t *pkt, int pkt_len)\n{\n EthernetDevice *net = opaque;\n return net->device_write_packet(net, pkt, pkt_len);\n}\n\nstatic void slirp_select_fill1(EthernetDevice *net, int *pfd_max,\n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *pdelay)\n{\n Slirp *slirp_state = net->opaque;\n slirp_select_fill(slirp_state, pfd_max, rfds, wfds, efds);\n}\n\nstatic void slirp_select_poll1(EthernetDevice *net, \n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int select_ret)\n{\n Slirp *slirp_state = net->opaque;\n slirp_select_poll(slirp_state, rfds, wfds, efds, (select_ret <= 0));\n}\n\nstatic EthernetDevice *slirp_open(void)\n{\n EthernetDevice *net;\n struct in_addr net_addr = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */\n struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */\n struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */\n struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */\n struct in_addr dns = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */\n const char *bootfile = NULL;\n const char *vhostname = NULL;\n int restricted = 0;\n \n if (slirp_state) {\n fprintf(stderr, \"Only a single slirp instance is allowed\\n\");\n return NULL;\n }\n net = mallocz(sizeof(*net));\n\n slirp_state = slirp_init(restricted, net_addr, mask, host, vhostname,\n \"\", bootfile, dhcp, dns, net);\n \n net->mac_addr[0] = 0x02;\n net->mac_addr[1] = 0x00;\n net->mac_addr[2] = 0x00;\n net->mac_addr[3] = 0x00;\n net->mac_addr[4] = 0x00;\n net->mac_addr[5] = 0x01;\n net->opaque = slirp_state;\n net->write_packet = slirp_write_packet;\n net->select_fill = slirp_select_fill1;\n net->select_poll = slirp_select_poll1;\n \n return net;\n}\n\n#endif /* CONFIG_SLIRP */\n\n#define MAX_EXEC_CYCLE 500000\n#define MAX_SLEEP_TIME 10 /* in ms */\n\nvoid virt_machine_run(VirtMachine *m)\n{\n fd_set rfds, wfds, efds;\n int fd_max, ret, delay;\n struct timeval tv;\n#ifndef _WIN32\n int stdin_fd;\n#endif\n \n delay = virt_machine_get_sleep_duration(m, MAX_SLEEP_TIME);\n \n /* wait for an event */\n FD_ZERO(&rfds);\n FD_ZERO(&wfds);\n FD_ZERO(&efds);\n fd_max = -1;\n#ifndef _WIN32\n if (m->console_dev && virtio_console_can_write_data(m->console_dev)) {\n STDIODevice *s = m->console->opaque;\n stdin_fd = s->stdin_fd;\n FD_SET(stdin_fd, &rfds);\n fd_max = stdin_fd;\n\n if (s->resize_pending) {\n int width, height;\n console_get_size(s, &width, &height);\n virtio_console_resize_event(m->console_dev, width, height);\n s->resize_pending = FALSE;\n }\n }\n#endif\n if (m->net) {\n m->net->select_fill(m->net, &fd_max, &rfds, &wfds, &efds, &delay);\n }\n#ifdef CONFIG_FS_NET\n fs_net_set_fdset(&fd_max, &rfds, &wfds, &efds, &delay);\n#endif\n tv.tv_sec = delay / 1000;\n tv.tv_usec = (delay % 1000) * 1000;\n ret = select(fd_max + 1, &rfds, &wfds, &efds, &tv);\n if (m->net) {\n m->net->select_poll(m->net, &rfds, &wfds, &efds, ret);\n }\n if (ret > 0) {\n#ifndef _WIN32\n if (m->console_dev && FD_ISSET(stdin_fd, &rfds)) {\n uint8_t buf[128];\n int ret, len;\n len = virtio_console_get_write_len(m->console_dev);\n len = min_int(len, sizeof(buf));\n ret = m->console->read_data(m->console->opaque, buf, len);\n if (ret > 0) {\n virtio_console_write_data(m->console_dev, buf, ret);\n }\n }\n#endif\n }\n\n#ifdef CONFIG_SDL\n sdl_refresh(m);\n#endif\n \n virt_machine_interp(m, MAX_EXEC_CYCLE);\n}\n\n/*******************************************************/\n\nstatic struct option options[] = {\n { \"help\", no_argument, NULL, 'h' },\n { \"ctrlc\", no_argument },\n { \"rw\", no_argument },\n { \"ro\", no_argument },\n { \"append\", required_argument },\n { \"no-accel\", no_argument },\n { \"build-preload\", required_argument },\n { NULL },\n};\n\nvoid help(void)\n{\n printf(\"temu version \" CONFIG_VERSION \", Copyright (c) 2016-2018 Fabrice Bellard\\n\"\n \"usage: riscvemu [options] config_file\\n\"\n \"options are:\\n\"\n \"-m ram_size set the RAM size in MB\\n\"\n \"-rw allow write access to the disk image (default=snapshot)\\n\"\n \"-ctrlc the C-c key stops the emulator instead of being sent to the\\n\"\n \" emulated software\\n\"\n \"-append cmdline append cmdline to the kernel command line\\n\"\n \"-no-accel disable VM acceleration (KVM, x86 machine only)\\n\"\n \"\\n\"\n \"Console keys:\\n\"\n \"Press C-a x to exit the emulator, C-a h to get some help.\\n\");\n exit(1);\n}\n\n#ifdef CONFIG_FS_NET\nstatic BOOL net_completed;\n\nstatic void net_start_cb(void *arg)\n{\n net_completed = TRUE;\n}\n\nstatic BOOL net_poll_cb(void *arg)\n{\n return net_completed;\n}\n\n#endif\n\nint main(int argc, char **argv)\n{\n VirtMachine *s;\n const char *path, *cmdline, *build_preload_file;\n int c, option_index, i, ram_size, accel_enable;\n BOOL allow_ctrlc;\n BlockDeviceModeEnum drive_mode;\n VirtMachineParams p_s, *p = &p_s;\n\n ram_size = -1;\n allow_ctrlc = FALSE;\n (void)allow_ctrlc;\n drive_mode = BF_MODE_SNAPSHOT;\n accel_enable = -1;\n cmdline = NULL;\n build_preload_file = NULL;\n for(;;) {\n c = getopt_long_only(argc, argv, \"hm:\", options, &option_index);\n if (c == -1)\n break;\n switch(c) {\n case 0:\n switch(option_index) {\n case 1: /* ctrlc */\n allow_ctrlc = TRUE;\n break;\n case 2: /* rw */\n drive_mode = BF_MODE_RW;\n break;\n case 3: /* ro */\n drive_mode = BF_MODE_RO;\n break;\n case 4: /* append */\n cmdline = optarg;\n break;\n case 5: /* no-accel */\n accel_enable = FALSE;\n break;\n case 6: /* build-preload */\n build_preload_file = optarg;\n break;\n default:\n fprintf(stderr, \"unknown option index: %d\\n\", option_index);\n exit(1);\n }\n break;\n case 'h':\n help();\n break;\n case 'm':\n ram_size = strtoul(optarg, NULL, 0);\n break;\n default:\n exit(1);\n }\n }\n\n if (optind >= argc) {\n help();\n }\n\n path = argv[optind++];\n\n virt_machine_set_defaults(p);\n#ifdef CONFIG_FS_NET\n fs_wget_init();\n#endif\n virt_machine_load_config_file(p, path, NULL, NULL);\n#ifdef CONFIG_FS_NET\n fs_net_event_loop(NULL, NULL);\n#endif\n\n /* override some config parameters */\n\n if (ram_size > 0) {\n p->ram_size = (uint64_t)ram_size << 20;\n }\n if (accel_enable != -1)\n p->accel_enable = accel_enable;\n if (cmdline) {\n vm_add_cmdline(p, cmdline);\n }\n \n /* open the files & devices */\n for(i = 0; i < p->drive_count; i++) {\n BlockDevice *drive;\n char *fname;\n fname = get_file_path(p->cfg_filename, p->tab_drive[i].filename);\n#ifdef CONFIG_FS_NET\n if (is_url(fname)) {\n net_completed = FALSE;\n drive = block_device_init_http(fname, 128 * 1024,\n net_start_cb, NULL);\n /* wait until the drive is initialized */\n fs_net_event_loop(net_poll_cb, NULL);\n } else\n#endif\n {\n drive = block_device_init(fname, drive_mode);\n }\n free(fname);\n p->tab_drive[i].block_dev = drive;\n }\n\n for(i = 0; i < p->fs_count; i++) {\n FSDevice *fs;\n const char *path;\n path = p->tab_fs[i].filename;\n#ifdef CONFIG_FS_NET\n if (is_url(path)) {\n fs = fs_net_init(path, NULL, NULL);\n if (!fs)\n exit(1);\n if (build_preload_file)\n fs_dump_cache_load(fs, build_preload_file);\n fs_net_event_loop(NULL, NULL);\n } else\n#endif\n {\n#ifdef _WIN32\n fprintf(stderr, \"Filesystem access not supported yet\\n\");\n exit(1);\n#else\n char *fname;\n fname = get_file_path(p->cfg_filename, path);\n fs = fs_disk_init(fname);\n if (!fs) {\n fprintf(stderr, \"%s: must be a directory\\n\", fname);\n exit(1);\n }\n free(fname);\n#endif\n }\n p->tab_fs[i].fs_dev = fs;\n }\n\n for(i = 0; i < p->eth_count; i++) {\n#ifdef CONFIG_SLIRP\n if (!strcmp(p->tab_eth[i].driver, \"user\")) {\n p->tab_eth[i].net = slirp_open();\n if (!p->tab_eth[i].net)\n exit(1);\n } else\n#endif\n#ifndef _WIN32\n if (!strcmp(p->tab_eth[i].driver, \"tap\")) {\n p->tab_eth[i].net = tun_open(p->tab_eth[i].ifname);\n if (!p->tab_eth[i].net)\n exit(1);\n } else\n#endif\n {\n fprintf(stderr, \"Unsupported network driver '%s'\\n\",\n p->tab_eth[i].driver);\n exit(1);\n }\n }\n \n#ifdef CONFIG_SDL\n if (p->display_device) {\n sdl_init(p->width, p->height);\n } else\n#endif\n {\n#ifdef _WIN32\n fprintf(stderr, \"Console not supported yet\\n\");\n exit(1);\n#else\n p->console = console_init(allow_ctrlc);\n#endif\n }\n p->rtc_real_time = TRUE;\n\n s = virt_machine_init(p);\n if (!s)\n exit(1);\n \n virt_machine_free_config(p);\n\n if (s->net) {\n s->net->device_set_carrier(s->net, TRUE);\n }\n \n for(;;) {\n virt_machine_run(s);\n }\n virt_machine_end(s);\n return 0;\n}\n"], ["/linuxpdf/tinyemu/riscv_cpu.c", "/*\n * RISCV CPU emulator\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"riscv_cpu.h\"\n\n#ifndef MAX_XLEN\n#error MAX_XLEN must be defined\n#endif\n#ifndef CONFIG_RISCV_MAX_XLEN\n#error CONFIG_RISCV_MAX_XLEN must be defined\n#endif\n\n//#define DUMP_INVALID_MEM_ACCESS\n//#define DUMP_MMU_EXCEPTIONS\n//#define DUMP_INTERRUPTS\n//#define DUMP_INVALID_CSR\n//#define DUMP_EXCEPTIONS\n//#define DUMP_CSR\n//#define CONFIG_LOGFILE\n\n#include \"riscv_cpu_priv.h\"\n\n#if FLEN > 0\n#include \"softfp.h\"\n#endif\n\n#ifdef USE_GLOBAL_STATE\nstatic RISCVCPUState riscv_cpu_global_state;\n#endif\n#ifdef USE_GLOBAL_VARIABLES\n#define code_ptr s->__code_ptr\n#define code_end s->__code_end\n#define code_to_pc_addend s->__code_to_pc_addend\n#endif\n\n#ifdef CONFIG_LOGFILE\nstatic FILE *log_file;\n\nstatic void log_vprintf(const char *fmt, va_list ap)\n{\n if (!log_file)\n log_file = fopen(\"/tmp/riscemu.log\", \"wb\");\n vfprintf(log_file, fmt, ap);\n}\n#else\nstatic void log_vprintf(const char *fmt, va_list ap)\n{\n vprintf(fmt, ap);\n}\n#endif\n\nstatic void __attribute__((format(printf, 1, 2), unused)) log_printf(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n log_vprintf(fmt, ap);\n va_end(ap);\n}\n\n#if MAX_XLEN == 128\nstatic void fprint_target_ulong(FILE *f, target_ulong a)\n{\n fprintf(f, \"%016\" PRIx64 \"%016\" PRIx64, (uint64_t)(a >> 64), (uint64_t)a);\n}\n#else\nstatic void fprint_target_ulong(FILE *f, target_ulong a)\n{\n fprintf(f, \"%\" PR_target_ulong, a);\n}\n#endif\n\nstatic void print_target_ulong(target_ulong a)\n{\n fprint_target_ulong(stdout, a);\n}\n\nstatic char *reg_name[32] = {\n\"zero\", \"ra\", \"sp\", \"gp\", \"tp\", \"t0\", \"t1\", \"t2\",\n\"s0\", \"s1\", \"a0\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\",\n\"a6\", \"a7\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\", \"s7\",\n\"s8\", \"s9\", \"s10\", \"s11\", \"t3\", \"t4\", \"t5\", \"t6\"\n};\n\nstatic void dump_regs(RISCVCPUState *s)\n{\n int i, cols;\n const char priv_str[4] = \"USHM\";\n cols = 256 / MAX_XLEN;\n printf(\"pc =\");\n print_target_ulong(s->pc);\n printf(\" \");\n for(i = 1; i < 32; i++) {\n printf(\"%-3s=\", reg_name[i]);\n print_target_ulong(s->reg[i]);\n if ((i & (cols - 1)) == (cols - 1))\n printf(\"\\n\");\n else\n printf(\" \");\n }\n printf(\"priv=%c\", priv_str[s->priv]);\n printf(\" mstatus=\");\n print_target_ulong(s->mstatus);\n printf(\" cycles=%\" PRId64, s->insn_counter);\n printf(\"\\n\");\n#if 1\n printf(\" mideleg=\");\n print_target_ulong(s->mideleg);\n printf(\" mie=\");\n print_target_ulong(s->mie);\n printf(\" mip=\");\n print_target_ulong(s->mip);\n printf(\"\\n\");\n#endif\n}\n\nstatic __attribute__((unused)) void cpu_abort(RISCVCPUState *s)\n{\n dump_regs(s);\n abort();\n}\n\n/* addr must be aligned. Only RAM accesses are supported */\n#define PHYS_MEM_READ_WRITE(size, uint_type) \\\nstatic __maybe_unused inline void phys_write_u ## size(RISCVCPUState *s, target_ulong addr,\\\n uint_type val) \\\n{\\\n PhysMemoryRange *pr = get_phys_mem_range(s->mem_map, addr);\\\n if (!pr || !pr->is_ram)\\\n return;\\\n *(uint_type *)(pr->phys_mem + \\\n (uintptr_t)(addr - pr->addr)) = val;\\\n}\\\n\\\nstatic __maybe_unused inline uint_type phys_read_u ## size(RISCVCPUState *s, target_ulong addr) \\\n{\\\n PhysMemoryRange *pr = get_phys_mem_range(s->mem_map, addr);\\\n if (!pr || !pr->is_ram)\\\n return 0;\\\n return *(uint_type *)(pr->phys_mem + \\\n (uintptr_t)(addr - pr->addr)); \\\n}\n\nPHYS_MEM_READ_WRITE(8, uint8_t)\nPHYS_MEM_READ_WRITE(32, uint32_t)\nPHYS_MEM_READ_WRITE(64, uint64_t)\n\n#define PTE_V_MASK (1 << 0)\n#define PTE_U_MASK (1 << 4)\n#define PTE_A_MASK (1 << 6)\n#define PTE_D_MASK (1 << 7)\n\n#define ACCESS_READ 0\n#define ACCESS_WRITE 1\n#define ACCESS_CODE 2\n\n/* access = 0: read, 1 = write, 2 = code. Set the exception_pending\n field if necessary. return 0 if OK, -1 if translation error */\nstatic int get_phys_addr(RISCVCPUState *s,\n target_ulong *ppaddr, target_ulong vaddr,\n int access)\n{\n int mode, levels, pte_bits, pte_idx, pte_mask, pte_size_log2, xwr, priv;\n int need_write, vaddr_shift, i, pte_addr_bits;\n target_ulong pte_addr, pte, vaddr_mask, paddr;\n\n if ((s->mstatus & MSTATUS_MPRV) && access != ACCESS_CODE) {\n /* use previous priviledge */\n priv = (s->mstatus >> MSTATUS_MPP_SHIFT) & 3;\n } else {\n priv = s->priv;\n }\n\n if (priv == PRV_M) {\n if (s->cur_xlen < MAX_XLEN) {\n /* truncate virtual address */\n *ppaddr = vaddr & (((target_ulong)1 << s->cur_xlen) - 1);\n } else {\n *ppaddr = vaddr;\n }\n return 0;\n }\n#if MAX_XLEN == 32\n /* 32 bits */\n mode = s->satp >> 31;\n if (mode == 0) {\n /* bare: no translation */\n *ppaddr = vaddr;\n return 0;\n } else {\n /* sv32 */\n levels = 2;\n pte_size_log2 = 2;\n pte_addr_bits = 22;\n }\n#else\n mode = (s->satp >> 60) & 0xf;\n if (mode == 0) {\n /* bare: no translation */\n *ppaddr = vaddr;\n return 0;\n } else {\n /* sv39/sv48 */\n levels = mode - 8 + 3;\n pte_size_log2 = 3;\n vaddr_shift = MAX_XLEN - (PG_SHIFT + levels * 9);\n if ((((target_long)vaddr << vaddr_shift) >> vaddr_shift) != vaddr)\n return -1;\n pte_addr_bits = 44;\n }\n#endif\n pte_addr = (s->satp & (((target_ulong)1 << pte_addr_bits) - 1)) << PG_SHIFT;\n pte_bits = 12 - pte_size_log2;\n pte_mask = (1 << pte_bits) - 1;\n for(i = 0; i < levels; i++) {\n vaddr_shift = PG_SHIFT + pte_bits * (levels - 1 - i);\n pte_idx = (vaddr >> vaddr_shift) & pte_mask;\n pte_addr += pte_idx << pte_size_log2;\n if (pte_size_log2 == 2)\n pte = phys_read_u32(s, pte_addr);\n else\n pte = phys_read_u64(s, pte_addr);\n //printf(\"pte=0x%08\" PRIx64 \"\\n\", pte);\n if (!(pte & PTE_V_MASK))\n return -1; /* invalid PTE */\n paddr = (pte >> 10) << PG_SHIFT;\n xwr = (pte >> 1) & 7;\n if (xwr != 0) {\n if (xwr == 2 || xwr == 6)\n return -1;\n /* priviledge check */\n if (priv == PRV_S) {\n if ((pte & PTE_U_MASK) && !(s->mstatus & MSTATUS_SUM))\n return -1;\n } else {\n if (!(pte & PTE_U_MASK))\n return -1;\n }\n /* protection check */\n /* MXR allows read access to execute-only pages */\n if (s->mstatus & MSTATUS_MXR)\n xwr |= (xwr >> 2);\n\n if (((xwr >> access) & 1) == 0)\n return -1;\n need_write = !(pte & PTE_A_MASK) ||\n (!(pte & PTE_D_MASK) && access == ACCESS_WRITE);\n pte |= PTE_A_MASK;\n if (access == ACCESS_WRITE)\n pte |= PTE_D_MASK;\n if (need_write) {\n if (pte_size_log2 == 2)\n phys_write_u32(s, pte_addr, pte);\n else\n phys_write_u64(s, pte_addr, pte);\n }\n vaddr_mask = ((target_ulong)1 << vaddr_shift) - 1;\n *ppaddr = (vaddr & vaddr_mask) | (paddr & ~vaddr_mask);\n return 0;\n } else {\n pte_addr = paddr;\n }\n }\n return -1;\n}\n\n/* return 0 if OK, != 0 if exception */\nint target_read_slow(RISCVCPUState *s, mem_uint_t *pval,\n target_ulong addr, int size_log2)\n{\n int size, tlb_idx, err, al;\n target_ulong paddr, offset;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n mem_uint_t ret;\n\n /* first handle unaligned accesses */\n size = 1 << size_log2;\n al = addr & (size - 1);\n if (al != 0) {\n switch(size_log2) {\n case 1:\n {\n uint8_t v0, v1;\n err = target_read_u8(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u8(s, &v1, addr + 1);\n if (err)\n return err;\n ret = v0 | (v1 << 8);\n }\n break;\n case 2:\n {\n uint32_t v0, v1;\n addr -= al;\n err = target_read_u32(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u32(s, &v1, addr + 4);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (32 - al * 8));\n }\n break;\n#if MLEN >= 64\n case 3:\n {\n uint64_t v0, v1;\n addr -= al;\n err = target_read_u64(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u64(s, &v1, addr + 8);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (64 - al * 8));\n }\n break;\n#endif\n#if MLEN >= 128\n case 4:\n {\n uint128_t v0, v1;\n addr -= al;\n err = target_read_u128(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u128(s, &v1, addr + 16);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (128 - al * 8));\n }\n break;\n#endif\n default:\n abort();\n }\n } else {\n if (get_phys_addr(s, &paddr, addr, ACCESS_READ)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_LOAD_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr) {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"target_read_slow: invalid physical address 0x\");\n print_target_ulong(paddr);\n printf(\"\\n\");\n#endif\n return 0;\n } else if (pr->is_ram) {\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_read[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_read[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n switch(size_log2) {\n case 0:\n ret = *(uint8_t *)ptr;\n break;\n case 1:\n ret = *(uint16_t *)ptr;\n break;\n case 2:\n ret = *(uint32_t *)ptr;\n break;\n#if MLEN >= 64\n case 3:\n ret = *(uint64_t *)ptr;\n break;\n#endif\n#if MLEN >= 128\n case 4:\n ret = *(uint128_t *)ptr;\n break;\n#endif\n default:\n abort();\n }\n } else {\n offset = paddr - pr->addr;\n if (((pr->devio_flags >> size_log2) & 1) != 0) {\n ret = pr->read_func(pr->opaque, offset, size_log2);\n }\n#if MLEN >= 64\n else if ((pr->devio_flags & DEVIO_SIZE32) && size_log2 == 3) {\n /* emulate 64 bit access */\n ret = pr->read_func(pr->opaque, offset, 2);\n ret |= (uint64_t)pr->read_func(pr->opaque, offset + 4, 2) << 32;\n \n }\n#endif\n else {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"unsupported device read access: addr=0x\");\n print_target_ulong(paddr);\n printf(\" width=%d bits\\n\", 1 << (3 + size_log2));\n#endif\n ret = 0;\n }\n }\n }\n *pval = ret;\n return 0;\n}\n\n/* return 0 if OK, != 0 if exception */\nint target_write_slow(RISCVCPUState *s, target_ulong addr,\n mem_uint_t val, int size_log2)\n{\n int size, i, tlb_idx, err;\n target_ulong paddr, offset;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n \n /* first handle unaligned accesses */\n size = 1 << size_log2;\n if ((addr & (size - 1)) != 0) {\n /* XXX: should avoid modifying the memory in case of exception */\n for(i = 0; i < size; i++) {\n err = target_write_u8(s, addr + i, (val >> (8 * i)) & 0xff);\n if (err)\n return err;\n }\n } else {\n if (get_phys_addr(s, &paddr, addr, ACCESS_WRITE)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_STORE_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr) {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"target_write_slow: invalid physical address 0x\");\n print_target_ulong(paddr);\n printf(\"\\n\");\n#endif\n } else if (pr->is_ram) {\n phys_mem_set_dirty_bit(pr, paddr - pr->addr);\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_write[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_write[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n switch(size_log2) {\n case 0:\n *(uint8_t *)ptr = val;\n break;\n case 1:\n *(uint16_t *)ptr = val;\n break;\n case 2:\n *(uint32_t *)ptr = val;\n break;\n#if MLEN >= 64\n case 3:\n *(uint64_t *)ptr = val;\n break;\n#endif\n#if MLEN >= 128\n case 4:\n *(uint128_t *)ptr = val;\n break;\n#endif\n default:\n abort();\n }\n } else {\n offset = paddr - pr->addr;\n if (((pr->devio_flags >> size_log2) & 1) != 0) {\n pr->write_func(pr->opaque, offset, val, size_log2);\n }\n#if MLEN >= 64\n else if ((pr->devio_flags & DEVIO_SIZE32) && size_log2 == 3) {\n /* emulate 64 bit access */\n pr->write_func(pr->opaque, offset,\n val & 0xffffffff, 2);\n pr->write_func(pr->opaque, offset + 4,\n (val >> 32) & 0xffffffff, 2);\n }\n#endif\n else {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"unsupported device write access: addr=0x\");\n print_target_ulong(paddr);\n printf(\" width=%d bits\\n\", 1 << (3 + size_log2));\n#endif\n }\n }\n }\n return 0;\n}\n\nstruct __attribute__((packed)) unaligned_u32 {\n uint32_t u32;\n};\n\n/* unaligned access at an address known to be a multiple of 2 */\nstatic uint32_t get_insn32(uint8_t *ptr)\n{\n#if defined(EMSCRIPTEN)\n return ((uint16_t *)ptr)[0] | (((uint16_t *)ptr)[1] << 16);\n#else\n return ((struct unaligned_u32 *)ptr)->u32;\n#endif\n}\n\n/* return 0 if OK, != 0 if exception */\nstatic no_inline __exception int target_read_insn_slow(RISCVCPUState *s,\n uint8_t **pptr,\n target_ulong addr)\n{\n int tlb_idx;\n target_ulong paddr;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n \n if (get_phys_addr(s, &paddr, addr, ACCESS_CODE)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_FETCH_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr || !pr->is_ram) {\n /* XXX: we only access to execute code from RAM */\n s->pending_tval = addr;\n s->pending_exception = CAUSE_FAULT_FETCH;\n return -1;\n }\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_code[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_code[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n *pptr = ptr;\n return 0;\n}\n\n/* addr must be aligned */\nstatic inline __exception int target_read_insn_u16(RISCVCPUState *s, uint16_t *pinsn,\n target_ulong addr)\n{\n uint32_t tlb_idx;\n uint8_t *ptr;\n \n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n if (likely(s->tlb_code[tlb_idx].vaddr == (addr & ~PG_MASK))) {\n ptr = (uint8_t *)(s->tlb_code[tlb_idx].mem_addend +\n (uintptr_t)addr);\n } else {\n if (target_read_insn_slow(s, &ptr, addr))\n return -1;\n }\n *pinsn = *(uint16_t *)ptr;\n return 0;\n}\n\nstatic void tlb_init(RISCVCPUState *s)\n{\n int i;\n \n for(i = 0; i < TLB_SIZE; i++) {\n s->tlb_read[i].vaddr = -1;\n s->tlb_write[i].vaddr = -1;\n s->tlb_code[i].vaddr = -1;\n }\n}\n\nstatic void tlb_flush_all(RISCVCPUState *s)\n{\n tlb_init(s);\n}\n\nstatic void tlb_flush_vaddr(RISCVCPUState *s, target_ulong vaddr)\n{\n tlb_flush_all(s);\n}\n\n/* XXX: inefficient but not critical as long as it is seldom used */\nstatic void glue(riscv_cpu_flush_tlb_write_range_ram,\n MAX_XLEN)(RISCVCPUState *s,\n uint8_t *ram_ptr, size_t ram_size)\n{\n uint8_t *ptr, *ram_end;\n int i;\n \n ram_end = ram_ptr + ram_size;\n for(i = 0; i < TLB_SIZE; i++) {\n if (s->tlb_write[i].vaddr != -1) {\n ptr = (uint8_t *)(s->tlb_write[i].mem_addend +\n (uintptr_t)s->tlb_write[i].vaddr);\n if (ptr >= ram_ptr && ptr < ram_end) {\n s->tlb_write[i].vaddr = -1;\n }\n }\n }\n}\n\n\n#define SSTATUS_MASK0 (MSTATUS_UIE | MSTATUS_SIE | \\\n MSTATUS_UPIE | MSTATUS_SPIE | \\\n MSTATUS_SPP | \\\n MSTATUS_FS | MSTATUS_XS | \\\n MSTATUS_SUM | MSTATUS_MXR)\n#if MAX_XLEN >= 64\n#define SSTATUS_MASK (SSTATUS_MASK0 | MSTATUS_UXL_MASK)\n#else\n#define SSTATUS_MASK SSTATUS_MASK0\n#endif\n\n\n#define MSTATUS_MASK (MSTATUS_UIE | MSTATUS_SIE | MSTATUS_MIE | \\\n MSTATUS_UPIE | MSTATUS_SPIE | MSTATUS_MPIE | \\\n MSTATUS_SPP | MSTATUS_MPP | \\\n MSTATUS_FS | \\\n MSTATUS_MPRV | MSTATUS_SUM | MSTATUS_MXR)\n\n/* cycle and insn counters */\n#define COUNTEREN_MASK ((1 << 0) | (1 << 2))\n\n/* return the complete mstatus with the SD bit */\nstatic target_ulong get_mstatus(RISCVCPUState *s, target_ulong mask)\n{\n target_ulong val;\n BOOL sd;\n val = s->mstatus | (s->fs << MSTATUS_FS_SHIFT);\n val &= mask;\n sd = ((val & MSTATUS_FS) == MSTATUS_FS) |\n ((val & MSTATUS_XS) == MSTATUS_XS);\n if (sd)\n val |= (target_ulong)1 << (s->cur_xlen - 1);\n return val;\n}\n \nstatic int get_base_from_xlen(int xlen)\n{\n if (xlen == 32)\n return 1;\n else if (xlen == 64)\n return 2;\n else\n return 3;\n}\n\nstatic void set_mstatus(RISCVCPUState *s, target_ulong val)\n{\n target_ulong mod, mask;\n \n /* flush the TLBs if change of MMU config */\n mod = s->mstatus ^ val;\n if ((mod & (MSTATUS_MPRV | MSTATUS_SUM | MSTATUS_MXR)) != 0 ||\n ((s->mstatus & MSTATUS_MPRV) && (mod & MSTATUS_MPP) != 0)) {\n tlb_flush_all(s);\n }\n s->fs = (val >> MSTATUS_FS_SHIFT) & 3;\n\n mask = MSTATUS_MASK & ~MSTATUS_FS;\n#if MAX_XLEN >= 64\n {\n int uxl, sxl;\n uxl = (val >> MSTATUS_UXL_SHIFT) & 3;\n if (uxl >= 1 && uxl <= get_base_from_xlen(MAX_XLEN))\n mask |= MSTATUS_UXL_MASK;\n sxl = (val >> MSTATUS_UXL_SHIFT) & 3;\n if (sxl >= 1 && sxl <= get_base_from_xlen(MAX_XLEN))\n mask |= MSTATUS_SXL_MASK;\n }\n#endif\n s->mstatus = (s->mstatus & ~mask) | (val & mask);\n}\n\n/* return -1 if invalid CSR. 0 if OK. 'will_write' indicate that the\n csr will be written after (used for CSR access check) */\nstatic int csr_read(RISCVCPUState *s, target_ulong *pval, uint32_t csr,\n BOOL will_write)\n{\n target_ulong val;\n\n if (((csr & 0xc00) == 0xc00) && will_write)\n return -1; /* read-only CSR */\n if (s->priv < ((csr >> 8) & 3))\n return -1; /* not enough priviledge */\n \n switch(csr) {\n#if FLEN > 0\n case 0x001: /* fflags */\n if (s->fs == 0)\n return -1;\n val = s->fflags;\n break;\n case 0x002: /* frm */\n if (s->fs == 0)\n return -1;\n val = s->frm;\n break;\n case 0x003:\n if (s->fs == 0)\n return -1;\n val = s->fflags | (s->frm << 5);\n break;\n#endif\n case 0xc00: /* ucycle */\n case 0xc02: /* uinstret */\n {\n uint32_t counteren;\n if (s->priv < PRV_M) {\n if (s->priv < PRV_S)\n counteren = s->scounteren;\n else\n counteren = s->mcounteren;\n if (((counteren >> (csr & 0x1f)) & 1) == 0)\n goto invalid_csr;\n }\n }\n val = (int64_t)s->insn_counter;\n break;\n case 0xc80: /* mcycleh */\n case 0xc82: /* minstreth */\n if (s->cur_xlen != 32)\n goto invalid_csr;\n {\n uint32_t counteren;\n if (s->priv < PRV_M) {\n if (s->priv < PRV_S)\n counteren = s->scounteren;\n else\n counteren = s->mcounteren;\n if (((counteren >> (csr & 0x1f)) & 1) == 0)\n goto invalid_csr;\n }\n }\n val = s->insn_counter >> 32;\n break;\n \n case 0x100:\n val = get_mstatus(s, SSTATUS_MASK);\n break;\n case 0x104: /* sie */\n val = s->mie & s->mideleg;\n break;\n case 0x105:\n val = s->stvec;\n break;\n case 0x106:\n val = s->scounteren;\n break;\n case 0x140:\n val = s->sscratch;\n break;\n case 0x141:\n val = s->sepc;\n break;\n case 0x142:\n val = s->scause;\n break;\n case 0x143:\n val = s->stval;\n break;\n case 0x144: /* sip */\n val = s->mip & s->mideleg;\n break;\n case 0x180:\n val = s->satp;\n break;\n case 0x300:\n val = get_mstatus(s, (target_ulong)-1);\n break;\n case 0x301:\n val = s->misa;\n val |= (target_ulong)s->mxl << (s->cur_xlen - 2);\n break;\n case 0x302:\n val = s->medeleg;\n break;\n case 0x303:\n val = s->mideleg;\n break;\n case 0x304:\n val = s->mie;\n break;\n case 0x305:\n val = s->mtvec;\n break;\n case 0x306:\n val = s->mcounteren;\n break;\n case 0x340:\n val = s->mscratch;\n break;\n case 0x341:\n val = s->mepc;\n break;\n case 0x342:\n val = s->mcause;\n break;\n case 0x343:\n val = s->mtval;\n break;\n case 0x344:\n val = s->mip;\n break;\n case 0xb00: /* mcycle */\n case 0xb02: /* minstret */\n val = (int64_t)s->insn_counter;\n break;\n case 0xb80: /* mcycleh */\n case 0xb82: /* minstreth */\n if (s->cur_xlen != 32)\n goto invalid_csr;\n val = s->insn_counter >> 32;\n break;\n case 0xf14:\n val = s->mhartid;\n break;\n default:\n invalid_csr:\n#ifdef DUMP_INVALID_CSR\n /* the 'time' counter is usually emulated */\n if (csr != 0xc01 && csr != 0xc81) {\n printf(\"csr_read: invalid CSR=0x%x\\n\", csr);\n }\n#endif\n *pval = 0;\n return -1;\n }\n *pval = val;\n return 0;\n}\n\n#if FLEN > 0\nstatic void set_frm(RISCVCPUState *s, unsigned int val)\n{\n if (val >= 5)\n val = 0;\n s->frm = val;\n}\n\n/* return -1 if invalid roundind mode */\nstatic int get_insn_rm(RISCVCPUState *s, unsigned int rm)\n{\n if (rm == 7)\n return s->frm;\n if (rm >= 5)\n return -1;\n else\n return rm;\n}\n#endif\n\n/* return -1 if invalid CSR, 0 if OK, 1 if the interpreter loop must be\n exited (e.g. XLEN was modified), 2 if TLBs have been flushed. */\nstatic int csr_write(RISCVCPUState *s, uint32_t csr, target_ulong val)\n{\n target_ulong mask;\n\n#if defined(DUMP_CSR)\n printf(\"csr_write: csr=0x%03x val=0x\", csr);\n print_target_ulong(val);\n printf(\"\\n\");\n#endif\n switch(csr) {\n#if FLEN > 0\n case 0x001: /* fflags */\n s->fflags = val & 0x1f;\n s->fs = 3;\n break;\n case 0x002: /* frm */\n set_frm(s, val & 7);\n s->fs = 3;\n break;\n case 0x003: /* fcsr */\n set_frm(s, (val >> 5) & 7);\n s->fflags = val & 0x1f;\n s->fs = 3;\n break;\n#endif\n case 0x100: /* sstatus */\n set_mstatus(s, (s->mstatus & ~SSTATUS_MASK) | (val & SSTATUS_MASK));\n break;\n case 0x104: /* sie */\n mask = s->mideleg;\n s->mie = (s->mie & ~mask) | (val & mask);\n break;\n case 0x105:\n s->stvec = val & ~3;\n break;\n case 0x106:\n s->scounteren = val & COUNTEREN_MASK;\n break;\n case 0x140:\n s->sscratch = val;\n break;\n case 0x141:\n s->sepc = val & ~1;\n break;\n case 0x142:\n s->scause = val;\n break;\n case 0x143:\n s->stval = val;\n break;\n case 0x144: /* sip */\n mask = s->mideleg;\n s->mip = (s->mip & ~mask) | (val & mask);\n break;\n case 0x180:\n /* no ASID implemented */\n#if MAX_XLEN == 32\n {\n int new_mode;\n new_mode = (val >> 31) & 1;\n s->satp = (val & (((target_ulong)1 << 22) - 1)) |\n (new_mode << 31);\n }\n#else\n {\n int mode, new_mode;\n mode = s->satp >> 60;\n new_mode = (val >> 60) & 0xf;\n if (new_mode == 0 || (new_mode >= 8 && new_mode <= 9))\n mode = new_mode;\n s->satp = (val & (((uint64_t)1 << 44) - 1)) |\n ((uint64_t)mode << 60);\n }\n#endif\n tlb_flush_all(s);\n return 2;\n \n case 0x300:\n set_mstatus(s, val);\n break;\n case 0x301: /* misa */\n#if MAX_XLEN >= 64\n {\n int new_mxl;\n new_mxl = (val >> (s->cur_xlen - 2)) & 3;\n if (new_mxl >= 1 && new_mxl <= get_base_from_xlen(MAX_XLEN)) {\n /* Note: misa is only modified in M level, so cur_xlen\n = 2^(mxl + 4) */\n if (s->mxl != new_mxl) {\n s->mxl = new_mxl;\n s->cur_xlen = 1 << (new_mxl + 4);\n return 1;\n }\n }\n }\n#endif\n break;\n case 0x302:\n mask = (1 << (CAUSE_STORE_PAGE_FAULT + 1)) - 1;\n s->medeleg = (s->medeleg & ~mask) | (val & mask);\n break;\n case 0x303:\n mask = MIP_SSIP | MIP_STIP | MIP_SEIP;\n s->mideleg = (s->mideleg & ~mask) | (val & mask);\n break;\n case 0x304:\n mask = MIP_MSIP | MIP_MTIP | MIP_SSIP | MIP_STIP | MIP_SEIP;\n s->mie = (s->mie & ~mask) | (val & mask);\n break;\n case 0x305:\n s->mtvec = val & ~3;\n break;\n case 0x306:\n s->mcounteren = val & COUNTEREN_MASK;\n break;\n case 0x340:\n s->mscratch = val;\n break;\n case 0x341:\n s->mepc = val & ~1;\n break;\n case 0x342:\n s->mcause = val;\n break;\n case 0x343:\n s->mtval = val;\n break;\n case 0x344:\n mask = MIP_SSIP | MIP_STIP;\n s->mip = (s->mip & ~mask) | (val & mask);\n break;\n default:\n#ifdef DUMP_INVALID_CSR\n printf(\"csr_write: invalid CSR=0x%x\\n\", csr);\n#endif\n return -1;\n }\n return 0;\n}\n\nstatic void set_priv(RISCVCPUState *s, int priv)\n{\n if (s->priv != priv) {\n tlb_flush_all(s);\n#if MAX_XLEN >= 64\n /* change the current xlen */\n {\n int mxl;\n if (priv == PRV_S)\n mxl = (s->mstatus >> MSTATUS_SXL_SHIFT) & 3;\n else if (priv == PRV_U)\n mxl = (s->mstatus >> MSTATUS_UXL_SHIFT) & 3;\n else\n mxl = s->mxl;\n s->cur_xlen = 1 << (4 + mxl);\n }\n#endif\n s->priv = priv;\n }\n}\n\nstatic void raise_exception2(RISCVCPUState *s, uint32_t cause,\n target_ulong tval)\n{\n BOOL deleg;\n target_ulong causel;\n \n#if defined(DUMP_EXCEPTIONS) || defined(DUMP_MMU_EXCEPTIONS) || defined(DUMP_INTERRUPTS)\n {\n int flag;\n flag = 0;\n#ifdef DUMP_MMU_EXCEPTIONS\n if (cause == CAUSE_FAULT_FETCH ||\n cause == CAUSE_FAULT_LOAD ||\n cause == CAUSE_FAULT_STORE ||\n cause == CAUSE_FETCH_PAGE_FAULT ||\n cause == CAUSE_LOAD_PAGE_FAULT ||\n cause == CAUSE_STORE_PAGE_FAULT)\n flag = 1;\n#endif\n#ifdef DUMP_INTERRUPTS\n flag |= (cause & CAUSE_INTERRUPT) != 0;\n#endif\n#ifdef DUMP_EXCEPTIONS\n flag = 1;\n flag = (cause & CAUSE_INTERRUPT) == 0;\n if (cause == CAUSE_SUPERVISOR_ECALL || cause == CAUSE_ILLEGAL_INSTRUCTION)\n flag = 0;\n#endif\n if (flag) {\n log_printf(\"raise_exception: cause=0x%08x tval=0x\", cause);\n#ifdef CONFIG_LOGFILE\n fprint_target_ulong(log_file, tval);\n#else\n print_target_ulong(tval);\n#endif\n log_printf(\"\\n\");\n dump_regs(s);\n }\n }\n#endif\n\n if (s->priv <= PRV_S) {\n /* delegate the exception to the supervisor priviledge */\n if (cause & CAUSE_INTERRUPT)\n deleg = (s->mideleg >> (cause & (MAX_XLEN - 1))) & 1;\n else\n deleg = (s->medeleg >> cause) & 1;\n } else {\n deleg = 0;\n }\n \n causel = cause & 0x7fffffff;\n if (cause & CAUSE_INTERRUPT)\n causel |= (target_ulong)1 << (s->cur_xlen - 1);\n \n if (deleg) {\n s->scause = causel;\n s->sepc = s->pc;\n s->stval = tval;\n s->mstatus = (s->mstatus & ~MSTATUS_SPIE) |\n (((s->mstatus >> s->priv) & 1) << MSTATUS_SPIE_SHIFT);\n s->mstatus = (s->mstatus & ~MSTATUS_SPP) |\n (s->priv << MSTATUS_SPP_SHIFT);\n s->mstatus &= ~MSTATUS_SIE;\n set_priv(s, PRV_S);\n s->pc = s->stvec;\n } else {\n s->mcause = causel;\n s->mepc = s->pc;\n s->mtval = tval;\n s->mstatus = (s->mstatus & ~MSTATUS_MPIE) |\n (((s->mstatus >> s->priv) & 1) << MSTATUS_MPIE_SHIFT);\n s->mstatus = (s->mstatus & ~MSTATUS_MPP) |\n (s->priv << MSTATUS_MPP_SHIFT);\n s->mstatus &= ~MSTATUS_MIE;\n set_priv(s, PRV_M);\n s->pc = s->mtvec;\n }\n}\n\nstatic void raise_exception(RISCVCPUState *s, uint32_t cause)\n{\n raise_exception2(s, cause, 0);\n}\n\nstatic void handle_sret(RISCVCPUState *s)\n{\n int spp, spie;\n spp = (s->mstatus >> MSTATUS_SPP_SHIFT) & 1;\n /* set the IE state to previous IE state */\n spie = (s->mstatus >> MSTATUS_SPIE_SHIFT) & 1;\n s->mstatus = (s->mstatus & ~(1 << spp)) |\n (spie << spp);\n /* set SPIE to 1 */\n s->mstatus |= MSTATUS_SPIE;\n /* set SPP to U */\n s->mstatus &= ~MSTATUS_SPP;\n set_priv(s, spp);\n s->pc = s->sepc;\n}\n\nstatic void handle_mret(RISCVCPUState *s)\n{\n int mpp, mpie;\n mpp = (s->mstatus >> MSTATUS_MPP_SHIFT) & 3;\n /* set the IE state to previous IE state */\n mpie = (s->mstatus >> MSTATUS_MPIE_SHIFT) & 1;\n s->mstatus = (s->mstatus & ~(1 << mpp)) |\n (mpie << mpp);\n /* set MPIE to 1 */\n s->mstatus |= MSTATUS_MPIE;\n /* set MPP to U */\n s->mstatus &= ~MSTATUS_MPP;\n set_priv(s, mpp);\n s->pc = s->mepc;\n}\n\nstatic inline uint32_t get_pending_irq_mask(RISCVCPUState *s)\n{\n uint32_t pending_ints, enabled_ints;\n\n pending_ints = s->mip & s->mie;\n if (pending_ints == 0)\n return 0;\n\n enabled_ints = 0;\n switch(s->priv) {\n case PRV_M:\n if (s->mstatus & MSTATUS_MIE)\n enabled_ints = ~s->mideleg;\n break;\n case PRV_S:\n enabled_ints = ~s->mideleg;\n if (s->mstatus & MSTATUS_SIE)\n enabled_ints |= s->mideleg;\n break;\n default:\n case PRV_U:\n enabled_ints = -1;\n break;\n }\n return pending_ints & enabled_ints;\n}\n\nstatic __exception int raise_interrupt(RISCVCPUState *s)\n{\n uint32_t mask;\n int irq_num;\n\n mask = get_pending_irq_mask(s);\n if (mask == 0)\n return 0;\n irq_num = ctz32(mask);\n raise_exception(s, irq_num | CAUSE_INTERRUPT);\n return -1;\n}\n\nstatic inline int32_t sext(int32_t val, int n)\n{\n return (val << (32 - n)) >> (32 - n);\n}\n\nstatic inline uint32_t get_field1(uint32_t val, int src_pos, \n int dst_pos, int dst_pos_max)\n{\n int mask;\n assert(dst_pos_max >= dst_pos);\n mask = ((1 << (dst_pos_max - dst_pos + 1)) - 1) << dst_pos;\n if (dst_pos >= src_pos)\n return (val << (dst_pos - src_pos)) & mask;\n else\n return (val >> (src_pos - dst_pos)) & mask;\n}\n\n#define XLEN 32\n#include \"riscv_cpu_template.h\"\n\n#if MAX_XLEN >= 64\n#define XLEN 64\n#include \"riscv_cpu_template.h\"\n#endif\n\n#if MAX_XLEN >= 128\n#define XLEN 128\n#include \"riscv_cpu_template.h\"\n#endif\n\nstatic void glue(riscv_cpu_interp, MAX_XLEN)(RISCVCPUState *s, int n_cycles)\n{\n#ifdef USE_GLOBAL_STATE\n s = &riscv_cpu_global_state;\n#endif\n uint64_t timeout;\n\n timeout = s->insn_counter + n_cycles;\n while (!s->power_down_flag &&\n (int)(timeout - s->insn_counter) > 0) {\n n_cycles = timeout - s->insn_counter;\n switch(s->cur_xlen) {\n case 32:\n riscv_cpu_interp_x32(s, n_cycles);\n break;\n#if MAX_XLEN >= 64\n case 64:\n riscv_cpu_interp_x64(s, n_cycles);\n break;\n#endif\n#if MAX_XLEN >= 128\n case 128:\n riscv_cpu_interp_x128(s, n_cycles);\n break;\n#endif\n default:\n abort();\n }\n }\n}\n\n/* Note: the value is not accurate when called in riscv_cpu_interp() */\nstatic uint64_t glue(riscv_cpu_get_cycles, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->insn_counter;\n}\n\nstatic void glue(riscv_cpu_set_mip, MAX_XLEN)(RISCVCPUState *s, uint32_t mask)\n{\n s->mip |= mask;\n /* exit from power down if an interrupt is pending */\n if (s->power_down_flag && (s->mip & s->mie) != 0)\n s->power_down_flag = FALSE;\n}\n\nstatic void glue(riscv_cpu_reset_mip, MAX_XLEN)(RISCVCPUState *s, uint32_t mask)\n{\n s->mip &= ~mask;\n}\n\nstatic uint32_t glue(riscv_cpu_get_mip, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->mip;\n}\n\nstatic BOOL glue(riscv_cpu_get_power_down, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->power_down_flag;\n}\n\nstatic RISCVCPUState *glue(riscv_cpu_init, MAX_XLEN)(PhysMemoryMap *mem_map)\n{\n RISCVCPUState *s;\n \n#ifdef USE_GLOBAL_STATE\n s = &riscv_cpu_global_state;\n#else\n s = mallocz(sizeof(*s));\n#endif\n s->common.class_ptr = &glue(riscv_cpu_class, MAX_XLEN);\n s->mem_map = mem_map;\n s->pc = 0x1000;\n s->priv = PRV_M;\n s->cur_xlen = MAX_XLEN;\n s->mxl = get_base_from_xlen(MAX_XLEN);\n s->mstatus = ((uint64_t)s->mxl << MSTATUS_UXL_SHIFT) |\n ((uint64_t)s->mxl << MSTATUS_SXL_SHIFT);\n s->misa |= MCPUID_SUPER | MCPUID_USER | MCPUID_I | MCPUID_M | MCPUID_A;\n#if FLEN >= 32\n s->misa |= MCPUID_F;\n#endif\n#if FLEN >= 64\n s->misa |= MCPUID_D;\n#endif\n#if FLEN >= 128\n s->misa |= MCPUID_Q;\n#endif\n#ifdef CONFIG_EXT_C\n s->misa |= MCPUID_C;\n#endif\n tlb_init(s);\n return s;\n}\n\nstatic void glue(riscv_cpu_end, MAX_XLEN)(RISCVCPUState *s)\n{\n#ifdef USE_GLOBAL_STATE\n free(s);\n#endif\n}\n\nstatic uint32_t glue(riscv_cpu_get_misa, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->misa;\n}\n\nconst RISCVCPUClass glue(riscv_cpu_class, MAX_XLEN) = {\n glue(riscv_cpu_init, MAX_XLEN),\n glue(riscv_cpu_end, MAX_XLEN),\n glue(riscv_cpu_interp, MAX_XLEN),\n glue(riscv_cpu_get_cycles, MAX_XLEN),\n glue(riscv_cpu_set_mip, MAX_XLEN),\n glue(riscv_cpu_reset_mip, MAX_XLEN),\n glue(riscv_cpu_get_mip, MAX_XLEN),\n glue(riscv_cpu_get_power_down, MAX_XLEN),\n glue(riscv_cpu_get_misa, MAX_XLEN),\n glue(riscv_cpu_flush_tlb_write_range_ram, MAX_XLEN),\n};\n\n#if CONFIG_RISCV_MAX_XLEN == MAX_XLEN\nRISCVCPUState *riscv_cpu_init(PhysMemoryMap *mem_map, int max_xlen)\n{\n const RISCVCPUClass *c;\n switch(max_xlen) {\n /* with emscripten we compile a single CPU */\n#if defined(EMSCRIPTEN)\n case MAX_XLEN:\n c = &glue(riscv_cpu_class, MAX_XLEN);\n break;\n#else\n case 32:\n c = &riscv_cpu_class32;\n break;\n case 64:\n c = &riscv_cpu_class64;\n break;\n#if CONFIG_RISCV_MAX_XLEN == 128\n case 128:\n c = &riscv_cpu_class128;\n break;\n#endif\n#endif /* !EMSCRIPTEN */\n default:\n return NULL;\n }\n return c->riscv_cpu_init(mem_map);\n}\n#endif /* CONFIG_RISCV_MAX_XLEN == MAX_XLEN */\n\n"], ["/linuxpdf/tinyemu/ide.c", "/*\n * IDE emulation\n * \n * Copyright (c) 2003-2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"ide.h\"\n\n//#define DEBUG_IDE\n\n/* Bits of HD_STATUS */\n#define ERR_STAT\t\t0x01\n#define INDEX_STAT\t\t0x02\n#define ECC_STAT\t\t0x04\t/* Corrected error */\n#define DRQ_STAT\t\t0x08\n#define SEEK_STAT\t\t0x10\n#define SRV_STAT\t\t0x10\n#define WRERR_STAT\t\t0x20\n#define READY_STAT\t\t0x40\n#define BUSY_STAT\t\t0x80\n\n/* Bits for HD_ERROR */\n#define MARK_ERR\t\t0x01\t/* Bad address mark */\n#define TRK0_ERR\t\t0x02\t/* couldn't find track 0 */\n#define ABRT_ERR\t\t0x04\t/* Command aborted */\n#define MCR_ERR\t\t\t0x08\t/* media change request */\n#define ID_ERR\t\t\t0x10\t/* ID field not found */\n#define MC_ERR\t\t\t0x20\t/* media changed */\n#define ECC_ERR\t\t\t0x40\t/* Uncorrectable ECC error */\n#define BBD_ERR\t\t\t0x80\t/* pre-EIDE meaning: block marked bad */\n#define ICRC_ERR\t\t0x80\t/* new meaning: CRC error during transfer */\n\n/* Bits of HD_NSECTOR */\n#define CD\t\t\t0x01\n#define IO\t\t\t0x02\n#define REL\t\t\t0x04\n#define TAG_MASK\t\t0xf8\n\n#define IDE_CMD_RESET 0x04\n#define IDE_CMD_DISABLE_IRQ 0x02\n\n/* ATA/ATAPI Commands pre T13 Spec */\n#define WIN_NOP\t\t\t\t0x00\n/*\n *\t0x01->0x02 Reserved\n */\n#define CFA_REQ_EXT_ERROR_CODE\t\t0x03 /* CFA Request Extended Error Code */\n/*\n *\t0x04->0x07 Reserved\n */\n#define WIN_SRST\t\t\t0x08 /* ATAPI soft reset command */\n#define WIN_DEVICE_RESET\t\t0x08\n/*\n *\t0x09->0x0F Reserved\n */\n#define WIN_RECAL\t\t\t0x10\n#define WIN_RESTORE\t\t\tWIN_RECAL\n/*\n *\t0x10->0x1F Reserved\n */\n#define WIN_READ\t\t\t0x20 /* 28-Bit */\n#define WIN_READ_ONCE\t\t\t0x21 /* 28-Bit without retries */\n#define WIN_READ_LONG\t\t\t0x22 /* 28-Bit */\n#define WIN_READ_LONG_ONCE\t\t0x23 /* 28-Bit without retries */\n#define WIN_READ_EXT\t\t\t0x24 /* 48-Bit */\n#define WIN_READDMA_EXT\t\t\t0x25 /* 48-Bit */\n#define WIN_READDMA_QUEUED_EXT\t\t0x26 /* 48-Bit */\n#define WIN_READ_NATIVE_MAX_EXT\t\t0x27 /* 48-Bit */\n/*\n *\t0x28\n */\n#define WIN_MULTREAD_EXT\t\t0x29 /* 48-Bit */\n/*\n *\t0x2A->0x2F Reserved\n */\n#define WIN_WRITE\t\t\t0x30 /* 28-Bit */\n#define WIN_WRITE_ONCE\t\t\t0x31 /* 28-Bit without retries */\n#define WIN_WRITE_LONG\t\t\t0x32 /* 28-Bit */\n#define WIN_WRITE_LONG_ONCE\t\t0x33 /* 28-Bit without retries */\n#define WIN_WRITE_EXT\t\t\t0x34 /* 48-Bit */\n#define WIN_WRITEDMA_EXT\t\t0x35 /* 48-Bit */\n#define WIN_WRITEDMA_QUEUED_EXT\t\t0x36 /* 48-Bit */\n#define WIN_SET_MAX_EXT\t\t\t0x37 /* 48-Bit */\n#define CFA_WRITE_SECT_WO_ERASE\t\t0x38 /* CFA Write Sectors without erase */\n#define WIN_MULTWRITE_EXT\t\t0x39 /* 48-Bit */\n/*\n *\t0x3A->0x3B Reserved\n */\n#define WIN_WRITE_VERIFY\t\t0x3C /* 28-Bit */\n/*\n *\t0x3D->0x3F Reserved\n */\n#define WIN_VERIFY\t\t\t0x40 /* 28-Bit - Read Verify Sectors */\n#define WIN_VERIFY_ONCE\t\t\t0x41 /* 28-Bit - without retries */\n#define WIN_VERIFY_EXT\t\t\t0x42 /* 48-Bit */\n/*\n *\t0x43->0x4F Reserved\n */\n#define WIN_FORMAT\t\t\t0x50\n/*\n *\t0x51->0x5F Reserved\n */\n#define WIN_INIT\t\t\t0x60\n/*\n *\t0x61->0x5F Reserved\n */\n#define WIN_SEEK\t\t\t0x70 /* 0x70-0x7F Reserved */\n#define CFA_TRANSLATE_SECTOR\t\t0x87 /* CFA Translate Sector */\n#define WIN_DIAGNOSE\t\t\t0x90\n#define WIN_SPECIFY\t\t\t0x91 /* set drive geometry translation */\n#define WIN_DOWNLOAD_MICROCODE\t\t0x92\n#define WIN_STANDBYNOW2\t\t\t0x94\n#define WIN_STANDBY2\t\t\t0x96\n#define WIN_SETIDLE2\t\t\t0x97\n#define WIN_CHECKPOWERMODE2\t\t0x98\n#define WIN_SLEEPNOW2\t\t\t0x99\n/*\n *\t0x9A VENDOR\n */\n#define WIN_PACKETCMD\t\t\t0xA0 /* Send a packet command. */\n#define WIN_PIDENTIFY\t\t\t0xA1 /* identify ATAPI device\t*/\n#define WIN_QUEUED_SERVICE\t\t0xA2\n#define WIN_SMART\t\t\t0xB0 /* self-monitoring and reporting */\n#define CFA_ERASE_SECTORS \t0xC0\n#define WIN_MULTREAD\t\t\t0xC4 /* read sectors using multiple mode*/\n#define WIN_MULTWRITE\t\t\t0xC5 /* write sectors using multiple mode */\n#define WIN_SETMULT\t\t\t0xC6 /* enable/disable multiple mode */\n#define WIN_READDMA_QUEUED\t\t0xC7 /* read sectors using Queued DMA transfers */\n#define WIN_READDMA\t\t\t0xC8 /* read sectors using DMA transfers */\n#define WIN_READDMA_ONCE\t\t0xC9 /* 28-Bit - without retries */\n#define WIN_WRITEDMA\t\t\t0xCA /* write sectors using DMA transfers */\n#define WIN_WRITEDMA_ONCE\t\t0xCB /* 28-Bit - without retries */\n#define WIN_WRITEDMA_QUEUED\t\t0xCC /* write sectors using Queued DMA transfers */\n#define CFA_WRITE_MULTI_WO_ERASE\t0xCD /* CFA Write multiple without erase */\n#define WIN_GETMEDIASTATUS\t\t0xDA\t\n#define WIN_ACKMEDIACHANGE\t\t0xDB /* ATA-1, ATA-2 vendor */\n#define WIN_POSTBOOT\t\t\t0xDC\n#define WIN_PREBOOT\t\t\t0xDD\n#define WIN_DOORLOCK\t\t\t0xDE /* lock door on removable drives */\n#define WIN_DOORUNLOCK\t\t\t0xDF /* unlock door on removable drives */\n#define WIN_STANDBYNOW1\t\t\t0xE0\n#define WIN_IDLEIMMEDIATE\t\t0xE1 /* force drive to become \"ready\" */\n#define WIN_STANDBY \t0xE2 /* Set device in Standby Mode */\n#define WIN_SETIDLE1\t\t\t0xE3\n#define WIN_READ_BUFFER\t\t\t0xE4 /* force read only 1 sector */\n#define WIN_CHECKPOWERMODE1\t\t0xE5\n#define WIN_SLEEPNOW1\t\t\t0xE6\n#define WIN_FLUSH_CACHE\t\t\t0xE7\n#define WIN_WRITE_BUFFER\t\t0xE8 /* force write only 1 sector */\n#define WIN_WRITE_SAME\t\t\t0xE9 /* read ata-2 to use */\n\t/* SET_FEATURES 0x22 or 0xDD */\n#define WIN_FLUSH_CACHE_EXT\t\t0xEA /* 48-Bit */\n#define WIN_IDENTIFY\t\t\t0xEC /* ask drive to identify itself\t*/\n#define WIN_MEDIAEJECT\t\t\t0xED\n#define WIN_IDENTIFY_DMA\t\t0xEE /* same as WIN_IDENTIFY, but DMA */\n#define WIN_SETFEATURES\t\t\t0xEF /* set special drive features */\n#define EXABYTE_ENABLE_NEST\t\t0xF0\n#define WIN_SECURITY_SET_PASS\t\t0xF1\n#define WIN_SECURITY_UNLOCK\t\t0xF2\n#define WIN_SECURITY_ERASE_PREPARE\t0xF3\n#define WIN_SECURITY_ERASE_UNIT\t\t0xF4\n#define WIN_SECURITY_FREEZE_LOCK\t0xF5\n#define WIN_SECURITY_DISABLE\t\t0xF6\n#define WIN_READ_NATIVE_MAX\t\t0xF8 /* return the native maximum address */\n#define WIN_SET_MAX\t\t\t0xF9\n#define DISABLE_SEAGATE\t\t\t0xFB\n\n#define MAX_MULT_SECTORS 128\n\ntypedef struct IDEState IDEState;\n\ntypedef void EndTransferFunc(IDEState *);\n\nstruct IDEState {\n IDEIFState *ide_if;\n BlockDevice *bs;\n int cylinders, heads, sectors;\n int mult_sectors;\n int64_t nb_sectors;\n\n /* ide regs */\n uint8_t feature;\n uint8_t error;\n uint16_t nsector; /* 0 is 256 to ease computations */\n uint8_t sector;\n uint8_t lcyl;\n uint8_t hcyl;\n uint8_t select;\n uint8_t status;\n\n int io_nb_sectors;\n int req_nb_sectors;\n EndTransferFunc *end_transfer_func;\n \n int data_index;\n int data_end;\n uint8_t io_buffer[MAX_MULT_SECTORS*512 + 4];\n};\n\nstruct IDEIFState {\n IRQSignal *irq;\n IDEState *cur_drive;\n IDEState *drives[2];\n /* 0x3f6 command */\n uint8_t cmd;\n};\n\nstatic void ide_sector_read_cb(void *opaque, int ret);\nstatic void ide_sector_read_cb_end(IDEState *s);\nstatic void ide_sector_write_cb2(void *opaque, int ret);\n\nstatic void padstr(char *str, const char *src, int len)\n{\n int i, v;\n for(i = 0; i < len; i++) {\n if (*src)\n v = *src++;\n else\n v = ' ';\n *(char *)((long)str ^ 1) = v;\n str++;\n }\n}\n\n/* little endian assume */\nstatic void stw(uint16_t *buf, int v)\n{\n *buf = v;\n}\n\nstatic void ide_identify(IDEState *s)\n{\n uint16_t *tab;\n uint32_t oldsize;\n \n tab = (uint16_t *)s->io_buffer;\n\n memset(tab, 0, 512 * 2);\n\n stw(tab + 0, 0x0040);\n stw(tab + 1, s->cylinders); \n stw(tab + 3, s->heads);\n stw(tab + 4, 512 * s->sectors); /* sectors */\n stw(tab + 5, 512); /* sector size */\n stw(tab + 6, s->sectors); \n stw(tab + 20, 3); /* buffer type */\n stw(tab + 21, 512); /* cache size in sectors */\n stw(tab + 22, 4); /* ecc bytes */\n padstr((char *)(tab + 27), \"RISCVEMU HARDDISK\", 40);\n stw(tab + 47, 0x8000 | MAX_MULT_SECTORS);\n stw(tab + 48, 0); /* dword I/O */\n stw(tab + 49, 1 << 9); /* LBA supported, no DMA */\n stw(tab + 51, 0x200); /* PIO transfer cycle */\n stw(tab + 52, 0x200); /* DMA transfer cycle */\n stw(tab + 54, s->cylinders);\n stw(tab + 55, s->heads);\n stw(tab + 56, s->sectors);\n oldsize = s->cylinders * s->heads * s->sectors;\n stw(tab + 57, oldsize);\n stw(tab + 58, oldsize >> 16);\n if (s->mult_sectors)\n stw(tab + 59, 0x100 | s->mult_sectors);\n stw(tab + 60, s->nb_sectors);\n stw(tab + 61, s->nb_sectors >> 16);\n stw(tab + 80, (1 << 1) | (1 << 2));\n stw(tab + 82, (1 << 14));\n stw(tab + 83, (1 << 14));\n stw(tab + 84, (1 << 14));\n stw(tab + 85, (1 << 14));\n stw(tab + 86, 0);\n stw(tab + 87, (1 << 14));\n}\n\nstatic void ide_set_signature(IDEState *s) \n{\n s->select &= 0xf0;\n s->nsector = 1;\n s->sector = 1;\n s->lcyl = 0;\n s->hcyl = 0;\n}\n\nstatic void ide_abort_command(IDEState *s) \n{\n s->status = READY_STAT | ERR_STAT;\n s->error = ABRT_ERR;\n}\n\nstatic void ide_set_irq(IDEState *s) \n{\n IDEIFState *ide_if = s->ide_if;\n if (!(ide_if->cmd & IDE_CMD_DISABLE_IRQ)) {\n set_irq(ide_if->irq, 1);\n }\n}\n\n/* prepare data transfer and tell what to do after */\nstatic void ide_transfer_start(IDEState *s, int size,\n EndTransferFunc *end_transfer_func)\n{\n s->end_transfer_func = end_transfer_func;\n s->data_index = 0;\n s->data_end = size;\n}\n\nstatic void ide_transfer_stop(IDEState *s)\n{\n s->end_transfer_func = ide_transfer_stop;\n s->data_index = 0;\n s->data_end = 0;\n}\n\nstatic int64_t ide_get_sector(IDEState *s)\n{\n int64_t sector_num;\n if (s->select & 0x40) {\n /* lba */\n sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) |\n (s->lcyl << 8) | s->sector;\n } else {\n sector_num = ((s->hcyl << 8) | s->lcyl) * \n s->heads * s->sectors +\n (s->select & 0x0f) * s->sectors + (s->sector - 1);\n }\n return sector_num;\n}\n\nstatic void ide_set_sector(IDEState *s, int64_t sector_num)\n{\n unsigned int cyl, r;\n if (s->select & 0x40) {\n s->select = (s->select & 0xf0) | ((sector_num >> 24) & 0x0f);\n s->hcyl = (sector_num >> 16) & 0xff;\n s->lcyl = (sector_num >> 8) & 0xff;\n s->sector = sector_num & 0xff;\n } else {\n cyl = sector_num / (s->heads * s->sectors);\n r = sector_num % (s->heads * s->sectors);\n s->hcyl = (cyl >> 8) & 0xff;\n s->lcyl = cyl & 0xff;\n s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f);\n s->sector = (r % s->sectors) + 1;\n }\n}\n\nstatic void ide_sector_read(IDEState *s)\n{\n int64_t sector_num;\n int ret, n;\n\n sector_num = ide_get_sector(s);\n n = s->nsector;\n if (n == 0) \n n = 256;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n#if defined(DEBUG_IDE)\n printf(\"read sector=%\" PRId64 \" count=%d\\n\", sector_num, n);\n#endif\n s->io_nb_sectors = n;\n ret = s->bs->read_async(s->bs, sector_num, s->io_buffer, n, \n ide_sector_read_cb, s);\n if (ret < 0) {\n /* error */\n ide_abort_command(s);\n ide_set_irq(s);\n } else if (ret == 0) {\n /* synchronous case (needed for performance) */\n ide_sector_read_cb(s, 0);\n } else {\n /* async case */\n s->status = READY_STAT | SEEK_STAT | BUSY_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n }\n}\n\nstatic void ide_sector_read_cb(void *opaque, int ret)\n{\n IDEState *s = opaque;\n int n;\n EndTransferFunc *func;\n \n n = s->io_nb_sectors;\n ide_set_sector(s, ide_get_sector(s) + n);\n s->nsector = (s->nsector - n) & 0xff;\n if (s->nsector == 0)\n func = ide_sector_read_cb_end;\n else\n func = ide_sector_read;\n ide_transfer_start(s, 512 * n, func);\n ide_set_irq(s);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n}\n\nstatic void ide_sector_read_cb_end(IDEState *s)\n{\n /* no more sector to read from disk */\n s->status = READY_STAT | SEEK_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n ide_transfer_stop(s);\n}\n\nstatic void ide_sector_write_cb1(IDEState *s)\n{\n int64_t sector_num;\n int ret;\n\n ide_transfer_stop(s);\n sector_num = ide_get_sector(s);\n#if defined(DEBUG_IDE)\n printf(\"write sector=%\" PRId64 \" count=%d\\n\",\n sector_num, s->io_nb_sectors);\n#endif\n ret = s->bs->write_async(s->bs, sector_num, s->io_buffer, s->io_nb_sectors, \n ide_sector_write_cb2, s);\n if (ret < 0) {\n /* error */\n ide_abort_command(s);\n ide_set_irq(s);\n } else if (ret == 0) {\n /* synchronous case (needed for performance) */\n ide_sector_write_cb2(s, 0);\n } else {\n /* async case */\n s->status = READY_STAT | SEEK_STAT | BUSY_STAT;\n }\n}\n\nstatic void ide_sector_write_cb2(void *opaque, int ret)\n{\n IDEState *s = opaque;\n int n;\n\n n = s->io_nb_sectors;\n ide_set_sector(s, ide_get_sector(s) + n);\n s->nsector = (s->nsector - n) & 0xff;\n if (s->nsector == 0) {\n /* no more sectors to write */\n s->status = READY_STAT | SEEK_STAT;\n } else {\n n = s->nsector;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n s->io_nb_sectors = n;\n ide_transfer_start(s, 512 * n, ide_sector_write_cb1);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n }\n ide_set_irq(s);\n}\n\nstatic void ide_sector_write(IDEState *s)\n{\n int n;\n n = s->nsector;\n if (n == 0)\n n = 256;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n s->io_nb_sectors = n;\n ide_transfer_start(s, 512 * n, ide_sector_write_cb1);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n}\n\nstatic void ide_identify_cb(IDEState *s)\n{\n ide_transfer_stop(s);\n s->status = READY_STAT;\n}\n\nstatic void ide_exec_cmd(IDEState *s, int val)\n{\n#if defined(DEBUG_IDE)\n printf(\"ide: exec_cmd=0x%02x\\n\", val);\n#endif\n switch(val) {\n case WIN_IDENTIFY:\n ide_identify(s);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n ide_transfer_start(s, 512, ide_identify_cb);\n ide_set_irq(s);\n break;\n case WIN_SPECIFY:\n case WIN_RECAL:\n s->error = 0;\n s->status = READY_STAT | SEEK_STAT;\n ide_set_irq(s);\n break;\n case WIN_SETMULT:\n if (s->nsector > MAX_MULT_SECTORS || \n (s->nsector & (s->nsector - 1)) != 0) {\n ide_abort_command(s);\n } else {\n s->mult_sectors = s->nsector;\n#if defined(DEBUG_IDE)\n printf(\"ide: setmult=%d\\n\", s->mult_sectors);\n#endif\n s->status = READY_STAT;\n }\n ide_set_irq(s);\n break;\n case WIN_READ:\n case WIN_READ_ONCE:\n s->req_nb_sectors = 1;\n ide_sector_read(s);\n break;\n case WIN_WRITE:\n case WIN_WRITE_ONCE:\n s->req_nb_sectors = 1;\n ide_sector_write(s);\n break;\n case WIN_MULTREAD:\n if (!s->mult_sectors) {\n ide_abort_command(s);\n ide_set_irq(s);\n } else {\n s->req_nb_sectors = s->mult_sectors;\n ide_sector_read(s);\n }\n break;\n case WIN_MULTWRITE:\n if (!s->mult_sectors) {\n ide_abort_command(s);\n ide_set_irq(s);\n } else {\n s->req_nb_sectors = s->mult_sectors;\n ide_sector_write(s);\n }\n break;\n case WIN_READ_NATIVE_MAX:\n ide_set_sector(s, s->nb_sectors - 1);\n s->status = READY_STAT;\n ide_set_irq(s);\n break;\n default:\n ide_abort_command(s);\n ide_set_irq(s);\n break;\n }\n}\n\nstatic void ide_ioport_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int addr = offset + 1;\n \n#ifdef DEBUG_IDE\n printf(\"ide: write addr=0x%02x val=0x%02x\\n\", addr, val);\n#endif\n switch(addr) {\n case 0:\n break;\n case 1:\n if (s) {\n s->feature = val;\n }\n break;\n case 2:\n if (s) {\n s->nsector = val;\n }\n break;\n case 3:\n if (s) {\n s->sector = val;\n }\n break;\n case 4:\n if (s) {\n s->lcyl = val;\n }\n break;\n case 5:\n if (s) {\n s->hcyl = val;\n }\n break;\n case 6:\n /* select drive */\n s = s1->cur_drive = s1->drives[(val >> 4) & 1];\n if (s) {\n s->select = val;\n }\n break;\n default:\n case 7:\n /* command */\n if (s) {\n ide_exec_cmd(s, val);\n }\n break;\n }\n}\n\nstatic uint32_t ide_ioport_read(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int ret, addr = offset + 1;\n\n if (!s) {\n ret = 0x00;\n } else {\n switch(addr) {\n case 0:\n ret = 0xff;\n break;\n case 1:\n ret = s->error;\n break;\n case 2:\n ret = s->nsector;\n break;\n case 3:\n ret = s->sector;\n break;\n case 4:\n ret = s->lcyl;\n break;\n case 5:\n ret = s->hcyl;\n break;\n case 6:\n ret = s->select;\n break;\n default:\n case 7:\n ret = s->status;\n set_irq(s1->irq, 0);\n break;\n }\n }\n#ifdef DEBUG_IDE\n printf(\"ide: read addr=0x%02x val=0x%02x\\n\", addr, ret);\n#endif\n return ret;\n}\n\nstatic uint32_t ide_status_read(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int ret;\n\n if (s) {\n ret = s->status;\n } else {\n ret = 0;\n }\n#ifdef DEBUG_IDE\n printf(\"ide: read status=0x%02x\\n\", ret);\n#endif\n return ret;\n}\n\nstatic void ide_cmd_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s;\n int i;\n \n#ifdef DEBUG_IDE\n printf(\"ide: cmd write=0x%02x\\n\", val);\n#endif\n if (!(s1->cmd & IDE_CMD_RESET) && (val & IDE_CMD_RESET)) {\n /* low to high */\n for(i = 0; i < 2; i++) {\n s = s1->drives[i];\n if (s) {\n s->status = BUSY_STAT | SEEK_STAT;\n s->error = 0x01;\n }\n }\n } else if ((s1->cmd & IDE_CMD_RESET) && !(val & IDE_CMD_RESET)) {\n /* high to low */\n for(i = 0; i < 2; i++) {\n s = s1->drives[i];\n if (s) {\n s->status = READY_STAT | SEEK_STAT;\n ide_set_signature(s);\n }\n }\n }\n s1->cmd = val;\n}\n\nstatic void ide_data_writew(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int p;\n uint8_t *tab;\n \n if (!s)\n return;\n p = s->data_index;\n tab = s->io_buffer;\n tab[p] = val & 0xff;\n tab[p + 1] = (val >> 8) & 0xff;\n p += 2;\n s->data_index = p;\n if (p >= s->data_end)\n s->end_transfer_func(s);\n}\n\nstatic uint32_t ide_data_readw(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int p, ret;\n uint8_t *tab;\n \n if (!s) {\n ret = 0;\n } else {\n p = s->data_index;\n tab = s->io_buffer;\n ret = tab[p] | (tab[p + 1] << 8);\n p += 2;\n s->data_index = p;\n if (p >= s->data_end)\n s->end_transfer_func(s);\n }\n return ret;\n}\n\nstatic IDEState *ide_drive_init(IDEIFState *ide_if, BlockDevice *bs)\n{\n IDEState *s;\n uint32_t cylinders;\n uint64_t nb_sectors;\n\n s = malloc(sizeof(*s));\n memset(s, 0, sizeof(*s));\n\n s->ide_if = ide_if;\n s->bs = bs;\n\n nb_sectors = s->bs->get_sector_count(s->bs);\n cylinders = nb_sectors / (16 * 63);\n if (cylinders > 16383)\n cylinders = 16383;\n else if (cylinders < 2)\n cylinders = 2;\n s->cylinders = cylinders;\n s->heads = 16;\n s->sectors = 63;\n s->nb_sectors = nb_sectors;\n\n s->mult_sectors = MAX_MULT_SECTORS;\n /* ide regs */\n s->feature = 0;\n s->error = 0;\n s->nsector = 0;\n s->sector = 0;\n s->lcyl = 0;\n s->hcyl = 0;\n s->select = 0xa0;\n s->status = READY_STAT | SEEK_STAT;\n\n /* init I/O buffer */\n s->data_index = 0;\n s->data_end = 0;\n s->end_transfer_func = ide_transfer_stop;\n\n s->req_nb_sectors = 0; /* temp for read/write */\n s->io_nb_sectors = 0; /* temp for read/write */\n return s;\n}\n\nIDEIFState *ide_init(PhysMemoryMap *port_map, uint32_t addr, uint32_t addr2,\n IRQSignal *irq, BlockDevice **tab_bs)\n{\n int i;\n IDEIFState *s;\n \n s = malloc(sizeof(IDEIFState));\n memset(s, 0, sizeof(*s));\n \n s->irq = irq;\n s->cmd = 0;\n\n cpu_register_device(port_map, addr, 1, s, ide_data_readw, ide_data_writew, \n DEVIO_SIZE16);\n cpu_register_device(port_map, addr + 1, 7, s, ide_ioport_read, ide_ioport_write, \n DEVIO_SIZE8);\n if (addr2) {\n cpu_register_device(port_map, addr2, 1, s, ide_status_read, ide_cmd_write, \n DEVIO_SIZE8);\n }\n \n for(i = 0; i < 2; i++) {\n if (tab_bs[i])\n s->drives[i] = ide_drive_init(s, tab_bs[i]);\n }\n s->cur_drive = s->drives[0];\n return s;\n}\n\n/* dummy PCI device for the IDE */\nPCIDevice *piix3_ide_init(PCIBus *pci_bus, int devfn)\n{\n PCIDevice *d;\n d = pci_register_device(pci_bus, \"PIIX3 IDE\", devfn, 0x8086, 0x7010, 0x00, 0x0101);\n pci_device_set_config8(d, 0x09, 0x00); /* ISA IDE ports, no DMA */\n return d;\n}\n"], ["/linuxpdf/tinyemu/slirp/bootp.c", "/*\n * QEMU BOOTP/DHCP server\n *\n * Copyright (c) 2004 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"slirp.h\"\n\n/* XXX: only DHCP is supported */\n\n#define LEASE_TIME (24 * 3600)\n\nstatic const uint8_t rfc1533_cookie[] = { RFC1533_COOKIE };\n\n#ifdef DEBUG\n#define DPRINTF(fmt, ...) \\\ndo if (slirp_debug & DBG_CALL) { fprintf(dfd, fmt, ## __VA_ARGS__); fflush(dfd); } while (0)\n#else\n#define DPRINTF(fmt, ...) do{}while(0)\n#endif\n\nstatic BOOTPClient *get_new_addr(Slirp *slirp, struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n BOOTPClient *bc;\n int i;\n\n for(i = 0; i < NB_BOOTP_CLIENTS; i++) {\n bc = &slirp->bootp_clients[i];\n if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6))\n goto found;\n }\n return NULL;\n found:\n bc = &slirp->bootp_clients[i];\n bc->allocated = 1;\n paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i);\n return bc;\n}\n\nstatic BOOTPClient *request_addr(Slirp *slirp, const struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n uint32_t req_addr = ntohl(paddr->s_addr);\n uint32_t dhcp_addr = ntohl(slirp->vdhcp_startaddr.s_addr);\n BOOTPClient *bc;\n\n if (req_addr >= dhcp_addr &&\n req_addr < (dhcp_addr + NB_BOOTP_CLIENTS)) {\n bc = &slirp->bootp_clients[req_addr - dhcp_addr];\n if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6)) {\n bc->allocated = 1;\n return bc;\n }\n }\n return NULL;\n}\n\nstatic BOOTPClient *find_addr(Slirp *slirp, struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n BOOTPClient *bc;\n int i;\n\n for(i = 0; i < NB_BOOTP_CLIENTS; i++) {\n if (!memcmp(macaddr, slirp->bootp_clients[i].macaddr, 6))\n goto found;\n }\n return NULL;\n found:\n bc = &slirp->bootp_clients[i];\n bc->allocated = 1;\n paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i);\n return bc;\n}\n\nstatic void dhcp_decode(const struct bootp_t *bp, int *pmsg_type,\n struct in_addr *preq_addr)\n{\n const uint8_t *p, *p_end;\n int len, tag;\n\n *pmsg_type = 0;\n preq_addr->s_addr = htonl(0L);\n\n p = bp->bp_vend;\n p_end = p + DHCP_OPT_LEN;\n if (memcmp(p, rfc1533_cookie, 4) != 0)\n return;\n p += 4;\n while (p < p_end) {\n tag = p[0];\n if (tag == RFC1533_PAD) {\n p++;\n } else if (tag == RFC1533_END) {\n break;\n } else {\n p++;\n if (p >= p_end)\n break;\n len = *p++;\n DPRINTF(\"dhcp: tag=%d len=%d\\n\", tag, len);\n\n switch(tag) {\n case RFC2132_MSG_TYPE:\n if (len >= 1)\n *pmsg_type = p[0];\n break;\n case RFC2132_REQ_ADDR:\n if (len >= 4) {\n memcpy(&(preq_addr->s_addr), p, 4);\n }\n break;\n default:\n break;\n }\n p += len;\n }\n }\n if (*pmsg_type == DHCPREQUEST && preq_addr->s_addr == htonl(0L) &&\n bp->bp_ciaddr.s_addr) {\n memcpy(&(preq_addr->s_addr), &bp->bp_ciaddr, 4);\n }\n}\n\nstatic void bootp_reply(Slirp *slirp, const struct bootp_t *bp)\n{\n BOOTPClient *bc = NULL;\n struct mbuf *m;\n struct bootp_t *rbp;\n struct sockaddr_in saddr, daddr;\n struct in_addr preq_addr;\n int dhcp_msg_type, val;\n uint8_t *q;\n\n /* extract exact DHCP msg type */\n dhcp_decode(bp, &dhcp_msg_type, &preq_addr);\n DPRINTF(\"bootp packet op=%d msgtype=%d\", bp->bp_op, dhcp_msg_type);\n if (preq_addr.s_addr != htonl(0L))\n DPRINTF(\" req_addr=%08x\\n\", ntohl(preq_addr.s_addr));\n else\n DPRINTF(\"\\n\");\n\n if (dhcp_msg_type == 0)\n dhcp_msg_type = DHCPREQUEST; /* Force reply for old BOOTP clients */\n\n if (dhcp_msg_type != DHCPDISCOVER &&\n dhcp_msg_type != DHCPREQUEST)\n return;\n /* XXX: this is a hack to get the client mac address */\n memcpy(slirp->client_ethaddr, bp->bp_hwaddr, 6);\n\n m = m_get(slirp);\n if (!m) {\n return;\n }\n m->m_data += IF_MAXLINKHDR;\n rbp = (struct bootp_t *)m->m_data;\n m->m_data += sizeof(struct udpiphdr);\n memset(rbp, 0, sizeof(struct bootp_t));\n\n if (dhcp_msg_type == DHCPDISCOVER) {\n if (preq_addr.s_addr != htonl(0L)) {\n bc = request_addr(slirp, &preq_addr, slirp->client_ethaddr);\n if (bc) {\n daddr.sin_addr = preq_addr;\n }\n }\n if (!bc) {\n new_addr:\n bc = get_new_addr(slirp, &daddr.sin_addr, slirp->client_ethaddr);\n if (!bc) {\n DPRINTF(\"no address left\\n\");\n return;\n }\n }\n memcpy(bc->macaddr, slirp->client_ethaddr, 6);\n } else if (preq_addr.s_addr != htonl(0L)) {\n bc = request_addr(slirp, &preq_addr, slirp->client_ethaddr);\n if (bc) {\n daddr.sin_addr = preq_addr;\n memcpy(bc->macaddr, slirp->client_ethaddr, 6);\n } else {\n daddr.sin_addr.s_addr = 0;\n }\n } else {\n bc = find_addr(slirp, &daddr.sin_addr, bp->bp_hwaddr);\n if (!bc) {\n /* if never assigned, behaves as if it was already\n assigned (windows fix because it remembers its address) */\n goto new_addr;\n }\n }\n\n saddr.sin_addr = slirp->vhost_addr;\n saddr.sin_port = htons(BOOTP_SERVER);\n\n daddr.sin_port = htons(BOOTP_CLIENT);\n\n rbp->bp_op = BOOTP_REPLY;\n rbp->bp_xid = bp->bp_xid;\n rbp->bp_htype = 1;\n rbp->bp_hlen = 6;\n memcpy(rbp->bp_hwaddr, bp->bp_hwaddr, 6);\n\n rbp->bp_yiaddr = daddr.sin_addr; /* Client IP address */\n rbp->bp_siaddr = saddr.sin_addr; /* Server IP address */\n\n q = rbp->bp_vend;\n memcpy(q, rfc1533_cookie, 4);\n q += 4;\n\n if (bc) {\n DPRINTF(\"%s addr=%08x\\n\",\n (dhcp_msg_type == DHCPDISCOVER) ? \"offered\" : \"ack'ed\",\n ntohl(daddr.sin_addr.s_addr));\n\n if (dhcp_msg_type == DHCPDISCOVER) {\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPOFFER;\n } else /* DHCPREQUEST */ {\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPACK;\n }\n\n if (slirp->bootp_filename)\n snprintf((char *)rbp->bp_file, sizeof(rbp->bp_file), \"%s\",\n slirp->bootp_filename);\n\n *q++ = RFC2132_SRV_ID;\n *q++ = 4;\n memcpy(q, &saddr.sin_addr, 4);\n q += 4;\n\n *q++ = RFC1533_NETMASK;\n *q++ = 4;\n memcpy(q, &slirp->vnetwork_mask, 4);\n q += 4;\n\n if (!slirp->restricted) {\n *q++ = RFC1533_GATEWAY;\n *q++ = 4;\n memcpy(q, &saddr.sin_addr, 4);\n q += 4;\n\n *q++ = RFC1533_DNS;\n *q++ = 4;\n memcpy(q, &slirp->vnameserver_addr, 4);\n q += 4;\n }\n\n *q++ = RFC2132_LEASE_TIME;\n *q++ = 4;\n val = htonl(LEASE_TIME);\n memcpy(q, &val, 4);\n q += 4;\n\n if (*slirp->client_hostname) {\n val = strlen(slirp->client_hostname);\n *q++ = RFC1533_HOSTNAME;\n *q++ = val;\n memcpy(q, slirp->client_hostname, val);\n q += val;\n }\n } else {\n static const char nak_msg[] = \"requested address not available\";\n\n DPRINTF(\"nak'ed addr=%08x\\n\", ntohl(preq_addr->s_addr));\n\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPNAK;\n\n *q++ = RFC2132_MESSAGE;\n *q++ = sizeof(nak_msg) - 1;\n memcpy(q, nak_msg, sizeof(nak_msg) - 1);\n q += sizeof(nak_msg) - 1;\n }\n *q = RFC1533_END;\n\n daddr.sin_addr.s_addr = 0xffffffffu;\n\n m->m_len = sizeof(struct bootp_t) -\n sizeof(struct ip) - sizeof(struct udphdr);\n udp_output2(NULL, m, &saddr, &daddr, IPTOS_LOWDELAY);\n}\n\nvoid bootp_input(struct mbuf *m)\n{\n struct bootp_t *bp = mtod(m, struct bootp_t *);\n\n if (bp->bp_op == BOOTP_REQUEST) {\n bootp_reply(m->slirp, bp);\n }\n}\n"], ["/linuxpdf/tinyemu/fs_net.c", "/*\n * Networked Filesystem using HTTP\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n#include \"fbuf.h\"\n\n#if defined(EMSCRIPTEN)\n#include \n#endif\n\n/*\n TODO:\n - implement fs_lock/fs_getlock\n - update fs_size with links ?\n - limit fs_size in dirent creation\n - limit filename length\n*/\n\n//#define DEBUG_CACHE\n#if !defined(EMSCRIPTEN)\n#define DUMP_CACHE_LOAD\n#endif\n\n#if defined(EMSCRIPTEN)\n#define DEFAULT_INODE_CACHE_SIZE (64 * 1024 * 1024)\n#else\n#define DEFAULT_INODE_CACHE_SIZE (256 * 1024 * 1024)\n#endif\n\ntypedef enum {\n FT_FIFO = 1,\n FT_CHR = 2,\n FT_DIR = 4,\n FT_BLK = 6,\n FT_REG = 8,\n FT_LNK = 10,\n FT_SOCK = 12,\n} FSINodeTypeEnum;\n\ntypedef enum {\n REG_STATE_LOCAL, /* local content */\n REG_STATE_UNLOADED, /* content not loaded */\n REG_STATE_LOADING, /* content is being loaded */\n REG_STATE_LOADED, /* loaded, not modified, stored in cached_inode_list */\n} FSINodeRegStateEnum;\n\ntypedef struct FSBaseURL {\n struct list_head link;\n int ref_count;\n char *base_url_id;\n char *url;\n char *user;\n char *password;\n BOOL encrypted;\n AES_KEY aes_state;\n} FSBaseURL;\n\ntypedef struct FSINode {\n struct list_head link;\n uint64_t inode_num; /* inode number */\n int32_t refcount;\n int32_t open_count;\n FSINodeTypeEnum type;\n uint32_t mode;\n uint32_t uid;\n uint32_t gid;\n uint32_t mtime_sec;\n uint32_t ctime_sec;\n uint32_t mtime_nsec;\n uint32_t ctime_nsec;\n union {\n struct {\n FSINodeRegStateEnum state;\n size_t size; /* real file size */\n FileBuffer fbuf;\n FSBaseURL *base_url;\n FSFileID file_id; /* network file ID */\n struct list_head link;\n struct FSOpenInfo *open_info; /* used in LOADING state */\n BOOL is_fscmd;\n#ifdef DUMP_CACHE_LOAD\n char *filename;\n#endif\n } reg;\n struct {\n struct list_head de_list; /* list of FSDirEntry */\n int size;\n } dir;\n struct {\n uint32_t major;\n uint32_t minor;\n } dev;\n struct {\n char *name;\n } symlink;\n } u;\n} FSINode;\n\ntypedef struct {\n struct list_head link;\n FSINode *inode;\n uint8_t mark; /* temporary use only */\n char name[0];\n} FSDirEntry;\n\ntypedef enum {\n FS_CMD_XHR,\n FS_CMD_PBKDF2,\n} FSCMDRequestEnum;\n\n#define FS_CMD_REPLY_LEN_MAX 64\n\ntypedef struct {\n FSCMDRequestEnum type;\n struct CmdXHRState *xhr_state;\n int reply_len;\n uint8_t reply_buf[FS_CMD_REPLY_LEN_MAX];\n} FSCMDRequest;\n\nstruct FSFile {\n uint32_t uid;\n FSINode *inode;\n BOOL is_opened;\n uint32_t open_flags;\n FSCMDRequest *req;\n};\n\ntypedef struct {\n struct list_head link;\n BOOL is_archive;\n const char *name;\n} PreloadFile;\n\ntypedef struct {\n struct list_head link;\n FSFileID file_id;\n struct list_head file_list; /* list of PreloadFile.link */\n} PreloadEntry;\n\ntypedef struct {\n struct list_head link;\n FSFileID file_id;\n uint64_t size;\n const char *name;\n} PreloadArchiveFile;\n\ntypedef struct {\n struct list_head link;\n const char *name;\n struct list_head file_list; /* list of PreloadArchiveFile.link */\n} PreloadArchive;\n\ntypedef struct FSDeviceMem {\n FSDevice common;\n\n struct list_head inode_list; /* list of FSINode */\n int64_t inode_count; /* current number of inodes */\n uint64_t inode_limit;\n int64_t fs_blocks;\n uint64_t fs_max_blocks;\n uint64_t inode_num_alloc;\n int block_size_log2;\n uint32_t block_size; /* for stat/statfs */\n FSINode *root_inode;\n struct list_head inode_cache_list; /* list of FSINode.u.reg.link */\n int64_t inode_cache_size;\n int64_t inode_cache_size_limit;\n struct list_head preload_list; /* list of PreloadEntry.link */\n struct list_head preload_archive_list; /* list of PreloadArchive.link */\n /* network */\n struct list_head base_url_list; /* list of FSBaseURL.link */\n char *import_dir;\n#ifdef DUMP_CACHE_LOAD\n BOOL dump_cache_load;\n BOOL dump_started;\n char *dump_preload_dir;\n FILE *dump_preload_file;\n FILE *dump_preload_archive_file;\n\n char *dump_archive_name;\n uint64_t dump_archive_size;\n FILE *dump_archive_file;\n\n int dump_archive_num;\n struct list_head dump_preload_list; /* list of PreloadFile.link */\n struct list_head dump_exclude_list; /* list of PreloadFile.link */\n#endif\n} FSDeviceMem;\n\ntypedef enum {\n FS_OPEN_WGET_REG,\n FS_OPEN_WGET_ARCHIVE,\n FS_OPEN_WGET_ARCHIVE_FILE,\n} FSOpenWgetEnum;\n\ntypedef struct FSOpenInfo {\n FSDevice *fs;\n FSOpenWgetEnum open_type;\n\n /* used for FS_OPEN_WGET_REG, FS_OPEN_WGET_ARCHIVE */\n XHRState *xhr;\n FSINode *n;\n DecryptFileState *dec_state;\n size_t cur_pos;\n\n struct list_head archive_link; /* FS_OPEN_WGET_ARCHIVE_FILE */\n uint64_t archive_offset; /* FS_OPEN_WGET_ARCHIVE_FILE */\n struct list_head archive_file_list; /* FS_OPEN_WGET_ARCHIVE */\n \n /* the following is set in case there is a fs_open callback */\n FSFile *f;\n FSOpenCompletionFunc *cb;\n void *opaque;\n} FSOpenInfo;\n\nstatic void fs_close(FSDevice *fs, FSFile *f);\nstatic void inode_decref(FSDevice *fs1, FSINode *n);\nstatic int fs_cmd_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int buf_len);\nstatic int fs_cmd_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int buf_len);\nstatic int fs_truncate(FSDevice *fs1, FSINode *n, uint64_t size);\nstatic void fs_open_end(FSOpenInfo *oi);\nstatic void fs_base_url_decref(FSDevice *fs, FSBaseURL *bu);\nstatic FSBaseURL *fs_net_set_base_url(FSDevice *fs1,\n const char *base_url_id,\n const char *url,\n const char *user, const char *password,\n AES_KEY *aes_state);\nstatic void fs_cmd_close(FSDevice *fs, FSFile *f);\nstatic void fs_error_archive(FSOpenInfo *oi);\n#ifdef DUMP_CACHE_LOAD\nstatic void dump_loaded_file(FSDevice *fs1, FSINode *n);\n#endif\n\n#if !defined(EMSCRIPTEN)\n/* file buffer (the content of the buffer can be stored elsewhere) */\nvoid file_buffer_init(FileBuffer *bs)\n{\n bs->data = NULL;\n bs->allocated_size = 0;\n}\n\nvoid file_buffer_reset(FileBuffer *bs)\n{\n free(bs->data);\n file_buffer_init(bs);\n}\n\nint file_buffer_resize(FileBuffer *bs, size_t new_size)\n{\n uint8_t *new_data;\n new_data = realloc(bs->data, new_size);\n if (!new_data && new_size != 0)\n return -1;\n bs->data = new_data;\n bs->allocated_size = new_size;\n return 0;\n}\n\nvoid file_buffer_write(FileBuffer *bs, size_t offset, const uint8_t *buf,\n size_t size)\n{\n memcpy(bs->data + offset, buf, size);\n}\n\nvoid file_buffer_set(FileBuffer *bs, size_t offset, int val, size_t size)\n{\n memset(bs->data + offset, val, size);\n}\n\nvoid file_buffer_read(FileBuffer *bs, size_t offset, uint8_t *buf,\n size_t size)\n{\n memcpy(buf, bs->data + offset, size);\n}\n#endif\n\nstatic int64_t to_blocks(FSDeviceMem *fs, uint64_t size)\n{\n return (size + fs->block_size - 1) >> fs->block_size_log2;\n}\n\nstatic FSINode *inode_incref(FSDevice *fs, FSINode *n)\n{\n n->refcount++;\n return n;\n}\n\nstatic FSINode *inode_inc_open(FSDevice *fs, FSINode *n)\n{\n n->open_count++;\n return n;\n}\n\nstatic void inode_free(FSDevice *fs1, FSINode *n)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n // printf(\"inode_free=%\" PRId64 \"\\n\", n->inode_num);\n assert(n->refcount == 0);\n assert(n->open_count == 0);\n switch(n->type) {\n case FT_REG:\n fs->fs_blocks -= to_blocks(fs, n->u.reg.size);\n assert(fs->fs_blocks >= 0);\n file_buffer_reset(&n->u.reg.fbuf);\n#ifdef DUMP_CACHE_LOAD\n free(n->u.reg.filename);\n#endif\n switch(n->u.reg.state) {\n case REG_STATE_LOADED:\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n fs_base_url_decref(fs1, n->u.reg.base_url);\n break;\n case REG_STATE_LOADING:\n {\n FSOpenInfo *oi = n->u.reg.open_info;\n if (oi->xhr)\n fs_wget_free(oi->xhr);\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE) {\n fs_error_archive(oi);\n }\n fs_open_end(oi);\n fs_base_url_decref(fs1, n->u.reg.base_url);\n }\n break;\n case REG_STATE_UNLOADED:\n fs_base_url_decref(fs1, n->u.reg.base_url);\n break;\n case REG_STATE_LOCAL:\n break;\n default:\n abort();\n }\n break;\n case FT_LNK:\n free(n->u.symlink.name);\n break;\n case FT_DIR:\n assert(list_empty(&n->u.dir.de_list));\n break;\n default:\n break;\n }\n list_del(&n->link);\n free(n);\n fs->inode_count--;\n assert(fs->inode_count >= 0);\n}\n\nstatic void inode_decref(FSDevice *fs1, FSINode *n)\n{\n assert(n->refcount >= 1);\n if (--n->refcount <= 0 && n->open_count <= 0) {\n inode_free(fs1, n);\n }\n}\n\nstatic void inode_dec_open(FSDevice *fs1, FSINode *n)\n{\n assert(n->open_count >= 1);\n if (--n->open_count <= 0 && n->refcount <= 0) {\n inode_free(fs1, n);\n }\n}\n\nstatic void inode_update_mtime(FSDevice *fs, FSINode *n)\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n n->mtime_sec = tv.tv_sec;\n n->mtime_nsec = tv.tv_usec * 1000;\n}\n\nstatic FSINode *inode_new(FSDevice *fs1, FSINodeTypeEnum type,\n uint32_t mode, uint32_t uid, uint32_t gid)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n;\n\n n = mallocz(sizeof(*n));\n n->refcount = 1;\n n->open_count = 0;\n n->inode_num = fs->inode_num_alloc;\n fs->inode_num_alloc++;\n n->type = type;\n n->mode = mode & 0xfff;\n n->uid = uid;\n n->gid = gid;\n\n switch(type) {\n case FT_REG:\n file_buffer_init(&n->u.reg.fbuf);\n break;\n case FT_DIR:\n init_list_head(&n->u.dir.de_list);\n break;\n default:\n break;\n }\n\n list_add(&n->link, &fs->inode_list);\n fs->inode_count++;\n\n inode_update_mtime(fs1, n);\n n->ctime_sec = n->mtime_sec;\n n->ctime_nsec = n->mtime_nsec;\n\n return n;\n}\n\n/* warning: the refcount of 'n1' is not incremented by this function */\n/* XXX: test FS max size */\nstatic FSDirEntry *inode_dir_add(FSDevice *fs1, FSINode *n, const char *name,\n FSINode *n1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSDirEntry *de;\n int name_len, dirent_size, new_size;\n assert(n->type == FT_DIR);\n\n name_len = strlen(name);\n de = mallocz(sizeof(*de) + name_len + 1);\n de->inode = n1;\n memcpy(de->name, name, name_len + 1);\n dirent_size = sizeof(*de) + name_len + 1;\n new_size = n->u.dir.size + dirent_size;\n fs->fs_blocks += to_blocks(fs, new_size) - to_blocks(fs, n->u.dir.size);\n n->u.dir.size = new_size;\n list_add_tail(&de->link, &n->u.dir.de_list);\n return de;\n}\n\nstatic FSDirEntry *inode_search(FSINode *n, const char *name)\n{\n struct list_head *el;\n FSDirEntry *de;\n \n if (n->type != FT_DIR)\n return NULL;\n\n list_for_each(el, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n if (!strcmp(de->name, name))\n return de;\n }\n return NULL;\n}\n\nstatic FSINode *inode_search_path1(FSDevice *fs, FSINode *n, const char *path)\n{\n char name[1024];\n const char *p, *p1;\n int len;\n FSDirEntry *de;\n \n p = path;\n if (*p == '/')\n p++;\n if (*p == '\\0')\n return n;\n for(;;) {\n p1 = strchr(p, '/');\n if (!p1) {\n len = strlen(p);\n } else {\n len = p1 - p;\n p1++;\n }\n if (len > sizeof(name) - 1)\n return NULL;\n memcpy(name, p, len);\n name[len] = '\\0';\n if (n->type != FT_DIR)\n return NULL;\n de = inode_search(n, name);\n if (!de)\n return NULL;\n n = de->inode;\n p = p1;\n if (!p)\n break;\n }\n return n;\n}\n\nstatic FSINode *inode_search_path(FSDevice *fs1, const char *path)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (!fs1)\n return NULL;\n return inode_search_path1(fs1, fs->root_inode, path);\n}\n\nstatic BOOL is_empty_dir(FSDevice *fs, FSINode *n)\n{\n struct list_head *el;\n FSDirEntry *de;\n\n list_for_each(el, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n if (strcmp(de->name, \".\") != 0 &&\n strcmp(de->name, \"..\") != 0)\n return FALSE;\n }\n return TRUE;\n}\n\nstatic void inode_dirent_delete_no_decref(FSDevice *fs1, FSINode *n, FSDirEntry *de)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int dirent_size, new_size;\n dirent_size = sizeof(*de) + strlen(de->name) + 1;\n\n new_size = n->u.dir.size - dirent_size;\n fs->fs_blocks += to_blocks(fs, new_size) - to_blocks(fs, n->u.dir.size);\n n->u.dir.size = new_size;\n assert(n->u.dir.size >= 0);\n assert(fs->fs_blocks >= 0);\n list_del(&de->link);\n free(de);\n}\n\nstatic void inode_dirent_delete(FSDevice *fs, FSINode *n, FSDirEntry *de)\n{\n FSINode *n1;\n n1 = de->inode;\n inode_dirent_delete_no_decref(fs, n, de);\n inode_decref(fs, n1);\n}\n\nstatic void flush_dir(FSDevice *fs, FSINode *n)\n{\n struct list_head *el, *el1;\n FSDirEntry *de;\n list_for_each_safe(el, el1, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n inode_dirent_delete(fs, n, de);\n }\n assert(n->u.dir.size == 0);\n}\n\nstatic void fs_delete(FSDevice *fs, FSFile *f)\n{\n fs_close(fs, f);\n inode_dec_open(fs, f->inode);\n free(f);\n}\n\nstatic FSFile *fid_create(FSDevice *fs1, FSINode *n, uint32_t uid)\n{\n FSFile *f;\n\n f = mallocz(sizeof(*f));\n f->inode = inode_inc_open(fs1, n);\n f->uid = uid;\n return f;\n}\n\nstatic void inode_to_qid(FSQID *qid, FSINode *n)\n{\n if (n->type == FT_DIR)\n qid->type = P9_QTDIR;\n else if (n->type == FT_LNK)\n qid->type = P9_QTSYMLINK;\n else\n qid->type = P9_QTFILE;\n qid->version = 0; /* no caching on client */\n qid->path = n->inode_num;\n}\n\nstatic void fs_statfs(FSDevice *fs1, FSStatFS *st)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n st->f_bsize = 1024;\n st->f_blocks = fs->fs_max_blocks <<\n (fs->block_size_log2 - 10);\n st->f_bfree = (fs->fs_max_blocks - fs->fs_blocks) <<\n (fs->block_size_log2 - 10);\n st->f_bavail = st->f_bfree;\n st->f_files = fs->inode_limit;\n st->f_ffree = fs->inode_limit - fs->inode_count;\n}\n\nstatic int fs_attach(FSDevice *fs1, FSFile **pf, FSQID *qid, uint32_t uid,\n const char *uname, const char *aname)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n *pf = fid_create(fs1, fs->root_inode, uid);\n inode_to_qid(qid, fs->root_inode);\n return 0;\n}\n\nstatic int fs_walk(FSDevice *fs, FSFile **pf, FSQID *qids,\n FSFile *f, int count, char **names)\n{\n int i;\n FSINode *n;\n FSDirEntry *de;\n\n n = f->inode;\n for(i = 0; i < count; i++) {\n de = inode_search(n, names[i]);\n if (!de)\n break;\n n = de->inode;\n inode_to_qid(&qids[i], n);\n }\n *pf = fid_create(fs, n, f->uid);\n return i;\n}\n\nstatic int fs_mkdir(FSDevice *fs, FSQID *qid, FSFile *f,\n const char *name, uint32_t mode, uint32_t gid)\n{\n FSINode *n, *n1;\n\n n = f->inode;\n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n if (inode_search(n, name))\n return -P9_EEXIST;\n n1 = inode_new(fs, FT_DIR, mode, f->uid, gid);\n inode_dir_add(fs, n1, \".\", inode_incref(fs, n1));\n inode_dir_add(fs, n1, \"..\", inode_incref(fs, n));\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\n/* remove elements in the cache considering that 'added_size' will be\n added */\nstatic void fs_trim_cache(FSDevice *fs1, int64_t added_size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el, *el1;\n FSINode *n;\n\n if ((fs->inode_cache_size + added_size) <= fs->inode_cache_size_limit)\n return;\n list_for_each_prev_safe(el, el1, &fs->inode_cache_list) {\n n = list_entry(el, FSINode, u.reg.link);\n assert(n->u.reg.state == REG_STATE_LOADED);\n /* cannot remove open files */\n // printf(\"open_count=%d\\n\", n->open_count);\n if (n->open_count != 0)\n continue;\n#ifdef DEBUG_CACHE\n printf(\"fs_trim_cache: remove '%s' size=%ld\\n\",\n n->u.reg.filename, (long)n->u.reg.size);\n#endif\n file_buffer_reset(&n->u.reg.fbuf);\n n->u.reg.state = REG_STATE_UNLOADED;\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n if ((fs->inode_cache_size + added_size) <= fs->inode_cache_size_limit)\n break;\n }\n}\n\nstatic void fs_open_end(FSOpenInfo *oi)\n{\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE_FILE) {\n list_del(&oi->archive_link);\n }\n if (oi->dec_state)\n decrypt_file_end(oi->dec_state);\n free(oi);\n}\n\nstatic int fs_open_write_cb(void *opaque, const uint8_t *data, size_t size)\n{\n FSOpenInfo *oi = opaque;\n size_t len;\n FSINode *n = oi->n;\n \n /* we ignore extraneous data */\n len = n->u.reg.size - oi->cur_pos;\n if (size < len)\n len = size;\n file_buffer_write(&n->u.reg.fbuf, oi->cur_pos, data, len);\n oi->cur_pos += len;\n return 0;\n}\n\nstatic void fs_wget_set_loaded(FSINode *n)\n{\n FSOpenInfo *oi;\n FSDeviceMem *fs;\n FSFile *f;\n FSQID qid;\n\n assert(n->u.reg.state == REG_STATE_LOADING);\n oi = n->u.reg.open_info;\n fs = (FSDeviceMem *)oi->fs;\n n->u.reg.state = REG_STATE_LOADED;\n list_add(&n->u.reg.link, &fs->inode_cache_list);\n fs->inode_cache_size += n->u.reg.size;\n \n if (oi->cb) {\n f = oi->f;\n f->is_opened = TRUE;\n inode_to_qid(&qid, n);\n oi->cb(oi->fs, &qid, 0, oi->opaque);\n }\n fs_open_end(oi);\n}\n\nstatic void fs_wget_set_error(FSINode *n)\n{\n FSOpenInfo *oi;\n assert(n->u.reg.state == REG_STATE_LOADING);\n oi = n->u.reg.open_info;\n n->u.reg.state = REG_STATE_UNLOADED;\n file_buffer_reset(&n->u.reg.fbuf);\n if (oi->cb) {\n oi->cb(oi->fs, NULL, -P9_EIO, oi->opaque);\n }\n fs_open_end(oi);\n}\n\nstatic void fs_read_archive(FSOpenInfo *oi)\n{\n FSINode *n = oi->n;\n uint64_t pos, pos1, l;\n uint8_t buf[1024];\n FSINode *n1;\n FSOpenInfo *oi1;\n struct list_head *el, *el1;\n \n list_for_each_safe(el, el1, &oi->archive_file_list) {\n oi1 = list_entry(el, FSOpenInfo, archive_link);\n n1 = oi1->n;\n /* copy the archive data to the file */\n pos = oi1->archive_offset;\n pos1 = 0;\n while (pos1 < n1->u.reg.size) {\n l = n1->u.reg.size - pos1;\n if (l > sizeof(buf))\n l = sizeof(buf);\n file_buffer_read(&n->u.reg.fbuf, pos, buf, l);\n file_buffer_write(&n1->u.reg.fbuf, pos1, buf, l);\n pos += l;\n pos1 += l;\n }\n fs_wget_set_loaded(n1);\n }\n}\n\nstatic void fs_error_archive(FSOpenInfo *oi)\n{\n FSOpenInfo *oi1;\n struct list_head *el, *el1;\n \n list_for_each_safe(el, el1, &oi->archive_file_list) {\n oi1 = list_entry(el, FSOpenInfo, archive_link);\n fs_wget_set_error(oi1->n);\n }\n}\n\nstatic void fs_open_cb(void *opaque, int err, void *data, size_t size)\n{\n FSOpenInfo *oi = opaque;\n FSINode *n = oi->n;\n \n // printf(\"open_cb: err=%d size=%ld\\n\", err, size);\n if (err < 0) {\n error:\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE)\n fs_error_archive(oi);\n fs_wget_set_error(n);\n } else {\n if (oi->dec_state) {\n if (decrypt_file(oi->dec_state, data, size) < 0)\n goto error;\n if (err == 0) {\n if (decrypt_file_flush(oi->dec_state) < 0)\n goto error;\n }\n } else {\n fs_open_write_cb(oi, data, size);\n }\n\n if (err == 0) {\n /* end of transfer */\n if (oi->cur_pos != n->u.reg.size)\n goto error;\n#ifdef DUMP_CACHE_LOAD\n dump_loaded_file(oi->fs, n);\n#endif\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE)\n fs_read_archive(oi);\n fs_wget_set_loaded(n);\n }\n }\n}\n\n\nstatic int fs_open_wget(FSDevice *fs1, FSINode *n, FSOpenWgetEnum open_type)\n{\n char *url;\n FSOpenInfo *oi;\n char fname[FILEID_SIZE_MAX];\n FSBaseURL *bu;\n\n assert(n->u.reg.state == REG_STATE_UNLOADED);\n \n fs_trim_cache(fs1, n->u.reg.size);\n \n if (file_buffer_resize(&n->u.reg.fbuf, n->u.reg.size) < 0)\n return -P9_EIO;\n n->u.reg.state = REG_STATE_LOADING;\n oi = mallocz(sizeof(*oi));\n oi->cur_pos = 0;\n oi->fs = fs1;\n oi->n = n;\n oi->open_type = open_type;\n if (open_type != FS_OPEN_WGET_ARCHIVE_FILE) {\n if (open_type == FS_OPEN_WGET_ARCHIVE)\n init_list_head(&oi->archive_file_list);\n file_id_to_filename(fname, n->u.reg.file_id);\n bu = n->u.reg.base_url;\n url = compose_path(bu->url, fname);\n if (bu->encrypted) {\n oi->dec_state = decrypt_file_init(&bu->aes_state, fs_open_write_cb, oi);\n }\n oi->xhr = fs_wget(url, bu->user, bu->password, oi, fs_open_cb, FALSE);\n }\n n->u.reg.open_info = oi;\n return 0;\n}\n\n\nstatic void fs_preload_file(FSDevice *fs1, const char *filename)\n{\n FSINode *n;\n\n n = inode_search_path(fs1, filename);\n if (n && n->type == FT_REG && n->u.reg.state == REG_STATE_UNLOADED) {\n#if defined(DEBUG_CACHE)\n printf(\"preload: %s\\n\", filename);\n#endif\n fs_open_wget(fs1, n, FS_OPEN_WGET_REG);\n }\n}\n\nstatic PreloadArchive *find_preload_archive(FSDeviceMem *fs,\n const char *filename)\n{\n PreloadArchive *pa;\n struct list_head *el;\n list_for_each(el, &fs->preload_archive_list) {\n pa = list_entry(el, PreloadArchive, link);\n if (!strcmp(pa->name, filename))\n return pa;\n }\n return NULL;\n}\n\nstatic void fs_preload_archive(FSDevice *fs1, const char *filename)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n PreloadArchive *pa;\n PreloadArchiveFile *paf;\n struct list_head *el;\n FSINode *n, *n1;\n uint64_t offset;\n BOOL has_unloaded;\n \n pa = find_preload_archive(fs, filename);\n if (!pa)\n return;\n#if defined(DEBUG_CACHE)\n printf(\"preload archive: %s\\n\", filename);\n#endif\n n = inode_search_path(fs1, filename);\n if (n && n->type == FT_REG && n->u.reg.state == REG_STATE_UNLOADED) {\n /* if all the files are loaded, no need to load the archive */\n offset = 0;\n has_unloaded = FALSE;\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n n1 = inode_search_path(fs1, paf->name);\n if (n1 && n1->type == FT_REG &&\n n1->u.reg.state == REG_STATE_UNLOADED) {\n has_unloaded = TRUE;\n }\n offset += paf->size;\n }\n if (!has_unloaded) {\n#if defined(DEBUG_CACHE)\n printf(\"archive files already loaded\\n\");\n#endif\n return;\n }\n /* check archive size consistency */\n if (offset != n->u.reg.size) {\n#if defined(DEBUG_CACHE)\n printf(\" inconsistent archive size: %\" PRId64 \" %\" PRId64 \"\\n\",\n offset, n->u.reg.size);\n#endif\n goto load_fallback;\n }\n\n /* start loading the archive */\n fs_open_wget(fs1, n, FS_OPEN_WGET_ARCHIVE);\n \n /* indicate that all the archive files are being loaded. Also\n check consistency of size and file id */\n offset = 0;\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n n1 = inode_search_path(fs1, paf->name);\n if (n1 && n1->type == FT_REG &&\n n1->u.reg.state == REG_STATE_UNLOADED) {\n if (n1->u.reg.size == paf->size &&\n n1->u.reg.file_id == paf->file_id) {\n fs_open_wget(fs1, n1, FS_OPEN_WGET_ARCHIVE_FILE);\n list_add_tail(&n1->u.reg.open_info->archive_link,\n &n->u.reg.open_info->archive_file_list);\n n1->u.reg.open_info->archive_offset = offset;\n } else {\n#if defined(DEBUG_CACHE)\n printf(\" inconsistent archive file: %s\\n\", paf->name);\n#endif\n /* fallback to file preload */\n fs_preload_file(fs1, paf->name);\n }\n }\n offset += paf->size;\n }\n } else {\n load_fallback:\n /* if the archive is already loaded or not loaded, we load the\n files separately (XXX: not optimal if the archive is\n already loaded, but it should not happen often) */\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n fs_preload_file(fs1, paf->name);\n }\n }\n}\n\nstatic void fs_preload_files(FSDevice *fs1, FSFileID file_id)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el;\n PreloadEntry *pe;\n PreloadFile *pf;\n \n list_for_each(el, &fs->preload_list) {\n pe = list_entry(el, PreloadEntry, link);\n if (pe->file_id == file_id)\n goto found;\n }\n return;\n found:\n list_for_each(el, &pe->file_list) {\n pf = list_entry(el, PreloadFile, link);\n if (pf->is_archive)\n fs_preload_archive(fs1, pf->name);\n else\n fs_preload_file(fs1, pf->name);\n }\n}\n\n/* return < 0 if error, 0 if OK, 1 if asynchronous completion */\n/* XXX: we don't support several simultaneous asynchronous open on the\n same inode */\nstatic int fs_open(FSDevice *fs1, FSQID *qid, FSFile *f, uint32_t flags,\n FSOpenCompletionFunc *cb, void *opaque)\n{\n FSINode *n = f->inode;\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int ret;\n \n fs_close(fs1, f);\n\n if (flags & P9_O_DIRECTORY) {\n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n } else {\n if (n->type != FT_REG && n->type != FT_DIR)\n return -P9_EINVAL; /* XXX */\n }\n f->open_flags = flags;\n if (n->type == FT_REG) {\n if ((flags & P9_O_TRUNC) && (flags & P9_O_NOACCESS) != P9_O_RDONLY) {\n fs_truncate(fs1, n, 0);\n }\n\n switch(n->u.reg.state) {\n case REG_STATE_UNLOADED:\n {\n FSOpenInfo *oi;\n /* need to load the file */\n fs_preload_files(fs1, n->u.reg.file_id);\n /* The state can be modified by the fs_preload_files */\n if (n->u.reg.state == REG_STATE_LOADING)\n goto handle_loading;\n ret = fs_open_wget(fs1, n, FS_OPEN_WGET_REG);\n if (ret)\n return ret;\n oi = n->u.reg.open_info;\n oi->f = f;\n oi->cb = cb;\n oi->opaque = opaque;\n return 1; /* completion callback will be called later */\n }\n break;\n case REG_STATE_LOADING:\n handle_loading:\n {\n FSOpenInfo *oi;\n /* we only handle the case where the file is being preloaded */\n oi = n->u.reg.open_info;\n if (oi->cb)\n return -P9_EIO;\n oi = n->u.reg.open_info;\n oi->f = f;\n oi->cb = cb;\n oi->opaque = opaque;\n return 1; /* completion callback will be called later */\n }\n break;\n case REG_STATE_LOCAL:\n goto do_open;\n case REG_STATE_LOADED:\n /* move to front */\n list_del(&n->u.reg.link);\n list_add(&n->u.reg.link, &fs->inode_cache_list);\n goto do_open;\n default:\n abort();\n }\n } else {\n do_open:\n f->is_opened = TRUE;\n inode_to_qid(qid, n);\n return 0;\n }\n}\n\nstatic int fs_create(FSDevice *fs, FSQID *qid, FSFile *f, const char *name, \n uint32_t flags, uint32_t mode, uint32_t gid)\n{\n FSINode *n1, *n = f->inode;\n \n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n if (inode_search(n, name)) {\n /* XXX: support it, but Linux does not seem to use this case */\n return -P9_EEXIST;\n } else {\n fs_close(fs, f);\n \n n1 = inode_new(fs, FT_REG, mode, f->uid, gid);\n inode_dir_add(fs, n, name, n1);\n \n inode_dec_open(fs, f->inode);\n f->inode = inode_inc_open(fs, n1);\n f->is_opened = TRUE;\n f->open_flags = flags;\n inode_to_qid(qid, n1);\n return 0;\n }\n}\n\nstatic int fs_readdir(FSDevice *fs, FSFile *f, uint64_t offset1,\n uint8_t *buf, int count)\n{\n FSINode *n1, *n = f->inode;\n int len, pos, name_len, type;\n struct list_head *el;\n FSDirEntry *de;\n uint64_t offset;\n\n if (!f->is_opened || n->type != FT_DIR)\n return -P9_EPROTO;\n \n el = n->u.dir.de_list.next;\n offset = 0;\n while (offset < offset1) {\n if (el == &n->u.dir.de_list)\n return 0; /* no more entries */\n offset++;\n el = el->next;\n }\n \n pos = 0;\n for(;;) {\n if (el == &n->u.dir.de_list)\n break;\n de = list_entry(el, FSDirEntry, link);\n name_len = strlen(de->name);\n len = 13 + 8 + 1 + 2 + name_len;\n if ((pos + len) > count)\n break;\n offset++;\n n1 = de->inode;\n if (n1->type == FT_DIR)\n type = P9_QTDIR;\n else if (n1->type == FT_LNK)\n type = P9_QTSYMLINK;\n else\n type = P9_QTFILE;\n buf[pos++] = type;\n put_le32(buf + pos, 0); /* version */\n pos += 4;\n put_le64(buf + pos, n1->inode_num);\n pos += 8;\n put_le64(buf + pos, offset);\n pos += 8;\n buf[pos++] = n1->type;\n put_le16(buf + pos, name_len);\n pos += 2;\n memcpy(buf + pos, de->name, name_len);\n pos += name_len;\n el = el->next;\n }\n return pos;\n}\n\nstatic int fs_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n FSINode *n = f->inode;\n uint64_t count1;\n\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n if ((f->open_flags & P9_O_NOACCESS) == P9_O_WRONLY)\n return -P9_EIO;\n if (n->u.reg.is_fscmd)\n return fs_cmd_read(fs, f, offset, buf, count);\n if (offset >= n->u.reg.size)\n return 0;\n count1 = n->u.reg.size - offset;\n if (count1 < count)\n count = count1;\n file_buffer_read(&n->u.reg.fbuf, offset, buf, count);\n return count;\n}\n\nstatic int fs_truncate(FSDevice *fs1, FSINode *n, uint64_t size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n intptr_t diff, diff_blocks;\n size_t new_allocated_size;\n \n if (n->type != FT_REG)\n return -P9_EINVAL;\n if (size > UINTPTR_MAX)\n return -P9_ENOSPC;\n diff = size - n->u.reg.size;\n if (diff == 0)\n return 0;\n diff_blocks = to_blocks(fs, size) - to_blocks(fs, n->u.reg.size);\n /* currently cannot resize while loading */\n switch(n->u.reg.state) {\n case REG_STATE_LOADING:\n return -P9_EIO;\n case REG_STATE_UNLOADED:\n if (size == 0) {\n /* now local content */\n n->u.reg.state = REG_STATE_LOCAL;\n }\n break;\n case REG_STATE_LOADED:\n case REG_STATE_LOCAL:\n if (diff > 0) {\n if ((fs->fs_blocks + diff_blocks) > fs->fs_max_blocks)\n return -P9_ENOSPC;\n if (size > n->u.reg.fbuf.allocated_size) {\n new_allocated_size = n->u.reg.fbuf.allocated_size * 5 / 4;\n if (size > new_allocated_size)\n new_allocated_size = size;\n if (file_buffer_resize(&n->u.reg.fbuf, new_allocated_size) < 0)\n return -P9_ENOSPC;\n }\n file_buffer_set(&n->u.reg.fbuf, n->u.reg.size, 0, diff);\n } else {\n new_allocated_size = n->u.reg.fbuf.allocated_size * 4 / 5;\n if (size <= new_allocated_size) {\n if (file_buffer_resize(&n->u.reg.fbuf, new_allocated_size) < 0)\n return -P9_ENOSPC;\n }\n }\n /* file is modified, so it is now local */\n if (n->u.reg.state == REG_STATE_LOADED) {\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n n->u.reg.state = REG_STATE_LOCAL;\n }\n break;\n default:\n abort();\n }\n fs->fs_blocks += diff_blocks;\n assert(fs->fs_blocks >= 0);\n n->u.reg.size = size;\n return 0;\n}\n\nstatic int fs_write(FSDevice *fs1, FSFile *f, uint64_t offset,\n const uint8_t *buf, int count)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n = f->inode;\n uint64_t end;\n int err;\n \n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n if ((f->open_flags & P9_O_NOACCESS) == P9_O_RDONLY)\n return -P9_EIO;\n if (count == 0)\n return 0;\n if (n->u.reg.is_fscmd) {\n return fs_cmd_write(fs1, f, offset, buf, count);\n }\n end = offset + count;\n if (end > n->u.reg.size) {\n err = fs_truncate(fs1, n, end);\n if (err)\n return err;\n }\n inode_update_mtime(fs1, n);\n /* file is modified, so it is now local */\n if (n->u.reg.state == REG_STATE_LOADED) {\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n n->u.reg.state = REG_STATE_LOCAL;\n }\n file_buffer_write(&n->u.reg.fbuf, offset, buf, count);\n return count;\n}\n\nstatic void fs_close(FSDevice *fs, FSFile *f)\n{\n if (f->is_opened) {\n f->is_opened = FALSE;\n }\n if (f->req)\n fs_cmd_close(fs, f);\n}\n\nstatic int fs_stat(FSDevice *fs1, FSFile *f, FSStat *st)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n = f->inode;\n\n inode_to_qid(&st->qid, n);\n st->st_mode = n->mode | (n->type << 12);\n st->st_uid = n->uid;\n st->st_gid = n->gid;\n st->st_nlink = n->refcount;\n if (n->type == FT_BLK || n->type == FT_CHR) {\n /* XXX: check */\n st->st_rdev = (n->u.dev.major << 8) | n->u.dev.minor;\n } else {\n st->st_rdev = 0;\n }\n st->st_blksize = fs->block_size;\n if (n->type == FT_REG) {\n st->st_size = n->u.reg.size;\n } else if (n->type == FT_LNK) {\n st->st_size = strlen(n->u.symlink.name);\n } else if (n->type == FT_DIR) {\n st->st_size = n->u.dir.size;\n } else {\n st->st_size = 0;\n }\n /* in 512 byte blocks */\n st->st_blocks = to_blocks(fs, st->st_size) << (fs->block_size_log2 - 9);\n \n /* Note: atime is not supported */\n st->st_atime_sec = n->mtime_sec;\n st->st_atime_nsec = n->mtime_nsec;\n st->st_mtime_sec = n->mtime_sec;\n st->st_mtime_nsec = n->mtime_nsec;\n st->st_ctime_sec = n->ctime_sec;\n st->st_ctime_nsec = n->ctime_nsec;\n return 0;\n}\n\nstatic int fs_setattr(FSDevice *fs1, FSFile *f, uint32_t mask,\n uint32_t mode, uint32_t uid, uint32_t gid,\n uint64_t size, uint64_t atime_sec, uint64_t atime_nsec,\n uint64_t mtime_sec, uint64_t mtime_nsec)\n{\n FSINode *n = f->inode;\n int ret;\n \n if (mask & P9_SETATTR_MODE) {\n n->mode = mode;\n }\n if (mask & P9_SETATTR_UID) {\n n->uid = uid;\n }\n if (mask & P9_SETATTR_GID) {\n n->gid = gid;\n }\n if (mask & P9_SETATTR_SIZE) {\n ret = fs_truncate(fs1, n, size);\n if (ret)\n return ret;\n }\n if (mask & P9_SETATTR_MTIME) {\n if (mask & P9_SETATTR_MTIME_SET) {\n n->mtime_sec = mtime_sec;\n n->mtime_nsec = mtime_nsec;\n } else {\n inode_update_mtime(fs1, n);\n }\n }\n if (mask & P9_SETATTR_CTIME) {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n n->ctime_sec = tv.tv_sec;\n n->ctime_nsec = tv.tv_usec * 1000;\n }\n return 0;\n}\n\nstatic int fs_link(FSDevice *fs, FSFile *df, FSFile *f, const char *name)\n{\n FSINode *n = df->inode;\n \n if (f->inode->type == FT_DIR)\n return -P9_EPERM;\n if (inode_search(n, name))\n return -P9_EEXIST;\n inode_dir_add(fs, n, name, inode_incref(fs, f->inode));\n return 0;\n}\n\nstatic int fs_symlink(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, const char *symgt, uint32_t gid)\n{\n FSINode *n1, *n = f->inode;\n \n if (inode_search(n, name))\n return -P9_EEXIST;\n\n n1 = inode_new(fs, FT_LNK, 0777, f->uid, gid);\n n1->u.symlink.name = strdup(symgt);\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\nstatic int fs_mknod(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, uint32_t mode, uint32_t major,\n uint32_t minor, uint32_t gid)\n{\n int type;\n FSINode *n1, *n = f->inode;\n\n type = (mode & P9_S_IFMT) >> 12;\n /* XXX: add FT_DIR support */\n if (type != FT_FIFO && type != FT_CHR && type != FT_BLK &&\n type != FT_REG && type != FT_SOCK)\n return -P9_EINVAL;\n if (inode_search(n, name))\n return -P9_EEXIST;\n n1 = inode_new(fs, type, mode, f->uid, gid);\n if (type == FT_CHR || type == FT_BLK) {\n n1->u.dev.major = major;\n n1->u.dev.minor = minor;\n }\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\nstatic int fs_readlink(FSDevice *fs, char *buf, int buf_size, FSFile *f)\n{\n FSINode *n = f->inode;\n int len;\n if (n->type != FT_LNK)\n return -P9_EIO;\n len = min_int(strlen(n->u.symlink.name), buf_size - 1);\n memcpy(buf, n->u.symlink.name, len);\n buf[len] = '\\0';\n return 0;\n}\n\nstatic int fs_renameat(FSDevice *fs, FSFile *f, const char *name, \n FSFile *new_f, const char *new_name)\n{\n FSDirEntry *de, *de1;\n FSINode *n1;\n \n de = inode_search(f->inode, name);\n if (!de)\n return -P9_ENOENT;\n de1 = inode_search(new_f->inode, new_name);\n n1 = NULL;\n if (de1) {\n n1 = de1->inode;\n if (n1->type == FT_DIR)\n return -P9_EEXIST; /* XXX: handle the case */\n inode_dirent_delete_no_decref(fs, new_f->inode, de1);\n }\n inode_dir_add(fs, new_f->inode, new_name, inode_incref(fs, de->inode));\n inode_dirent_delete(fs, f->inode, de);\n if (n1)\n inode_decref(fs, n1);\n return 0;\n}\n\nstatic int fs_unlinkat(FSDevice *fs, FSFile *f, const char *name)\n{\n FSDirEntry *de;\n FSINode *n;\n\n if (!strcmp(name, \".\") || !strcmp(name, \"..\"))\n return -P9_ENOENT;\n de = inode_search(f->inode, name);\n if (!de)\n return -P9_ENOENT;\n n = de->inode;\n if (n->type == FT_DIR) {\n if (!is_empty_dir(fs, n))\n return -P9_ENOTEMPTY;\n flush_dir(fs, n);\n }\n inode_dirent_delete(fs, f->inode, de);\n return 0;\n}\n\nstatic int fs_lock(FSDevice *fs, FSFile *f, const FSLock *lock)\n{\n FSINode *n = f->inode;\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n /* XXX: implement it */\n return P9_LOCK_SUCCESS;\n}\n\nstatic int fs_getlock(FSDevice *fs, FSFile *f, FSLock *lock)\n{\n FSINode *n = f->inode;\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n /* XXX: implement it */\n return 0;\n}\n\n/* XXX: only used with file lists, so not all the data is released */\nstatic void fs_mem_end(FSDevice *fs1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el, *el1, *el2, *el3;\n FSINode *n;\n FSDirEntry *de;\n\n list_for_each_safe(el, el1, &fs->inode_list) {\n n = list_entry(el, FSINode, link);\n n->refcount = 0;\n if (n->type == FT_DIR) {\n list_for_each_safe(el2, el3, &n->u.dir.de_list) {\n de = list_entry(el2, FSDirEntry, link);\n list_del(&de->link);\n free(de);\n }\n init_list_head(&n->u.dir.de_list);\n }\n inode_free(fs1, n);\n }\n assert(list_empty(&fs->inode_cache_list));\n free(fs->import_dir);\n}\n\nFSDevice *fs_mem_init(void)\n{\n FSDeviceMem *fs;\n FSDevice *fs1;\n FSINode *n;\n\n fs = mallocz(sizeof(*fs));\n fs1 = &fs->common;\n\n fs->common.fs_end = fs_mem_end;\n fs->common.fs_delete = fs_delete;\n fs->common.fs_statfs = fs_statfs;\n fs->common.fs_attach = fs_attach;\n fs->common.fs_walk = fs_walk;\n fs->common.fs_mkdir = fs_mkdir;\n fs->common.fs_open = fs_open;\n fs->common.fs_create = fs_create;\n fs->common.fs_stat = fs_stat;\n fs->common.fs_setattr = fs_setattr;\n fs->common.fs_close = fs_close;\n fs->common.fs_readdir = fs_readdir;\n fs->common.fs_read = fs_read;\n fs->common.fs_write = fs_write;\n fs->common.fs_link = fs_link;\n fs->common.fs_symlink = fs_symlink;\n fs->common.fs_mknod = fs_mknod;\n fs->common.fs_readlink = fs_readlink;\n fs->common.fs_renameat = fs_renameat;\n fs->common.fs_unlinkat = fs_unlinkat;\n fs->common.fs_lock = fs_lock;\n fs->common.fs_getlock = fs_getlock;\n\n init_list_head(&fs->inode_list);\n fs->inode_num_alloc = 1;\n fs->block_size_log2 = FS_BLOCK_SIZE_LOG2;\n fs->block_size = 1 << fs->block_size_log2;\n fs->inode_limit = 1 << 20; /* arbitrary */\n fs->fs_max_blocks = 1 << (30 - fs->block_size_log2); /* arbitrary */\n\n init_list_head(&fs->inode_cache_list);\n fs->inode_cache_size_limit = DEFAULT_INODE_CACHE_SIZE;\n\n init_list_head(&fs->preload_list);\n init_list_head(&fs->preload_archive_list);\n\n init_list_head(&fs->base_url_list);\n\n /* create the root inode */\n n = inode_new(fs1, FT_DIR, 0777, 0, 0);\n inode_dir_add(fs1, n, \".\", inode_incref(fs1, n));\n inode_dir_add(fs1, n, \"..\", inode_incref(fs1, n));\n fs->root_inode = n;\n\n return (FSDevice *)fs;\n}\n\nstatic BOOL fs_is_net(FSDevice *fs)\n{\n return (fs->fs_end == fs_mem_end);\n}\n\nstatic FSBaseURL *fs_find_base_url(FSDevice *fs1,\n const char *base_url_id)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el;\n FSBaseURL *bu;\n \n list_for_each(el, &fs->base_url_list) {\n bu = list_entry(el, FSBaseURL, link);\n if (!strcmp(bu->base_url_id, base_url_id))\n return bu;\n }\n return NULL;\n}\n\nstatic void fs_base_url_decref(FSDevice *fs, FSBaseURL *bu)\n{\n assert(bu->ref_count >= 1);\n if (--bu->ref_count == 0) {\n free(bu->base_url_id);\n free(bu->url);\n free(bu->user);\n free(bu->password);\n list_del(&bu->link);\n free(bu);\n }\n}\n\nstatic FSBaseURL *fs_net_set_base_url(FSDevice *fs1,\n const char *base_url_id,\n const char *url,\n const char *user, const char *password,\n AES_KEY *aes_state)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSBaseURL *bu;\n \n assert(fs_is_net(fs1));\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu) {\n bu = mallocz(sizeof(*bu));\n bu->base_url_id = strdup(base_url_id);\n bu->ref_count = 1;\n list_add_tail(&bu->link, &fs->base_url_list);\n } else {\n free(bu->url);\n free(bu->user);\n free(bu->password);\n }\n\n bu->url = strdup(url);\n if (user)\n bu->user = strdup(user);\n else\n bu->user = NULL;\n if (password)\n bu->password = strdup(password);\n else\n bu->password = NULL;\n if (aes_state) {\n bu->encrypted = TRUE;\n bu->aes_state = *aes_state;\n } else {\n bu->encrypted = FALSE;\n }\n return bu;\n}\n\nstatic int fs_net_reset_base_url(FSDevice *fs1,\n const char *base_url_id)\n{\n FSBaseURL *bu;\n \n assert(fs_is_net(fs1));\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu)\n return -P9_ENOENT;\n fs_base_url_decref(fs1, bu);\n return 0;\n}\n\nstatic void fs_net_set_fs_max_size(FSDevice *fs1, uint64_t fs_max_size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n assert(fs_is_net(fs1));\n fs->fs_max_blocks = to_blocks(fs, fs_max_size);\n}\n\nstatic int fs_net_set_url(FSDevice *fs1, FSINode *n,\n const char *base_url_id, FSFileID file_id, uint64_t size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSBaseURL *bu;\n\n assert(fs_is_net(fs1));\n\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu)\n return -P9_ENOENT;\n\n /* XXX: could accept more state */\n if (n->type != FT_REG ||\n n->u.reg.state != REG_STATE_LOCAL ||\n n->u.reg.fbuf.allocated_size != 0)\n return -P9_EIO;\n \n if (size > 0) {\n n->u.reg.state = REG_STATE_UNLOADED;\n n->u.reg.base_url = bu;\n bu->ref_count++;\n n->u.reg.size = size;\n fs->fs_blocks += to_blocks(fs, size);\n n->u.reg.file_id = file_id;\n }\n return 0;\n}\n\n#ifdef DUMP_CACHE_LOAD\n\n#include \"json.h\"\n\n#define ARCHIVE_SIZE_MAX (4 << 20)\n\nstatic void fs_dump_add_file(struct list_head *head, const char *name)\n{\n PreloadFile *pf;\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(name);\n list_add_tail(&pf->link, head);\n}\n\nstatic PreloadFile *fs_dump_find_file(struct list_head *head, const char *name)\n{\n PreloadFile *pf;\n struct list_head *el;\n list_for_each(el, head) {\n pf = list_entry(el, PreloadFile, link);\n if (!strcmp(pf->name, name))\n return pf;\n }\n return NULL;\n}\n\nstatic void dump_close_archive(FSDevice *fs1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (fs->dump_archive_file) {\n fclose(fs->dump_archive_file);\n }\n fs->dump_archive_file = NULL;\n fs->dump_archive_size = 0;\n}\n\nstatic void dump_loaded_file(FSDevice *fs1, FSINode *n)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char filename[1024];\n const char *fname, *p;\n \n if (!fs->dump_cache_load || !n->u.reg.filename)\n return;\n fname = n->u.reg.filename;\n \n if (fs_dump_find_file(&fs->dump_preload_list, fname)) {\n dump_close_archive(fs1);\n p = strrchr(fname, '/');\n if (!p)\n p = fname;\n else\n p++;\n free(fs->dump_archive_name);\n fs->dump_archive_name = strdup(p);\n fs->dump_started = TRUE;\n fs->dump_archive_num = 0;\n\n fprintf(fs->dump_preload_file, \"\\n%s :\\n\", fname);\n }\n if (!fs->dump_started)\n return;\n \n if (!fs->dump_archive_file) {\n snprintf(filename, sizeof(filename), \"%s/%s%d\",\n fs->dump_preload_dir, fs->dump_archive_name,\n fs->dump_archive_num);\n fs->dump_archive_file = fopen(filename, \"wb\");\n if (!fs->dump_archive_file) {\n perror(filename);\n exit(1);\n }\n fprintf(fs->dump_preload_archive_file, \"\\n@.preload2/%s%d :\\n\",\n fs->dump_archive_name, fs->dump_archive_num);\n fprintf(fs->dump_preload_file, \" @.preload2/%s%d\\n\",\n fs->dump_archive_name, fs->dump_archive_num);\n fflush(fs->dump_preload_file);\n fs->dump_archive_num++;\n }\n\n if (n->u.reg.size >= ARCHIVE_SIZE_MAX) {\n /* exclude large files from archive */\n /* add indicative size */\n fprintf(fs->dump_preload_file, \" %s %\" PRId64 \"\\n\",\n fname, n->u.reg.size);\n fflush(fs->dump_preload_file);\n } else {\n fprintf(fs->dump_preload_archive_file, \" %s %\" PRId64 \" %\" PRIx64 \"\\n\",\n n->u.reg.filename, n->u.reg.size, n->u.reg.file_id);\n fflush(fs->dump_preload_archive_file);\n fwrite(n->u.reg.fbuf.data, 1, n->u.reg.size, fs->dump_archive_file);\n fflush(fs->dump_archive_file);\n fs->dump_archive_size += n->u.reg.size;\n if (fs->dump_archive_size >= ARCHIVE_SIZE_MAX) {\n dump_close_archive(fs1);\n }\n }\n}\n\nstatic JSONValue json_load(const char *filename)\n{\n FILE *f;\n JSONValue val;\n size_t size;\n char *buf;\n \n f = fopen(filename, \"rb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n size = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = malloc(size + 1);\n fread(buf, 1, size, f);\n fclose(f);\n val = json_parse_value_len(buf, size);\n free(buf);\n return val;\n}\n\nvoid fs_dump_cache_load(FSDevice *fs1, const char *cfg_filename)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n JSONValue cfg, val, array;\n char *fname;\n const char *preload_dir, *name;\n int i;\n \n if (!fs_is_net(fs1))\n return;\n cfg = json_load(cfg_filename);\n if (json_is_error(cfg)) {\n fprintf(stderr, \"%s\\n\", json_get_error(cfg));\n exit(1);\n }\n\n val = json_object_get(cfg, \"preload_dir\");\n if (json_is_undefined(cfg)) {\n config_error:\n exit(1);\n }\n preload_dir = json_get_str(val);\n if (!preload_dir) {\n fprintf(stderr, \"expecting preload_filename\\n\");\n goto config_error;\n }\n fs->dump_preload_dir = strdup(preload_dir);\n \n init_list_head(&fs->dump_preload_list);\n init_list_head(&fs->dump_exclude_list);\n\n array = json_object_get(cfg, \"preload\");\n if (array.type != JSON_ARRAY) {\n fprintf(stderr, \"expecting preload array\\n\");\n goto config_error;\n }\n for(i = 0; i < array.u.array->len; i++) {\n val = json_array_get(array, i);\n name = json_get_str(val);\n if (!name) {\n fprintf(stderr, \"expecting a string\\n\");\n goto config_error;\n }\n fs_dump_add_file(&fs->dump_preload_list, name);\n }\n json_free(cfg);\n\n fname = compose_path(fs->dump_preload_dir, \"preload.txt\");\n fs->dump_preload_file = fopen(fname, \"w\");\n if (!fs->dump_preload_file) {\n perror(fname);\n exit(1);\n }\n free(fname);\n\n fname = compose_path(fs->dump_preload_dir, \"preload_archive.txt\");\n fs->dump_preload_archive_file = fopen(fname, \"w\");\n if (!fs->dump_preload_archive_file) {\n perror(fname);\n exit(1);\n }\n free(fname);\n\n fs->dump_cache_load = TRUE;\n}\n#else\nvoid fs_dump_cache_load(FSDevice *fs1, const char *cfg_filename)\n{\n}\n#endif\n\n/***********************************************/\n/* file list processing */\n\nstatic int filelist_load_rec(FSDevice *fs1, const char **pp, FSINode *dir,\n const char *path)\n{\n // FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char fname[1024], lname[1024];\n int ret;\n const char *p;\n FSINodeTypeEnum type;\n uint32_t mode, uid, gid;\n uint64_t size;\n FSINode *n;\n\n p = *pp;\n for(;;) {\n /* skip comments or empty lines */\n if (*p == '\\0')\n break;\n if (*p == '#') {\n skip_line(&p);\n continue;\n }\n /* end of directory */\n if (*p == '.') {\n p++;\n skip_line(&p);\n break;\n }\n if (parse_uint32_base(&mode, &p, 8) < 0) {\n fprintf(stderr, \"invalid mode\\n\");\n return -1;\n }\n type = mode >> 12;\n mode &= 0xfff;\n \n if (parse_uint32(&uid, &p) < 0) {\n fprintf(stderr, \"invalid uid\\n\");\n return -1;\n }\n\n if (parse_uint32(&gid, &p) < 0) {\n fprintf(stderr, \"invalid gid\\n\");\n return -1;\n }\n\n n = inode_new(fs1, type, mode, uid, gid);\n \n size = 0;\n switch(type) {\n case FT_CHR:\n case FT_BLK:\n if (parse_uint32(&n->u.dev.major, &p) < 0) {\n fprintf(stderr, \"invalid major\\n\");\n return -1;\n }\n if (parse_uint32(&n->u.dev.minor, &p) < 0) {\n fprintf(stderr, \"invalid minor\\n\");\n return -1;\n }\n break;\n case FT_REG:\n if (parse_uint64(&size, &p) < 0) {\n fprintf(stderr, \"invalid size\\n\");\n return -1;\n }\n break;\n case FT_DIR:\n inode_dir_add(fs1, n, \".\", inode_incref(fs1, n));\n inode_dir_add(fs1, n, \"..\", inode_incref(fs1, dir));\n break;\n default:\n break;\n }\n \n /* modification time */\n if (parse_time(&n->mtime_sec, &n->mtime_nsec, &p) < 0) {\n fprintf(stderr, \"invalid mtime\\n\");\n return -1;\n }\n\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return -1;\n }\n inode_dir_add(fs1, dir, fname, n);\n \n if (type == FT_LNK) {\n if (parse_fname(lname, sizeof(lname), &p) < 0) {\n fprintf(stderr, \"invalid symlink name\\n\");\n return -1;\n }\n n->u.symlink.name = strdup(lname);\n } else if (type == FT_REG && size > 0) {\n FSFileID file_id;\n if (parse_file_id(&file_id, &p) < 0) {\n fprintf(stderr, \"invalid file id\\n\");\n return -1;\n }\n fs_net_set_url(fs1, n, \"/\", file_id, size);\n#ifdef DUMP_CACHE_LOAD\n {\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (fs->dump_cache_load\n#ifdef DEBUG_CACHE\n || 1\n#endif\n ) {\n n->u.reg.filename = compose_path(path, fname);\n } else {\n n->u.reg.filename = NULL;\n }\n }\n#endif\n }\n\n skip_line(&p);\n \n if (type == FT_DIR) {\n char *path1;\n path1 = compose_path(path, fname);\n ret = filelist_load_rec(fs1, &p, n, path1);\n free(path1);\n if (ret)\n return ret;\n }\n }\n *pp = p;\n return 0;\n}\n\nstatic int filelist_load(FSDevice *fs1, const char *str)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int ret;\n const char *p;\n \n if (parse_tag_version(str) != 1)\n return -1;\n p = skip_header(str);\n if (!p)\n return -1;\n ret = filelist_load_rec(fs1, &p, fs->root_inode, \"\");\n return ret;\n}\n\n/************************************************************/\n/* FS init from network */\n\nstatic void __attribute__((format(printf, 1, 2))) fatal_error(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n fprintf(stderr, \"Error: \");\n vfprintf(stderr, fmt, ap);\n fprintf(stderr, \"\\n\");\n va_end(ap);\n exit(1);\n}\n\nstatic void fs_create_cmd(FSDevice *fs)\n{\n FSFile *root_fd;\n FSQID qid;\n FSINode *n;\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\"));\n assert(!fs->fs_create(fs, &qid, root_fd, FSCMD_NAME, P9_O_RDWR | P9_O_TRUNC,\n 0666, 0));\n n = root_fd->inode;\n n->u.reg.is_fscmd = TRUE;\n fs->fs_delete(fs, root_fd);\n}\n\ntypedef struct {\n FSDevice *fs;\n char *url;\n void (*start_cb)(void *opaque);\n void *start_opaque;\n \n FSFile *root_fd;\n FSFile *fd;\n int file_index;\n \n} FSNetInitState;\n\nstatic void fs_initial_sync(FSDevice *fs,\n const char *url, void (*start_cb)(void *opaque),\n void *start_opaque);\nstatic void head_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque);\nstatic void filelist_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque);\nstatic void kernel_load_cb(FSDevice *fs, FSQID *qid, int err,\n void *opaque);\nstatic int preload_parse(FSDevice *fs, const char *fname, BOOL is_new);\n\n#ifdef EMSCRIPTEN\nstatic FSDevice *fs_import_fs;\n#endif\n\n#define DEFAULT_IMPORT_FILE_PATH \"/tmp\"\n\nFSDevice *fs_net_init(const char *url, void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n FSDevice *fs;\n FSDeviceMem *fs1;\n \n fs_wget_init();\n \n fs = fs_mem_init();\n#ifdef EMSCRIPTEN\n if (!fs_import_fs)\n fs_import_fs = fs;\n#endif\n fs1 = (FSDeviceMem *)fs;\n fs1->import_dir = strdup(DEFAULT_IMPORT_FILE_PATH);\n \n fs_create_cmd(fs);\n\n if (url) {\n fs_initial_sync(fs, url, start_cb, start_opaque);\n }\n return fs;\n}\n\nstatic void fs_initial_sync(FSDevice *fs,\n const char *url, void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n FSNetInitState *s;\n FSFile *head_fd;\n FSQID qid;\n char *head_url;\n char buf[128];\n struct timeval tv;\n \n s = mallocz(sizeof(*s));\n s->fs = fs;\n s->url = strdup(url);\n s->start_cb = start_cb;\n s->start_opaque = start_opaque;\n assert(!fs->fs_attach(fs, &s->root_fd, &qid, 0, \"\", \"\"));\n \n /* avoid using cached version */\n gettimeofday(&tv, NULL);\n snprintf(buf, sizeof(buf), HEAD_FILENAME \"?nocache=%\" PRId64,\n (int64_t)tv.tv_sec * 1000000 + tv.tv_usec);\n head_url = compose_url(s->url, buf);\n head_fd = fs_dup(fs, s->root_fd);\n assert(!fs->fs_create(fs, &qid, head_fd, \".head\",\n P9_O_RDWR | P9_O_TRUNC, 0644, 0));\n fs_wget_file2(fs, head_fd, head_url, NULL, NULL, NULL, 0,\n head_loaded, s, NULL);\n free(head_url);\n}\n\nstatic void head_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque)\n{\n FSNetInitState *s = opaque;\n char *buf, *root_url, *url;\n char fname[FILEID_SIZE_MAX];\n FSFileID root_id;\n FSFile *new_filelist_fd;\n FSQID qid;\n uint64_t fs_max_size;\n \n if (size < 0)\n fatal_error(\"could not load 'head' file (HTTP error=%d)\", -(int)size);\n \n buf = malloc(size + 1);\n fs->fs_read(fs, f, 0, (uint8_t *)buf, size);\n buf[size] = '\\0';\n fs->fs_delete(fs, f);\n fs->fs_unlinkat(fs, s->root_fd, \".head\");\n\n if (parse_tag_version(buf) != 1)\n fatal_error(\"invalid head version\");\n\n if (parse_tag_file_id(&root_id, buf, \"RootID\") < 0)\n fatal_error(\"expected RootID tag\");\n\n if (parse_tag_uint64(&fs_max_size, buf, \"FSMaxSize\") == 0 &&\n fs_max_size >= ((uint64_t)1 << 20)) {\n fs_net_set_fs_max_size(fs, fs_max_size);\n }\n \n /* set the Root URL in the filesystem */\n root_url = compose_url(s->url, ROOT_FILENAME);\n fs_net_set_base_url(fs, \"/\", root_url, NULL, NULL, NULL);\n \n new_filelist_fd = fs_dup(fs, s->root_fd);\n assert(!fs->fs_create(fs, &qid, new_filelist_fd, \".filelist.txt\",\n P9_O_RDWR | P9_O_TRUNC, 0644, 0));\n\n file_id_to_filename(fname, root_id);\n url = compose_url(root_url, fname);\n fs_wget_file2(fs, new_filelist_fd, url, NULL, NULL, NULL, 0,\n filelist_loaded, s, NULL);\n free(root_url);\n free(url);\n}\n\nstatic void filelist_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque)\n{\n FSNetInitState *s = opaque;\n uint8_t *buf;\n\n if (size < 0)\n fatal_error(\"could not load file list (HTTP error=%d)\", -(int)size);\n \n buf = malloc(size + 1);\n fs->fs_read(fs, f, 0, buf, size);\n buf[size] = '\\0';\n fs->fs_delete(fs, f);\n fs->fs_unlinkat(fs, s->root_fd, \".filelist.txt\");\n \n if (filelist_load(fs, (char *)buf) != 0)\n fatal_error(\"error while parsing file list\");\n\n /* try to load the kernel and the preload file */\n s->file_index = 0;\n kernel_load_cb(fs, NULL, 0, s);\n}\n\n\n#define FILE_LOAD_COUNT 2\n\nstatic const char *kernel_file_list[FILE_LOAD_COUNT] = {\n \".preload\",\n \".preload2/preload.txt\",\n};\n\nstatic void kernel_load_cb(FSDevice *fs, FSQID *qid1, int err,\n void *opaque)\n{\n FSNetInitState *s = opaque;\n FSQID qid;\n\n#ifdef DUMP_CACHE_LOAD\n /* disable preloading if dumping cache load */\n if (((FSDeviceMem *)fs)->dump_cache_load)\n return;\n#endif\n\n if (s->fd) {\n fs->fs_delete(fs, s->fd);\n s->fd = NULL;\n }\n \n if (s->file_index >= FILE_LOAD_COUNT) {\n /* all files are loaded */\n if (preload_parse(fs, \".preload2/preload.txt\", TRUE) < 0) { \n preload_parse(fs, \".preload\", FALSE);\n }\n fs->fs_delete(fs, s->root_fd);\n if (s->start_cb)\n s->start_cb(s->start_opaque);\n free(s);\n } else {\n s->fd = fs_walk_path(fs, s->root_fd, kernel_file_list[s->file_index++]);\n if (!s->fd)\n goto done;\n err = fs->fs_open(fs, &qid, s->fd, P9_O_RDONLY, kernel_load_cb, s);\n if (err <= 0) {\n done:\n kernel_load_cb(fs, NULL, 0, s);\n }\n }\n}\n\nstatic void preload_parse_str_old(FSDevice *fs1, const char *p)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char fname[1024];\n PreloadEntry *pe;\n PreloadFile *pf;\n FSINode *n;\n\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\n') {\n p++;\n continue;\n }\n if (*p == '\\0')\n break;\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n // printf(\"preload file='%s\\n\", fname);\n n = inode_search_path(fs1, fname);\n if (!n || n->type != FT_REG || n->u.reg.state == REG_STATE_LOCAL) {\n fprintf(stderr, \"invalid preload file: '%s'\\n\", fname);\n while (*p != '\\n' && *p != '\\0')\n p++;\n } else {\n pe = mallocz(sizeof(*pe));\n pe->file_id = n->u.reg.file_id;\n init_list_head(&pe->file_list);\n list_add_tail(&pe->link, &fs->preload_list);\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\0' || *p == '\\n')\n break;\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n // printf(\" adding '%s'\\n\", fname);\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(fname);\n list_add_tail(&pf->link, &pe->file_list); \n }\n }\n }\n}\n\nstatic void preload_parse_str(FSDevice *fs1, const char *p)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n PreloadEntry *pe;\n PreloadArchive *pa;\n FSINode *n;\n BOOL is_archive;\n char fname[1024];\n \n pe = NULL;\n pa = NULL;\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\n') {\n pe = NULL;\n p++;\n continue;\n }\n if (*p == '#')\n continue; /* comment */\n if (*p == '\\0')\n break;\n\n is_archive = FALSE;\n if (*p == '@') {\n is_archive = TRUE;\n p++;\n }\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n while (isspace_nolf(*p))\n p++;\n if (*p == ':') {\n p++;\n // printf(\"preload file='%s' archive=%d\\n\", fname, is_archive);\n n = inode_search_path(fs1, fname);\n pe = NULL;\n pa = NULL;\n if (!n || n->type != FT_REG || n->u.reg.state == REG_STATE_LOCAL) {\n fprintf(stderr, \"invalid preload file: '%s'\\n\", fname);\n while (*p != '\\n' && *p != '\\0')\n p++;\n } else if (is_archive) {\n pa = mallocz(sizeof(*pa));\n pa->name = strdup(fname);\n init_list_head(&pa->file_list);\n list_add_tail(&pa->link, &fs->preload_archive_list);\n } else {\n pe = mallocz(sizeof(*pe));\n pe->file_id = n->u.reg.file_id;\n init_list_head(&pe->file_list);\n list_add_tail(&pe->link, &fs->preload_list);\n }\n } else {\n if (!pe && !pa) {\n fprintf(stderr, \"filename without target: %s\\n\", fname);\n return;\n }\n if (pa) {\n PreloadArchiveFile *paf;\n FSFileID file_id;\n uint64_t size;\n\n if (parse_uint64(&size, &p) < 0) {\n fprintf(stderr, \"invalid size\\n\");\n return;\n }\n\n if (parse_file_id(&file_id, &p) < 0) {\n fprintf(stderr, \"invalid file id\\n\");\n return;\n }\n\n paf = mallocz(sizeof(*paf));\n paf->name = strdup(fname);\n paf->file_id = file_id;\n paf->size = size;\n list_add_tail(&paf->link, &pa->file_list);\n } else {\n PreloadFile *pf;\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(fname);\n pf->is_archive = is_archive;\n list_add_tail(&pf->link, &pe->file_list);\n }\n }\n /* skip the rest of the line */\n while (*p != '\\n' && *p != '\\0')\n p++;\n if (*p == '\\n')\n p++;\n }\n}\n\nstatic int preload_parse(FSDevice *fs, const char *fname, BOOL is_new)\n{\n FSINode *n;\n char *buf;\n size_t size;\n \n n = inode_search_path(fs, fname);\n if (!n || n->type != FT_REG || n->u.reg.state != REG_STATE_LOADED)\n return -1;\n /* transform to zero terminated string */\n size = n->u.reg.size;\n buf = malloc(size + 1);\n file_buffer_read(&n->u.reg.fbuf, 0, (uint8_t *)buf, size);\n buf[size] = '\\0';\n if (is_new)\n preload_parse_str(fs, buf);\n else\n preload_parse_str_old(fs, buf);\n free(buf);\n return 0;\n}\n\n\n\n/************************************************************/\n/* FS user interface */\n\ntypedef struct CmdXHRState {\n FSFile *req_fd;\n FSFile *root_fd;\n FSFile *fd;\n FSFile *post_fd;\n AES_KEY aes_state;\n} CmdXHRState;\n\nstatic void fs_cmd_xhr_on_load(FSDevice *fs, FSFile *f, int64_t size,\n void *opaque);\n\nstatic int parse_hex_buf(uint8_t *buf, int buf_size, const char **pp)\n{\n char buf1[1024];\n int len;\n \n if (parse_fname(buf1, sizeof(buf1), pp) < 0)\n return -1;\n len = strlen(buf1);\n if ((len & 1) != 0)\n return -1;\n len >>= 1;\n if (len > buf_size)\n return -1;\n if (decode_hex(buf, buf1, len) < 0)\n return -1;\n return len;\n}\n\nstatic int fs_cmd_xhr(FSDevice *fs, FSFile *f,\n const char *p, uint32_t uid, uint32_t gid)\n{\n char url[1024], post_filename[1024], filename[1024];\n char user_buf[128], *user;\n char password_buf[128], *password;\n FSQID qid;\n FSFile *fd, *root_fd, *post_fd;\n uint64_t post_data_len;\n int err, aes_key_len;\n CmdXHRState *s;\n char *name;\n AES_KEY *paes_state;\n uint8_t aes_key[FS_KEY_LEN];\n uint32_t flags;\n FSCMDRequest *req;\n\n /* a request is already done or in progress */\n if (f->req != NULL)\n return -P9_EIO;\n\n if (parse_fname(url, sizeof(url), &p) < 0)\n goto fail;\n if (parse_fname(user_buf, sizeof(user_buf), &p) < 0)\n goto fail;\n if (parse_fname(password_buf, sizeof(password_buf), &p) < 0)\n goto fail;\n if (parse_fname(post_filename, sizeof(post_filename), &p) < 0)\n goto fail;\n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n aes_key_len = parse_hex_buf(aes_key, FS_KEY_LEN, &p);\n if (aes_key_len < 0)\n goto fail;\n if (parse_uint32(&flags, &p) < 0)\n goto fail;\n if (aes_key_len != 0 && aes_key_len != FS_KEY_LEN)\n goto fail;\n\n if (user_buf[0] != '\\0')\n user = user_buf;\n else\n user = NULL;\n if (password_buf[0] != '\\0')\n password = password_buf;\n else\n password = NULL;\n\n // printf(\"url='%s' '%s' '%s' filename='%s'\\n\", url, user, password, filename);\n assert(!fs->fs_attach(fs, &root_fd, &qid, uid, \"\", \"\"));\n post_fd = NULL;\n\n fd = fs_walk_path1(fs, root_fd, filename, &name);\n if (!fd) {\n err = -P9_ENOENT;\n goto fail1;\n }\n /* XXX: until fs_create is fixed */\n fs->fs_unlinkat(fs, fd, name);\n\n err = fs->fs_create(fs, &qid, fd, name,\n P9_O_RDWR | P9_O_TRUNC, 0600, gid);\n if (err < 0) {\n goto fail1;\n }\n\n if (post_filename[0] != '\\0') {\n FSINode *n;\n \n post_fd = fs_walk_path(fs, root_fd, post_filename);\n if (!post_fd) {\n err = -P9_ENOENT;\n goto fail1;\n }\n err = fs->fs_open(fs, &qid, post_fd, P9_O_RDONLY, NULL, NULL);\n if (err < 0)\n goto fail1;\n n = post_fd->inode;\n assert(n->type == FT_REG && n->u.reg.state == REG_STATE_LOCAL);\n post_data_len = n->u.reg.size;\n } else {\n post_data_len = 0;\n }\n\n s = mallocz(sizeof(*s));\n s->root_fd = root_fd;\n s->fd = fd;\n s->post_fd = post_fd;\n if (aes_key_len != 0) {\n AES_set_decrypt_key(aes_key, FS_KEY_LEN * 8, &s->aes_state);\n paes_state = &s->aes_state;\n } else {\n paes_state = NULL;\n }\n\n req = mallocz(sizeof(*req));\n req->type = FS_CMD_XHR;\n req->reply_len = 0;\n req->xhr_state = s;\n s->req_fd = f;\n f->req = req;\n \n fs_wget_file2(fs, fd, url, user, password, post_fd, post_data_len,\n fs_cmd_xhr_on_load, s, paes_state);\n return 0;\n fail1:\n if (fd)\n fs->fs_delete(fs, fd);\n if (post_fd)\n fs->fs_delete(fs, post_fd);\n fs->fs_delete(fs, root_fd);\n return err;\n fail:\n return -P9_EIO;\n}\n\nstatic void fs_cmd_xhr_on_load(FSDevice *fs, FSFile *f, int64_t size,\n void *opaque)\n{\n CmdXHRState *s = opaque;\n FSCMDRequest *req;\n int ret;\n \n // printf(\"fs_cmd_xhr_on_load: size=%d\\n\", (int)size);\n\n if (s->fd)\n fs->fs_delete(fs, s->fd);\n if (s->post_fd)\n fs->fs_delete(fs, s->post_fd);\n fs->fs_delete(fs, s->root_fd);\n \n if (s->req_fd) {\n req = s->req_fd->req;\n if (size < 0) {\n ret = size;\n } else {\n ret = 0;\n }\n put_le32(req->reply_buf, ret);\n req->reply_len = sizeof(ret);\n req->xhr_state = NULL;\n }\n free(s);\n}\n\nstatic int fs_cmd_set_base_url(FSDevice *fs, const char *p)\n{\n // FSDeviceMem *fs1 = (FSDeviceMem *)fs;\n char url[1024], base_url_id[1024];\n char user_buf[128], *user;\n char password_buf[128], *password;\n AES_KEY aes_state, *paes_state;\n uint8_t aes_key[FS_KEY_LEN];\n int aes_key_len;\n \n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n if (parse_fname(url, sizeof(url), &p) < 0)\n goto fail;\n if (parse_fname(user_buf, sizeof(user_buf), &p) < 0)\n goto fail;\n if (parse_fname(password_buf, sizeof(password_buf), &p) < 0)\n goto fail;\n aes_key_len = parse_hex_buf(aes_key, FS_KEY_LEN, &p);\n if (aes_key_len < 0)\n goto fail;\n\n if (user_buf[0] != '\\0')\n user = user_buf;\n else\n user = NULL;\n if (password_buf[0] != '\\0')\n password = password_buf;\n else\n password = NULL;\n\n if (aes_key_len != 0) {\n if (aes_key_len != FS_KEY_LEN)\n goto fail;\n AES_set_decrypt_key(aes_key, FS_KEY_LEN * 8, &aes_state);\n paes_state = &aes_state;\n } else {\n paes_state = NULL;\n }\n\n fs_net_set_base_url(fs, base_url_id, url, user, password,\n paes_state);\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_reset_base_url(FSDevice *fs, const char *p)\n{\n char base_url_id[1024];\n \n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n fs_net_reset_base_url(fs, base_url_id);\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_set_url(FSDevice *fs, const char *p)\n{\n char base_url_id[1024];\n char filename[1024];\n FSFileID file_id;\n uint64_t size;\n FSINode *n;\n \n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n if (parse_file_id(&file_id, &p) < 0)\n goto fail;\n if (parse_uint64(&size, &p) < 0)\n goto fail;\n \n n = inode_search_path(fs, filename);\n if (!n) {\n return -P9_ENOENT;\n }\n return fs_net_set_url(fs, n, base_url_id, file_id, size);\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_export_file(FSDevice *fs, const char *p)\n{\n char filename[1024];\n FSINode *n;\n const char *name;\n uint8_t *buf;\n \n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n n = inode_search_path(fs, filename);\n if (!n)\n return -P9_ENOENT;\n if (n->type != FT_REG ||\n (n->u.reg.state != REG_STATE_LOCAL &&\n n->u.reg.state != REG_STATE_LOADED))\n goto fail;\n name = strrchr(filename, '/');\n if (name)\n name++;\n else\n name = filename;\n /* XXX: pass the buffer to JS to avoid the allocation */\n buf = malloc(n->u.reg.size);\n file_buffer_read(&n->u.reg.fbuf, 0, buf, n->u.reg.size);\n fs_export_file(name, buf, n->u.reg.size);\n free(buf);\n return 0;\n fail:\n return -P9_EIO;\n}\n\n/* PBKDF2 crypto acceleration */\nstatic int fs_cmd_pbkdf2(FSDevice *fs, FSFile *f, const char *p)\n{\n uint8_t pwd[1024];\n uint8_t salt[128];\n uint32_t iter, key_len;\n int pwd_len, salt_len;\n FSCMDRequest *req;\n \n /* a request is already done or in progress */\n if (f->req != NULL)\n return -P9_EIO;\n\n pwd_len = parse_hex_buf(pwd, sizeof(pwd), &p);\n if (pwd_len < 0)\n goto fail;\n salt_len = parse_hex_buf(salt, sizeof(salt), &p);\n if (pwd_len < 0)\n goto fail;\n if (parse_uint32(&iter, &p) < 0)\n goto fail;\n if (parse_uint32(&key_len, &p) < 0)\n goto fail;\n if (key_len > FS_CMD_REPLY_LEN_MAX ||\n key_len == 0)\n goto fail;\n req = mallocz(sizeof(*req));\n req->type = FS_CMD_PBKDF2;\n req->reply_len = key_len;\n pbkdf2_hmac_sha256(pwd, pwd_len, salt, salt_len, iter, key_len,\n req->reply_buf);\n f->req = req;\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_set_import_dir(FSDevice *fs, FSFile *f, const char *p)\n{\n FSDeviceMem *fs1 = (FSDeviceMem *)fs;\n char filename[1024];\n\n if (parse_fname(filename, sizeof(filename), &p) < 0)\n return -P9_EINVAL;\n free(fs1->import_dir);\n fs1->import_dir = strdup(filename);\n return 0;\n}\n\nstatic int fs_cmd_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int buf_len)\n{\n char *buf1;\n const char *p;\n char cmd[64];\n int err;\n \n /* transform into a string */\n buf1 = malloc(buf_len + 1);\n memcpy(buf1, buf, buf_len);\n buf1[buf_len] = '\\0';\n \n err = 0;\n p = buf1;\n if (parse_fname(cmd, sizeof(cmd), &p) < 0)\n goto fail;\n if (!strcmp(cmd, \"xhr\")) {\n err = fs_cmd_xhr(fs, f, p, f->uid, 0);\n } else if (!strcmp(cmd, \"set_base_url\")) {\n err = fs_cmd_set_base_url(fs, p);\n } else if (!strcmp(cmd, \"reset_base_url\")) {\n err = fs_cmd_reset_base_url(fs, p);\n } else if (!strcmp(cmd, \"set_url\")) {\n err = fs_cmd_set_url(fs, p);\n } else if (!strcmp(cmd, \"export_file\")) {\n err = fs_cmd_export_file(fs, p);\n } else if (!strcmp(cmd, \"pbkdf2\")) {\n err = fs_cmd_pbkdf2(fs, f, p);\n } else if (!strcmp(cmd, \"set_import_dir\")) {\n err = fs_cmd_set_import_dir(fs, f, p);\n } else {\n printf(\"unknown command: '%s'\\n\", cmd);\n fail:\n err = -P9_EIO;\n }\n free(buf1);\n if (err == 0)\n return buf_len;\n else\n return err;\n}\n\nstatic int fs_cmd_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int buf_len)\n{\n FSCMDRequest *req;\n int l;\n \n req = f->req;\n if (!req)\n return -P9_EIO;\n l = min_int(req->reply_len, buf_len);\n memcpy(buf, req->reply_buf, l);\n return l;\n}\n\nstatic void fs_cmd_close(FSDevice *fs, FSFile *f)\n{\n FSCMDRequest *req;\n req = f->req;\n\n if (req) {\n if (req->xhr_state) {\n req->xhr_state->req_fd = NULL;\n }\n free(req);\n f->req = NULL;\n }\n}\n\n/* Create a .fscmd_pwd file to avoid passing the password thru the\n Linux command line */\nvoid fs_net_set_pwd(FSDevice *fs, const char *pwd)\n{\n FSFile *root_fd;\n FSQID qid;\n \n assert(fs_is_net(fs));\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\"));\n assert(!fs->fs_create(fs, &qid, root_fd, \".fscmd_pwd\", P9_O_RDWR | P9_O_TRUNC,\n 0600, 0));\n fs->fs_write(fs, root_fd, 0, (uint8_t *)pwd, strlen(pwd));\n fs->fs_delete(fs, root_fd);\n}\n\n/* external file import */\n\n#ifdef EMSCRIPTEN\n\nvoid fs_import_file(const char *filename, uint8_t *buf, int buf_len)\n{\n FSDevice *fs;\n FSDeviceMem *fs1;\n FSFile *fd, *root_fd;\n FSQID qid;\n \n // printf(\"importing file: %s len=%d\\n\", filename, buf_len);\n fs = fs_import_fs;\n if (!fs) {\n free(buf);\n return;\n }\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 1000, \"\", \"\"));\n fs1 = (FSDeviceMem *)fs;\n fd = fs_walk_path(fs, root_fd, fs1->import_dir);\n if (!fd)\n goto fail;\n fs_unlinkat(fs, root_fd, filename);\n if (fs->fs_create(fs, &qid, fd, filename, P9_O_RDWR | P9_O_TRUNC,\n 0600, 0) < 0)\n goto fail;\n fs->fs_write(fs, fd, 0, buf, buf_len);\n fail:\n if (fd)\n fs->fs_delete(fs, fd);\n if (root_fd)\n fs->fs_delete(fs, root_fd);\n free(buf);\n}\n\n#else\n\nvoid fs_export_file(const char *filename,\n const uint8_t *buf, int buf_len)\n{\n}\n\n#endif\n"], ["/linuxpdf/tinyemu/ps2.c", "/*\n * QEMU PS/2 keyboard/mouse emulation\n *\n * Copyright (c) 2003 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n\n/* debug PC keyboard */\n//#define DEBUG_KBD\n\n/* debug PC keyboard : only mouse */\n//#define DEBUG_MOUSE\n\n/* Keyboard Commands */\n#define KBD_CMD_SET_LEDS\t0xED\t/* Set keyboard leds */\n#define KBD_CMD_ECHO \t0xEE\n#define KBD_CMD_GET_ID \t 0xF2\t/* get keyboard ID */\n#define KBD_CMD_SET_RATE\t0xF3\t/* Set typematic rate */\n#define KBD_CMD_ENABLE\t\t0xF4\t/* Enable scanning */\n#define KBD_CMD_RESET_DISABLE\t0xF5\t/* reset and disable scanning */\n#define KBD_CMD_RESET_ENABLE \t0xF6 /* reset and enable scanning */\n#define KBD_CMD_RESET\t\t0xFF\t/* Reset */\n\n/* Keyboard Replies */\n#define KBD_REPLY_POR\t\t0xAA\t/* Power on reset */\n#define KBD_REPLY_ACK\t\t0xFA\t/* Command ACK */\n#define KBD_REPLY_RESEND\t0xFE\t/* Command NACK, send the cmd again */\n\n/* Mouse Commands */\n#define AUX_SET_SCALE11\t\t0xE6\t/* Set 1:1 scaling */\n#define AUX_SET_SCALE21\t\t0xE7\t/* Set 2:1 scaling */\n#define AUX_SET_RES\t\t0xE8\t/* Set resolution */\n#define AUX_GET_SCALE\t\t0xE9\t/* Get scaling factor */\n#define AUX_SET_STREAM\t\t0xEA\t/* Set stream mode */\n#define AUX_POLL\t\t0xEB\t/* Poll */\n#define AUX_RESET_WRAP\t\t0xEC\t/* Reset wrap mode */\n#define AUX_SET_WRAP\t\t0xEE\t/* Set wrap mode */\n#define AUX_SET_REMOTE\t\t0xF0\t/* Set remote mode */\n#define AUX_GET_TYPE\t\t0xF2\t/* Get type */\n#define AUX_SET_SAMPLE\t\t0xF3\t/* Set sample rate */\n#define AUX_ENABLE_DEV\t\t0xF4\t/* Enable aux device */\n#define AUX_DISABLE_DEV\t\t0xF5\t/* Disable aux device */\n#define AUX_SET_DEFAULT\t\t0xF6\n#define AUX_RESET\t\t0xFF\t/* Reset aux device */\n#define AUX_ACK\t\t\t0xFA\t/* Command byte ACK. */\n\n#define MOUSE_STATUS_REMOTE 0x40\n#define MOUSE_STATUS_ENABLED 0x20\n#define MOUSE_STATUS_SCALE21 0x10\n\n#define PS2_QUEUE_SIZE 256\n\ntypedef struct {\n uint8_t data[PS2_QUEUE_SIZE];\n int rptr, wptr, count;\n} PS2Queue;\n\ntypedef struct {\n PS2Queue queue;\n int32_t write_cmd;\n void (*update_irq)(void *, int);\n void *update_arg;\n} PS2State;\n\nstruct PS2KbdState {\n PS2State common;\n int scan_enabled;\n /* Qemu uses translated PC scancodes internally. To avoid multiple\n conversions we do the translation (if any) in the PS/2 emulation\n not the keyboard controller. */\n int translate;\n};\n\nstruct PS2MouseState {\n PS2State common;\n uint8_t mouse_status;\n uint8_t mouse_resolution;\n uint8_t mouse_sample_rate;\n uint8_t mouse_wrap;\n uint8_t mouse_type; /* 0 = PS2, 3 = IMPS/2, 4 = IMEX */\n uint8_t mouse_detect_state;\n int mouse_dx; /* current values, needed for 'poll' mode */\n int mouse_dy;\n int mouse_dz;\n uint8_t mouse_buttons;\n};\n\nvoid ps2_queue(void *opaque, int b)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q = &s->queue;\n\n if (q->count >= PS2_QUEUE_SIZE)\n return;\n q->data[q->wptr] = b;\n if (++q->wptr == PS2_QUEUE_SIZE)\n q->wptr = 0;\n q->count++;\n s->update_irq(s->update_arg, 1);\n}\n\n#define INPUT_MAKE_KEY_MIN 96\n#define INPUT_MAKE_KEY_MAX 127\n\nstatic const uint8_t linux_input_to_keycode_set1[INPUT_MAKE_KEY_MAX - INPUT_MAKE_KEY_MIN + 1] = {\n 0x1c, 0x1d, 0x35, 0x00, 0x38, 0x00, 0x47, 0x48, \n 0x49, 0x4b, 0x4d, 0x4f, 0x50, 0x51, 0x52, 0x53, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x5b, 0x5c, 0x5d, \n};\n\n/* keycode is a Linux input layer keycode. We only support the PS/2\n keycode set 1 */\nvoid ps2_put_keycode(PS2KbdState *s, BOOL is_down, int keycode)\n{\n if (keycode >= INPUT_MAKE_KEY_MIN) {\n if (keycode > INPUT_MAKE_KEY_MAX)\n return;\n keycode = linux_input_to_keycode_set1[keycode - INPUT_MAKE_KEY_MIN];\n if (keycode == 0)\n return;\n ps2_queue(&s->common, 0xe0);\n }\n ps2_queue(&s->common, keycode | ((!is_down) << 7));\n}\n\nuint32_t ps2_read_data(void *opaque)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q;\n int val, index;\n\n q = &s->queue;\n if (q->count == 0) {\n /* NOTE: if no data left, we return the last keyboard one\n (needed for EMM386) */\n /* XXX: need a timer to do things correctly */\n index = q->rptr - 1;\n if (index < 0)\n index = PS2_QUEUE_SIZE - 1;\n val = q->data[index];\n } else {\n val = q->data[q->rptr];\n if (++q->rptr == PS2_QUEUE_SIZE)\n q->rptr = 0;\n q->count--;\n /* reading deasserts IRQ */\n s->update_irq(s->update_arg, 0);\n /* reassert IRQs if data left */\n s->update_irq(s->update_arg, q->count != 0);\n }\n return val;\n}\n\nstatic void ps2_reset_keyboard(PS2KbdState *s)\n{\n s->scan_enabled = 1;\n}\n\nvoid ps2_write_keyboard(void *opaque, int val)\n{\n PS2KbdState *s = (PS2KbdState *)opaque;\n\n switch(s->common.write_cmd) {\n default:\n case -1:\n switch(val) {\n case 0x00:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case 0x05:\n ps2_queue(&s->common, KBD_REPLY_RESEND);\n break;\n case KBD_CMD_GET_ID:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n ps2_queue(&s->common, 0xab);\n ps2_queue(&s->common, 0x83);\n break;\n case KBD_CMD_ECHO:\n ps2_queue(&s->common, KBD_CMD_ECHO);\n break;\n case KBD_CMD_ENABLE:\n s->scan_enabled = 1;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_SET_LEDS:\n case KBD_CMD_SET_RATE:\n s->common.write_cmd = val;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET_DISABLE:\n ps2_reset_keyboard(s);\n s->scan_enabled = 0;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET_ENABLE:\n ps2_reset_keyboard(s);\n s->scan_enabled = 1;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET:\n ps2_reset_keyboard(s);\n ps2_queue(&s->common, KBD_REPLY_ACK);\n ps2_queue(&s->common, KBD_REPLY_POR);\n break;\n default:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n }\n break;\n case KBD_CMD_SET_LEDS:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n s->common.write_cmd = -1;\n break;\n case KBD_CMD_SET_RATE:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n s->common.write_cmd = -1;\n break;\n }\n}\n\n/* Set the scancode translation mode.\n 0 = raw scancodes.\n 1 = translated scancodes (used by qemu internally). */\n\nvoid ps2_keyboard_set_translation(void *opaque, int mode)\n{\n PS2KbdState *s = (PS2KbdState *)opaque;\n s->translate = mode;\n}\n\nstatic void ps2_mouse_send_packet(PS2MouseState *s)\n{\n unsigned int b;\n int dx1, dy1, dz1;\n\n dx1 = s->mouse_dx;\n dy1 = s->mouse_dy;\n dz1 = s->mouse_dz;\n /* XXX: increase range to 8 bits ? */\n if (dx1 > 127)\n dx1 = 127;\n else if (dx1 < -127)\n dx1 = -127;\n if (dy1 > 127)\n dy1 = 127;\n else if (dy1 < -127)\n dy1 = -127;\n b = 0x08 | ((dx1 < 0) << 4) | ((dy1 < 0) << 5) | (s->mouse_buttons & 0x07);\n ps2_queue(&s->common, b);\n ps2_queue(&s->common, dx1 & 0xff);\n ps2_queue(&s->common, dy1 & 0xff);\n /* extra byte for IMPS/2 or IMEX */\n switch(s->mouse_type) {\n default:\n break;\n case 3:\n if (dz1 > 127)\n dz1 = 127;\n else if (dz1 < -127)\n dz1 = -127;\n ps2_queue(&s->common, dz1 & 0xff);\n break;\n case 4:\n if (dz1 > 7)\n dz1 = 7;\n else if (dz1 < -7)\n dz1 = -7;\n b = (dz1 & 0x0f) | ((s->mouse_buttons & 0x18) << 1);\n ps2_queue(&s->common, b);\n break;\n }\n\n /* update deltas */\n s->mouse_dx -= dx1;\n s->mouse_dy -= dy1;\n s->mouse_dz -= dz1;\n}\n\nvoid ps2_mouse_event(PS2MouseState *s,\n int dx, int dy, int dz, int buttons_state)\n{\n /* check if deltas are recorded when disabled */\n if (!(s->mouse_status & MOUSE_STATUS_ENABLED))\n return;\n\n s->mouse_dx += dx;\n s->mouse_dy -= dy;\n s->mouse_dz += dz;\n /* XXX: SDL sometimes generates nul events: we delete them */\n if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0 &&\n s->mouse_buttons == buttons_state)\n\treturn;\n s->mouse_buttons = buttons_state;\n\n if (!(s->mouse_status & MOUSE_STATUS_REMOTE) &&\n (s->common.queue.count < (PS2_QUEUE_SIZE - 16))) {\n for(;;) {\n /* if not remote, send event. Multiple events are sent if\n too big deltas */\n ps2_mouse_send_packet(s);\n if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0)\n break;\n }\n }\n}\n\nvoid ps2_write_mouse(void *opaque, int val)\n{\n PS2MouseState *s = (PS2MouseState *)opaque;\n#ifdef DEBUG_MOUSE\n printf(\"kbd: write mouse 0x%02x\\n\", val);\n#endif\n switch(s->common.write_cmd) {\n default:\n case -1:\n /* mouse command */\n if (s->mouse_wrap) {\n if (val == AUX_RESET_WRAP) {\n s->mouse_wrap = 0;\n ps2_queue(&s->common, AUX_ACK);\n return;\n } else if (val != AUX_RESET) {\n ps2_queue(&s->common, val);\n return;\n }\n }\n switch(val) {\n case AUX_SET_SCALE11:\n s->mouse_status &= ~MOUSE_STATUS_SCALE21;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_SCALE21:\n s->mouse_status |= MOUSE_STATUS_SCALE21;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_STREAM:\n s->mouse_status &= ~MOUSE_STATUS_REMOTE;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_WRAP:\n s->mouse_wrap = 1;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_REMOTE:\n s->mouse_status |= MOUSE_STATUS_REMOTE;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_GET_TYPE:\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, s->mouse_type);\n break;\n case AUX_SET_RES:\n case AUX_SET_SAMPLE:\n s->common.write_cmd = val;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_GET_SCALE:\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, s->mouse_status);\n ps2_queue(&s->common, s->mouse_resolution);\n ps2_queue(&s->common, s->mouse_sample_rate);\n break;\n case AUX_POLL:\n ps2_queue(&s->common, AUX_ACK);\n ps2_mouse_send_packet(s);\n break;\n case AUX_ENABLE_DEV:\n s->mouse_status |= MOUSE_STATUS_ENABLED;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_DISABLE_DEV:\n s->mouse_status &= ~MOUSE_STATUS_ENABLED;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_DEFAULT:\n s->mouse_sample_rate = 100;\n s->mouse_resolution = 2;\n s->mouse_status = 0;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_RESET:\n s->mouse_sample_rate = 100;\n s->mouse_resolution = 2;\n s->mouse_status = 0;\n s->mouse_type = 0;\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, 0xaa);\n ps2_queue(&s->common, s->mouse_type);\n break;\n default:\n break;\n }\n break;\n case AUX_SET_SAMPLE:\n s->mouse_sample_rate = val;\n /* detect IMPS/2 or IMEX */\n switch(s->mouse_detect_state) {\n default:\n case 0:\n if (val == 200)\n s->mouse_detect_state = 1;\n break;\n case 1:\n if (val == 100)\n s->mouse_detect_state = 2;\n else if (val == 200)\n s->mouse_detect_state = 3;\n else\n s->mouse_detect_state = 0;\n break;\n case 2:\n if (val == 80)\n s->mouse_type = 3; /* IMPS/2 */\n s->mouse_detect_state = 0;\n break;\n case 3:\n if (val == 80)\n s->mouse_type = 4; /* IMEX */\n s->mouse_detect_state = 0;\n break;\n }\n ps2_queue(&s->common, AUX_ACK);\n s->common.write_cmd = -1;\n break;\n case AUX_SET_RES:\n s->mouse_resolution = val;\n ps2_queue(&s->common, AUX_ACK);\n s->common.write_cmd = -1;\n break;\n }\n}\n\nstatic void ps2_reset(void *opaque)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q;\n s->write_cmd = -1;\n q = &s->queue;\n q->rptr = 0;\n q->wptr = 0;\n q->count = 0;\n}\n\nPS2KbdState *ps2_kbd_init(void (*update_irq)(void *, int), void *update_arg)\n{\n PS2KbdState *s = (PS2KbdState *)mallocz(sizeof(PS2KbdState));\n\n s->common.update_irq = update_irq;\n s->common.update_arg = update_arg;\n ps2_reset(&s->common);\n return s;\n}\n\nPS2MouseState *ps2_mouse_init(void (*update_irq)(void *, int), void *update_arg)\n{\n PS2MouseState *s = (PS2MouseState *)mallocz(sizeof(PS2MouseState));\n\n s->common.update_irq = update_irq;\n s->common.update_arg = update_arg;\n ps2_reset(&s->common);\n return s;\n}\n"], ["/linuxpdf/tinyemu/fs_disk.c", "/*\n * Filesystem on disk\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n\ntypedef struct {\n FSDevice common;\n char *root_path;\n} FSDeviceDisk;\n\nstatic void fs_close(FSDevice *fs, FSFile *f);\n\nstruct FSFile {\n uint32_t uid;\n char *path; /* complete path */\n BOOL is_opened;\n BOOL is_dir;\n union {\n int fd;\n DIR *dirp;\n } u;\n};\n\nstatic void fs_delete(FSDevice *fs, FSFile *f)\n{\n if (f->is_opened)\n fs_close(fs, f);\n free(f->path);\n free(f);\n}\n\n/* warning: path belong to fid_create() */\nstatic FSFile *fid_create(FSDevice *s1, char *path, uint32_t uid)\n{\n FSFile *f;\n f = mallocz(sizeof(*f));\n f->path = path;\n f->uid = uid;\n return f;\n}\n\n\nstatic int errno_table[][2] = {\n { P9_EPERM, EPERM },\n { P9_ENOENT, ENOENT },\n { P9_EIO, EIO },\n { P9_EEXIST, EEXIST },\n { P9_EINVAL, EINVAL },\n { P9_ENOSPC, ENOSPC },\n { P9_ENOTEMPTY, ENOTEMPTY },\n { P9_EPROTO, EPROTO },\n { P9_ENOTSUP, ENOTSUP },\n};\n\nstatic int errno_to_p9(int err)\n{\n int i;\n if (err == 0)\n return 0;\n for(i = 0; i < countof(errno_table); i++) {\n if (err == errno_table[i][1])\n return errno_table[i][0];\n }\n return P9_EINVAL;\n}\n\nstatic int open_flags[][2] = {\n { P9_O_CREAT, O_CREAT },\n { P9_O_EXCL, O_EXCL },\n // { P9_O_NOCTTY, O_NOCTTY },\n { P9_O_TRUNC, O_TRUNC },\n { P9_O_APPEND, O_APPEND },\n { P9_O_NONBLOCK, O_NONBLOCK },\n { P9_O_DSYNC, O_DSYNC },\n // { P9_O_FASYNC, O_FASYNC },\n // { P9_O_DIRECT, O_DIRECT },\n // { P9_O_LARGEFILE, O_LARGEFILE },\n // { P9_O_DIRECTORY, O_DIRECTORY },\n { P9_O_NOFOLLOW, O_NOFOLLOW },\n // { P9_O_NOATIME, O_NOATIME },\n // { P9_O_CLOEXEC, O_CLOEXEC },\n { P9_O_SYNC, O_SYNC },\n};\n\nstatic int p9_flags_to_host(int flags)\n{\n int ret, i;\n\n ret = (flags & P9_O_NOACCESS);\n for(i = 0; i < countof(open_flags); i++) {\n if (flags & open_flags[i][0])\n ret |= open_flags[i][1];\n }\n return ret;\n}\n\nstatic void stat_to_qid(FSQID *qid, const struct stat *st)\n{\n if (S_ISDIR(st->st_mode))\n qid->type = P9_QTDIR;\n else if (S_ISLNK(st->st_mode))\n qid->type = P9_QTSYMLINK;\n else\n qid->type = P9_QTFILE;\n qid->version = 0; /* no caching on client */\n qid->path = st->st_ino;\n}\n\nstatic void fs_statfs(FSDevice *fs1, FSStatFS *st)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n struct statfs st1;\n statfs(fs->root_path, &st1);\n st->f_bsize = st1.f_bsize;\n st->f_blocks = st1.f_blocks;\n st->f_bfree = st1.f_bfree;\n st->f_bavail = st1.f_bavail;\n st->f_files = st1.f_files;\n st->f_ffree = st1.f_ffree;\n}\n\nstatic char *compose_path(const char *path, const char *name)\n{\n int path_len, name_len;\n char *d;\n\n path_len = strlen(path);\n name_len = strlen(name);\n d = malloc(path_len + 1 + name_len + 1);\n memcpy(d, path, path_len);\n d[path_len] = '/';\n memcpy(d + path_len + 1, name, name_len + 1);\n return d;\n}\n\nstatic int fs_attach(FSDevice *fs1, FSFile **pf,\n FSQID *qid, uint32_t uid,\n const char *uname, const char *aname)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n struct stat st;\n FSFile *f;\n \n if (lstat(fs->root_path, &st) != 0) {\n *pf = NULL;\n return -errno_to_p9(errno);\n }\n f = fid_create(fs1, strdup(fs->root_path), uid);\n stat_to_qid(qid, &st);\n *pf = f;\n return 0;\n}\n\nstatic int fs_walk(FSDevice *fs, FSFile **pf, FSQID *qids,\n FSFile *f, int n, char **names)\n{\n char *path, *path1;\n struct stat st;\n int i;\n\n path = strdup(f->path);\n for(i = 0; i < n; i++) {\n path1 = compose_path(path, names[i]);\n if (lstat(path1, &st) != 0) {\n free(path1);\n break;\n }\n free(path);\n path = path1;\n stat_to_qid(&qids[i], &st);\n }\n *pf = fid_create(fs, path, f->uid);\n return i;\n}\n\n\nstatic int fs_mkdir(FSDevice *fs, FSQID *qid, FSFile *f,\n const char *name, uint32_t mode, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (mkdir(path, mode) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_open(FSDevice *fs, FSQID *qid, FSFile *f, uint32_t flags,\n FSOpenCompletionFunc *cb, void *opaque)\n{\n struct stat st;\n fs_close(fs, f);\n\n if (stat(f->path, &st) != 0) \n return -errno_to_p9(errno);\n stat_to_qid(qid, &st);\n \n if (flags & P9_O_DIRECTORY) {\n DIR *dirp;\n dirp = opendir(f->path);\n if (!dirp)\n return -errno_to_p9(errno);\n f->is_opened = TRUE;\n f->is_dir = TRUE;\n f->u.dirp = dirp;\n } else {\n int fd;\n fd = open(f->path, p9_flags_to_host(flags) & ~O_CREAT);\n if (fd < 0)\n return -errno_to_p9(errno);\n f->is_opened = TRUE;\n f->is_dir = FALSE;\n f->u.fd = fd;\n }\n return 0;\n}\n\nstatic int fs_create(FSDevice *fs, FSQID *qid, FSFile *f, const char *name, \n uint32_t flags, uint32_t mode, uint32_t gid)\n{\n struct stat st;\n char *path;\n int ret, fd;\n\n fs_close(fs, f);\n \n path = compose_path(f->path, name);\n fd = open(path, p9_flags_to_host(flags) | O_CREAT, mode);\n if (fd < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n ret = lstat(path, &st);\n if (ret != 0) {\n free(path);\n close(fd);\n return -errno_to_p9(errno);\n }\n free(f->path);\n f->path = path;\n f->is_opened = TRUE;\n f->is_dir = FALSE;\n f->u.fd = fd;\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_readdir(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n struct dirent *de;\n int len, pos, name_len, type, d_type;\n\n if (!f->is_opened || !f->is_dir)\n return -P9_EPROTO;\n if (offset == 0)\n rewinddir(f->u.dirp);\n else\n seekdir(f->u.dirp, offset);\n pos = 0;\n for(;;) {\n de = readdir(f->u.dirp);\n if (de == NULL)\n break;\n name_len = strlen(de->d_name);\n len = 13 + 8 + 1 + 2 + name_len;\n if ((pos + len) > count)\n break;\n offset = telldir(f->u.dirp);\n d_type = de->d_type;\n if (d_type == DT_UNKNOWN) {\n char *path;\n struct stat st;\n path = compose_path(f->path, de->d_name);\n if (lstat(path, &st) == 0) {\n d_type = st.st_mode >> 12;\n } else {\n d_type = DT_REG; /* default */\n }\n free(path);\n }\n if (d_type == DT_DIR)\n type = P9_QTDIR;\n else if (d_type == DT_LNK)\n type = P9_QTSYMLINK;\n else\n type = P9_QTFILE;\n buf[pos++] = type;\n put_le32(buf + pos, 0); /* version */\n pos += 4;\n put_le64(buf + pos, de->d_ino);\n pos += 8;\n put_le64(buf + pos, offset);\n pos += 8;\n buf[pos++] = d_type;\n put_le16(buf + pos, name_len);\n pos += 2;\n memcpy(buf + pos, de->d_name, name_len);\n pos += name_len;\n }\n return pos;\n}\n\nstatic int fs_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n int ret;\n\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n ret = pread(f->u.fd, buf, count, offset);\n if (ret < 0) \n return -errno_to_p9(errno);\n else\n return ret;\n}\n\nstatic int fs_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int count)\n{\n int ret;\n\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n ret = pwrite(f->u.fd, buf, count, offset);\n if (ret < 0) \n return -errno_to_p9(errno);\n else\n return ret;\n}\n\nstatic void fs_close(FSDevice *fs, FSFile *f)\n{\n if (!f->is_opened)\n return;\n if (f->is_dir)\n closedir(f->u.dirp);\n else\n close(f->u.fd);\n f->is_opened = FALSE;\n}\n\nstatic int fs_stat(FSDevice *fs, FSFile *f, FSStat *st)\n{\n struct stat st1;\n\n if (lstat(f->path, &st1) != 0)\n return -P9_ENOENT;\n stat_to_qid(&st->qid, &st1);\n st->st_mode = st1.st_mode;\n st->st_uid = st1.st_uid;\n st->st_gid = st1.st_gid;\n st->st_nlink = st1.st_nlink;\n st->st_rdev = st1.st_rdev;\n st->st_size = st1.st_size;\n st->st_blksize = st1.st_blksize;\n st->st_blocks = st1.st_blocks;\n st->st_atime_sec = st1.st_atim.tv_sec;\n st->st_atime_nsec = st1.st_atim.tv_nsec;\n st->st_mtime_sec = st1.st_mtim.tv_sec;\n st->st_mtime_nsec = st1.st_mtim.tv_nsec;\n st->st_ctime_sec = st1.st_ctim.tv_sec;\n st->st_ctime_nsec = st1.st_ctim.tv_nsec;\n return 0;\n}\n\nstatic int fs_setattr(FSDevice *fs, FSFile *f, uint32_t mask,\n uint32_t mode, uint32_t uid, uint32_t gid,\n uint64_t size, uint64_t atime_sec, uint64_t atime_nsec,\n uint64_t mtime_sec, uint64_t mtime_nsec)\n{\n BOOL ctime_updated = FALSE;\n\n if (mask & (P9_SETATTR_UID | P9_SETATTR_GID)) {\n if (lchown(f->path, (mask & P9_SETATTR_UID) ? uid : -1,\n (mask & P9_SETATTR_GID) ? gid : -1) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n /* must be done after uid change for suid */\n if (mask & P9_SETATTR_MODE) {\n if (chmod(f->path, mode) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if (mask & P9_SETATTR_SIZE) {\n if (truncate(f->path, size) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if (mask & (P9_SETATTR_ATIME | P9_SETATTR_MTIME)) {\n struct timespec ts[2];\n if (mask & P9_SETATTR_ATIME) {\n if (mask & P9_SETATTR_ATIME_SET) {\n ts[0].tv_sec = atime_sec;\n ts[0].tv_nsec = atime_nsec;\n } else {\n ts[0].tv_sec = 0;\n ts[0].tv_nsec = UTIME_NOW;\n }\n } else {\n ts[0].tv_sec = 0;\n ts[0].tv_nsec = UTIME_OMIT;\n }\n if (mask & P9_SETATTR_MTIME) {\n if (mask & P9_SETATTR_MTIME_SET) {\n ts[1].tv_sec = mtime_sec;\n ts[1].tv_nsec = mtime_nsec;\n } else {\n ts[1].tv_sec = 0;\n ts[1].tv_nsec = UTIME_NOW;\n }\n } else {\n ts[1].tv_sec = 0;\n ts[1].tv_nsec = UTIME_OMIT;\n }\n if (utimensat(AT_FDCWD, f->path, ts, AT_SYMLINK_NOFOLLOW) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if ((mask & P9_SETATTR_CTIME) && !ctime_updated) {\n if (lchown(f->path, -1, -1) < 0)\n return -errno_to_p9(errno);\n }\n return 0;\n}\n\nstatic int fs_link(FSDevice *fs, FSFile *df, FSFile *f, const char *name)\n{\n char *path;\n \n path = compose_path(df->path, name);\n if (link(f->path, path) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n return 0;\n}\n\nstatic int fs_symlink(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, const char *symgt, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (symlink(symgt, path) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_mknod(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, uint32_t mode, uint32_t major,\n uint32_t minor, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (mknod(path, mode, makedev(major, minor)) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_readlink(FSDevice *fs, char *buf, int buf_size, FSFile *f)\n{\n int ret;\n ret = readlink(f->path, buf, buf_size - 1);\n if (ret < 0)\n return -errno_to_p9(errno);\n buf[ret] = '\\0';\n return 0;\n}\n\nstatic int fs_renameat(FSDevice *fs, FSFile *f, const char *name, \n FSFile *new_f, const char *new_name)\n{\n char *path, *new_path;\n int ret;\n\n path = compose_path(f->path, name);\n new_path = compose_path(new_f->path, new_name);\n ret = rename(path, new_path);\n free(path);\n free(new_path);\n if (ret < 0)\n return -errno_to_p9(errno);\n return 0;\n}\n\nstatic int fs_unlinkat(FSDevice *fs, FSFile *f, const char *name)\n{\n char *path;\n int ret;\n\n path = compose_path(f->path, name);\n ret = remove(path);\n free(path);\n if (ret < 0)\n return -errno_to_p9(errno);\n return 0;\n \n}\n\nstatic int fs_lock(FSDevice *fs, FSFile *f, const FSLock *lock)\n{\n int ret;\n struct flock fl;\n \n /* XXX: lock directories too */\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n\n fl.l_type = lock->type;\n fl.l_whence = SEEK_SET;\n fl.l_start = lock->start;\n fl.l_len = lock->length;\n \n ret = fcntl(f->u.fd, F_SETLK, &fl);\n if (ret == 0) {\n ret = P9_LOCK_SUCCESS;\n } else if (errno == EAGAIN || errno == EACCES) {\n ret = P9_LOCK_BLOCKED;\n } else {\n ret = -errno_to_p9(errno);\n }\n return ret;\n}\n\nstatic int fs_getlock(FSDevice *fs, FSFile *f, FSLock *lock)\n{\n int ret;\n struct flock fl;\n \n /* XXX: lock directories too */\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n\n fl.l_type = lock->type;\n fl.l_whence = SEEK_SET;\n fl.l_start = lock->start;\n fl.l_len = lock->length;\n\n ret = fcntl(f->u.fd, F_GETLK, &fl);\n if (ret < 0) {\n ret = -errno_to_p9(errno);\n } else {\n lock->type = fl.l_type;\n lock->start = fl.l_start;\n lock->length = fl.l_len;\n }\n return ret;\n}\n\nstatic void fs_disk_end(FSDevice *fs1)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n free(fs->root_path);\n}\n\nFSDevice *fs_disk_init(const char *root_path)\n{\n FSDeviceDisk *fs;\n struct stat st;\n\n lstat(root_path, &st);\n if (!S_ISDIR(st.st_mode))\n return NULL;\n\n fs = mallocz(sizeof(*fs));\n\n fs->common.fs_end = fs_disk_end;\n fs->common.fs_delete = fs_delete;\n fs->common.fs_statfs = fs_statfs;\n fs->common.fs_attach = fs_attach;\n fs->common.fs_walk = fs_walk;\n fs->common.fs_mkdir = fs_mkdir;\n fs->common.fs_open = fs_open;\n fs->common.fs_create = fs_create;\n fs->common.fs_stat = fs_stat;\n fs->common.fs_setattr = fs_setattr;\n fs->common.fs_close = fs_close;\n fs->common.fs_readdir = fs_readdir;\n fs->common.fs_read = fs_read;\n fs->common.fs_write = fs_write;\n fs->common.fs_link = fs_link;\n fs->common.fs_symlink = fs_symlink;\n fs->common.fs_mknod = fs_mknod;\n fs->common.fs_readlink = fs_readlink;\n fs->common.fs_renameat = fs_renameat;\n fs->common.fs_unlinkat = fs_unlinkat;\n fs->common.fs_lock = fs_lock;\n fs->common.fs_getlock = fs_getlock;\n \n fs->root_path = strdup(root_path);\n return (FSDevice *)fs;\n}\n"], ["/linuxpdf/tinyemu/jsemu.c", "/*\n * JS emulator main\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#include \"list.h\"\n#include \"fbuf.h\"\n\nint virt_machine_run(void *opaque);\n\n/* provided in lib.js */\nextern void console_write(void *opaque, const uint8_t *buf, int len);\nextern void console_get_size(int *pw, int *ph);\nextern void fb_refresh(void *opaque, void *data,\n int x, int y, int w, int h, int stride);\nextern void net_recv_packet(EthernetDevice *bs,\n const uint8_t *buf, int len);\n\nstatic uint8_t console_fifo[1024];\nstatic int console_fifo_windex;\nstatic int console_fifo_rindex;\nstatic int console_fifo_count;\nstatic BOOL console_resize_pending;\n\nstatic int global_width;\nstatic int global_height;\nstatic VirtMachine *global_vm;\nstatic BOOL global_carrier_state;\n\nstatic int console_read(void *opaque, uint8_t *buf, int len)\n{\n int out_len, l;\n len = min_int(len, console_fifo_count);\n console_fifo_count -= len;\n out_len = 0;\n while (len != 0) {\n l = min_int(len, sizeof(console_fifo) - console_fifo_rindex);\n memcpy(buf + out_len, console_fifo + console_fifo_rindex, l);\n len -= l;\n out_len += l;\n console_fifo_rindex += l;\n if (console_fifo_rindex == sizeof(console_fifo))\n console_fifo_rindex = 0;\n }\n return out_len;\n}\n\n/* called from JS */\nvoid console_queue_char(int c)\n{\n if (console_fifo_count < sizeof(console_fifo)) {\n console_fifo[console_fifo_windex] = c;\n if (++console_fifo_windex == sizeof(console_fifo))\n console_fifo_windex = 0;\n console_fifo_count++;\n }\n}\n\n/* called from JS */\nvoid display_key_event(int is_down, int key_code)\n{\n if (global_vm) {\n vm_send_key_event(global_vm, is_down, key_code);\n }\n}\n\n/* called from JS */\nstatic int mouse_last_x, mouse_last_y, mouse_last_buttons;\n\nvoid display_mouse_event(int dx, int dy, int buttons)\n{\n if (global_vm) {\n if (vm_mouse_is_absolute(global_vm) || 1) {\n dx = min_int(dx, global_width - 1);\n dy = min_int(dy, global_height - 1);\n dx = (dx * VIRTIO_INPUT_ABS_SCALE) / global_width;\n dy = (dy * VIRTIO_INPUT_ABS_SCALE) / global_height;\n } else {\n /* relative mouse is not supported */\n dx = 0;\n dy = 0;\n }\n mouse_last_x = dx;\n mouse_last_y = dy;\n mouse_last_buttons = buttons;\n vm_send_mouse_event(global_vm, dx, dy, 0, buttons);\n }\n}\n\n/* called from JS */\nvoid display_wheel_event(int dz)\n{\n if (global_vm) {\n vm_send_mouse_event(global_vm, mouse_last_x, mouse_last_y, dz,\n mouse_last_buttons);\n }\n}\n\n/* called from JS */\nvoid net_write_packet(const uint8_t *buf, int buf_len)\n{\n EthernetDevice *net = global_vm->net;\n if (net) {\n net->device_write_packet(net, buf, buf_len);\n }\n}\n\n/* called from JS */\nvoid net_set_carrier(BOOL carrier_state)\n{\n EthernetDevice *net;\n global_carrier_state = carrier_state;\n if (global_vm && global_vm->net) {\n net = global_vm->net;\n net->device_set_carrier(net, carrier_state);\n }\n}\n\nstatic void fb_refresh1(FBDevice *fb_dev, void *opaque,\n int x, int y, int w, int h)\n{\n int stride = fb_dev->stride;\n fb_refresh(opaque, fb_dev->fb_data + y * stride + x * 4, x, y, w, h,\n stride);\n}\n\nstatic CharacterDevice *console_init(void)\n{\n CharacterDevice *dev;\n console_resize_pending = TRUE;\n dev = mallocz(sizeof(*dev));\n dev->write_data = console_write;\n dev->read_data = console_read;\n return dev;\n}\n\ntypedef struct {\n VirtMachineParams *p;\n int ram_size;\n char *cmdline;\n BOOL has_network;\n char *pwd;\n} VMStartState;\n\nstatic void init_vm(void *arg);\nstatic void init_vm_fs(void *arg);\nstatic void init_vm_drive(void *arg);\n\nvoid vm_start(const char *url, int ram_size, const char *cmdline,\n const char *pwd, int width, int height, BOOL has_network)\n{\n VMStartState *s;\n\n s = mallocz(sizeof(*s));\n s->ram_size = ram_size;\n s->cmdline = strdup(cmdline);\n if (pwd)\n s->pwd = strdup(pwd);\n global_width = width;\n global_height = height;\n s->has_network = has_network;\n s->p = mallocz(sizeof(VirtMachineParams));\n virt_machine_set_defaults(s->p);\n virt_machine_load_config_file(s->p, url, init_vm_fs, s);\n}\n\nstatic void init_vm_fs(void *arg)\n{\n VMStartState *s = arg;\n VirtMachineParams *p = s->p;\n\n if (p->fs_count > 0) {\n assert(p->fs_count == 1);\n p->tab_fs[0].fs_dev = fs_net_init(p->tab_fs[0].filename,\n init_vm_drive, s);\n if (s->pwd) {\n fs_net_set_pwd(p->tab_fs[0].fs_dev, s->pwd);\n }\n } else {\n init_vm_drive(s);\n }\n}\n\nstatic void init_vm_drive(void *arg)\n{\n VMStartState *s = arg;\n VirtMachineParams *p = s->p;\n\n if (p->drive_count > 0) {\n assert(p->drive_count == 1);\n p->tab_drive[0].block_dev =\n block_device_init_http(p->tab_drive[0].filename,\n 131072,\n init_vm, s);\n } else {\n init_vm(s);\n }\n}\n\nstatic void init_vm(void *arg)\n{\n VMStartState *s = arg;\n VirtMachine *m;\n VirtMachineParams *p = s->p;\n int i;\n \n p->rtc_real_time = TRUE;\n p->ram_size = s->ram_size << 20;\n if (s->cmdline && s->cmdline[0] != '\\0') {\n vm_add_cmdline(s->p, s->cmdline);\n }\n\n if (global_width > 0 && global_height > 0) {\n /* enable graphic output if needed */\n if (!p->display_device)\n p->display_device = strdup(\"simplefb\");\n p->width = global_width;\n p->height = global_height;\n } else {\n p->console = console_init();\n }\n \n if (p->eth_count > 0 && !s->has_network) {\n /* remove the interfaces */\n for(i = 0; i < p->eth_count; i++) {\n free(p->tab_eth[i].ifname);\n free(p->tab_eth[i].driver);\n }\n p->eth_count = 0;\n }\n\n if (p->eth_count > 0) {\n EthernetDevice *net;\n int i;\n assert(p->eth_count == 1);\n net = mallocz(sizeof(EthernetDevice));\n net->mac_addr[0] = 0x02;\n for(i = 1; i < 6; i++)\n net->mac_addr[i] = (int)(emscripten_random() * 256);\n net->write_packet = net_recv_packet;\n net->opaque = NULL;\n p->tab_eth[0].net = net;\n }\n\n m = virt_machine_init(p);\n global_vm = m;\n\n virt_machine_free_config(s->p);\n\n if (m->net) {\n m->net->device_set_carrier(m->net, global_carrier_state);\n }\n \n free(s->p);\n free(s->cmdline);\n if (s->pwd) {\n memset(s->pwd, 0, strlen(s->pwd));\n free(s->pwd);\n }\n free(s);\n \n EM_ASM({\n start_machine_interval($0);\n }, m);\n}\n\n/* need to be long enough to hide the non zero delay of setTimeout(_, 0) */\n#define MAX_EXEC_TOTAL_CYCLE 100000\n#define MAX_EXEC_CYCLE 1000\n\n#define MAX_SLEEP_TIME 10 /* in ms */\n\nint virt_machine_run(void *opaque)\n{\n VirtMachine *m = opaque;\n int delay, i;\n FBDevice *fb_dev;\n \n if (m->console_dev && virtio_console_can_write_data(m->console_dev)) {\n uint8_t buf[128];\n int ret, len;\n len = virtio_console_get_write_len(m->console_dev);\n len = min_int(len, sizeof(buf));\n ret = m->console->read_data(m->console->opaque, buf, len);\n if (ret > 0)\n virtio_console_write_data(m->console_dev, buf, ret);\n if (console_resize_pending) {\n int w, h;\n console_get_size(&w, &h);\n virtio_console_resize_event(m->console_dev, w, h);\n console_resize_pending = FALSE;\n }\n }\n\n fb_dev = m->fb_dev;\n if (fb_dev) {\n /* refresh the display */\n fb_dev->refresh(fb_dev, fb_refresh1, NULL);\n }\n \n i = 0;\n for(;;) {\n /* wait for an event: the only asynchronous event is the RTC timer */\n delay = virt_machine_get_sleep_duration(m, MAX_SLEEP_TIME);\n if (delay != 0 || i >= MAX_EXEC_TOTAL_CYCLE / MAX_EXEC_CYCLE)\n break;\n virt_machine_interp(m, MAX_EXEC_CYCLE);\n i++;\n }\n return i * MAX_EXEC_CYCLE;\n \n /*\n if (delay == 0) {\n emscripten_async_call(virt_machine_run, m, 0);\n } else {\n emscripten_async_call(virt_machine_run, m, MAX_SLEEP_TIME);\n }\n */\n}\n\n"], ["/linuxpdf/tinyemu/pckbd.c", "/*\n * QEMU PC keyboard emulation\n *\n * Copyright (c) 2003 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n/* debug PC keyboard */\n//#define DEBUG_KBD\n\n/* debug PC keyboard : only mouse */\n//#define DEBUG_MOUSE\n\n/*\tKeyboard Controller Commands */\n#define KBD_CCMD_READ_MODE\t0x20\t/* Read mode bits */\n#define KBD_CCMD_WRITE_MODE\t0x60\t/* Write mode bits */\n#define KBD_CCMD_GET_VERSION\t0xA1\t/* Get controller version */\n#define KBD_CCMD_MOUSE_DISABLE\t0xA7\t/* Disable mouse interface */\n#define KBD_CCMD_MOUSE_ENABLE\t0xA8\t/* Enable mouse interface */\n#define KBD_CCMD_TEST_MOUSE\t0xA9\t/* Mouse interface test */\n#define KBD_CCMD_SELF_TEST\t0xAA\t/* Controller self test */\n#define KBD_CCMD_KBD_TEST\t0xAB\t/* Keyboard interface test */\n#define KBD_CCMD_KBD_DISABLE\t0xAD\t/* Keyboard interface disable */\n#define KBD_CCMD_KBD_ENABLE\t0xAE\t/* Keyboard interface enable */\n#define KBD_CCMD_READ_INPORT 0xC0 /* read input port */\n#define KBD_CCMD_READ_OUTPORT\t0xD0 /* read output port */\n#define KBD_CCMD_WRITE_OUTPORT\t0xD1 /* write output port */\n#define KBD_CCMD_WRITE_OBUF\t0xD2\n#define KBD_CCMD_WRITE_AUX_OBUF\t0xD3 /* Write to output buffer as if\n\t\t\t\t\t initiated by the auxiliary device */\n#define KBD_CCMD_WRITE_MOUSE\t0xD4\t/* Write the following byte to the mouse */\n#define KBD_CCMD_DISABLE_A20 0xDD /* HP vectra only ? */\n#define KBD_CCMD_ENABLE_A20 0xDF /* HP vectra only ? */\n#define KBD_CCMD_RESET\t 0xFE\n\n/* Status Register Bits */\n#define KBD_STAT_OBF \t\t0x01\t/* Keyboard output buffer full */\n#define KBD_STAT_IBF \t\t0x02\t/* Keyboard input buffer full */\n#define KBD_STAT_SELFTEST\t0x04\t/* Self test successful */\n#define KBD_STAT_CMD\t\t0x08\t/* Last write was a command write (0=data) */\n#define KBD_STAT_UNLOCKED\t0x10\t/* Zero if keyboard locked */\n#define KBD_STAT_MOUSE_OBF\t0x20\t/* Mouse output buffer full */\n#define KBD_STAT_GTO \t\t0x40\t/* General receive/xmit timeout */\n#define KBD_STAT_PERR \t\t0x80\t/* Parity error */\n\n/* Controller Mode Register Bits */\n#define KBD_MODE_KBD_INT\t0x01\t/* Keyboard data generate IRQ1 */\n#define KBD_MODE_MOUSE_INT\t0x02\t/* Mouse data generate IRQ12 */\n#define KBD_MODE_SYS \t\t0x04\t/* The system flag (?) */\n#define KBD_MODE_NO_KEYLOCK\t0x08\t/* The keylock doesn't affect the keyboard if set */\n#define KBD_MODE_DISABLE_KBD\t0x10\t/* Disable keyboard interface */\n#define KBD_MODE_DISABLE_MOUSE\t0x20\t/* Disable mouse interface */\n#define KBD_MODE_KCC \t\t0x40\t/* Scan code conversion to PC format */\n#define KBD_MODE_RFU\t\t0x80\n\n#define KBD_PENDING_KBD 1\n#define KBD_PENDING_AUX 2\n\nstruct KBDState {\n uint8_t write_cmd; /* if non zero, write data to port 60 is expected */\n uint8_t status;\n uint8_t mode;\n /* Bitmask of devices with data available. */\n uint8_t pending;\n PS2KbdState *kbd;\n PS2MouseState *mouse;\n\n IRQSignal *irq_kbd;\n IRQSignal *irq_mouse;\n};\n\nstatic void qemu_system_reset_request(void)\n{\n printf(\"system_reset_request\\n\");\n exit(1);\n /* XXX */\n}\n\nstatic void ioport_set_a20(int val)\n{\n}\n\nstatic int ioport_get_a20(void)\n{\n return 1;\n}\n\n/* update irq and KBD_STAT_[MOUSE_]OBF */\n/* XXX: not generating the irqs if KBD_MODE_DISABLE_KBD is set may be\n incorrect, but it avoids having to simulate exact delays */\nstatic void kbd_update_irq(KBDState *s)\n{\n int irq_kbd_level, irq_mouse_level;\n\n irq_kbd_level = 0;\n irq_mouse_level = 0;\n s->status &= ~(KBD_STAT_OBF | KBD_STAT_MOUSE_OBF);\n if (s->pending) {\n s->status |= KBD_STAT_OBF;\n /* kbd data takes priority over aux data. */\n if (s->pending == KBD_PENDING_AUX) {\n s->status |= KBD_STAT_MOUSE_OBF;\n if (s->mode & KBD_MODE_MOUSE_INT)\n irq_mouse_level = 1;\n } else {\n if ((s->mode & KBD_MODE_KBD_INT) &&\n !(s->mode & KBD_MODE_DISABLE_KBD))\n irq_kbd_level = 1;\n }\n }\n set_irq(s->irq_kbd, irq_kbd_level);\n set_irq(s->irq_mouse, irq_mouse_level);\n}\n\nstatic void kbd_update_kbd_irq(void *opaque, int level)\n{\n KBDState *s = (KBDState *)opaque;\n\n if (level)\n s->pending |= KBD_PENDING_KBD;\n else\n s->pending &= ~KBD_PENDING_KBD;\n kbd_update_irq(s);\n}\n\nstatic void kbd_update_aux_irq(void *opaque, int level)\n{\n KBDState *s = (KBDState *)opaque;\n\n if (level)\n s->pending |= KBD_PENDING_AUX;\n else\n s->pending &= ~KBD_PENDING_AUX;\n kbd_update_irq(s);\n}\n\nstatic uint32_t kbd_read_status(void *opaque, uint32_t addr, int size_log2)\n{\n KBDState *s = opaque;\n int val;\n val = s->status;\n#if defined(DEBUG_KBD)\n printf(\"kbd: read status=0x%02x\\n\", val);\n#endif\n return val;\n}\n\nstatic void kbd_queue(KBDState *s, int b, int aux)\n{\n if (aux)\n ps2_queue(s->mouse, b);\n else\n ps2_queue(s->kbd, b);\n}\n\nstatic void kbd_write_command(void *opaque, uint32_t addr, uint32_t val,\n int size_log2)\n{\n KBDState *s = opaque;\n\n#if defined(DEBUG_KBD)\n printf(\"kbd: write cmd=0x%02x\\n\", val);\n#endif\n switch(val) {\n case KBD_CCMD_READ_MODE:\n kbd_queue(s, s->mode, 1);\n break;\n case KBD_CCMD_WRITE_MODE:\n case KBD_CCMD_WRITE_OBUF:\n case KBD_CCMD_WRITE_AUX_OBUF:\n case KBD_CCMD_WRITE_MOUSE:\n case KBD_CCMD_WRITE_OUTPORT:\n s->write_cmd = val;\n break;\n case KBD_CCMD_MOUSE_DISABLE:\n s->mode |= KBD_MODE_DISABLE_MOUSE;\n break;\n case KBD_CCMD_MOUSE_ENABLE:\n s->mode &= ~KBD_MODE_DISABLE_MOUSE;\n break;\n case KBD_CCMD_TEST_MOUSE:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_SELF_TEST:\n s->status |= KBD_STAT_SELFTEST;\n kbd_queue(s, 0x55, 0);\n break;\n case KBD_CCMD_KBD_TEST:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_KBD_DISABLE:\n s->mode |= KBD_MODE_DISABLE_KBD;\n kbd_update_irq(s);\n break;\n case KBD_CCMD_KBD_ENABLE:\n s->mode &= ~KBD_MODE_DISABLE_KBD;\n kbd_update_irq(s);\n break;\n case KBD_CCMD_READ_INPORT:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_READ_OUTPORT:\n /* XXX: check that */\n val = 0x01 | (ioport_get_a20() << 1);\n if (s->status & KBD_STAT_OBF)\n val |= 0x10;\n if (s->status & KBD_STAT_MOUSE_OBF)\n val |= 0x20;\n kbd_queue(s, val, 0);\n break;\n case KBD_CCMD_ENABLE_A20:\n ioport_set_a20(1);\n break;\n case KBD_CCMD_DISABLE_A20:\n ioport_set_a20(0);\n break;\n case KBD_CCMD_RESET:\n qemu_system_reset_request();\n break;\n case 0xff:\n /* ignore that - I don't know what is its use */\n break;\n default:\n fprintf(stderr, \"qemu: unsupported keyboard cmd=0x%02x\\n\", val);\n break;\n }\n}\n\nstatic uint32_t kbd_read_data(void *opaque, uint32_t addr, int size_log2)\n{\n KBDState *s = opaque;\n uint32_t val;\n if (s->pending == KBD_PENDING_AUX)\n val = ps2_read_data(s->mouse);\n else\n val = ps2_read_data(s->kbd);\n#ifdef DEBUG_KBD\n printf(\"kbd: read data=0x%02x\\n\", val);\n#endif\n return val;\n}\n\nstatic void kbd_write_data(void *opaque, uint32_t addr, uint32_t val, int size_log2)\n{\n KBDState *s = opaque;\n\n#ifdef DEBUG_KBD\n printf(\"kbd: write data=0x%02x\\n\", val);\n#endif\n\n switch(s->write_cmd) {\n case 0:\n ps2_write_keyboard(s->kbd, val);\n break;\n case KBD_CCMD_WRITE_MODE:\n s->mode = val;\n ps2_keyboard_set_translation(s->kbd, (s->mode & KBD_MODE_KCC) != 0);\n /* ??? */\n kbd_update_irq(s);\n break;\n case KBD_CCMD_WRITE_OBUF:\n kbd_queue(s, val, 0);\n break;\n case KBD_CCMD_WRITE_AUX_OBUF:\n kbd_queue(s, val, 1);\n break;\n case KBD_CCMD_WRITE_OUTPORT:\n ioport_set_a20((val >> 1) & 1);\n if (!(val & 1)) {\n qemu_system_reset_request();\n }\n break;\n case KBD_CCMD_WRITE_MOUSE:\n ps2_write_mouse(s->mouse, val);\n break;\n default:\n break;\n }\n s->write_cmd = 0;\n}\n\nstatic void kbd_reset(void *opaque)\n{\n KBDState *s = opaque;\n\n s->mode = KBD_MODE_KBD_INT | KBD_MODE_MOUSE_INT;\n s->status = KBD_STAT_CMD | KBD_STAT_UNLOCKED;\n}\n\nKBDState *i8042_init(PS2KbdState **pkbd,\n PS2MouseState **pmouse,\n PhysMemoryMap *port_map,\n IRQSignal *kbd_irq, IRQSignal *mouse_irq, uint32_t io_base)\n{\n KBDState *s;\n \n s = mallocz(sizeof(*s));\n \n s->irq_kbd = kbd_irq;\n s->irq_mouse = mouse_irq;\n\n kbd_reset(s);\n cpu_register_device(port_map, io_base, 1, s, kbd_read_data, kbd_write_data, \n DEVIO_SIZE8);\n cpu_register_device(port_map, io_base + 4, 1, s, kbd_read_status, kbd_write_command, \n DEVIO_SIZE8);\n\n s->kbd = ps2_kbd_init(kbd_update_kbd_irq, s);\n s->mouse = ps2_mouse_init(kbd_update_aux_irq, s);\n\n *pkbd = s->kbd;\n *pmouse = s->mouse;\n return s;\n}\n"], ["/linuxpdf/tinyemu/fs_wget.c", "/*\n * HTTP file download\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n\n#if defined(EMSCRIPTEN)\n#include \n#else\n#include \n#endif\n\n/***********************************************/\n/* HTTP get */\n\n#ifdef EMSCRIPTEN\n\nstruct XHRState {\n void *opaque;\n WGetWriteCallback *cb;\n};\n\nstatic int downloading_count;\n\nvoid fs_wget_init(void)\n{\n}\n\nextern void fs_wget_update_downloading(int flag);\n\nstatic void fs_wget_update_downloading_count(int incr)\n{\n int prev_state, state;\n prev_state = (downloading_count > 0);\n downloading_count += incr;\n state = (downloading_count > 0);\n if (prev_state != state)\n fs_wget_update_downloading(state);\n}\n\nstatic void fs_wget_onerror(unsigned int handle, void *opaque, int status,\n const char *status_text)\n{\n XHRState *s = opaque;\n if (status <= 0)\n status = -404; /* HTTP not found error */\n else\n status = -status;\n fs_wget_update_downloading_count(-1);\n if (s->cb)\n s->cb(s->opaque, status, NULL, 0);\n}\n\nstatic void fs_wget_onload(unsigned int handle,\n void *opaque, void *data, unsigned int size)\n{\n XHRState *s = opaque;\n fs_wget_update_downloading_count(-1);\n if (s->cb)\n s->cb(s->opaque, 0, data, size);\n}\n\nextern int emscripten_async_wget3_data(const char* url, const char* requesttype, const char *user, const char *password, const uint8_t *post_data, int post_data_len, void *arg, int free, em_async_wget2_data_onload_func onload, em_async_wget2_data_onerror_func onerror, em_async_wget2_data_onprogress_func onprogress);\n\nXHRState *fs_wget2(const char *url, const char *user, const char *password,\n WGetReadCallback *read_cb, uint64_t post_data_len,\n void *opaque, WGetWriteCallback *cb, BOOL single_write)\n{\n XHRState *s;\n const char *request;\n uint8_t *post_data;\n \n s = mallocz(sizeof(*s));\n s->opaque = opaque;\n s->cb = cb;\n\n if (post_data_len != 0) {\n request = \"POST\";\n post_data = malloc(post_data_len);\n read_cb(opaque, post_data, post_data_len);\n } else {\n request = \"GET\";\n post_data = NULL;\n }\n fs_wget_update_downloading_count(1);\n\n emscripten_async_wget3_data(url, request, user, password,\n post_data, post_data_len, s, 1, fs_wget_onload,\n fs_wget_onerror, NULL);\n if (post_data_len != 0)\n free(post_data);\n return s;\n}\n\nvoid fs_wget_free(XHRState *s)\n{\n s->cb = NULL;\n s->opaque = NULL;\n}\n\n#else\n\nstruct XHRState {\n struct list_head link;\n CURL *eh;\n void *opaque;\n WGetWriteCallback *write_cb;\n WGetReadCallback *read_cb;\n\n BOOL single_write;\n DynBuf dbuf; /* used if single_write */\n};\n\ntypedef struct {\n struct list_head link;\n int64_t timeout;\n void (*cb)(void *opaque);\n void *opaque;\n} AsyncCallState;\n\nstatic CURLM *curl_multi_ctx;\nstatic struct list_head xhr_list; /* list of XHRState.link */\n\nvoid fs_wget_init(void)\n{\n if (curl_multi_ctx)\n return;\n curl_global_init(CURL_GLOBAL_ALL);\n curl_multi_ctx = curl_multi_init();\n init_list_head(&xhr_list);\n}\n\nvoid fs_wget_end(void)\n{\n curl_multi_cleanup(curl_multi_ctx);\n curl_global_cleanup();\n}\n\nstatic size_t fs_wget_write_cb(char *ptr, size_t size, size_t nmemb,\n void *userdata)\n{\n XHRState *s = userdata;\n size *= nmemb;\n\n if (s->single_write) {\n dbuf_write(&s->dbuf, s->dbuf.size, (void *)ptr, size);\n } else {\n s->write_cb(s->opaque, 1, ptr, size);\n }\n return size;\n}\n\nstatic size_t fs_wget_read_cb(char *ptr, size_t size, size_t nmemb,\n void *userdata)\n{\n XHRState *s = userdata;\n size *= nmemb;\n return s->read_cb(s->opaque, ptr, size);\n}\n\nXHRState *fs_wget2(const char *url, const char *user, const char *password,\n WGetReadCallback *read_cb, uint64_t post_data_len,\n void *opaque, WGetWriteCallback *write_cb, BOOL single_write)\n{\n XHRState *s;\n s = mallocz(sizeof(*s));\n s->eh = curl_easy_init();\n s->opaque = opaque;\n s->write_cb = write_cb;\n s->read_cb = read_cb;\n s->single_write = single_write;\n dbuf_init(&s->dbuf);\n \n curl_easy_setopt(s->eh, CURLOPT_PRIVATE, s);\n curl_easy_setopt(s->eh, CURLOPT_WRITEDATA, s);\n curl_easy_setopt(s->eh, CURLOPT_WRITEFUNCTION, fs_wget_write_cb);\n curl_easy_setopt(s->eh, CURLOPT_HEADER, 0);\n curl_easy_setopt(s->eh, CURLOPT_URL, url);\n curl_easy_setopt(s->eh, CURLOPT_VERBOSE, 0L);\n curl_easy_setopt(s->eh, CURLOPT_ACCEPT_ENCODING, \"\");\n if (user) {\n curl_easy_setopt(s->eh, CURLOPT_USERNAME, user);\n curl_easy_setopt(s->eh, CURLOPT_PASSWORD, password);\n }\n if (post_data_len != 0) {\n struct curl_slist *headers = NULL;\n headers = curl_slist_append(headers,\n \"Content-Type: application/octet-stream\");\n curl_easy_setopt(s->eh, CURLOPT_HTTPHEADER, headers);\n curl_easy_setopt(s->eh, CURLOPT_POST, 1L);\n curl_easy_setopt(s->eh, CURLOPT_POSTFIELDSIZE_LARGE,\n (curl_off_t)post_data_len);\n curl_easy_setopt(s->eh, CURLOPT_READDATA, s);\n curl_easy_setopt(s->eh, CURLOPT_READFUNCTION, fs_wget_read_cb);\n }\n curl_multi_add_handle(curl_multi_ctx, s->eh);\n list_add_tail(&s->link, &xhr_list);\n return s;\n}\n\nvoid fs_wget_free(XHRState *s)\n{\n dbuf_free(&s->dbuf);\n curl_easy_cleanup(s->eh);\n list_del(&s->link);\n free(s);\n}\n\n/* timeout is in ms */\nvoid fs_net_set_fdset(int *pfd_max, fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *ptimeout)\n{\n long timeout;\n int n, fd_max;\n CURLMsg *msg;\n \n if (!curl_multi_ctx)\n return;\n \n curl_multi_perform(curl_multi_ctx, &n);\n\n for(;;) {\n msg = curl_multi_info_read(curl_multi_ctx, &n);\n if (!msg)\n break;\n if (msg->msg == CURLMSG_DONE) {\n XHRState *s;\n long http_code;\n\n curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char **)&s);\n curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE,\n &http_code);\n /* signal the end of the transfer or error */\n if (http_code == 200) {\n if (s->single_write) {\n s->write_cb(s->opaque, 0, s->dbuf.buf, s->dbuf.size);\n } else {\n s->write_cb(s->opaque, 0, NULL, 0);\n }\n } else {\n s->write_cb(s->opaque, -http_code, NULL, 0);\n }\n curl_multi_remove_handle(curl_multi_ctx, s->eh);\n curl_easy_cleanup(s->eh);\n dbuf_free(&s->dbuf);\n list_del(&s->link);\n free(s);\n }\n }\n\n curl_multi_fdset(curl_multi_ctx, rfds, wfds, efds, &fd_max);\n *pfd_max = max_int(*pfd_max, fd_max);\n curl_multi_timeout(curl_multi_ctx, &timeout);\n if (timeout >= 0)\n *ptimeout = min_int(*ptimeout, timeout);\n}\n\nvoid fs_net_event_loop(FSNetEventLoopCompletionFunc *cb, void *opaque)\n{\n fd_set rfds, wfds, efds;\n int timeout, fd_max;\n struct timeval tv;\n \n if (!curl_multi_ctx)\n return;\n\n for(;;) {\n fd_max = -1;\n FD_ZERO(&rfds);\n FD_ZERO(&wfds);\n FD_ZERO(&efds);\n timeout = 10000;\n fs_net_set_fdset(&fd_max, &rfds, &wfds, &efds, &timeout);\n if (cb) {\n if (cb(opaque))\n break;\n } else {\n if (list_empty(&xhr_list))\n break;\n }\n tv.tv_sec = timeout / 1000;\n tv.tv_usec = (timeout % 1000) * 1000;\n select(fd_max + 1, &rfds, &wfds, &efds, &tv);\n }\n}\n\n#endif /* !EMSCRIPTEN */\n\nXHRState *fs_wget(const char *url, const char *user, const char *password,\n void *opaque, WGetWriteCallback *cb, BOOL single_write)\n{\n return fs_wget2(url, user, password, NULL, 0, opaque, cb, single_write);\n}\n\n/***********************************************/\n/* file decryption */\n\n#define ENCRYPTED_FILE_HEADER_SIZE (4 + AES_BLOCK_SIZE)\n\n#define DEC_BUF_SIZE (256 * AES_BLOCK_SIZE)\n\nstruct DecryptFileState {\n DecryptFileCB *write_cb;\n void *opaque;\n int dec_state;\n int dec_buf_pos;\n AES_KEY *aes_state;\n uint8_t iv[AES_BLOCK_SIZE];\n uint8_t dec_buf[DEC_BUF_SIZE];\n};\n\nDecryptFileState *decrypt_file_init(AES_KEY *aes_state,\n DecryptFileCB *write_cb,\n void *opaque)\n{\n DecryptFileState *s;\n s = mallocz(sizeof(*s));\n s->write_cb = write_cb;\n s->opaque = opaque;\n s->aes_state = aes_state;\n return s;\n}\n \nint decrypt_file(DecryptFileState *s, const uint8_t *data,\n size_t size)\n{\n int l, len, ret;\n\n while (size != 0) {\n switch(s->dec_state) {\n case 0:\n l = min_int(size, ENCRYPTED_FILE_HEADER_SIZE - s->dec_buf_pos);\n memcpy(s->dec_buf + s->dec_buf_pos, data, l);\n s->dec_buf_pos += l;\n if (s->dec_buf_pos >= ENCRYPTED_FILE_HEADER_SIZE) {\n if (memcmp(s->dec_buf, encrypted_file_magic, 4) != 0)\n return -1;\n memcpy(s->iv, s->dec_buf + 4, AES_BLOCK_SIZE);\n s->dec_state = 1;\n s->dec_buf_pos = 0;\n }\n break;\n case 1:\n l = min_int(size, DEC_BUF_SIZE - s->dec_buf_pos);\n memcpy(s->dec_buf + s->dec_buf_pos, data, l);\n s->dec_buf_pos += l;\n if (s->dec_buf_pos >= DEC_BUF_SIZE) {\n /* keep one block in case it is the padding */\n len = s->dec_buf_pos - AES_BLOCK_SIZE;\n AES_cbc_encrypt(s->dec_buf, s->dec_buf, len,\n s->aes_state, s->iv, FALSE);\n ret = s->write_cb(s->opaque, s->dec_buf, len);\n if (ret < 0)\n return ret;\n memcpy(s->dec_buf, s->dec_buf + s->dec_buf_pos - AES_BLOCK_SIZE,\n AES_BLOCK_SIZE);\n s->dec_buf_pos = AES_BLOCK_SIZE;\n }\n break;\n default:\n abort();\n }\n data += l;\n size -= l;\n }\n return 0;\n}\n\n/* write last blocks */\nint decrypt_file_flush(DecryptFileState *s)\n{\n int len, pad_len, ret;\n\n if (s->dec_state != 1)\n return -1;\n len = s->dec_buf_pos;\n if (len == 0 || \n (len % AES_BLOCK_SIZE) != 0)\n return -1;\n AES_cbc_encrypt(s->dec_buf, s->dec_buf, len,\n s->aes_state, s->iv, FALSE);\n pad_len = s->dec_buf[s->dec_buf_pos - 1];\n if (pad_len < 1 || pad_len > AES_BLOCK_SIZE)\n return -1;\n len -= pad_len;\n if (len != 0) {\n ret = s->write_cb(s->opaque, s->dec_buf, len);\n if (ret < 0)\n return ret;\n }\n return 0;\n}\n\nvoid decrypt_file_end(DecryptFileState *s)\n{\n free(s);\n}\n\n/* XHR file */\n\ntypedef struct {\n FSDevice *fs;\n FSFile *f;\n int64_t pos;\n FSWGetFileCB *cb;\n void *opaque;\n FSFile *posted_file;\n int64_t read_pos;\n DecryptFileState *dec_state;\n} FSWGetFileState;\n\nstatic int fs_wget_file_write_cb(void *opaque, const uint8_t *data,\n size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n\n ret = fs->fs_write(fs, s->f, s->pos, data, size);\n if (ret < 0)\n return ret;\n s->pos += ret;\n return ret;\n}\n\nstatic void fs_wget_file_on_load(void *opaque, int err, void *data, size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n int64_t ret_size;\n \n // printf(\"err=%d size=%ld\\n\", err, size);\n if (err < 0) {\n ret_size = err;\n goto done;\n } else {\n if (s->dec_state) {\n ret = decrypt_file(s->dec_state, data, size);\n if (ret >= 0 && err == 0) {\n /* handle the end of file */\n decrypt_file_flush(s->dec_state);\n }\n } else {\n ret = fs_wget_file_write_cb(s, data, size);\n }\n if (ret < 0) {\n ret_size = ret;\n goto done;\n } else if (err == 0) {\n /* end of transfer */\n ret_size = s->pos;\n done:\n s->cb(fs, s->f, ret_size, s->opaque);\n if (s->dec_state)\n decrypt_file_end(s->dec_state);\n free(s);\n }\n }\n}\n\nstatic size_t fs_wget_file_read_cb(void *opaque, void *data, size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n \n if (!s->posted_file)\n return 0;\n ret = fs->fs_read(fs, s->posted_file, s->read_pos, data, size);\n if (ret < 0)\n return 0;\n s->read_pos += ret;\n return ret;\n}\n\nvoid fs_wget_file2(FSDevice *fs, FSFile *f, const char *url,\n const char *user, const char *password,\n FSFile *posted_file, uint64_t post_data_len,\n FSWGetFileCB *cb, void *opaque,\n AES_KEY *aes_state)\n{\n FSWGetFileState *s;\n s = mallocz(sizeof(*s));\n s->fs = fs;\n s->f = f;\n s->pos = 0;\n s->cb = cb;\n s->opaque = opaque;\n s->posted_file = posted_file;\n s->read_pos = 0;\n if (aes_state) {\n s->dec_state = decrypt_file_init(aes_state, fs_wget_file_write_cb, s);\n }\n \n fs_wget2(url, user, password, fs_wget_file_read_cb, post_data_len,\n s, fs_wget_file_on_load, FALSE);\n}\n\n/***********************************************/\n/* PBKDF2 */\n\n#ifdef USE_BUILTIN_CRYPTO\n\n#define HMAC_BLOCK_SIZE 64\n\ntypedef struct {\n SHA256_CTX ctx;\n uint8_t K[HMAC_BLOCK_SIZE + SHA256_DIGEST_LENGTH];\n} HMAC_SHA256_CTX;\n\nvoid hmac_sha256_init(HMAC_SHA256_CTX *s, const uint8_t *key, int key_len)\n{\n int i, l;\n \n if (key_len > HMAC_BLOCK_SIZE) {\n SHA256(key, key_len, s->K);\n l = SHA256_DIGEST_LENGTH;\n } else {\n memcpy(s->K, key, key_len);\n l = key_len;\n }\n memset(s->K + l, 0, HMAC_BLOCK_SIZE - l);\n for(i = 0; i < HMAC_BLOCK_SIZE; i++)\n s->K[i] ^= 0x36;\n SHA256_Init(&s->ctx);\n SHA256_Update(&s->ctx, s->K, HMAC_BLOCK_SIZE);\n}\n\nvoid hmac_sha256_update(HMAC_SHA256_CTX *s, const uint8_t *buf, int len)\n{\n SHA256_Update(&s->ctx, buf, len);\n}\n\n/* out has a length of SHA256_DIGEST_LENGTH */\nvoid hmac_sha256_final(HMAC_SHA256_CTX *s, uint8_t *out)\n{\n int i;\n \n SHA256_Final(s->K + HMAC_BLOCK_SIZE, &s->ctx);\n for(i = 0; i < HMAC_BLOCK_SIZE; i++)\n s->K[i] ^= (0x36 ^ 0x5c);\n SHA256(s->K, HMAC_BLOCK_SIZE + SHA256_DIGEST_LENGTH, out);\n}\n\n#define SALT_LEN_MAX 32\n\nvoid pbkdf2_hmac_sha256(const uint8_t *pwd, int pwd_len,\n const uint8_t *salt, int salt_len,\n int iter, int key_len, uint8_t *out)\n{\n uint8_t F[SHA256_DIGEST_LENGTH], U[SALT_LEN_MAX + 4];\n HMAC_SHA256_CTX ctx;\n int it, U_len, j, l;\n uint32_t i;\n \n assert(salt_len <= SALT_LEN_MAX);\n i = 1;\n while (key_len > 0) {\n memset(F, 0, SHA256_DIGEST_LENGTH);\n memcpy(U, salt, salt_len);\n U[salt_len] = i >> 24;\n U[salt_len + 1] = i >> 16;\n U[salt_len + 2] = i >> 8;\n U[salt_len + 3] = i;\n U_len = salt_len + 4;\n for(it = 0; it < iter; it++) {\n hmac_sha256_init(&ctx, pwd, pwd_len);\n hmac_sha256_update(&ctx, U, U_len);\n hmac_sha256_final(&ctx, U);\n for(j = 0; j < SHA256_DIGEST_LENGTH; j++)\n F[j] ^= U[j];\n U_len = SHA256_DIGEST_LENGTH;\n }\n l = min_int(key_len, SHA256_DIGEST_LENGTH);\n memcpy(out, F, l);\n out += l;\n key_len -= l;\n i++;\n }\n}\n\n#else\n\nvoid pbkdf2_hmac_sha256(const uint8_t *pwd, int pwd_len,\n const uint8_t *salt, int salt_len,\n int iter, int key_len, uint8_t *out)\n{\n PKCS5_PBKDF2_HMAC((const char *)pwd, pwd_len, salt, salt_len,\n iter, EVP_sha256(), key_len, out);\n}\n\n#endif /* !USE_BUILTIN_CRYPTO */\n"], ["/linuxpdf/tinyemu/machine.c", "/*\n * VM utilities\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#include \"fs_utils.h\"\n#ifdef CONFIG_FS_NET\n#include \"fs_wget.h\"\n#endif\n\nvoid __attribute__((format(printf, 1, 2))) vm_error(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n#ifdef EMSCRIPTEN\n vprintf(fmt, ap);\n#else\n vfprintf(stderr, fmt, ap);\n#endif\n va_end(ap);\n}\n\nint vm_get_int(JSONValue obj, const char *name, int *pval)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n vm_error(\"expecting '%s' property\\n\", name);\n return -1;\n }\n if (val.type != JSON_INT) {\n vm_error(\"%s: integer expected\\n\", name);\n return -1;\n }\n *pval = val.u.int32;\n return 0;\n}\n\nint vm_get_int_opt(JSONValue obj, const char *name, int *pval, int def_val)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n *pval = def_val;\n return 0;\n }\n if (val.type != JSON_INT) {\n vm_error(\"%s: integer expected\\n\", name);\n return -1;\n }\n *pval = val.u.int32;\n return 0;\n}\n\nstatic int vm_get_str2(JSONValue obj, const char *name, const char **pstr,\n BOOL is_opt)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n if (is_opt) {\n *pstr = NULL;\n return 0;\n } else {\n vm_error(\"expecting '%s' property\\n\", name);\n return -1;\n }\n }\n if (val.type != JSON_STR) {\n vm_error(\"%s: string expected\\n\", name);\n return -1;\n }\n *pstr = val.u.str->data;\n return 0;\n}\n\nstatic int vm_get_str(JSONValue obj, const char *name, const char **pstr)\n{ \n return vm_get_str2(obj, name, pstr, FALSE);\n}\n\nstatic int vm_get_str_opt(JSONValue obj, const char *name, const char **pstr)\n{ \n return vm_get_str2(obj, name, pstr, TRUE);\n}\n\nstatic char *strdup_null(const char *str)\n{\n if (!str)\n return NULL;\n else\n return strdup(str);\n}\n\n/* currently only for \"TZ\" */\nstatic char *cmdline_subst(const char *cmdline)\n{\n DynBuf dbuf;\n const char *p;\n char var_name[32], *q, buf[32];\n \n dbuf_init(&dbuf);\n p = cmdline;\n while (*p != '\\0') {\n if (p[0] == '$' && p[1] == '{') {\n p += 2;\n q = var_name;\n while (*p != '\\0' && *p != '}') {\n if ((q - var_name) < sizeof(var_name) - 1)\n *q++ = *p;\n p++;\n }\n *q = '\\0';\n if (*p == '}')\n p++;\n if (!strcmp(var_name, \"TZ\")) {\n time_t ti;\n struct tm tm;\n int n, sg;\n /* get the offset to UTC */\n time(&ti);\n localtime_r(&ti, &tm);\n n = tm.tm_gmtoff / 60;\n sg = '-';\n if (n < 0) {\n sg = '+';\n n = -n;\n }\n snprintf(buf, sizeof(buf), \"UTC%c%02d:%02d\",\n sg, n / 60, n % 60);\n dbuf_putstr(&dbuf, buf);\n }\n } else {\n dbuf_putc(&dbuf, *p++);\n }\n }\n dbuf_putc(&dbuf, 0);\n return (char *)dbuf.buf;\n}\n\nstatic BOOL find_name(const char *name, const char *name_list)\n{\n size_t len;\n const char *p, *r;\n \n p = name_list;\n for(;;) {\n r = strchr(p, ',');\n if (!r) {\n if (!strcmp(name, p))\n return TRUE;\n break;\n } else {\n len = r - p;\n if (len == strlen(name) && !memcmp(name, p, len))\n return TRUE;\n p = r + 1;\n }\n }\n return FALSE;\n}\n\nstatic const VirtMachineClass *virt_machine_list[] = {\n#if defined(EMSCRIPTEN)\n /* only a single machine in the EMSCRIPTEN target */\n#ifndef CONFIG_X86EMU\n &riscv_machine_class,\n#endif \n#else\n &riscv_machine_class,\n#endif /* !EMSCRIPTEN */\n#ifdef CONFIG_X86EMU\n &pc_machine_class,\n#endif\n NULL,\n};\n\nstatic const VirtMachineClass *virt_machine_find_class(const char *machine_name)\n{\n const VirtMachineClass *vmc, **pvmc;\n \n for(pvmc = virt_machine_list; *pvmc != NULL; pvmc++) {\n vmc = *pvmc;\n if (find_name(machine_name, vmc->machine_names))\n return vmc;\n }\n return NULL;\n}\n\nstatic int virt_machine_parse_config(VirtMachineParams *p,\n char *config_file_str, int len)\n{\n int version, val;\n const char *tag_name, *str;\n char buf1[256];\n JSONValue cfg, obj, el;\n \n cfg = json_parse_value_len(config_file_str, len);\n if (json_is_error(cfg)) {\n vm_error(\"error: %s\\n\", json_get_error(cfg));\n json_free(cfg);\n return -1;\n }\n\n if (vm_get_int(cfg, \"version\", &version) < 0)\n goto tag_fail;\n if (version != VM_CONFIG_VERSION) {\n if (version > VM_CONFIG_VERSION) {\n vm_error(\"The emulator is too old to run this VM: please upgrade\\n\");\n return -1;\n } else {\n vm_error(\"The VM configuration file is too old for this emulator version: please upgrade the VM configuration file\\n\");\n return -1;\n }\n }\n \n if (vm_get_str(cfg, \"machine\", &str) < 0)\n goto tag_fail;\n p->machine_name = strdup(str);\n p->vmc = virt_machine_find_class(p->machine_name);\n if (!p->vmc) {\n vm_error(\"Unknown machine name: %s\\n\", p->machine_name);\n goto tag_fail;\n }\n p->vmc->virt_machine_set_defaults(p);\n\n tag_name = \"memory_size\";\n if (vm_get_int(cfg, tag_name, &val) < 0)\n goto tag_fail;\n p->ram_size = (uint64_t)val << 20;\n \n tag_name = \"bios\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_BIOS].filename = strdup(str);\n }\n\n tag_name = \"kernel\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_KERNEL].filename = strdup(str);\n }\n\n tag_name = \"initrd\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_INITRD].filename = strdup(str);\n }\n\n if (vm_get_str_opt(cfg, \"cmdline\", &str) < 0)\n goto tag_fail;\n if (str) {\n p->cmdline = cmdline_subst(str);\n }\n \n for(;;) {\n snprintf(buf1, sizeof(buf1), \"drive%d\", p->drive_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->drive_count >= MAX_DRIVE_DEVICE) {\n vm_error(\"Too many drives\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"file\", &str) < 0)\n goto tag_fail;\n p->tab_drive[p->drive_count].filename = strdup(str);\n if (vm_get_str_opt(obj, \"device\", &str) < 0)\n goto tag_fail;\n p->tab_drive[p->drive_count].device = strdup_null(str);\n p->drive_count++;\n }\n\n for(;;) {\n snprintf(buf1, sizeof(buf1), \"fs%d\", p->fs_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->fs_count >= MAX_DRIVE_DEVICE) {\n vm_error(\"Too many filesystems\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"file\", &str) < 0)\n goto tag_fail;\n p->tab_fs[p->fs_count].filename = strdup(str);\n if (vm_get_str_opt(obj, \"tag\", &str) < 0)\n goto tag_fail;\n if (!str) {\n if (p->fs_count == 0)\n strcpy(buf1, \"/dev/root\");\n else\n snprintf(buf1, sizeof(buf1), \"/dev/root%d\", p->fs_count);\n str = buf1;\n }\n p->tab_fs[p->fs_count].tag = strdup(str);\n p->fs_count++;\n }\n\n for(;;) {\n snprintf(buf1, sizeof(buf1), \"eth%d\", p->eth_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->eth_count >= MAX_ETH_DEVICE) {\n vm_error(\"Too many ethernet interfaces\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"driver\", &str) < 0)\n goto tag_fail;\n p->tab_eth[p->eth_count].driver = strdup(str);\n if (!strcmp(str, \"tap\")) {\n if (vm_get_str(obj, \"ifname\", &str) < 0)\n goto tag_fail;\n p->tab_eth[p->eth_count].ifname = strdup(str);\n }\n p->eth_count++;\n }\n\n p->display_device = NULL;\n obj = json_object_get(cfg, \"display0\");\n if (!json_is_undefined(obj)) {\n if (vm_get_str(obj, \"device\", &str) < 0)\n goto tag_fail;\n p->display_device = strdup(str);\n if (vm_get_int(obj, \"width\", &p->width) < 0)\n goto tag_fail;\n if (vm_get_int(obj, \"height\", &p->height) < 0)\n goto tag_fail;\n if (vm_get_str_opt(obj, \"vga_bios\", &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_VGA_BIOS].filename = strdup(str);\n }\n }\n\n if (vm_get_str_opt(cfg, \"input_device\", &str) < 0)\n goto tag_fail;\n p->input_device = strdup_null(str);\n\n if (vm_get_str_opt(cfg, \"accel\", &str) < 0)\n goto tag_fail;\n if (str) {\n if (!strcmp(str, \"none\")) {\n p->accel_enable = FALSE;\n } else if (!strcmp(str, \"auto\")) {\n p->accel_enable = TRUE;\n } else {\n vm_error(\"unsupported 'accel' config: %s\\n\", str);\n return -1;\n }\n }\n\n tag_name = \"rtc_local_time\";\n el = json_object_get(cfg, tag_name);\n if (!json_is_undefined(el)) {\n if (el.type != JSON_BOOL) {\n vm_error(\"%s: boolean expected\\n\", tag_name);\n goto tag_fail;\n }\n p->rtc_local_time = el.u.b;\n }\n \n json_free(cfg);\n return 0;\n tag_fail:\n json_free(cfg);\n return -1;\n}\n\ntypedef void FSLoadFileCB(void *opaque, uint8_t *buf, int buf_len);\n\ntypedef struct {\n VirtMachineParams *vm_params;\n void (*start_cb)(void *opaque);\n void *opaque;\n \n FSLoadFileCB *file_load_cb;\n void *file_load_opaque;\n int file_index;\n} VMConfigLoadState;\n\nstatic void config_file_loaded(void *opaque, uint8_t *buf, int buf_len);\nstatic void config_additional_file_load(VMConfigLoadState *s);\nstatic void config_additional_file_load_cb(void *opaque,\n uint8_t *buf, int buf_len);\n\n/* XXX: win32, URL */\nchar *get_file_path(const char *base_filename, const char *filename)\n{\n int len, len1;\n char *fname, *p;\n \n if (!base_filename)\n goto done;\n if (strchr(filename, ':'))\n goto done; /* full URL */\n if (filename[0] == '/')\n goto done;\n p = strrchr(base_filename, '/');\n if (!p) {\n done:\n return strdup(filename);\n }\n len = p + 1 - base_filename;\n len1 = strlen(filename);\n fname = malloc(len + len1 + 1);\n memcpy(fname, base_filename, len);\n memcpy(fname + len, filename, len1 + 1);\n return fname;\n}\n\n\n#ifdef EMSCRIPTEN\nstatic int load_file(uint8_t **pbuf, const char *filename)\n{\n abort();\n}\n#else\n/* return -1 if error. */\nstatic int load_file(uint8_t **pbuf, const char *filename)\n{\n FILE *f;\n int size;\n uint8_t *buf;\n \n f = fopen(filename, \"rb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n size = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = malloc(size);\n if (fread(buf, 1, size, f) != size) {\n fprintf(stderr, \"%s: read error\\n\", filename);\n exit(1);\n }\n fclose(f);\n *pbuf = buf;\n return size;\n}\n#endif\n\n#ifdef CONFIG_FS_NET\nstatic void config_load_file_cb(void *opaque, int err, void *data, size_t size)\n{\n VMConfigLoadState *s = opaque;\n \n // printf(\"err=%d data=%p size=%ld\\n\", err, data, size);\n if (err < 0) {\n vm_error(\"Error %d while loading file\\n\", -err);\n exit(1);\n }\n s->file_load_cb(s->file_load_opaque, data, size);\n}\n#endif\n\nstatic void config_load_file(VMConfigLoadState *s, const char *filename,\n FSLoadFileCB *cb, void *opaque)\n{\n // printf(\"loading %s\\n\", filename);\n#ifdef CONFIG_FS_NET\n if (is_url(filename)) {\n s->file_load_cb = cb;\n s->file_load_opaque = opaque;\n fs_wget(filename, NULL, NULL, s, config_load_file_cb, TRUE);\n } else\n#endif\n {\n uint8_t *buf;\n int size;\n size = load_file(&buf, filename);\n cb(opaque, buf, size);\n free(buf);\n }\n}\n\nvoid virt_machine_load_config_file(VirtMachineParams *p,\n const char *filename,\n void (*start_cb)(void *opaque),\n void *opaque)\n{\n VMConfigLoadState *s;\n \n s = mallocz(sizeof(*s));\n s->vm_params = p;\n s->start_cb = start_cb;\n s->opaque = opaque;\n p->cfg_filename = strdup(filename);\n\n config_load_file(s, filename, config_file_loaded, s);\n}\n\nstatic void config_file_loaded(void *opaque, uint8_t *buf, int buf_len)\n{\n VMConfigLoadState *s = opaque;\n VirtMachineParams *p = s->vm_params;\n\n if (virt_machine_parse_config(p, (char *)buf, buf_len) < 0)\n exit(1);\n \n /* load the additional files */\n s->file_index = 0;\n config_additional_file_load(s);\n}\n\nstatic void config_additional_file_load(VMConfigLoadState *s)\n{\n VirtMachineParams *p = s->vm_params;\n while (s->file_index < VM_FILE_COUNT &&\n p->files[s->file_index].filename == NULL) {\n s->file_index++;\n }\n if (s->file_index == VM_FILE_COUNT) {\n if (s->start_cb)\n s->start_cb(s->opaque);\n free(s);\n } else {\n char *fname;\n \n fname = get_file_path(p->cfg_filename,\n p->files[s->file_index].filename);\n config_load_file(s, fname,\n config_additional_file_load_cb, s);\n free(fname);\n }\n}\n\nstatic void config_additional_file_load_cb(void *opaque,\n uint8_t *buf, int buf_len)\n{\n VMConfigLoadState *s = opaque;\n VirtMachineParams *p = s->vm_params;\n\n p->files[s->file_index].buf = malloc(buf_len);\n memcpy(p->files[s->file_index].buf, buf, buf_len);\n p->files[s->file_index].len = buf_len;\n\n /* load the next files */\n s->file_index++;\n config_additional_file_load(s);\n}\n\nvoid vm_add_cmdline(VirtMachineParams *p, const char *cmdline)\n{\n char *new_cmdline, *old_cmdline;\n if (cmdline[0] == '!') {\n new_cmdline = strdup(cmdline + 1);\n } else {\n old_cmdline = p->cmdline;\n if (!old_cmdline)\n old_cmdline = \"\";\n new_cmdline = malloc(strlen(old_cmdline) + 1 + strlen(cmdline) + 1);\n strcpy(new_cmdline, old_cmdline);\n strcat(new_cmdline, \" \");\n strcat(new_cmdline, cmdline);\n }\n free(p->cmdline);\n p->cmdline = new_cmdline;\n}\n\nvoid virt_machine_free_config(VirtMachineParams *p)\n{\n int i;\n \n free(p->machine_name);\n free(p->cmdline);\n for(i = 0; i < VM_FILE_COUNT; i++) {\n free(p->files[i].filename);\n free(p->files[i].buf);\n }\n for(i = 0; i < p->drive_count; i++) {\n free(p->tab_drive[i].filename);\n free(p->tab_drive[i].device);\n }\n for(i = 0; i < p->fs_count; i++) {\n free(p->tab_fs[i].filename);\n free(p->tab_fs[i].tag);\n }\n for(i = 0; i < p->eth_count; i++) {\n free(p->tab_eth[i].driver);\n free(p->tab_eth[i].ifname);\n }\n free(p->input_device);\n free(p->display_device);\n free(p->cfg_filename);\n}\n\nVirtMachine *virt_machine_init(const VirtMachineParams *p)\n{\n const VirtMachineClass *vmc = p->vmc;\n return vmc->virt_machine_init(p);\n}\n\nvoid virt_machine_set_defaults(VirtMachineParams *p)\n{\n memset(p, 0, sizeof(*p));\n}\n\nvoid virt_machine_end(VirtMachine *s)\n{\n s->vmc->virt_machine_end(s);\n}\n"], ["/linuxpdf/tinyemu/vga.c", "/*\n * Dummy VGA device\n * \n * Copyright (c) 2003-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n//#define DEBUG_VBE\n\n#define MSR_COLOR_EMULATION 0x01\n#define MSR_PAGE_SELECT 0x20\n\n#define ST01_V_RETRACE 0x08\n#define ST01_DISP_ENABLE 0x01\n\n#define VBE_DISPI_INDEX_ID 0x0\n#define VBE_DISPI_INDEX_XRES 0x1\n#define VBE_DISPI_INDEX_YRES 0x2\n#define VBE_DISPI_INDEX_BPP 0x3\n#define VBE_DISPI_INDEX_ENABLE 0x4\n#define VBE_DISPI_INDEX_BANK 0x5\n#define VBE_DISPI_INDEX_VIRT_WIDTH 0x6\n#define VBE_DISPI_INDEX_VIRT_HEIGHT 0x7\n#define VBE_DISPI_INDEX_X_OFFSET 0x8\n#define VBE_DISPI_INDEX_Y_OFFSET 0x9\n#define VBE_DISPI_INDEX_VIDEO_MEMORY_64K 0xa\n#define VBE_DISPI_INDEX_NB 0xb\n\n#define VBE_DISPI_ID0 0xB0C0\n#define VBE_DISPI_ID1 0xB0C1\n#define VBE_DISPI_ID2 0xB0C2\n#define VBE_DISPI_ID3 0xB0C3\n#define VBE_DISPI_ID4 0xB0C4\n#define VBE_DISPI_ID5 0xB0C5\n\n#define VBE_DISPI_DISABLED 0x00\n#define VBE_DISPI_ENABLED 0x01\n#define VBE_DISPI_GETCAPS 0x02\n#define VBE_DISPI_8BIT_DAC 0x20\n#define VBE_DISPI_LFB_ENABLED 0x40\n#define VBE_DISPI_NOCLEARMEM 0x80\n\n#define FB_ALLOC_ALIGN (1 << 20)\n\n#define MAX_TEXT_WIDTH 132\n#define MAX_TEXT_HEIGHT 60\n\nstruct VGAState {\n FBDevice *fb_dev;\n int fb_page_count;\n PhysMemoryRange *mem_range;\n PhysMemoryRange *mem_range2;\n PCIDevice *pci_dev;\n PhysMemoryRange *rom_range;\n\n uint8_t *vga_ram; /* 128K at 0xa0000 */\n \n uint8_t sr_index;\n uint8_t sr[8];\n uint8_t gr_index;\n uint8_t gr[16];\n uint8_t ar_index;\n uint8_t ar[21];\n int ar_flip_flop;\n uint8_t cr_index;\n uint8_t cr[256]; /* CRT registers */\n uint8_t msr; /* Misc Output Register */\n uint8_t fcr; /* Feature Control Register */\n uint8_t st00; /* status 0 */\n uint8_t st01; /* status 1 */\n uint8_t dac_state;\n uint8_t dac_sub_index;\n uint8_t dac_read_index;\n uint8_t dac_write_index;\n uint8_t dac_cache[3]; /* used when writing */\n uint8_t palette[768];\n \n /* text mode state */\n uint32_t last_palette[16];\n uint16_t last_ch_attr[MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT];\n uint32_t last_width;\n uint32_t last_height;\n uint16_t last_line_offset;\n uint16_t last_start_addr;\n uint16_t last_cursor_offset;\n uint8_t last_cursor_start;\n uint8_t last_cursor_end;\n \n /* VBE extension */\n uint16_t vbe_index;\n uint16_t vbe_regs[VBE_DISPI_INDEX_NB];\n};\n\nstatic void vga_draw_glyph8(uint8_t *d, int linesize,\n const uint8_t *font_ptr, int h,\n uint32_t fgcol, uint32_t bgcol)\n{\n uint32_t font_data, xorcol;\n\n xorcol = bgcol ^ fgcol;\n do {\n font_data = font_ptr[0];\n ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol;\n ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[7] = (-((font_data >> 0) & 1) & xorcol) ^ bgcol;\n font_ptr++;\n d += linesize;\n } while (--h);\n}\n\nstatic void vga_draw_glyph9(uint8_t *d, int linesize,\n const uint8_t *font_ptr, int h,\n uint32_t fgcol, uint32_t bgcol,\n int dup9)\n{\n uint32_t font_data, xorcol, v;\n\n xorcol = bgcol ^ fgcol;\n do {\n font_data = font_ptr[0];\n ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol;\n ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol;\n v = (-((font_data >> 0) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[7] = v;\n if (dup9)\n ((uint32_t *)d)[8] = v;\n else\n ((uint32_t *)d)[8] = bgcol;\n font_ptr++;\n d += linesize;\n } while (--h);\n}\n\nstatic const uint8_t cursor_glyph[32] = {\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n};\n\nstatic inline int c6_to_8(int v)\n{\n int b;\n v &= 0x3f;\n b = v & 1;\n return (v << 2) | (b << 1) | b;\n}\n\nstatic int update_palette16(VGAState *s, uint32_t *palette)\n{\n int full_update, i;\n uint32_t v, col;\n\n full_update = 0;\n for(i = 0; i < 16; i++) {\n v = s->ar[i];\n if (s->ar[0x10] & 0x80)\n v = ((s->ar[0x14] & 0xf) << 4) | (v & 0xf);\n else\n v = ((s->ar[0x14] & 0xc) << 4) | (v & 0x3f);\n v = v * 3;\n col = (c6_to_8(s->palette[v]) << 16) |\n (c6_to_8(s->palette[v + 1]) << 8) |\n c6_to_8(s->palette[v + 2]);\n if (col != palette[i]) {\n full_update = 1;\n palette[i] = col;\n }\n }\n return full_update;\n}\n\n/* the text refresh is just for debugging and initial boot message, so\n it is very incomplete */\nstatic void vga_text_refresh(VGAState *s,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n FBDevice *fb_dev = s->fb_dev;\n int width, height, cwidth, cheight, cy, cx, x1, y1, width1, height1;\n int cx_min, cx_max, dup9;\n uint32_t ch_attr, line_offset, start_addr, ch_addr, ch_addr1, ch, cattr;\n uint8_t *vga_ram, *font_ptr, *dst;\n uint32_t fgcol, bgcol, cursor_offset, cursor_start, cursor_end;\n BOOL full_update;\n\n full_update = update_palette16(s, s->last_palette);\n\n vga_ram = s->vga_ram;\n \n line_offset = s->cr[0x13];\n line_offset <<= 3;\n line_offset >>= 1;\n\n start_addr = s->cr[0x0d] | (s->cr[0x0c] << 8);\n \n cheight = (s->cr[9] & 0x1f) + 1;\n cwidth = 8;\n if (!(s->sr[1] & 0x01))\n cwidth++;\n \n width = (s->cr[0x01] + 1);\n height = s->cr[0x12] |\n ((s->cr[0x07] & 0x02) << 7) |\n ((s->cr[0x07] & 0x40) << 3);\n height = (height + 1) / cheight;\n \n width1 = width * cwidth;\n height1 = height * cheight;\n if (fb_dev->width < width1 || fb_dev->height < height1 ||\n width > MAX_TEXT_WIDTH || height > MAX_TEXT_HEIGHT)\n return; /* not enough space */\n if (s->last_line_offset != line_offset ||\n s->last_start_addr != start_addr ||\n s->last_width != width ||\n s->last_height != height) {\n s->last_line_offset = line_offset;\n s->last_start_addr = start_addr;\n s->last_width = width;\n s->last_height = height;\n full_update = TRUE;\n }\n \n /* update cursor position */\n cursor_offset = ((s->cr[0x0e] << 8) | s->cr[0x0f]) - start_addr;\n cursor_start = s->cr[0xa];\n cursor_end = s->cr[0xb];\n if (cursor_offset != s->last_cursor_offset ||\n cursor_start != s->last_cursor_start ||\n cursor_end != s->last_cursor_end) {\n /* force refresh of characters with the cursor */\n if (s->last_cursor_offset < MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT)\n s->last_ch_attr[s->last_cursor_offset] = -1;\n if (cursor_offset < MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT)\n s->last_ch_attr[cursor_offset] = -1;\n s->last_cursor_offset = cursor_offset;\n s->last_cursor_start = cursor_start;\n s->last_cursor_end = cursor_end;\n }\n\n ch_addr1 = 0x18000 + (start_addr * 2);\n cursor_offset = 0x18000 + (start_addr + cursor_offset) * 2;\n \n x1 = (fb_dev->width - width1) / 2;\n y1 = (fb_dev->height - height1) / 2;\n#if 0\n printf(\"text refresh %dx%d font=%dx%d start_addr=0x%x line_offset=0x%x\\n\",\n width, height, cwidth, cheight, start_addr, line_offset);\n#endif\n for(cy = 0; cy < height; cy++) {\n ch_addr = ch_addr1;\n dst = fb_dev->fb_data + (y1 + cy * cheight) * fb_dev->stride + x1 * 4;\n cx_min = width;\n cx_max = -1;\n for(cx = 0; cx < width; cx++) {\n ch_attr = *(uint16_t *)(vga_ram + (ch_addr & 0x1fffe));\n if (full_update || ch_attr != s->last_ch_attr[cy * width + cx]) {\n s->last_ch_attr[cy * width + cx] = ch_attr;\n cx_min = min_int(cx_min, cx);\n cx_max = max_int(cx_max, cx);\n ch = ch_attr & 0xff;\n cattr = ch_attr >> 8;\n font_ptr = vga_ram + 32 * ch;\n bgcol = s->last_palette[cattr >> 4];\n fgcol = s->last_palette[cattr & 0x0f];\n if (cwidth == 8) {\n vga_draw_glyph8(dst, fb_dev->stride, font_ptr, cheight,\n fgcol, bgcol);\n } else {\n dup9 = 0;\n if (ch >= 0xb0 && ch <= 0xdf && (s->ar[0x10] & 0x04))\n dup9 = 1;\n vga_draw_glyph9(dst, fb_dev->stride, font_ptr, cheight,\n fgcol, bgcol, dup9);\n }\n /* cursor display */\n if (cursor_offset == ch_addr && !(cursor_start & 0x20)) {\n int line_start, line_last, h;\n uint8_t *dst1;\n line_start = cursor_start & 0x1f;\n line_last = min_int(cursor_end & 0x1f, cheight - 1);\n\n if (line_last >= line_start && line_start < cheight) {\n h = line_last - line_start + 1;\n dst1 = dst + fb_dev->stride * line_start;\n if (cwidth == 8) {\n vga_draw_glyph8(dst1, fb_dev->stride,\n cursor_glyph,\n h, fgcol, bgcol);\n } else {\n vga_draw_glyph9(dst1, fb_dev->stride,\n cursor_glyph,\n h, fgcol, bgcol, 1);\n }\n }\n }\n }\n ch_addr += 2;\n dst += 4 * cwidth;\n }\n if (cx_max >= cx_min) {\n // printf(\"redraw %d %d %d\\n\", cy, cx_min, cx_max);\n redraw_func(fb_dev, opaque,\n x1 + cx_min * cwidth, y1 + cy * cheight,\n (cx_max - cx_min + 1) * cwidth, cheight);\n }\n ch_addr1 += line_offset;\n }\n}\n\nstatic void vga_refresh(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n VGAState *s = fb_dev->device_opaque;\n\n if (!(s->ar_index & 0x20)) {\n /* blank */\n } else if (s->gr[0x06] & 1) {\n /* graphic mode (VBE) */\n simplefb_refresh(fb_dev, redraw_func, opaque, s->mem_range, s->fb_page_count);\n } else {\n /* text mode */\n vga_text_refresh(s, redraw_func, opaque);\n }\n}\n\n/* force some bits to zero */\nstatic const uint8_t sr_mask[8] = {\n (uint8_t)~0xfc,\n (uint8_t)~0xc2,\n (uint8_t)~0xf0,\n (uint8_t)~0xc0,\n (uint8_t)~0xf1,\n (uint8_t)~0xff,\n (uint8_t)~0xff,\n (uint8_t)~0x00,\n};\n\nstatic const uint8_t gr_mask[16] = {\n (uint8_t)~0xf0, /* 0x00 */\n (uint8_t)~0xf0, /* 0x01 */\n (uint8_t)~0xf0, /* 0x02 */\n (uint8_t)~0xe0, /* 0x03 */\n (uint8_t)~0xfc, /* 0x04 */\n (uint8_t)~0x84, /* 0x05 */\n (uint8_t)~0xf0, /* 0x06 */\n (uint8_t)~0xf0, /* 0x07 */\n (uint8_t)~0x00, /* 0x08 */\n (uint8_t)~0xff, /* 0x09 */\n (uint8_t)~0xff, /* 0x0a */\n (uint8_t)~0xff, /* 0x0b */\n (uint8_t)~0xff, /* 0x0c */\n (uint8_t)~0xff, /* 0x0d */\n (uint8_t)~0xff, /* 0x0e */\n (uint8_t)~0xff, /* 0x0f */\n};\n\nstatic uint32_t vga_ioport_read(VGAState *s, uint32_t addr)\n{\n int val, index;\n\n /* check port range access depending on color/monochrome mode */\n if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION)) ||\n (addr >= 0x3d0 && addr <= 0x3df && !(s->msr & MSR_COLOR_EMULATION))) {\n val = 0xff;\n } else {\n switch(addr) {\n case 0x3c0:\n if (s->ar_flip_flop == 0) {\n val = s->ar_index;\n } else {\n val = 0;\n }\n break;\n case 0x3c1:\n index = s->ar_index & 0x1f;\n if (index < 21)\n val = s->ar[index];\n else\n val = 0;\n break;\n case 0x3c2:\n val = s->st00;\n break;\n case 0x3c4:\n val = s->sr_index;\n break;\n case 0x3c5:\n val = s->sr[s->sr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n break;\n case 0x3c7:\n val = s->dac_state;\n break;\n\tcase 0x3c8:\n\t val = s->dac_write_index;\n\t break;\n case 0x3c9:\n val = s->palette[s->dac_read_index * 3 + s->dac_sub_index];\n if (++s->dac_sub_index == 3) {\n s->dac_sub_index = 0;\n s->dac_read_index++;\n }\n break;\n case 0x3ca:\n val = s->fcr;\n break;\n case 0x3cc:\n val = s->msr;\n break;\n case 0x3ce:\n val = s->gr_index;\n break;\n case 0x3cf:\n val = s->gr[s->gr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n break;\n case 0x3b4:\n case 0x3d4:\n val = s->cr_index;\n break;\n case 0x3b5:\n case 0x3d5:\n val = s->cr[s->cr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n break;\n case 0x3ba:\n case 0x3da:\n /* just toggle to fool polling */\n s->st01 ^= ST01_V_RETRACE | ST01_DISP_ENABLE;\n val = s->st01;\n s->ar_flip_flop = 0;\n break;\n default:\n val = 0x00;\n break;\n }\n }\n#if defined(DEBUG_VGA)\n printf(\"VGA: read addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n return val;\n}\n\nstatic void vga_ioport_write(VGAState *s, uint32_t addr, uint32_t val)\n{\n int index;\n\n /* check port range access depending on color/monochrome mode */\n if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION)) ||\n (addr >= 0x3d0 && addr <= 0x3df && !(s->msr & MSR_COLOR_EMULATION)))\n return;\n\n#ifdef DEBUG_VGA\n printf(\"VGA: write addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n\n switch(addr) {\n case 0x3c0:\n if (s->ar_flip_flop == 0) {\n val &= 0x3f;\n s->ar_index = val;\n } else {\n index = s->ar_index & 0x1f;\n switch(index) {\n case 0x00 ... 0x0f:\n s->ar[index] = val & 0x3f;\n break;\n case 0x10:\n s->ar[index] = val & ~0x10;\n break;\n case 0x11:\n s->ar[index] = val;\n break;\n case 0x12:\n s->ar[index] = val & ~0xc0;\n break;\n case 0x13:\n s->ar[index] = val & ~0xf0;\n break;\n case 0x14:\n s->ar[index] = val & ~0xf0;\n break;\n default:\n break;\n }\n }\n s->ar_flip_flop ^= 1;\n break;\n case 0x3c2:\n s->msr = val & ~0x10;\n break;\n case 0x3c4:\n s->sr_index = val & 7;\n break;\n case 0x3c5:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n s->sr[s->sr_index] = val & sr_mask[s->sr_index];\n break;\n case 0x3c7:\n s->dac_read_index = val;\n s->dac_sub_index = 0;\n s->dac_state = 3;\n break;\n case 0x3c8:\n s->dac_write_index = val;\n s->dac_sub_index = 0;\n s->dac_state = 0;\n break;\n case 0x3c9:\n s->dac_cache[s->dac_sub_index] = val;\n if (++s->dac_sub_index == 3) {\n memcpy(&s->palette[s->dac_write_index * 3], s->dac_cache, 3);\n s->dac_sub_index = 0;\n s->dac_write_index++;\n }\n break;\n case 0x3ce:\n s->gr_index = val & 0x0f;\n break;\n case 0x3cf:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n s->gr[s->gr_index] = val & gr_mask[s->gr_index];\n break;\n case 0x3b4:\n case 0x3d4:\n s->cr_index = val;\n break;\n case 0x3b5:\n case 0x3d5:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n /* handle CR0-7 protection */\n if ((s->cr[0x11] & 0x80) && s->cr_index <= 7) {\n /* can always write bit 4 of CR7 */\n if (s->cr_index == 7)\n s->cr[7] = (s->cr[7] & ~0x10) | (val & 0x10);\n return;\n }\n switch(s->cr_index) {\n case 0x01: /* horizontal display end */\n case 0x07:\n case 0x09:\n case 0x0c:\n case 0x0d:\n case 0x12: /* vertical display end */\n s->cr[s->cr_index] = val;\n break;\n default:\n s->cr[s->cr_index] = val;\n break;\n }\n break;\n case 0x3ba:\n case 0x3da:\n s->fcr = val & 0x10;\n break;\n }\n}\n\n#define VGA_IO(base) \\\nstatic uint32_t vga_read_ ## base(void *opaque, uint32_t addr, int size_log2)\\\n{\\\n return vga_ioport_read(opaque, base + addr);\\\n}\\\nstatic void vga_write_ ## base(void *opaque, uint32_t addr, uint32_t val, int size_log2)\\\n{\\\n return vga_ioport_write(opaque, base + addr, val);\\\n}\n\nVGA_IO(0x3c0)\nVGA_IO(0x3b4)\nVGA_IO(0x3d4)\nVGA_IO(0x3ba)\nVGA_IO(0x3da)\n\nstatic void vbe_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n VGAState *s = opaque;\n FBDevice *fb_dev = s->fb_dev;\n \n if (offset == 0) {\n s->vbe_index = val;\n } else {\n#ifdef DEBUG_VBE\n printf(\"VBE write: index=0x%04x val=0x%04x\\n\", s->vbe_index, val);\n#endif\n switch(s->vbe_index) {\n case VBE_DISPI_INDEX_ID:\n if (val >= VBE_DISPI_ID0 && val <= VBE_DISPI_ID5)\n s->vbe_regs[s->vbe_index] = val;\n break;\n case VBE_DISPI_INDEX_ENABLE:\n if ((val & VBE_DISPI_ENABLED) &&\n !(s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED)) {\n /* set graphic mode */\n /* XXX: resolution change not really supported */\n if (s->vbe_regs[VBE_DISPI_INDEX_XRES] <= 4096 &&\n s->vbe_regs[VBE_DISPI_INDEX_YRES] <= 4096 &&\n (s->vbe_regs[VBE_DISPI_INDEX_XRES] * 4 *\n s->vbe_regs[VBE_DISPI_INDEX_YRES]) <= fb_dev->fb_size) {\n fb_dev->width = s->vbe_regs[VBE_DISPI_INDEX_XRES];\n fb_dev->height = s->vbe_regs[VBE_DISPI_INDEX_YRES];\n fb_dev->stride = fb_dev->width * 4;\n }\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] =\n s->vbe_regs[VBE_DISPI_INDEX_XRES];\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_HEIGHT] =\n s->vbe_regs[VBE_DISPI_INDEX_YRES];\n s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET] = 0;\n s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET] = 0;\n }\n s->vbe_regs[s->vbe_index] = val;\n break;\n case VBE_DISPI_INDEX_XRES:\n case VBE_DISPI_INDEX_YRES:\n case VBE_DISPI_INDEX_BPP:\n case VBE_DISPI_INDEX_BANK:\n case VBE_DISPI_INDEX_VIRT_WIDTH:\n case VBE_DISPI_INDEX_VIRT_HEIGHT:\n case VBE_DISPI_INDEX_X_OFFSET:\n case VBE_DISPI_INDEX_Y_OFFSET:\n s->vbe_regs[s->vbe_index] = val;\n break;\n }\n }\n}\n\nstatic uint32_t vbe_read(void *opaque, uint32_t offset, int size_log2)\n{\n VGAState *s = opaque;\n uint32_t val;\n\n if (offset == 0) {\n val = s->vbe_index;\n } else {\n if (s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_GETCAPS) {\n switch(s->vbe_index) {\n case VBE_DISPI_INDEX_XRES:\n val = s->fb_dev->width;\n break;\n case VBE_DISPI_INDEX_YRES:\n val = s->fb_dev->height;\n break;\n case VBE_DISPI_INDEX_BPP:\n val = 32;\n break;\n default:\n goto read_reg;\n }\n } else {\n read_reg:\n if (s->vbe_index < VBE_DISPI_INDEX_NB)\n val = s->vbe_regs[s->vbe_index];\n else\n val = 0;\n }\n#ifdef DEBUG_VBE\n printf(\"VBE read: index=0x%04x val=0x%04x\\n\", s->vbe_index, val);\n#endif\n }\n return val;\n}\n\n\nstatic void simplefb_bar_set(void *opaque, int bar_num,\n uint32_t addr, BOOL enabled)\n{\n VGAState *s = opaque;\n if (bar_num == 0)\n phys_mem_set_addr(s->mem_range, addr, enabled);\n else\n phys_mem_set_addr(s->rom_range, addr, enabled);\n}\n\nVGAState *pci_vga_init(PCIBus *bus, FBDevice *fb_dev,\n int width, int height,\n const uint8_t *vga_rom_buf, int vga_rom_size)\n{\n VGAState *s;\n PCIDevice *d;\n uint32_t bar_size;\n PhysMemoryMap *mem_map, *port_map;\n \n d = pci_register_device(bus, \"VGA\", -1, 0x1234, 0x1111, 0x00, 0x0300);\n \n mem_map = pci_device_get_mem_map(d);\n port_map = pci_device_get_port_map(d);\n\n s = mallocz(sizeof(*s));\n s->fb_dev = fb_dev;\n \n fb_dev->width = width;\n fb_dev->height = height;\n fb_dev->stride = width * 4;\n\n fb_dev->fb_size = (height * fb_dev->stride + FB_ALLOC_ALIGN - 1) & ~(FB_ALLOC_ALIGN - 1);\n s->fb_page_count = fb_dev->fb_size >> DEVRAM_PAGE_SIZE_LOG2;\n\n s->mem_range =\n cpu_register_ram(mem_map, 0, fb_dev->fb_size,\n DEVRAM_FLAG_DIRTY_BITS | DEVRAM_FLAG_DISABLED);\n \n fb_dev->fb_data = s->mem_range->phys_mem;\n\n s->pci_dev = d;\n bar_size = 1;\n while (bar_size < fb_dev->fb_size)\n bar_size <<= 1;\n pci_register_bar(d, 0, bar_size, PCI_ADDRESS_SPACE_MEM, s,\n simplefb_bar_set);\n\n if (vga_rom_size > 0) {\n int rom_size;\n /* align to page size */\n rom_size = (vga_rom_size + DEVRAM_PAGE_SIZE - 1) & ~(DEVRAM_PAGE_SIZE - 1);\n s->rom_range = cpu_register_ram(mem_map, 0, rom_size,\n DEVRAM_FLAG_ROM | DEVRAM_FLAG_DISABLED);\n memcpy(s->rom_range->phys_mem, vga_rom_buf, vga_rom_size);\n\n bar_size = 1;\n while (bar_size < rom_size)\n bar_size <<= 1;\n pci_register_bar(d, PCI_ROM_SLOT, bar_size, PCI_ADDRESS_SPACE_MEM, s,\n simplefb_bar_set);\n }\n\n /* VGA memory (for simple text mode no need for callbacks) */\n s->mem_range2 = cpu_register_ram(mem_map, 0xa0000, 0x20000, 0);\n s->vga_ram = s->mem_range2->phys_mem;\n \n /* standard VGA ports */\n \n cpu_register_device(port_map, 0x3c0, 16, s, vga_read_0x3c0, vga_write_0x3c0,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3b4, 2, s, vga_read_0x3b4, vga_write_0x3b4,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3d4, 2, s, vga_read_0x3d4, vga_write_0x3d4,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3ba, 1, s, vga_read_0x3ba, vga_write_0x3ba,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3da, 1, s, vga_read_0x3da, vga_write_0x3da,\n DEVIO_SIZE8);\n \n /* VBE extension */\n cpu_register_device(port_map, 0x1ce, 2, s, vbe_read, vbe_write, \n DEVIO_SIZE16);\n \n s->vbe_regs[VBE_DISPI_INDEX_ID] = VBE_DISPI_ID5;\n s->vbe_regs[VBE_DISPI_INDEX_VIDEO_MEMORY_64K] = fb_dev->fb_size >> 16;\n\n fb_dev->device_opaque = s;\n fb_dev->refresh = vga_refresh;\n return s;\n}\n"], ["/linuxpdf/tinyemu/aes.c", "/**\n *\n * aes.c - integrated in QEMU by Fabrice Bellard from the OpenSSL project.\n */\n/*\n * rijndael-alg-fst.c\n *\n * @version 3.0 (December 2000)\n *\n * Optimised ANSI C code for the Rijndael cipher (now AES)\n *\n * @author Vincent Rijmen \n * @author Antoon Bosselaers \n * @author Paulo Barreto \n *\n * This code is hereby placed in the public domain.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS\n * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n#include \n#include \n#include \"aes.h\"\n\n#ifndef NDEBUG\n#define NDEBUG\n#endif\n\n#include \n\ntypedef uint32_t u32;\ntypedef uint16_t u16;\ntypedef uint8_t u8;\n\n#define MAXKC (256/32)\n#define MAXKB (256/8)\n#define MAXNR 14\n\n/* This controls loop-unrolling in aes_core.c */\n#undef FULL_UNROLL\n# define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3]))\n# define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); }\n\n/*\nTe0[x] = S [x].[02, 01, 01, 03];\nTe1[x] = S [x].[03, 02, 01, 01];\nTe2[x] = S [x].[01, 03, 02, 01];\nTe3[x] = S [x].[01, 01, 03, 02];\nTe4[x] = S [x].[01, 01, 01, 01];\n\nTd0[x] = Si[x].[0e, 09, 0d, 0b];\nTd1[x] = Si[x].[0b, 0e, 09, 0d];\nTd2[x] = Si[x].[0d, 0b, 0e, 09];\nTd3[x] = Si[x].[09, 0d, 0b, 0e];\nTd4[x] = Si[x].[01, 01, 01, 01];\n*/\n\nstatic const u32 Te0[256] = {\n 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU,\n 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U,\n 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU,\n 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU,\n 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U,\n 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU,\n 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU,\n 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU,\n 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU,\n 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU,\n 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U,\n 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU,\n 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU,\n 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U,\n 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU,\n 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU,\n 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU,\n 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU,\n 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU,\n 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U,\n 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU,\n 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU,\n 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU,\n 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU,\n 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U,\n 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U,\n 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U,\n 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U,\n 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU,\n 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U,\n 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U,\n 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU,\n 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU,\n 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U,\n 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U,\n 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U,\n 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU,\n 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U,\n 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU,\n 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U,\n 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU,\n 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U,\n 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U,\n 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU,\n 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U,\n 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U,\n 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U,\n 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U,\n 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U,\n 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U,\n 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U,\n 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U,\n 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU,\n 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U,\n 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U,\n 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U,\n 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U,\n 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U,\n 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U,\n 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU,\n 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U,\n 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U,\n 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U,\n 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU,\n};\nstatic const u32 Te1[256] = {\n 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU,\n 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U,\n 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU,\n 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U,\n 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU,\n 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U,\n 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU,\n 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U,\n 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U,\n 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU,\n 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U,\n 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U,\n 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U,\n 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU,\n 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U,\n 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U,\n 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU,\n 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U,\n 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U,\n 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U,\n 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU,\n 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU,\n 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U,\n 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU,\n 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU,\n 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U,\n 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU,\n 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U,\n 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU,\n 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U,\n 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U,\n 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U,\n 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU,\n 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U,\n 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU,\n 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U,\n 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU,\n 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U,\n 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U,\n 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU,\n 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU,\n 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU,\n 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U,\n 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U,\n 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU,\n 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U,\n 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU,\n 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U,\n 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU,\n 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U,\n 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU,\n 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU,\n 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U,\n 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU,\n 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U,\n 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU,\n 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U,\n 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U,\n 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U,\n 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU,\n 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU,\n 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U,\n 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU,\n 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U,\n};\nstatic const u32 Te2[256] = {\n 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU,\n 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U,\n 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU,\n 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U,\n 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU,\n 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U,\n 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU,\n 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U,\n 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U,\n 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU,\n 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U,\n 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U,\n 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U,\n 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU,\n 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U,\n 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U,\n 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU,\n 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U,\n 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U,\n 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U,\n 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU,\n 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU,\n 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U,\n 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU,\n 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU,\n 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U,\n 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU,\n 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U,\n 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU,\n 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U,\n 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U,\n 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U,\n 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU,\n 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U,\n 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU,\n 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U,\n 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU,\n 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U,\n 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U,\n 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU,\n 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU,\n 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU,\n 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U,\n 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U,\n 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU,\n 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U,\n 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU,\n 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U,\n 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU,\n 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U,\n 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU,\n 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU,\n 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U,\n 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU,\n 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U,\n 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU,\n 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U,\n 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U,\n 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U,\n 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU,\n 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU,\n 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U,\n 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU,\n 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U,\n};\nstatic const u32 Te3[256] = {\n\n 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U,\n 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U,\n 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U,\n 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU,\n 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU,\n 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU,\n 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U,\n 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU,\n 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU,\n 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U,\n 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U,\n 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU,\n 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU,\n 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU,\n 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU,\n 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU,\n 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U,\n 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU,\n 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU,\n 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U,\n 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U,\n 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U,\n 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U,\n 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U,\n 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU,\n 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U,\n 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU,\n 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU,\n 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U,\n 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U,\n 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U,\n 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU,\n 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U,\n 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU,\n 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU,\n 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U,\n 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U,\n 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU,\n 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U,\n 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU,\n 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U,\n 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U,\n 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U,\n 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U,\n 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU,\n 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U,\n 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU,\n 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U,\n 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU,\n 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U,\n 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU,\n 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU,\n 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU,\n 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU,\n 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U,\n 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U,\n 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U,\n 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U,\n 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U,\n 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U,\n 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU,\n 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U,\n 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU,\n 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU,\n};\nstatic const u32 Te4[256] = {\n 0x63636363U, 0x7c7c7c7cU, 0x77777777U, 0x7b7b7b7bU,\n 0xf2f2f2f2U, 0x6b6b6b6bU, 0x6f6f6f6fU, 0xc5c5c5c5U,\n 0x30303030U, 0x01010101U, 0x67676767U, 0x2b2b2b2bU,\n 0xfefefefeU, 0xd7d7d7d7U, 0xababababU, 0x76767676U,\n 0xcacacacaU, 0x82828282U, 0xc9c9c9c9U, 0x7d7d7d7dU,\n 0xfafafafaU, 0x59595959U, 0x47474747U, 0xf0f0f0f0U,\n 0xadadadadU, 0xd4d4d4d4U, 0xa2a2a2a2U, 0xafafafafU,\n 0x9c9c9c9cU, 0xa4a4a4a4U, 0x72727272U, 0xc0c0c0c0U,\n 0xb7b7b7b7U, 0xfdfdfdfdU, 0x93939393U, 0x26262626U,\n 0x36363636U, 0x3f3f3f3fU, 0xf7f7f7f7U, 0xccccccccU,\n 0x34343434U, 0xa5a5a5a5U, 0xe5e5e5e5U, 0xf1f1f1f1U,\n 0x71717171U, 0xd8d8d8d8U, 0x31313131U, 0x15151515U,\n 0x04040404U, 0xc7c7c7c7U, 0x23232323U, 0xc3c3c3c3U,\n 0x18181818U, 0x96969696U, 0x05050505U, 0x9a9a9a9aU,\n 0x07070707U, 0x12121212U, 0x80808080U, 0xe2e2e2e2U,\n 0xebebebebU, 0x27272727U, 0xb2b2b2b2U, 0x75757575U,\n 0x09090909U, 0x83838383U, 0x2c2c2c2cU, 0x1a1a1a1aU,\n 0x1b1b1b1bU, 0x6e6e6e6eU, 0x5a5a5a5aU, 0xa0a0a0a0U,\n 0x52525252U, 0x3b3b3b3bU, 0xd6d6d6d6U, 0xb3b3b3b3U,\n 0x29292929U, 0xe3e3e3e3U, 0x2f2f2f2fU, 0x84848484U,\n 0x53535353U, 0xd1d1d1d1U, 0x00000000U, 0xededededU,\n 0x20202020U, 0xfcfcfcfcU, 0xb1b1b1b1U, 0x5b5b5b5bU,\n 0x6a6a6a6aU, 0xcbcbcbcbU, 0xbebebebeU, 0x39393939U,\n 0x4a4a4a4aU, 0x4c4c4c4cU, 0x58585858U, 0xcfcfcfcfU,\n 0xd0d0d0d0U, 0xefefefefU, 0xaaaaaaaaU, 0xfbfbfbfbU,\n 0x43434343U, 0x4d4d4d4dU, 0x33333333U, 0x85858585U,\n 0x45454545U, 0xf9f9f9f9U, 0x02020202U, 0x7f7f7f7fU,\n 0x50505050U, 0x3c3c3c3cU, 0x9f9f9f9fU, 0xa8a8a8a8U,\n 0x51515151U, 0xa3a3a3a3U, 0x40404040U, 0x8f8f8f8fU,\n 0x92929292U, 0x9d9d9d9dU, 0x38383838U, 0xf5f5f5f5U,\n 0xbcbcbcbcU, 0xb6b6b6b6U, 0xdadadadaU, 0x21212121U,\n 0x10101010U, 0xffffffffU, 0xf3f3f3f3U, 0xd2d2d2d2U,\n 0xcdcdcdcdU, 0x0c0c0c0cU, 0x13131313U, 0xececececU,\n 0x5f5f5f5fU, 0x97979797U, 0x44444444U, 0x17171717U,\n 0xc4c4c4c4U, 0xa7a7a7a7U, 0x7e7e7e7eU, 0x3d3d3d3dU,\n 0x64646464U, 0x5d5d5d5dU, 0x19191919U, 0x73737373U,\n 0x60606060U, 0x81818181U, 0x4f4f4f4fU, 0xdcdcdcdcU,\n 0x22222222U, 0x2a2a2a2aU, 0x90909090U, 0x88888888U,\n 0x46464646U, 0xeeeeeeeeU, 0xb8b8b8b8U, 0x14141414U,\n 0xdedededeU, 0x5e5e5e5eU, 0x0b0b0b0bU, 0xdbdbdbdbU,\n 0xe0e0e0e0U, 0x32323232U, 0x3a3a3a3aU, 0x0a0a0a0aU,\n 0x49494949U, 0x06060606U, 0x24242424U, 0x5c5c5c5cU,\n 0xc2c2c2c2U, 0xd3d3d3d3U, 0xacacacacU, 0x62626262U,\n 0x91919191U, 0x95959595U, 0xe4e4e4e4U, 0x79797979U,\n 0xe7e7e7e7U, 0xc8c8c8c8U, 0x37373737U, 0x6d6d6d6dU,\n 0x8d8d8d8dU, 0xd5d5d5d5U, 0x4e4e4e4eU, 0xa9a9a9a9U,\n 0x6c6c6c6cU, 0x56565656U, 0xf4f4f4f4U, 0xeaeaeaeaU,\n 0x65656565U, 0x7a7a7a7aU, 0xaeaeaeaeU, 0x08080808U,\n 0xbabababaU, 0x78787878U, 0x25252525U, 0x2e2e2e2eU,\n 0x1c1c1c1cU, 0xa6a6a6a6U, 0xb4b4b4b4U, 0xc6c6c6c6U,\n 0xe8e8e8e8U, 0xddddddddU, 0x74747474U, 0x1f1f1f1fU,\n 0x4b4b4b4bU, 0xbdbdbdbdU, 0x8b8b8b8bU, 0x8a8a8a8aU,\n 0x70707070U, 0x3e3e3e3eU, 0xb5b5b5b5U, 0x66666666U,\n 0x48484848U, 0x03030303U, 0xf6f6f6f6U, 0x0e0e0e0eU,\n 0x61616161U, 0x35353535U, 0x57575757U, 0xb9b9b9b9U,\n 0x86868686U, 0xc1c1c1c1U, 0x1d1d1d1dU, 0x9e9e9e9eU,\n 0xe1e1e1e1U, 0xf8f8f8f8U, 0x98989898U, 0x11111111U,\n 0x69696969U, 0xd9d9d9d9U, 0x8e8e8e8eU, 0x94949494U,\n 0x9b9b9b9bU, 0x1e1e1e1eU, 0x87878787U, 0xe9e9e9e9U,\n 0xcecececeU, 0x55555555U, 0x28282828U, 0xdfdfdfdfU,\n 0x8c8c8c8cU, 0xa1a1a1a1U, 0x89898989U, 0x0d0d0d0dU,\n 0xbfbfbfbfU, 0xe6e6e6e6U, 0x42424242U, 0x68686868U,\n 0x41414141U, 0x99999999U, 0x2d2d2d2dU, 0x0f0f0f0fU,\n 0xb0b0b0b0U, 0x54545454U, 0xbbbbbbbbU, 0x16161616U,\n};\nstatic const u32 Td0[256] = {\n 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U,\n 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U,\n 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U,\n 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU,\n 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U,\n 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U,\n 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU,\n 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U,\n 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU,\n 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U,\n 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U,\n 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U,\n 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U,\n 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU,\n 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U,\n 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU,\n 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U,\n 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU,\n 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U,\n 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U,\n 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U,\n 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU,\n 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U,\n 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU,\n 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U,\n 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU,\n 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U,\n 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU,\n 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU,\n 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U,\n 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU,\n 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U,\n 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU,\n 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U,\n 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U,\n 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U,\n 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU,\n 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U,\n 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U,\n 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU,\n 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U,\n 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U,\n 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U,\n 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U,\n 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U,\n 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU,\n 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U,\n 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U,\n 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U,\n 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U,\n 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U,\n 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU,\n 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU,\n 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU,\n 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU,\n 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U,\n 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U,\n 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU,\n 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU,\n 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U,\n 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU,\n 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U,\n 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U,\n 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U,\n};\nstatic const u32 Td1[256] = {\n 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU,\n 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U,\n 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU,\n 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U,\n 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U,\n 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U,\n 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U,\n 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U,\n 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U,\n 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU,\n 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU,\n 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU,\n 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U,\n 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU,\n 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U,\n 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U,\n 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U,\n 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU,\n 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU,\n 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U,\n 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU,\n 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U,\n 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU,\n 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU,\n 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U,\n 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U,\n 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U,\n 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU,\n 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U,\n 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU,\n 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U,\n 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U,\n 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U,\n 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU,\n 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U,\n 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U,\n 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U,\n 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U,\n 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U,\n 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U,\n 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU,\n 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU,\n 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U,\n 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU,\n 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U,\n 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU,\n 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU,\n 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U,\n 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU,\n 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U,\n 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U,\n 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U,\n 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U,\n 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U,\n 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U,\n 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U,\n 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU,\n 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U,\n 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U,\n 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU,\n 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U,\n 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U,\n 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U,\n 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U,\n};\nstatic const u32 Td2[256] = {\n 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U,\n 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U,\n 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U,\n 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U,\n 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU,\n 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U,\n 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U,\n 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U,\n 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U,\n 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU,\n 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U,\n 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U,\n 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU,\n 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U,\n 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U,\n 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U,\n 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U,\n 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U,\n 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U,\n 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU,\n\n 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U,\n 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U,\n 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U,\n 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U,\n 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U,\n 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU,\n 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU,\n 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U,\n 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU,\n 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U,\n 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU,\n 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU,\n 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU,\n 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU,\n 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U,\n 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U,\n 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U,\n 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U,\n 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U,\n 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U,\n 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U,\n 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU,\n 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU,\n 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U,\n 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U,\n 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU,\n 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU,\n 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U,\n 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U,\n 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U,\n 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U,\n 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U,\n 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U,\n 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U,\n 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU,\n 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U,\n 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U,\n 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U,\n 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U,\n 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U,\n 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U,\n 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU,\n 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U,\n 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U,\n};\nstatic const u32 Td3[256] = {\n 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU,\n 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU,\n 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U,\n 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U,\n 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU,\n 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU,\n 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U,\n 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU,\n 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U,\n 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU,\n 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U,\n 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U,\n 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U,\n 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U,\n 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U,\n 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU,\n 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU,\n 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U,\n 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U,\n 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU,\n 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU,\n 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U,\n 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U,\n 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U,\n 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U,\n 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU,\n 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U,\n 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U,\n 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU,\n 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU,\n 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U,\n 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U,\n 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U,\n 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU,\n 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U,\n 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U,\n 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U,\n 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U,\n 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U,\n 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U,\n 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U,\n 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU,\n 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U,\n 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U,\n 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU,\n 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU,\n 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U,\n 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU,\n 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U,\n 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U,\n 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U,\n 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U,\n 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U,\n 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U,\n 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU,\n 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU,\n 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU,\n 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU,\n 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U,\n 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U,\n 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U,\n 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU,\n 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U,\n 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U,\n};\nstatic const u32 Td4[256] = {\n 0x52525252U, 0x09090909U, 0x6a6a6a6aU, 0xd5d5d5d5U,\n 0x30303030U, 0x36363636U, 0xa5a5a5a5U, 0x38383838U,\n 0xbfbfbfbfU, 0x40404040U, 0xa3a3a3a3U, 0x9e9e9e9eU,\n 0x81818181U, 0xf3f3f3f3U, 0xd7d7d7d7U, 0xfbfbfbfbU,\n 0x7c7c7c7cU, 0xe3e3e3e3U, 0x39393939U, 0x82828282U,\n 0x9b9b9b9bU, 0x2f2f2f2fU, 0xffffffffU, 0x87878787U,\n 0x34343434U, 0x8e8e8e8eU, 0x43434343U, 0x44444444U,\n 0xc4c4c4c4U, 0xdedededeU, 0xe9e9e9e9U, 0xcbcbcbcbU,\n 0x54545454U, 0x7b7b7b7bU, 0x94949494U, 0x32323232U,\n 0xa6a6a6a6U, 0xc2c2c2c2U, 0x23232323U, 0x3d3d3d3dU,\n 0xeeeeeeeeU, 0x4c4c4c4cU, 0x95959595U, 0x0b0b0b0bU,\n 0x42424242U, 0xfafafafaU, 0xc3c3c3c3U, 0x4e4e4e4eU,\n 0x08080808U, 0x2e2e2e2eU, 0xa1a1a1a1U, 0x66666666U,\n 0x28282828U, 0xd9d9d9d9U, 0x24242424U, 0xb2b2b2b2U,\n 0x76767676U, 0x5b5b5b5bU, 0xa2a2a2a2U, 0x49494949U,\n 0x6d6d6d6dU, 0x8b8b8b8bU, 0xd1d1d1d1U, 0x25252525U,\n 0x72727272U, 0xf8f8f8f8U, 0xf6f6f6f6U, 0x64646464U,\n 0x86868686U, 0x68686868U, 0x98989898U, 0x16161616U,\n 0xd4d4d4d4U, 0xa4a4a4a4U, 0x5c5c5c5cU, 0xccccccccU,\n 0x5d5d5d5dU, 0x65656565U, 0xb6b6b6b6U, 0x92929292U,\n 0x6c6c6c6cU, 0x70707070U, 0x48484848U, 0x50505050U,\n 0xfdfdfdfdU, 0xededededU, 0xb9b9b9b9U, 0xdadadadaU,\n 0x5e5e5e5eU, 0x15151515U, 0x46464646U, 0x57575757U,\n 0xa7a7a7a7U, 0x8d8d8d8dU, 0x9d9d9d9dU, 0x84848484U,\n 0x90909090U, 0xd8d8d8d8U, 0xababababU, 0x00000000U,\n 0x8c8c8c8cU, 0xbcbcbcbcU, 0xd3d3d3d3U, 0x0a0a0a0aU,\n 0xf7f7f7f7U, 0xe4e4e4e4U, 0x58585858U, 0x05050505U,\n 0xb8b8b8b8U, 0xb3b3b3b3U, 0x45454545U, 0x06060606U,\n 0xd0d0d0d0U, 0x2c2c2c2cU, 0x1e1e1e1eU, 0x8f8f8f8fU,\n 0xcacacacaU, 0x3f3f3f3fU, 0x0f0f0f0fU, 0x02020202U,\n 0xc1c1c1c1U, 0xafafafafU, 0xbdbdbdbdU, 0x03030303U,\n 0x01010101U, 0x13131313U, 0x8a8a8a8aU, 0x6b6b6b6bU,\n 0x3a3a3a3aU, 0x91919191U, 0x11111111U, 0x41414141U,\n 0x4f4f4f4fU, 0x67676767U, 0xdcdcdcdcU, 0xeaeaeaeaU,\n 0x97979797U, 0xf2f2f2f2U, 0xcfcfcfcfU, 0xcecececeU,\n 0xf0f0f0f0U, 0xb4b4b4b4U, 0xe6e6e6e6U, 0x73737373U,\n 0x96969696U, 0xacacacacU, 0x74747474U, 0x22222222U,\n 0xe7e7e7e7U, 0xadadadadU, 0x35353535U, 0x85858585U,\n 0xe2e2e2e2U, 0xf9f9f9f9U, 0x37373737U, 0xe8e8e8e8U,\n 0x1c1c1c1cU, 0x75757575U, 0xdfdfdfdfU, 0x6e6e6e6eU,\n 0x47474747U, 0xf1f1f1f1U, 0x1a1a1a1aU, 0x71717171U,\n 0x1d1d1d1dU, 0x29292929U, 0xc5c5c5c5U, 0x89898989U,\n 0x6f6f6f6fU, 0xb7b7b7b7U, 0x62626262U, 0x0e0e0e0eU,\n 0xaaaaaaaaU, 0x18181818U, 0xbebebebeU, 0x1b1b1b1bU,\n 0xfcfcfcfcU, 0x56565656U, 0x3e3e3e3eU, 0x4b4b4b4bU,\n 0xc6c6c6c6U, 0xd2d2d2d2U, 0x79797979U, 0x20202020U,\n 0x9a9a9a9aU, 0xdbdbdbdbU, 0xc0c0c0c0U, 0xfefefefeU,\n 0x78787878U, 0xcdcdcdcdU, 0x5a5a5a5aU, 0xf4f4f4f4U,\n 0x1f1f1f1fU, 0xddddddddU, 0xa8a8a8a8U, 0x33333333U,\n 0x88888888U, 0x07070707U, 0xc7c7c7c7U, 0x31313131U,\n 0xb1b1b1b1U, 0x12121212U, 0x10101010U, 0x59595959U,\n 0x27272727U, 0x80808080U, 0xececececU, 0x5f5f5f5fU,\n 0x60606060U, 0x51515151U, 0x7f7f7f7fU, 0xa9a9a9a9U,\n 0x19191919U, 0xb5b5b5b5U, 0x4a4a4a4aU, 0x0d0d0d0dU,\n 0x2d2d2d2dU, 0xe5e5e5e5U, 0x7a7a7a7aU, 0x9f9f9f9fU,\n 0x93939393U, 0xc9c9c9c9U, 0x9c9c9c9cU, 0xefefefefU,\n 0xa0a0a0a0U, 0xe0e0e0e0U, 0x3b3b3b3bU, 0x4d4d4d4dU,\n 0xaeaeaeaeU, 0x2a2a2a2aU, 0xf5f5f5f5U, 0xb0b0b0b0U,\n 0xc8c8c8c8U, 0xebebebebU, 0xbbbbbbbbU, 0x3c3c3c3cU,\n 0x83838383U, 0x53535353U, 0x99999999U, 0x61616161U,\n 0x17171717U, 0x2b2b2b2bU, 0x04040404U, 0x7e7e7e7eU,\n 0xbabababaU, 0x77777777U, 0xd6d6d6d6U, 0x26262626U,\n 0xe1e1e1e1U, 0x69696969U, 0x14141414U, 0x63636363U,\n 0x55555555U, 0x21212121U, 0x0c0c0c0cU, 0x7d7d7d7dU,\n};\nstatic const u32 rcon[] = {\n\t0x01000000, 0x02000000, 0x04000000, 0x08000000,\n\t0x10000000, 0x20000000, 0x40000000, 0x80000000,\n\t0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */\n};\n\n/**\n * Expand the cipher key into the encryption key schedule.\n */\nint AES_set_encrypt_key(const unsigned char *userKey, const int bits,\n\t\t\tAES_KEY *key) {\n\n\tu32 *rk;\n \tint i = 0;\n\tu32 temp;\n\n\tif (!userKey || !key)\n\t\treturn -1;\n\tif (bits != 128 && bits != 192 && bits != 256)\n\t\treturn -2;\n\n\trk = key->rd_key;\n\n\tif (bits==128)\n\t\tkey->rounds = 10;\n\telse if (bits==192)\n\t\tkey->rounds = 12;\n\telse\n\t\tkey->rounds = 14;\n\n\trk[0] = GETU32(userKey );\n\trk[1] = GETU32(userKey + 4);\n\trk[2] = GETU32(userKey + 8);\n\trk[3] = GETU32(userKey + 12);\n\tif (bits == 128) {\n\t\twhile (1) {\n\t\t\ttemp = rk[3];\n\t\t\trk[4] = rk[0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[5] = rk[1] ^ rk[4];\n\t\t\trk[6] = rk[2] ^ rk[5];\n\t\t\trk[7] = rk[3] ^ rk[6];\n\t\t\tif (++i == 10) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\trk += 4;\n\t\t}\n\t}\n\trk[4] = GETU32(userKey + 16);\n\trk[5] = GETU32(userKey + 20);\n\tif (bits == 192) {\n\t\twhile (1) {\n\t\t\ttemp = rk[ 5];\n\t\t\trk[ 6] = rk[ 0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[ 7] = rk[ 1] ^ rk[ 6];\n\t\t\trk[ 8] = rk[ 2] ^ rk[ 7];\n\t\t\trk[ 9] = rk[ 3] ^ rk[ 8];\n\t\t\tif (++i == 8) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\trk[10] = rk[ 4] ^ rk[ 9];\n\t\t\trk[11] = rk[ 5] ^ rk[10];\n\t\t\trk += 6;\n\t\t}\n\t}\n\trk[6] = GETU32(userKey + 24);\n\trk[7] = GETU32(userKey + 28);\n\tif (bits == 256) {\n\t\twhile (1) {\n\t\t\ttemp = rk[ 7];\n\t\t\trk[ 8] = rk[ 0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[ 9] = rk[ 1] ^ rk[ 8];\n\t\t\trk[10] = rk[ 2] ^ rk[ 9];\n\t\t\trk[11] = rk[ 3] ^ rk[10];\n\t\t\tif (++i == 7) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\ttemp = rk[11];\n\t\t\trk[12] = rk[ 4] ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x000000ff);\n\t\t\trk[13] = rk[ 5] ^ rk[12];\n\t\t\trk[14] = rk[ 6] ^ rk[13];\n\t\t\trk[15] = rk[ 7] ^ rk[14];\n\n\t\t\trk += 8;\n \t}\n\t}\n\treturn 0;\n}\n\n/**\n * Expand the cipher key into the decryption key schedule.\n */\nint AES_set_decrypt_key(const unsigned char *userKey, const int bits,\n\t\t\t AES_KEY *key) {\n\n u32 *rk;\n\tint i, j, status;\n\tu32 temp;\n\n\t/* first, start with an encryption schedule */\n\tstatus = AES_set_encrypt_key(userKey, bits, key);\n\tif (status < 0)\n\t\treturn status;\n\n\trk = key->rd_key;\n\n\t/* invert the order of the round keys: */\n\tfor (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) {\n\t\ttemp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp;\n\t\ttemp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;\n\t\ttemp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;\n\t\ttemp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;\n\t}\n\t/* apply the inverse MixColumn transform to all round keys but the first and the last: */\n\tfor (i = 1; i < (key->rounds); i++) {\n\t\trk += 4;\n\t\trk[0] =\n\t\t\tTd0[Te4[(rk[0] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[0] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[0] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[0] ) & 0xff] & 0xff];\n\t\trk[1] =\n\t\t\tTd0[Te4[(rk[1] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[1] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[1] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[1] ) & 0xff] & 0xff];\n\t\trk[2] =\n\t\t\tTd0[Te4[(rk[2] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[2] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[2] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[2] ) & 0xff] & 0xff];\n\t\trk[3] =\n\t\t\tTd0[Te4[(rk[3] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[3] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[3] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[3] ) & 0xff] & 0xff];\n\t}\n\treturn 0;\n}\n\n#ifndef AES_ASM\n/*\n * Encrypt a single block\n * in and out can overlap\n */\nvoid AES_encrypt(const unsigned char *in, unsigned char *out,\n\t\t const AES_KEY *key) {\n\n\tconst u32 *rk;\n\tu32 s0, s1, s2, s3, t0, t1, t2, t3;\n#ifndef FULL_UNROLL\n\tint r;\n#endif /* ?FULL_UNROLL */\n\n\tassert(in && out && key);\n\trk = key->rd_key;\n\n\t/*\n\t * map byte array block to cipher state\n\t * and add initial round key:\n\t */\n\ts0 = GETU32(in ) ^ rk[0];\n\ts1 = GETU32(in + 4) ^ rk[1];\n\ts2 = GETU32(in + 8) ^ rk[2];\n\ts3 = GETU32(in + 12) ^ rk[3];\n#ifdef FULL_UNROLL\n\t/* round 1: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7];\n \t/* round 2: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11];\n\t/* round 3: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15];\n \t/* round 4: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19];\n\t/* round 5: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23];\n \t/* round 6: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27];\n\t/* round 7: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31];\n \t/* round 8: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35];\n\t/* round 9: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39];\n if (key->rounds > 10) {\n /* round 10: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43];\n /* round 11: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47];\n if (key->rounds > 12) {\n /* round 12: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51];\n /* round 13: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55];\n }\n }\n rk += key->rounds << 2;\n#else /* !FULL_UNROLL */\n /*\n * Nr - 1 full rounds:\n */\n r = key->rounds >> 1;\n for (;;) {\n t0 =\n Te0[(s0 >> 24) ] ^\n Te1[(s1 >> 16) & 0xff] ^\n Te2[(s2 >> 8) & 0xff] ^\n Te3[(s3 ) & 0xff] ^\n rk[4];\n t1 =\n Te0[(s1 >> 24) ] ^\n Te1[(s2 >> 16) & 0xff] ^\n Te2[(s3 >> 8) & 0xff] ^\n Te3[(s0 ) & 0xff] ^\n rk[5];\n t2 =\n Te0[(s2 >> 24) ] ^\n Te1[(s3 >> 16) & 0xff] ^\n Te2[(s0 >> 8) & 0xff] ^\n Te3[(s1 ) & 0xff] ^\n rk[6];\n t3 =\n Te0[(s3 >> 24) ] ^\n Te1[(s0 >> 16) & 0xff] ^\n Te2[(s1 >> 8) & 0xff] ^\n Te3[(s2 ) & 0xff] ^\n rk[7];\n\n rk += 8;\n if (--r == 0) {\n break;\n }\n\n s0 =\n Te0[(t0 >> 24) ] ^\n Te1[(t1 >> 16) & 0xff] ^\n Te2[(t2 >> 8) & 0xff] ^\n Te3[(t3 ) & 0xff] ^\n rk[0];\n s1 =\n Te0[(t1 >> 24) ] ^\n Te1[(t2 >> 16) & 0xff] ^\n Te2[(t3 >> 8) & 0xff] ^\n Te3[(t0 ) & 0xff] ^\n rk[1];\n s2 =\n Te0[(t2 >> 24) ] ^\n Te1[(t3 >> 16) & 0xff] ^\n Te2[(t0 >> 8) & 0xff] ^\n Te3[(t1 ) & 0xff] ^\n rk[2];\n s3 =\n Te0[(t3 >> 24) ] ^\n Te1[(t0 >> 16) & 0xff] ^\n Te2[(t1 >> 8) & 0xff] ^\n Te3[(t2 ) & 0xff] ^\n rk[3];\n }\n#endif /* ?FULL_UNROLL */\n /*\n\t * apply last round and\n\t * map cipher state to byte array block:\n\t */\n\ts0 =\n\t\t(Te4[(t0 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t3 ) & 0xff] & 0x000000ff) ^\n\t\trk[0];\n\tPUTU32(out , s0);\n\ts1 =\n\t\t(Te4[(t1 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t0 ) & 0xff] & 0x000000ff) ^\n\t\trk[1];\n\tPUTU32(out + 4, s1);\n\ts2 =\n\t\t(Te4[(t2 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t1 ) & 0xff] & 0x000000ff) ^\n\t\trk[2];\n\tPUTU32(out + 8, s2);\n\ts3 =\n\t\t(Te4[(t3 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t2 ) & 0xff] & 0x000000ff) ^\n\t\trk[3];\n\tPUTU32(out + 12, s3);\n}\n\n/*\n * Decrypt a single block\n * in and out can overlap\n */\nvoid AES_decrypt(const unsigned char *in, unsigned char *out,\n\t\t const AES_KEY *key) {\n\n\tconst u32 *rk;\n\tu32 s0, s1, s2, s3, t0, t1, t2, t3;\n#ifndef FULL_UNROLL\n\tint r;\n#endif /* ?FULL_UNROLL */\n\n\tassert(in && out && key);\n\trk = key->rd_key;\n\n\t/*\n\t * map byte array block to cipher state\n\t * and add initial round key:\n\t */\n s0 = GETU32(in ) ^ rk[0];\n s1 = GETU32(in + 4) ^ rk[1];\n s2 = GETU32(in + 8) ^ rk[2];\n s3 = GETU32(in + 12) ^ rk[3];\n#ifdef FULL_UNROLL\n /* round 1: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[ 4];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[ 5];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[ 6];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[ 7];\n /* round 2: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[ 8];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[ 9];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11];\n /* round 3: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15];\n /* round 4: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19];\n /* round 5: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23];\n /* round 6: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27];\n /* round 7: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31];\n /* round 8: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35];\n /* round 9: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39];\n if (key->rounds > 10) {\n /* round 10: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43];\n /* round 11: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47];\n if (key->rounds > 12) {\n /* round 12: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51];\n /* round 13: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55];\n }\n }\n\trk += key->rounds << 2;\n#else /* !FULL_UNROLL */\n /*\n * Nr - 1 full rounds:\n */\n r = key->rounds >> 1;\n for (;;) {\n t0 =\n Td0[(s0 >> 24) ] ^\n Td1[(s3 >> 16) & 0xff] ^\n Td2[(s2 >> 8) & 0xff] ^\n Td3[(s1 ) & 0xff] ^\n rk[4];\n t1 =\n Td0[(s1 >> 24) ] ^\n Td1[(s0 >> 16) & 0xff] ^\n Td2[(s3 >> 8) & 0xff] ^\n Td3[(s2 ) & 0xff] ^\n rk[5];\n t2 =\n Td0[(s2 >> 24) ] ^\n Td1[(s1 >> 16) & 0xff] ^\n Td2[(s0 >> 8) & 0xff] ^\n Td3[(s3 ) & 0xff] ^\n rk[6];\n t3 =\n Td0[(s3 >> 24) ] ^\n Td1[(s2 >> 16) & 0xff] ^\n Td2[(s1 >> 8) & 0xff] ^\n Td3[(s0 ) & 0xff] ^\n rk[7];\n\n rk += 8;\n if (--r == 0) {\n break;\n }\n\n s0 =\n Td0[(t0 >> 24) ] ^\n Td1[(t3 >> 16) & 0xff] ^\n Td2[(t2 >> 8) & 0xff] ^\n Td3[(t1 ) & 0xff] ^\n rk[0];\n s1 =\n Td0[(t1 >> 24) ] ^\n Td1[(t0 >> 16) & 0xff] ^\n Td2[(t3 >> 8) & 0xff] ^\n Td3[(t2 ) & 0xff] ^\n rk[1];\n s2 =\n Td0[(t2 >> 24) ] ^\n Td1[(t1 >> 16) & 0xff] ^\n Td2[(t0 >> 8) & 0xff] ^\n Td3[(t3 ) & 0xff] ^\n rk[2];\n s3 =\n Td0[(t3 >> 24) ] ^\n Td1[(t2 >> 16) & 0xff] ^\n Td2[(t1 >> 8) & 0xff] ^\n Td3[(t0 ) & 0xff] ^\n rk[3];\n }\n#endif /* ?FULL_UNROLL */\n /*\n\t * apply last round and\n\t * map cipher state to byte array block:\n\t */\n \ts0 =\n \t\t(Td4[(t0 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t3 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t2 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t1 ) & 0xff] & 0x000000ff) ^\n \t\trk[0];\n\tPUTU32(out , s0);\n \ts1 =\n \t\t(Td4[(t1 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t0 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t3 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t2 ) & 0xff] & 0x000000ff) ^\n \t\trk[1];\n\tPUTU32(out + 4, s1);\n \ts2 =\n \t\t(Td4[(t2 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t1 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t0 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t3 ) & 0xff] & 0x000000ff) ^\n \t\trk[2];\n\tPUTU32(out + 8, s2);\n \ts3 =\n \t\t(Td4[(t3 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t2 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t1 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t0 ) & 0xff] & 0x000000ff) ^\n \t\trk[3];\n\tPUTU32(out + 12, s3);\n}\n\n#endif /* AES_ASM */\n\nvoid AES_cbc_encrypt(const unsigned char *in, unsigned char *out,\n\t\t const unsigned long length, const AES_KEY *key,\n\t\t unsigned char *ivec, const int enc)\n{\n\n\tunsigned long n;\n\tunsigned long len = length;\n\tunsigned char tmp[AES_BLOCK_SIZE];\n\n\tassert(in && out && key && ivec);\n\n\tif (enc) {\n\t\twhile (len >= AES_BLOCK_SIZE) {\n\t\t\tfor(n=0; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\ttmp[n] = in[n] ^ ivec[n];\n\t\t\tAES_encrypt(tmp, out, key);\n\t\t\tmemcpy(ivec, out, AES_BLOCK_SIZE);\n\t\t\tlen -= AES_BLOCK_SIZE;\n\t\t\tin += AES_BLOCK_SIZE;\n\t\t\tout += AES_BLOCK_SIZE;\n\t\t}\n\t\tif (len) {\n\t\t\tfor(n=0; n < len; ++n)\n\t\t\t\ttmp[n] = in[n] ^ ivec[n];\n\t\t\tfor(n=len; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\ttmp[n] = ivec[n];\n\t\t\tAES_encrypt(tmp, tmp, key);\n\t\t\tmemcpy(out, tmp, AES_BLOCK_SIZE);\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t}\n\t} else {\n\t\twhile (len >= AES_BLOCK_SIZE) {\n\t\t\tmemcpy(tmp, in, AES_BLOCK_SIZE);\n\t\t\tAES_decrypt(in, out, key);\n\t\t\tfor(n=0; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\tout[n] ^= ivec[n];\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t\tlen -= AES_BLOCK_SIZE;\n\t\t\tin += AES_BLOCK_SIZE;\n\t\t\tout += AES_BLOCK_SIZE;\n\t\t}\n\t\tif (len) {\n\t\t\tmemcpy(tmp, in, AES_BLOCK_SIZE);\n\t\t\tAES_decrypt(tmp, tmp, key);\n\t\t\tfor(n=0; n < len; ++n)\n\t\t\t\tout[n] = tmp[n] ^ ivec[n];\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t}\n\t}\n}\n"], ["/linuxpdf/tinyemu/pci.c", "/*\n * Simple PCI bus driver\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"pci.h\"\n\n//#define DEBUG_CONFIG\n\ntypedef struct {\n uint32_t size; /* 0 means no mapping defined */\n uint8_t type;\n uint8_t enabled; /* true if mapping is enabled */\n void *opaque;\n PCIBarSetFunc *bar_set;\n} PCIIORegion;\n\nstruct PCIDevice {\n PCIBus *bus;\n uint8_t devfn;\n IRQSignal irq[4];\n uint8_t config[256];\n uint8_t next_cap_offset; /* offset of the next capability */\n char *name; /* for debug only */\n PCIIORegion io_regions[PCI_NUM_REGIONS];\n};\n\nstruct PCIBus {\n int bus_num;\n PCIDevice *device[256];\n PhysMemoryMap *mem_map;\n PhysMemoryMap *port_map;\n uint32_t irq_state[4][8]; /* one bit per device */\n IRQSignal irq[4];\n};\n\nstatic int bus_map_irq(PCIDevice *d, int irq_num)\n{\n int slot_addend;\n slot_addend = (d->devfn >> 3) - 1;\n return (irq_num + slot_addend) & 3;\n}\n\nstatic void pci_device_set_irq(void *opaque, int irq_num, int level)\n{\n PCIDevice *d = opaque;\n PCIBus *b = d->bus;\n uint32_t mask;\n int i, irq_level;\n \n // printf(\"%s: pci_device_seq_irq: %d %d\\n\", d->name, irq_num, level);\n irq_num = bus_map_irq(d, irq_num);\n mask = 1 << (d->devfn & 0x1f);\n if (level)\n b->irq_state[irq_num][d->devfn >> 5] |= mask;\n else\n b->irq_state[irq_num][d->devfn >> 5] &= ~mask;\n\n /* compute the IRQ state */\n mask = 0;\n for(i = 0; i < 8; i++)\n mask |= b->irq_state[irq_num][i];\n irq_level = (mask != 0);\n set_irq(&b->irq[irq_num], irq_level);\n}\n\nstatic int devfn_alloc(PCIBus *b)\n{\n int devfn;\n for(devfn = 0; devfn < 256; devfn += 8) {\n if (!b->device[devfn])\n return devfn;\n }\n return -1;\n}\n\n/* devfn < 0 means to allocate it */\nPCIDevice *pci_register_device(PCIBus *b, const char *name, int devfn,\n uint16_t vendor_id, uint16_t device_id,\n uint8_t revision, uint16_t class_id)\n{\n PCIDevice *d;\n int i;\n \n if (devfn < 0) {\n devfn = devfn_alloc(b);\n if (devfn < 0)\n return NULL;\n }\n if (b->device[devfn])\n return NULL;\n\n d = mallocz(sizeof(PCIDevice));\n d->bus = b;\n d->name = strdup(name);\n d->devfn = devfn;\n\n put_le16(d->config + 0x00, vendor_id);\n put_le16(d->config + 0x02, device_id);\n d->config[0x08] = revision;\n put_le16(d->config + 0x0a, class_id);\n d->config[0x0e] = 0x00; /* header type */\n d->next_cap_offset = 0x40;\n \n for(i = 0; i < 4; i++)\n irq_init(&d->irq[i], pci_device_set_irq, d, i);\n b->device[devfn] = d;\n\n return d;\n}\n\nIRQSignal *pci_device_get_irq(PCIDevice *d, unsigned int irq_num)\n{\n assert(irq_num < 4);\n return &d->irq[irq_num];\n}\n\nstatic uint32_t pci_device_config_read(PCIDevice *d, uint32_t addr,\n int size_log2)\n{\n uint32_t val;\n switch(size_log2) {\n case 0:\n val = *(uint8_t *)(d->config + addr);\n break;\n case 1:\n /* Note: may be unaligned */\n if (addr <= 0xfe)\n val = get_le16(d->config + addr);\n else\n val = *(uint8_t *)(d->config + addr);\n break;\n case 2:\n /* always aligned */\n val = get_le32(d->config + addr);\n break;\n default:\n abort();\n }\n#ifdef DEBUG_CONFIG\n printf(\"pci_config_read: dev=%s addr=0x%02x val=0x%x s=%d\\n\",\n d->name, addr, val, 1 << size_log2);\n#endif\n return val;\n}\n\nPhysMemoryMap *pci_device_get_mem_map(PCIDevice *d)\n{\n return d->bus->mem_map;\n}\n\nPhysMemoryMap *pci_device_get_port_map(PCIDevice *d)\n{\n return d->bus->port_map;\n}\n\nvoid pci_register_bar(PCIDevice *d, unsigned int bar_num,\n uint32_t size, int type,\n void *opaque, PCIBarSetFunc *bar_set)\n{\n PCIIORegion *r;\n uint32_t val, config_addr;\n \n assert(bar_num < PCI_NUM_REGIONS);\n assert((size & (size - 1)) == 0); /* power of two */\n assert(size >= 4);\n r = &d->io_regions[bar_num];\n assert(r->size == 0);\n r->size = size;\n r->type = type;\n r->enabled = FALSE;\n r->opaque = opaque;\n r->bar_set = bar_set;\n /* set the config value */\n val = 0;\n if (bar_num == PCI_ROM_SLOT) {\n config_addr = 0x30;\n } else {\n val |= r->type;\n config_addr = 0x10 + 4 * bar_num;\n }\n put_le32(&d->config[config_addr], val);\n}\n\nstatic void pci_update_mappings(PCIDevice *d)\n{\n int cmd, i, offset;\n uint32_t new_addr;\n BOOL new_enabled;\n PCIIORegion *r;\n \n cmd = get_le16(&d->config[PCI_COMMAND]);\n\n for(i = 0; i < PCI_NUM_REGIONS; i++) {\n r = &d->io_regions[i];\n if (i == PCI_ROM_SLOT) {\n offset = 0x30;\n } else {\n offset = 0x10 + i * 4;\n }\n new_addr = get_le32(&d->config[offset]);\n new_enabled = FALSE;\n if (r->size != 0) {\n if ((r->type & PCI_ADDRESS_SPACE_IO) &&\n (cmd & PCI_COMMAND_IO)) {\n new_enabled = TRUE;\n } else {\n if (cmd & PCI_COMMAND_MEMORY) {\n if (i == PCI_ROM_SLOT) {\n new_enabled = (new_addr & 1);\n } else {\n new_enabled = TRUE;\n }\n }\n }\n }\n if (new_enabled) {\n /* new address */\n new_addr = get_le32(&d->config[offset]) & ~(r->size - 1);\n r->bar_set(r->opaque, i, new_addr, TRUE);\n r->enabled = TRUE;\n } else if (r->enabled) {\n r->bar_set(r->opaque, i, 0, FALSE);\n r->enabled = FALSE;\n }\n }\n}\n\n/* return != 0 if write is not handled */\nstatic int pci_write_bar(PCIDevice *d, uint32_t addr,\n uint32_t val)\n{\n PCIIORegion *r;\n int reg;\n \n if (addr == 0x30)\n reg = PCI_ROM_SLOT;\n else\n reg = (addr - 0x10) >> 2;\n // printf(\"%s: write bar addr=%x data=%x\\n\", d->name, addr, val);\n r = &d->io_regions[reg];\n if (r->size == 0)\n return -1;\n if (reg == PCI_ROM_SLOT) {\n val = val & ((~(r->size - 1)) | 1);\n } else {\n val = (val & ~(r->size - 1)) | r->type;\n }\n put_le32(d->config + addr, val);\n pci_update_mappings(d);\n return 0;\n}\n\nstatic void pci_device_config_write8(PCIDevice *d, uint32_t addr,\n uint32_t data)\n{\n int can_write;\n\n if (addr == PCI_STATUS || addr == (PCI_STATUS + 1)) {\n /* write 1 reset bits */\n d->config[addr] &= ~data;\n return;\n }\n \n switch(d->config[0x0e]) {\n case 0x00:\n case 0x80:\n switch(addr) {\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x08:\n case 0x09:\n case 0x0a:\n case 0x0b:\n case 0x0e:\n case 0x10 ... 0x27: /* base */\n case 0x30 ... 0x33: /* rom */\n case 0x3d:\n can_write = 0;\n break;\n default:\n can_write = 1;\n break;\n }\n break;\n default:\n case 0x01:\n switch(addr) {\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x08:\n case 0x09:\n case 0x0a:\n case 0x0b:\n case 0x0e:\n case 0x38 ... 0x3b: /* rom */\n case 0x3d:\n can_write = 0;\n break;\n default:\n can_write = 1;\n break;\n }\n break;\n }\n if (can_write)\n d->config[addr] = data;\n}\n \n\nstatic void pci_device_config_write(PCIDevice *d, uint32_t addr,\n uint32_t data, int size_log2)\n{\n int size, i;\n uint32_t addr1;\n \n#ifdef DEBUG_CONFIG\n printf(\"pci_config_write: dev=%s addr=0x%02x val=0x%x s=%d\\n\",\n d->name, addr, data, 1 << size_log2);\n#endif\n if (size_log2 == 2 &&\n ((addr >= 0x10 && addr < 0x10 + 4 * 6) ||\n addr == 0x30)) {\n if (pci_write_bar(d, addr, data) == 0)\n return;\n }\n size = 1 << size_log2;\n for(i = 0; i < size; i++) {\n addr1 = addr + i;\n if (addr1 <= 0xff) {\n pci_device_config_write8(d, addr1, (data >> (i * 8)) & 0xff);\n }\n }\n if (PCI_COMMAND >= addr && PCI_COMMAND < addr + size) {\n pci_update_mappings(d);\n }\n}\n\n\nstatic void pci_data_write(PCIBus *s, uint32_t addr,\n uint32_t data, int size_log2)\n{\n PCIDevice *d;\n int bus_num, devfn, config_addr;\n \n bus_num = (addr >> 16) & 0xff;\n if (bus_num != s->bus_num)\n return;\n devfn = (addr >> 8) & 0xff;\n d = s->device[devfn];\n if (!d)\n return;\n config_addr = addr & 0xff;\n pci_device_config_write(d, config_addr, data, size_log2);\n}\n\nstatic const uint32_t val_ones[3] = { 0xff, 0xffff, 0xffffffff };\n\nstatic uint32_t pci_data_read(PCIBus *s, uint32_t addr, int size_log2)\n{\n PCIDevice *d;\n int bus_num, devfn, config_addr;\n \n bus_num = (addr >> 16) & 0xff;\n if (bus_num != s->bus_num)\n return val_ones[size_log2];\n devfn = (addr >> 8) & 0xff;\n d = s->device[devfn];\n if (!d)\n return val_ones[size_log2];\n config_addr = addr & 0xff;\n return pci_device_config_read(d, config_addr, size_log2);\n}\n\n/* warning: only valid for one DEVIO page. Return NULL if no memory at\n the given address */\nuint8_t *pci_device_get_dma_ptr(PCIDevice *d, uint64_t addr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(d->bus->mem_map, addr, is_rw);\n}\n\nvoid pci_device_set_config8(PCIDevice *d, uint8_t addr, uint8_t val)\n{\n d->config[addr] = val;\n}\n\nvoid pci_device_set_config16(PCIDevice *d, uint8_t addr, uint16_t val)\n{\n put_le16(&d->config[addr], val);\n}\n\nint pci_device_get_devfn(PCIDevice *d)\n{\n return d->devfn;\n}\n\n/* return the offset of the capability or < 0 if error. */\nint pci_add_capability(PCIDevice *d, const uint8_t *buf, int size)\n{\n int offset;\n \n offset = d->next_cap_offset;\n if ((offset + size) > 256)\n return -1;\n d->next_cap_offset += size;\n d->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;\n memcpy(d->config + offset, buf, size);\n d->config[offset + 1] = d->config[PCI_CAPABILITY_LIST];\n d->config[PCI_CAPABILITY_LIST] = offset;\n return offset;\n}\n\n/* i440FX host bridge */\n\nstruct I440FXState {\n PCIBus *pci_bus;\n PCIDevice *pci_dev;\n PCIDevice *piix3_dev;\n uint32_t config_reg;\n uint8_t pic_irq_state[16];\n IRQSignal *pic_irqs; /* 16 irqs */\n};\n\nstatic void i440fx_write_addr(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n I440FXState *s = opaque;\n s->config_reg = data;\n}\n\nstatic uint32_t i440fx_read_addr(void *opaque, uint32_t offset, int size_log2)\n{\n I440FXState *s = opaque;\n return s->config_reg;\n}\n\nstatic void i440fx_write_data(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n I440FXState *s = opaque;\n if (s->config_reg & 0x80000000) {\n if (size_log2 == 2) {\n /* it is simpler to assume 32 bit config accesses are\n always aligned */\n pci_data_write(s->pci_bus, s->config_reg & ~3, data, size_log2);\n } else {\n pci_data_write(s->pci_bus, s->config_reg | offset, data, size_log2);\n }\n }\n}\n\nstatic uint32_t i440fx_read_data(void *opaque, uint32_t offset, int size_log2)\n{\n I440FXState *s = opaque;\n if (!(s->config_reg & 0x80000000))\n return val_ones[size_log2];\n if (size_log2 == 2) {\n /* it is simpler to assume 32 bit config accesses are\n always aligned */\n return pci_data_read(s->pci_bus, s->config_reg & ~3, size_log2);\n } else {\n return pci_data_read(s->pci_bus, s->config_reg | offset, size_log2);\n }\n}\n\nstatic void i440fx_set_irq(void *opaque, int irq_num, int irq_level)\n{\n I440FXState *s = opaque;\n PCIDevice *hd = s->piix3_dev;\n int pic_irq;\n \n /* map to the PIC irq (different IRQs can be mapped to the same\n PIC irq) */\n hd->config[0x60 + irq_num] &= ~0x80;\n pic_irq = hd->config[0x60 + irq_num];\n if (pic_irq < 16) {\n if (irq_level)\n s->pic_irq_state[pic_irq] |= 1 << irq_num;\n else\n s->pic_irq_state[pic_irq] &= ~(1 << irq_num);\n set_irq(&s->pic_irqs[pic_irq], (s->pic_irq_state[pic_irq] != 0));\n }\n}\n\nI440FXState *i440fx_init(PCIBus **pbus, int *ppiix3_devfn,\n PhysMemoryMap *mem_map, PhysMemoryMap *port_map,\n IRQSignal *pic_irqs)\n{\n I440FXState *s;\n PCIBus *b;\n PCIDevice *d;\n int i;\n \n s = mallocz(sizeof(*s));\n \n b = mallocz(sizeof(PCIBus));\n b->bus_num = 0;\n b->mem_map = mem_map;\n b->port_map = port_map;\n\n s->pic_irqs = pic_irqs;\n for(i = 0; i < 4; i++) {\n irq_init(&b->irq[i], i440fx_set_irq, s, i);\n }\n \n cpu_register_device(port_map, 0xcf8, 1, s, i440fx_read_addr, i440fx_write_addr, \n DEVIO_SIZE32);\n cpu_register_device(port_map, 0xcfc, 4, s, i440fx_read_data, i440fx_write_data, \n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32);\n d = pci_register_device(b, \"i440FX\", 0, 0x8086, 0x1237, 0x02, 0x0600);\n put_le16(&d->config[PCI_SUBSYSTEM_VENDOR_ID], 0x1af4); /* Red Hat, Inc. */\n put_le16(&d->config[PCI_SUBSYSTEM_ID], 0x1100); /* QEMU virtual machine */\n \n s->pci_dev = d;\n s->pci_bus = b;\n\n s->piix3_dev = pci_register_device(b, \"PIIX3\", 8, 0x8086, 0x7000,\n 0x00, 0x0601);\n pci_device_set_config8(s->piix3_dev, 0x0e, 0x80); /* header type */\n\n *pbus = b;\n *ppiix3_devfn = s->piix3_dev->devfn;\n return s;\n}\n\n/* in case no BIOS is used, map the interrupts. */\nvoid i440fx_map_interrupts(I440FXState *s, uint8_t *elcr,\n const uint8_t *pci_irqs)\n{\n PCIBus *b = s->pci_bus;\n PCIDevice *d, *hd;\n int irq_num, pic_irq, devfn, i;\n \n /* set a default PCI IRQ mapping to PIC IRQs */\n hd = s->piix3_dev;\n\n elcr[0] = 0;\n elcr[1] = 0;\n for(i = 0; i < 4; i++) {\n irq_num = pci_irqs[i];\n hd->config[0x60 + i] = irq_num;\n elcr[irq_num >> 3] |= (1 << (irq_num & 7));\n }\n\n for(devfn = 0; devfn < 256; devfn++) {\n d = b->device[devfn];\n if (!d)\n continue;\n if (d->config[PCI_INTERRUPT_PIN]) {\n irq_num = 0;\n irq_num = bus_map_irq(d, irq_num);\n pic_irq = hd->config[0x60 + irq_num];\n if (pic_irq < 16) {\n d->config[PCI_INTERRUPT_LINE] = pic_irq;\n }\n }\n }\n}\n"], ["/linuxpdf/tinyemu/block_net.c", "/*\n * HTTP block device\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"virtio.h\"\n#include \"fs_wget.h\"\n#include \"list.h\"\n#include \"fbuf.h\"\n#include \"machine.h\"\n\ntypedef enum {\n CBLOCK_LOADING,\n CBLOCK_LOADED,\n} CachedBlockStateEnum;\n\ntypedef struct CachedBlock {\n struct list_head link;\n struct BlockDeviceHTTP *bf;\n unsigned int block_num;\n CachedBlockStateEnum state;\n FileBuffer fbuf;\n} CachedBlock;\n\n#define BLK_FMT \"%sblk%09u.bin\"\n#define GROUP_FMT \"%sgrp%09u.bin\"\n#define PREFETCH_GROUP_LEN_MAX 32\n\ntypedef struct {\n struct BlockDeviceHTTP *bf;\n int group_num;\n int n_block_num;\n CachedBlock *tab_block[PREFETCH_GROUP_LEN_MAX];\n} PrefetchGroupRequest;\n\n/* modified data is stored per cluster (smaller than cached blocks to\n avoid losing space) */\ntypedef struct Cluster {\n FileBuffer fbuf;\n} Cluster;\n\ntypedef struct BlockDeviceHTTP {\n BlockDevice *bs;\n int max_cache_size_kb;\n char url[1024];\n int prefetch_count;\n void (*start_cb)(void *opaque);\n void *start_opaque;\n \n int64_t nb_sectors;\n int block_size; /* in sectors, power of two */\n int nb_blocks;\n struct list_head cached_blocks; /* list of CachedBlock */\n int n_cached_blocks;\n int n_cached_blocks_max;\n\n /* write support */\n int sectors_per_cluster; /* power of two */\n Cluster **clusters; /* NULL if no written data */\n int n_clusters;\n int n_allocated_clusters;\n \n /* statistics */\n int64_t n_read_sectors;\n int64_t n_read_blocks;\n int64_t n_write_sectors;\n\n /* current read request */\n BOOL is_write;\n uint64_t sector_num;\n int cur_block_num;\n int sector_index, sector_count;\n BlockDeviceCompletionFunc *cb;\n void *opaque;\n uint8_t *io_buf;\n\n /* prefetch */\n int prefetch_group_len;\n} BlockDeviceHTTP;\n\nstatic void bf_update_block(CachedBlock *b, const uint8_t *data);\nstatic void bf_read_onload(void *opaque, int err, void *data, size_t size);\nstatic void bf_init_onload(void *opaque, int err, void *data, size_t size);\nstatic void bf_prefetch_group_onload(void *opaque, int err, void *data,\n size_t size);\n\nstatic CachedBlock *bf_find_block(BlockDeviceHTTP *bf, unsigned int block_num)\n{\n CachedBlock *b;\n struct list_head *el;\n \n list_for_each(el, &bf->cached_blocks) {\n b = list_entry(el, CachedBlock, link);\n if (b->block_num == block_num) {\n /* move to front */\n if (bf->cached_blocks.next != el) {\n list_del(&b->link);\n list_add(&b->link, &bf->cached_blocks);\n }\n return b;\n }\n }\n return NULL;\n}\n\nstatic void bf_free_block(BlockDeviceHTTP *bf, CachedBlock *b)\n{\n bf->n_cached_blocks--;\n file_buffer_reset(&b->fbuf);\n list_del(&b->link);\n free(b);\n}\n\nstatic CachedBlock *bf_add_block(BlockDeviceHTTP *bf, unsigned int block_num)\n{\n CachedBlock *b;\n if (bf->n_cached_blocks >= bf->n_cached_blocks_max) {\n struct list_head *el, *el1;\n /* start by looking at the least unused blocks */\n list_for_each_prev_safe(el, el1, &bf->cached_blocks) {\n b = list_entry(el, CachedBlock, link);\n if (b->state == CBLOCK_LOADED) {\n bf_free_block(bf, b);\n if (bf->n_cached_blocks < bf->n_cached_blocks_max)\n break;\n }\n }\n }\n b = mallocz(sizeof(CachedBlock));\n b->bf = bf;\n b->block_num = block_num;\n b->state = CBLOCK_LOADING;\n file_buffer_init(&b->fbuf);\n file_buffer_resize(&b->fbuf, bf->block_size * 512);\n list_add(&b->link, &bf->cached_blocks);\n bf->n_cached_blocks++;\n return b;\n}\n\nstatic int64_t bf_get_sector_count(BlockDevice *bs)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n return bf->nb_sectors;\n}\n\nstatic void bf_start_load_block(BlockDevice *bs, int block_num)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n char filename[1024];\n CachedBlock *b;\n b = bf_add_block(bf, block_num);\n bf->n_read_blocks++;\n /* make a XHR to read the block */\n#if 0\n printf(\"%u,\\n\", block_num);\n#endif\n#if 0\n printf(\"load_blk=%d cached=%d read=%d KB (%d KB) write=%d KB (%d KB)\\n\",\n block_num, bf->n_cached_blocks,\n (int)(bf->n_read_sectors / 2),\n (int)(bf->n_read_blocks * bf->block_size / 2),\n (int)(bf->n_write_sectors / 2),\n (int)(bf->n_allocated_clusters * bf->sectors_per_cluster / 2));\n#endif\n snprintf(filename, sizeof(filename), BLK_FMT, bf->url, block_num);\n // printf(\"wget %s\\n\", filename);\n fs_wget(filename, NULL, NULL, b, bf_read_onload, TRUE);\n}\n\nstatic void bf_start_load_prefetch_group(BlockDevice *bs, int group_num,\n const int *tab_block_num,\n int n_block_num)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n CachedBlock *b;\n PrefetchGroupRequest *req;\n char filename[1024];\n BOOL req_flag;\n int i;\n \n req_flag = FALSE;\n req = malloc(sizeof(*req));\n req->bf = bf;\n req->group_num = group_num;\n req->n_block_num = n_block_num;\n for(i = 0; i < n_block_num; i++) {\n b = bf_find_block(bf, tab_block_num[i]);\n if (!b) {\n b = bf_add_block(bf, tab_block_num[i]);\n req_flag = TRUE;\n } else {\n /* no need to read the block if it is already loading or\n loaded */\n b = NULL;\n }\n req->tab_block[i] = b;\n }\n\n if (req_flag) {\n snprintf(filename, sizeof(filename), GROUP_FMT, bf->url, group_num);\n // printf(\"wget %s\\n\", filename);\n fs_wget(filename, NULL, NULL, req, bf_prefetch_group_onload, TRUE);\n /* XXX: should add request in a list to free it for clean exit */\n } else {\n free(req);\n }\n}\n\nstatic void bf_prefetch_group_onload(void *opaque, int err, void *data,\n size_t size)\n{\n PrefetchGroupRequest *req = opaque;\n BlockDeviceHTTP *bf = req->bf;\n CachedBlock *b;\n int block_bytes, i;\n \n if (err < 0) {\n fprintf(stderr, \"Could not load group %u\\n\", req->group_num);\n exit(1);\n }\n block_bytes = bf->block_size * 512;\n assert(size == block_bytes * req->n_block_num);\n for(i = 0; i < req->n_block_num; i++) {\n b = req->tab_block[i];\n if (b) {\n bf_update_block(b, (const uint8_t *)data + block_bytes * i);\n }\n }\n free(req);\n}\n\nstatic int bf_rw_async1(BlockDevice *bs, BOOL is_sync)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n int offset, block_num, n, cluster_num;\n CachedBlock *b;\n Cluster *c;\n \n for(;;) {\n n = bf->sector_count - bf->sector_index;\n if (n == 0)\n break;\n cluster_num = bf->sector_num / bf->sectors_per_cluster;\n c = bf->clusters[cluster_num];\n if (c) {\n offset = bf->sector_num % bf->sectors_per_cluster;\n n = min_int(n, bf->sectors_per_cluster - offset);\n if (bf->is_write) {\n file_buffer_write(&c->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n } else {\n file_buffer_read(&c->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n }\n bf->sector_index += n;\n bf->sector_num += n;\n } else {\n block_num = bf->sector_num / bf->block_size;\n offset = bf->sector_num % bf->block_size;\n n = min_int(n, bf->block_size - offset);\n bf->cur_block_num = block_num;\n \n b = bf_find_block(bf, block_num);\n if (b) {\n if (b->state == CBLOCK_LOADING) {\n /* wait until the block is loaded */\n return 1;\n } else {\n if (bf->is_write) {\n int cluster_size, cluster_offset;\n uint8_t *buf;\n /* allocate a new cluster */\n c = mallocz(sizeof(Cluster));\n cluster_size = bf->sectors_per_cluster * 512;\n buf = malloc(cluster_size);\n file_buffer_init(&c->fbuf);\n file_buffer_resize(&c->fbuf, cluster_size);\n bf->clusters[cluster_num] = c;\n /* copy the cached block data to the cluster */\n cluster_offset = (cluster_num * bf->sectors_per_cluster) &\n (bf->block_size - 1);\n file_buffer_read(&b->fbuf, cluster_offset * 512,\n buf, cluster_size);\n file_buffer_write(&c->fbuf, 0, buf, cluster_size);\n free(buf);\n bf->n_allocated_clusters++;\n continue; /* write to the allocated cluster */\n } else {\n file_buffer_read(&b->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n }\n bf->sector_index += n;\n bf->sector_num += n;\n }\n } else {\n bf_start_load_block(bs, block_num);\n return 1;\n }\n bf->cur_block_num = -1;\n }\n }\n\n if (!is_sync) {\n // printf(\"end of request\\n\");\n /* end of request */\n bf->cb(bf->opaque, 0);\n } \n return 0;\n}\n\nstatic void bf_update_block(CachedBlock *b, const uint8_t *data)\n{\n BlockDeviceHTTP *bf = b->bf;\n BlockDevice *bs = bf->bs;\n\n assert(b->state == CBLOCK_LOADING);\n file_buffer_write(&b->fbuf, 0, data, bf->block_size * 512);\n b->state = CBLOCK_LOADED;\n \n /* continue I/O read/write if necessary */\n if (b->block_num == bf->cur_block_num) {\n bf_rw_async1(bs, FALSE);\n }\n}\n\nstatic void bf_read_onload(void *opaque, int err, void *data, size_t size)\n{\n CachedBlock *b = opaque;\n BlockDeviceHTTP *bf = b->bf;\n\n if (err < 0) {\n fprintf(stderr, \"Could not load block %u\\n\", b->block_num);\n exit(1);\n }\n \n assert(size == bf->block_size * 512);\n bf_update_block(b, data);\n}\n\nstatic int bf_read_async(BlockDevice *bs,\n uint64_t sector_num, uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n // printf(\"bf_read_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n bf->is_write = FALSE;\n bf->sector_num = sector_num;\n bf->io_buf = buf;\n bf->sector_count = n;\n bf->sector_index = 0;\n bf->cb = cb;\n bf->opaque = opaque;\n bf->n_read_sectors += n;\n return bf_rw_async1(bs, TRUE);\n}\n\nstatic int bf_write_async(BlockDevice *bs,\n uint64_t sector_num, const uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n // printf(\"bf_write_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n bf->is_write = TRUE;\n bf->sector_num = sector_num;\n bf->io_buf = (uint8_t *)buf;\n bf->sector_count = n;\n bf->sector_index = 0;\n bf->cb = cb;\n bf->opaque = opaque;\n bf->n_write_sectors += n;\n return bf_rw_async1(bs, TRUE);\n}\n\nBlockDevice *block_device_init_http(const char *url,\n int max_cache_size_kb,\n void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n BlockDevice *bs;\n BlockDeviceHTTP *bf;\n char *p;\n\n bs = mallocz(sizeof(*bs));\n bf = mallocz(sizeof(*bf));\n strcpy(bf->url, url);\n /* get the path with the trailing '/' */\n p = strrchr(bf->url, '/');\n if (!p)\n p = bf->url;\n else\n p++;\n *p = '\\0';\n\n init_list_head(&bf->cached_blocks);\n bf->max_cache_size_kb = max_cache_size_kb;\n bf->start_cb = start_cb;\n bf->start_opaque = start_opaque;\n bf->bs = bs;\n \n bs->opaque = bf;\n bs->get_sector_count = bf_get_sector_count;\n bs->read_async = bf_read_async;\n bs->write_async = bf_write_async;\n \n fs_wget(url, NULL, NULL, bs, bf_init_onload, TRUE);\n return bs;\n}\n\nstatic void bf_init_onload(void *opaque, int err, void *data, size_t size)\n{\n BlockDevice *bs = opaque;\n BlockDeviceHTTP *bf = bs->opaque;\n int block_size_kb, block_num;\n JSONValue cfg, array;\n \n if (err < 0) {\n fprintf(stderr, \"Could not load block device file (err=%d)\\n\", -err);\n exit(1);\n }\n\n /* parse the disk image info */\n cfg = json_parse_value_len(data, size);\n if (json_is_error(cfg)) {\n vm_error(\"error: %s\\n\", json_get_error(cfg));\n config_error:\n json_free(cfg);\n exit(1);\n }\n\n if (vm_get_int(cfg, \"block_size\", &block_size_kb) < 0)\n goto config_error;\n bf->block_size = block_size_kb * 2;\n if (bf->block_size <= 0 ||\n (bf->block_size & (bf->block_size - 1)) != 0) {\n vm_error(\"invalid block_size\\n\");\n goto config_error;\n }\n if (vm_get_int(cfg, \"n_block\", &bf->nb_blocks) < 0)\n goto config_error;\n if (bf->nb_blocks <= 0) {\n vm_error(\"invalid n_block\\n\");\n goto config_error;\n }\n\n bf->nb_sectors = bf->block_size * (uint64_t)bf->nb_blocks;\n bf->n_cached_blocks = 0;\n bf->n_cached_blocks_max = max_int(1, bf->max_cache_size_kb / block_size_kb);\n bf->cur_block_num = -1; /* no request in progress */\n \n bf->sectors_per_cluster = 8; /* 4 KB */\n bf->n_clusters = (bf->nb_sectors + bf->sectors_per_cluster - 1) / bf->sectors_per_cluster;\n bf->clusters = mallocz(sizeof(bf->clusters[0]) * bf->n_clusters);\n\n if (vm_get_int_opt(cfg, \"prefetch_group_len\",\n &bf->prefetch_group_len, 1) < 0)\n goto config_error;\n if (bf->prefetch_group_len > PREFETCH_GROUP_LEN_MAX) {\n vm_error(\"prefetch_group_len is too large\");\n goto config_error;\n }\n \n array = json_object_get(cfg, \"prefetch\");\n if (!json_is_undefined(array)) {\n int idx, prefetch_len, l, i;\n JSONValue el;\n int tab_block_num[PREFETCH_GROUP_LEN_MAX];\n \n if (array.type != JSON_ARRAY) {\n vm_error(\"expecting an array\\n\");\n goto config_error;\n }\n prefetch_len = array.u.array->len;\n idx = 0;\n while (idx < prefetch_len) {\n l = min_int(prefetch_len - idx, bf->prefetch_group_len);\n for(i = 0; i < l; i++) {\n el = json_array_get(array, idx + i);\n if (el.type != JSON_INT) {\n vm_error(\"expecting an integer\\n\");\n goto config_error;\n }\n tab_block_num[i] = el.u.int32;\n }\n if (l == 1) {\n block_num = tab_block_num[0];\n if (!bf_find_block(bf, block_num)) {\n bf_start_load_block(bs, block_num);\n }\n } else {\n bf_start_load_prefetch_group(bs, idx / bf->prefetch_group_len,\n tab_block_num, l);\n }\n idx += l;\n }\n }\n json_free(cfg);\n \n if (bf->start_cb) {\n bf->start_cb(bf->start_opaque);\n }\n}\n"], ["/linuxpdf/tinyemu/sha256.c", "/* LibTomCrypt, modular cryptographic library -- Tom St Denis\n *\n * LibTomCrypt is a library that provides various cryptographic\n * algorithms in a highly modular and flexible manner.\n *\n * The library is free for all purposes without any express\n * guarantee it works.\n *\n * Tom St Denis, tomstdenis@gmail.com, http://libtom.org\n */\n#include \n#include \n#include \"cutils.h\"\n#include \"sha256.h\"\n\n#define LOAD32H(a, b) a = get_be32(b)\n#define STORE32H(a, b) put_be32(b, a)\n#define STORE64H(a, b) put_be64(b, a)\n#define RORc(x, y) ( ((((uint32_t)(x)&0xFFFFFFFFUL)>>(uint32_t)((y)&31)) | ((uint32_t)(x)<<(uint32_t)(32-((y)&31)))) & 0xFFFFFFFFUL)\n\n#if defined(CONFIG_EMBUE)\n#define LTC_SMALL_CODE\n#endif\n\n/**\n @file sha256.c\n LTC_SHA256 by Tom St Denis\n*/\n\n#ifdef LTC_SMALL_CODE\n/* the K array */\nstatic const uint32_t K[64] = {\n 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,\n 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,\n 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,\n 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,\n 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,\n 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,\n 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,\n 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,\n 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,\n 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,\n 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,\n 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,\n 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL\n};\n#endif\n\n/* Various logical functions */\n#define Ch(x,y,z) (z ^ (x & (y ^ z)))\n#define Maj(x,y,z) (((x | y) & z) | (x & y))\n#define S(x, n) RORc((x),(n))\n#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))\n#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))\n#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25))\n#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3))\n#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10))\n\n/* compress 512-bits */\nstatic void sha256_compress(SHA256_CTX *s, unsigned char *buf)\n{\n uint32_t S[8], W[64], t0, t1;\n#ifdef LTC_SMALL_CODE\n uint32_t t;\n#endif\n int i;\n\n /* copy state into S */\n for (i = 0; i < 8; i++) {\n S[i] = s->state[i];\n }\n\n /* copy the state into 512-bits into W[0..15] */\n for (i = 0; i < 16; i++) {\n LOAD32H(W[i], buf + (4*i));\n }\n\n /* fill W[16..63] */\n for (i = 16; i < 64; i++) {\n W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];\n }\n\n /* Compress */\n#ifdef LTC_SMALL_CODE\n#define RND(a,b,c,d,e,f,g,h,i) \\\n t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \\\n t1 = Sigma0(a) + Maj(a, b, c); \\\n d += t0; \\\n h = t0 + t1;\n\n for (i = 0; i < 64; ++i) {\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i);\n t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4];\n S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;\n }\n#else\n#define RND(a,b,c,d,e,f,g,h,i,ki) \\\n t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i]; \\\n t1 = Sigma0(a) + Maj(a, b, c); \\\n d += t0; \\\n h = t0 + t1;\n\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,0x428a2f98);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,0x71374491);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,0xb5c0fbcf);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,0xe9b5dba5);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,0x3956c25b);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],5,0x59f111f1);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],6,0x923f82a4);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],7,0xab1c5ed5);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],8,0xd807aa98);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],9,0x12835b01);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],10,0x243185be);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],11,0x550c7dc3);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],12,0x72be5d74);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],13,0x80deb1fe);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],14,0x9bdc06a7);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],15,0xc19bf174);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],16,0xe49b69c1);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],17,0xefbe4786);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],18,0x0fc19dc6);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],19,0x240ca1cc);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],20,0x2de92c6f);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],21,0x4a7484aa);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],22,0x5cb0a9dc);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],23,0x76f988da);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],24,0x983e5152);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],25,0xa831c66d);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],26,0xb00327c8);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],27,0xbf597fc7);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],28,0xc6e00bf3);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],29,0xd5a79147);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],30,0x06ca6351);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],31,0x14292967);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],32,0x27b70a85);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],33,0x2e1b2138);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],34,0x4d2c6dfc);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],35,0x53380d13);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],36,0x650a7354);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],37,0x766a0abb);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],38,0x81c2c92e);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],39,0x92722c85);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],40,0xa2bfe8a1);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],41,0xa81a664b);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],42,0xc24b8b70);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],43,0xc76c51a3);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],44,0xd192e819);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],45,0xd6990624);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],46,0xf40e3585);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],47,0x106aa070);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],48,0x19a4c116);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],49,0x1e376c08);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],50,0x2748774c);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],51,0x34b0bcb5);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],52,0x391c0cb3);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],53,0x4ed8aa4a);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],54,0x5b9cca4f);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],55,0x682e6ff3);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],56,0x748f82ee);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],57,0x78a5636f);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],58,0x84c87814);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],59,0x8cc70208);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],60,0x90befffa);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],61,0xa4506ceb);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);\n\n#undef RND\n\n#endif\n\n /* feedback */\n for (i = 0; i < 8; i++) {\n s->state[i] = s->state[i] + S[i];\n }\n}\n\n#ifdef LTC_CLEAN_STACK\nstatic int sha256_compress(hash_state * md, unsigned char *buf)\n{\n int err;\n err = _sha256_compress(md, buf);\n burn_stack(sizeof(uint32_t) * 74);\n return err;\n}\n#endif\n\n/**\n Initialize the hash state\n @param md The hash state you wish to initialize\n @return CRYPT_OK if successful\n*/\nvoid SHA256_Init(SHA256_CTX *s)\n{\n s->curlen = 0;\n s->length = 0;\n s->state[0] = 0x6A09E667UL;\n s->state[1] = 0xBB67AE85UL;\n s->state[2] = 0x3C6EF372UL;\n s->state[3] = 0xA54FF53AUL;\n s->state[4] = 0x510E527FUL;\n s->state[5] = 0x9B05688CUL;\n s->state[6] = 0x1F83D9ABUL;\n s->state[7] = 0x5BE0CD19UL;\n}\n\nvoid SHA256_Update(SHA256_CTX *s, const uint8_t *in, unsigned long inlen)\n{\n unsigned long n;\n\n if (s->curlen > sizeof(s->buf)) {\n abort();\n }\n if ((s->length + inlen) < s->length) {\n abort();\n }\n while (inlen > 0) {\n if (s->curlen == 0 && inlen >= 64) {\n sha256_compress(s, (unsigned char *)in);\n s->length += 64 * 8;\n in += 64;\n inlen -= 64;\n } else {\n n = min_int(inlen, 64 - s->curlen);\n memcpy(s->buf + s->curlen, in, (size_t)n);\n s->curlen += n;\n in += n;\n inlen -= n;\n if (s->curlen == 64) {\n sha256_compress(s, s->buf);\n s->length += 8*64;\n s->curlen = 0;\n }\n }\n } }\n\n/**\n Terminate the hash to get the digest\n @param md The hash state\n @param out [out] The destination of the hash (32 bytes)\n @return CRYPT_OK if successful\n*/\nvoid SHA256_Final(uint8_t *out, SHA256_CTX *s)\n{\n int i;\n\n if (s->curlen >= sizeof(s->buf)) {\n abort();\n }\n\n\n /* increase the length of the message */\n s->length += s->curlen * 8;\n\n /* append the '1' bit */\n s->buf[s->curlen++] = (unsigned char)0x80;\n\n /* if the length is currently above 56 bytes we append zeros\n * then compress. Then we can fall back to padding zeros and length\n * encoding like normal.\n */\n if (s->curlen > 56) {\n while (s->curlen < 64) {\n s->buf[s->curlen++] = (unsigned char)0;\n }\n sha256_compress(s, s->buf);\n s->curlen = 0;\n }\n\n /* pad upto 56 bytes of zeroes */\n while (s->curlen < 56) {\n s->buf[s->curlen++] = (unsigned char)0;\n }\n\n /* store length */\n STORE64H(s->length, s->buf+56);\n sha256_compress(s, s->buf);\n\n /* copy output */\n for (i = 0; i < 8; i++) {\n STORE32H(s->state[i], out+(4*i));\n }\n#ifdef LTC_CLEAN_STACK\n zeromem(md, sizeof(hash_state));\n#endif\n}\n\nvoid SHA256(const uint8_t *buf, int buf_len, uint8_t *out)\n{\n SHA256_CTX ctx;\n\n SHA256_Init(&ctx);\n SHA256_Update(&ctx, buf, buf_len);\n SHA256_Final(out, &ctx);\n}\n\n#if 0\n/**\n Self-test the hash\n @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled\n*/\nint sha256_test(void)\n{\n #ifndef LTC_TEST\n return CRYPT_NOP;\n #else\n static const struct {\n char *msg;\n unsigned char hash[32];\n } tests[] = {\n { \"abc\",\n { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,\n 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,\n 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,\n 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }\n },\n { \"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\",\n { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,\n 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,\n 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,\n 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }\n },\n };\n\n int i;\n unsigned char tmp[32];\n hash_state md;\n\n for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {\n sha256_init(&md);\n sha256_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));\n sha256_done(&md, tmp);\n if (XMEMCMP(tmp, tests[i].hash, 32) != 0) {\n return CRYPT_FAIL_TESTVECTOR;\n }\n }\n return CRYPT_OK;\n #endif\n}\n\n#endif\n"], ["/linuxpdf/tinyemu/build_filelist.c", "/*\n * File list builder for RISCVEMU network filesystem\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"fs_utils.h\"\n\nvoid print_str(FILE *f, const char *str)\n{\n const char *s;\n int c;\n s = str;\n while (*s != '\\0') {\n if (*s <= ' ' || *s > '~')\n goto use_quote;\n s++;\n }\n fputs(str, f);\n return;\n use_quote:\n s = str;\n fputc('\"', f);\n while (*s != '\\0') {\n c = *(uint8_t *)s;\n if (c < ' ' || c == 127) {\n fprintf(f, \"\\\\x%02x\", c);\n } else if (c == '\\\\' || c == '\\\"') {\n fprintf(f, \"\\\\%c\", c);\n } else {\n fputc(c, f);\n }\n s++;\n }\n fputc('\"', f);\n}\n\n#define COPY_BUF_LEN (1024 * 1024)\n\nstatic void copy_file(const char *src_filename, const char *dst_filename)\n{\n uint8_t *buf;\n FILE *fi, *fo;\n int len;\n \n buf = malloc(COPY_BUF_LEN);\n fi = fopen(src_filename, \"rb\");\n if (!fi) {\n perror(src_filename);\n exit(1);\n }\n fo = fopen(dst_filename, \"wb\");\n if (!fo) {\n perror(dst_filename);\n exit(1);\n }\n for(;;) {\n len = fread(buf, 1, COPY_BUF_LEN, fi);\n if (len == 0)\n break;\n fwrite(buf, 1, len, fo);\n }\n fclose(fo);\n fclose(fi);\n}\n\ntypedef struct {\n char *files_path;\n uint64_t next_inode_num;\n uint64_t fs_size;\n uint64_t fs_max_size;\n FILE *f;\n} ScanState;\n\nstatic void add_file_size(ScanState *s, uint64_t size)\n{\n s->fs_size += block_align(size, FS_BLOCK_SIZE);\n if (s->fs_size > s->fs_max_size) {\n fprintf(stderr, \"Filesystem Quota exceeded (%\" PRId64 \" bytes)\\n\", s->fs_max_size);\n exit(1);\n }\n}\n\nvoid scan_dir(ScanState *s, const char *path)\n{\n FILE *f = s->f;\n DIR *dirp;\n struct dirent *de;\n const char *name;\n struct stat st;\n char *path1;\n uint32_t mode, v;\n\n dirp = opendir(path);\n if (!dirp) {\n perror(path);\n exit(1);\n }\n for(;;) {\n de = readdir(dirp);\n if (!de)\n break;\n name = de->d_name;\n if (!strcmp(name, \".\") || !strcmp(name, \"..\"))\n continue;\n path1 = compose_path(path, name);\n if (lstat(path1, &st) < 0) {\n perror(path1);\n exit(1);\n }\n\n mode = st.st_mode & 0xffff;\n fprintf(f, \"%06o %u %u\", \n mode, \n (int)st.st_uid,\n (int)st.st_gid);\n if (S_ISCHR(mode) || S_ISBLK(mode)) {\n fprintf(f, \" %u %u\",\n (int)major(st.st_rdev),\n (int)minor(st.st_rdev));\n }\n if (S_ISREG(mode)) {\n fprintf(f, \" %\" PRIu64, st.st_size);\n }\n /* modification time (at most ms resolution) */\n fprintf(f, \" %u\", (int)st.st_mtim.tv_sec);\n v = st.st_mtim.tv_nsec;\n if (v != 0) {\n fprintf(f, \".\");\n while (v != 0) {\n fprintf(f, \"%u\", v / 100000000);\n v = (v % 100000000) * 10;\n }\n }\n \n fprintf(f, \" \");\n print_str(f, name);\n if (S_ISLNK(mode)) {\n char buf[1024];\n int len;\n len = readlink(path1, buf, sizeof(buf) - 1);\n if (len < 0) {\n perror(\"readlink\");\n exit(1);\n }\n buf[len] = '\\0';\n fprintf(f, \" \");\n print_str(f, buf);\n } else if (S_ISREG(mode) && st.st_size > 0) {\n char buf1[FILEID_SIZE_MAX], *fname;\n FSFileID file_id;\n file_id = s->next_inode_num++;\n fprintf(f, \" %\" PRIx64, file_id);\n file_id_to_filename(buf1, file_id);\n fname = compose_path(s->files_path, buf1);\n copy_file(path1, fname);\n add_file_size(s, st.st_size);\n }\n\n fprintf(f, \"\\n\");\n if (S_ISDIR(mode)) {\n scan_dir(s, path1);\n }\n free(path1);\n }\n\n closedir(dirp);\n fprintf(f, \".\\n\"); /* end of directory */\n}\n\nvoid help(void)\n{\n printf(\"usage: build_filelist [options] source_path dest_path\\n\"\n \"\\n\"\n \"Options:\\n\"\n \"-m size_mb set the max filesystem size in MiB\\n\");\n exit(1);\n}\n\n#define LOCK_FILENAME \"lock\"\n\nint main(int argc, char **argv)\n{\n const char *dst_path, *src_path;\n ScanState s_s, *s = &s_s;\n FILE *f;\n char *filename;\n FSFileID root_id;\n char fname[FILEID_SIZE_MAX];\n struct stat st;\n uint64_t first_inode, fs_max_size;\n int c;\n \n first_inode = 1;\n fs_max_size = (uint64_t)1 << 30;\n for(;;) {\n c = getopt(argc, argv, \"hi:m:\");\n if (c == -1)\n break;\n switch(c) {\n case 'h':\n help();\n case 'i':\n first_inode = strtoul(optarg, NULL, 0);\n break;\n case 'm':\n fs_max_size = (uint64_t)strtoul(optarg, NULL, 0) << 20;\n break;\n default:\n exit(1);\n }\n }\n\n if (optind + 1 >= argc)\n help();\n src_path = argv[optind];\n dst_path = argv[optind + 1];\n \n mkdir(dst_path, 0755);\n\n s->files_path = compose_path(dst_path, ROOT_FILENAME);\n s->next_inode_num = first_inode;\n s->fs_size = 0;\n s->fs_max_size = fs_max_size;\n \n mkdir(s->files_path, 0755);\n\n root_id = s->next_inode_num++;\n file_id_to_filename(fname, root_id);\n filename = compose_path(s->files_path, fname);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fprintf(f, \"Version: 1\\n\");\n fprintf(f, \"Revision: 1\\n\");\n fprintf(f, \"\\n\");\n s->f = f;\n scan_dir(s, src_path);\n fclose(f);\n\n /* take into account the filelist size */\n if (stat(filename, &st) < 0) {\n perror(filename);\n exit(1);\n }\n add_file_size(s, st.st_size);\n \n free(filename);\n \n filename = compose_path(dst_path, HEAD_FILENAME);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fprintf(f, \"Version: 1\\n\");\n fprintf(f, \"Revision: 1\\n\");\n fprintf(f, \"NextFileID: %\" PRIx64 \"\\n\", s->next_inode_num);\n fprintf(f, \"FSFileCount: %\" PRIu64 \"\\n\", s->next_inode_num - 1);\n fprintf(f, \"FSSize: %\" PRIu64 \"\\n\", s->fs_size);\n fprintf(f, \"FSMaxSize: %\" PRIu64 \"\\n\", s->fs_max_size);\n fprintf(f, \"Key:\\n\"); /* not encrypted */\n fprintf(f, \"RootID: %\" PRIx64 \"\\n\", root_id);\n fclose(f);\n free(filename);\n \n filename = compose_path(dst_path, LOCK_FILENAME);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fclose(f);\n free(filename);\n\n return 0;\n}\n"], ["/linuxpdf/tinyemu/sdl.c", "/*\n * SDL display driver\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"cutils.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n#define KEYCODE_MAX 127\n\nstatic SDL_Surface *screen;\nstatic SDL_Surface *fb_surface;\nstatic int screen_width, screen_height, fb_width, fb_height, fb_stride;\nstatic SDL_Cursor *sdl_cursor_hidden;\nstatic uint8_t key_pressed[KEYCODE_MAX + 1];\n\nstatic void sdl_update_fb_surface(FBDevice *fb_dev)\n{\n if (!fb_surface)\n goto force_alloc;\n if (fb_width != fb_dev->width ||\n fb_height != fb_dev->height ||\n fb_stride != fb_dev->stride) {\n force_alloc:\n if (fb_surface != NULL)\n SDL_FreeSurface(fb_surface);\n fb_width = fb_dev->width;\n fb_height = fb_dev->height;\n fb_stride = fb_dev->stride;\n fb_surface = SDL_CreateRGBSurfaceFrom(fb_dev->fb_data,\n fb_dev->width, fb_dev->height,\n 32, fb_dev->stride,\n 0x00ff0000,\n 0x0000ff00,\n 0x000000ff,\n 0x00000000);\n if (!fb_surface) {\n fprintf(stderr, \"Could not create SDL framebuffer surface\\n\");\n exit(1);\n }\n }\n}\n\nstatic void sdl_update(FBDevice *fb_dev, void *opaque,\n int x, int y, int w, int h)\n{\n SDL_Rect r;\n // printf(\"sdl_update: %d %d %d %d\\n\", x, y, w, h);\n r.x = x;\n r.y = y;\n r.w = w;\n r.h = h;\n SDL_BlitSurface(fb_surface, &r, screen, &r);\n SDL_UpdateRect(screen, r.x, r.y, r.w, r.h);\n}\n\n#if defined(_WIN32)\n\nstatic int sdl_get_keycode(const SDL_KeyboardEvent *ev)\n{\n return ev->keysym.scancode;\n}\n\n#else\n\n/* we assume Xorg is used with a PC keyboard. Return 0 if no keycode found. */\nstatic int sdl_get_keycode(const SDL_KeyboardEvent *ev)\n{\n int keycode;\n keycode = ev->keysym.scancode;\n if (keycode < 9) {\n keycode = 0;\n } else if (keycode < 127 + 8) {\n keycode -= 8;\n } else {\n keycode = 0;\n }\n return keycode;\n}\n\n#endif\n\n/* release all pressed keys */\nstatic void sdl_reset_keys(VirtMachine *m)\n{\n int i;\n \n for(i = 1; i <= KEYCODE_MAX; i++) {\n if (key_pressed[i]) {\n vm_send_key_event(m, FALSE, i);\n key_pressed[i] = FALSE;\n }\n }\n}\n\nstatic void sdl_handle_key_event(const SDL_KeyboardEvent *ev, VirtMachine *m)\n{\n int keycode, keypress;\n\n keycode = sdl_get_keycode(ev);\n if (keycode) {\n if (keycode == 0x3a || keycode ==0x45) {\n /* SDL does not generate key up for numlock & caps lock */\n vm_send_key_event(m, TRUE, keycode);\n vm_send_key_event(m, FALSE, keycode);\n } else {\n keypress = (ev->type == SDL_KEYDOWN);\n if (keycode <= KEYCODE_MAX)\n key_pressed[keycode] = keypress;\n vm_send_key_event(m, keypress, keycode);\n }\n } else if (ev->type == SDL_KEYUP) {\n /* workaround to reset the keyboard state (used when changing\n desktop with ctrl-alt-x on Linux) */\n sdl_reset_keys(m);\n }\n}\n\nstatic void sdl_send_mouse_event(VirtMachine *m, int x1, int y1,\n int dz, int state, BOOL is_absolute)\n{\n int buttons, x, y;\n\n buttons = 0;\n if (state & SDL_BUTTON(SDL_BUTTON_LEFT))\n buttons |= (1 << 0);\n if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))\n buttons |= (1 << 1);\n if (state & SDL_BUTTON(SDL_BUTTON_MIDDLE))\n buttons |= (1 << 2);\n if (is_absolute) {\n x = (x1 * 32768) / screen_width;\n y = (y1 * 32768) / screen_height;\n } else {\n x = x1;\n y = y1;\n }\n vm_send_mouse_event(m, x, y, dz, buttons);\n}\n\nstatic void sdl_handle_mouse_motion_event(const SDL_Event *ev, VirtMachine *m)\n{\n BOOL is_absolute = vm_mouse_is_absolute(m);\n int x, y;\n if (is_absolute) {\n x = ev->motion.x;\n y = ev->motion.y;\n } else {\n x = ev->motion.xrel;\n y = ev->motion.yrel;\n }\n sdl_send_mouse_event(m, x, y, 0, ev->motion.state, is_absolute);\n}\n\nstatic void sdl_handle_mouse_button_event(const SDL_Event *ev, VirtMachine *m)\n{\n BOOL is_absolute = vm_mouse_is_absolute(m);\n int state, dz;\n\n dz = 0;\n if (ev->type == SDL_MOUSEBUTTONDOWN) {\n if (ev->button.button == SDL_BUTTON_WHEELUP) {\n dz = 1;\n } else if (ev->button.button == SDL_BUTTON_WHEELDOWN) {\n dz = -1;\n }\n }\n \n state = SDL_GetMouseState(NULL, NULL);\n /* just in case */\n if (ev->type == SDL_MOUSEBUTTONDOWN)\n state |= SDL_BUTTON(ev->button.button);\n else\n state &= ~SDL_BUTTON(ev->button.button);\n\n if (is_absolute) {\n sdl_send_mouse_event(m, ev->button.x, ev->button.y,\n dz, state, is_absolute);\n } else {\n sdl_send_mouse_event(m, 0, 0, dz, state, is_absolute);\n }\n}\n\nvoid sdl_refresh(VirtMachine *m)\n{\n SDL_Event ev_s, *ev = &ev_s;\n\n if (!m->fb_dev)\n return;\n \n sdl_update_fb_surface(m->fb_dev);\n\n m->fb_dev->refresh(m->fb_dev, sdl_update, NULL);\n \n while (SDL_PollEvent(ev)) {\n switch (ev->type) {\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n sdl_handle_key_event(&ev->key, m);\n break;\n case SDL_MOUSEMOTION:\n sdl_handle_mouse_motion_event(ev, m);\n break;\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n sdl_handle_mouse_button_event(ev, m);\n break;\n case SDL_QUIT:\n exit(0);\n }\n }\n}\n\nstatic void sdl_hide_cursor(void)\n{\n uint8_t data = 0;\n sdl_cursor_hidden = SDL_CreateCursor(&data, &data, 8, 1, 0, 0);\n SDL_ShowCursor(1);\n SDL_SetCursor(sdl_cursor_hidden);\n}\n\nvoid sdl_init(int width, int height)\n{\n int flags;\n \n screen_width = width;\n screen_height = height;\n\n if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE)) {\n fprintf(stderr, \"Could not initialize SDL - exiting\\n\");\n exit(1);\n }\n\n flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;\n screen = SDL_SetVideoMode(width, height, 0, flags);\n if (!screen || !screen->pixels) {\n fprintf(stderr, \"Could not open SDL display\\n\");\n exit(1);\n }\n\n SDL_WM_SetCaption(\"TinyEMU\", \"TinyEMU\");\n\n sdl_hide_cursor();\n}\n\n"], ["/linuxpdf/tinyemu/iomem.c", "/*\n * IO memory handling\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n\nstatic PhysMemoryRange *default_register_ram(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags);\nstatic void default_free_ram(PhysMemoryMap *s, PhysMemoryRange *pr);\nstatic const uint32_t *default_get_dirty_bits(PhysMemoryMap *map, PhysMemoryRange *pr);\nstatic void default_set_addr(PhysMemoryMap *map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled);\n\nPhysMemoryMap *phys_mem_map_init(void)\n{\n PhysMemoryMap *s;\n s = mallocz(sizeof(*s));\n s->register_ram = default_register_ram;\n s->free_ram = default_free_ram;\n s->get_dirty_bits = default_get_dirty_bits;\n s->set_ram_addr = default_set_addr;\n return s;\n}\n\nvoid phys_mem_map_end(PhysMemoryMap *s)\n{\n int i;\n PhysMemoryRange *pr;\n\n for(i = 0; i < s->n_phys_mem_range; i++) {\n pr = &s->phys_mem_range[i];\n if (pr->is_ram) {\n s->free_ram(s, pr);\n }\n }\n free(s);\n}\n\n/* return NULL if not found */\n/* XXX: optimize */\nPhysMemoryRange *get_phys_mem_range(PhysMemoryMap *s, uint64_t paddr)\n{\n PhysMemoryRange *pr;\n int i;\n for(i = 0; i < s->n_phys_mem_range; i++) {\n pr = &s->phys_mem_range[i];\n if (paddr >= pr->addr && paddr < pr->addr + pr->size)\n return pr;\n }\n return NULL;\n}\n\nPhysMemoryRange *register_ram_entry(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n\n assert(s->n_phys_mem_range < PHYS_MEM_RANGE_MAX);\n assert((size & (DEVRAM_PAGE_SIZE - 1)) == 0 && size != 0);\n pr = &s->phys_mem_range[s->n_phys_mem_range++];\n pr->map = s;\n pr->is_ram = TRUE;\n pr->devram_flags = devram_flags & ~DEVRAM_FLAG_DISABLED;\n pr->addr = addr;\n pr->org_size = size;\n if (devram_flags & DEVRAM_FLAG_DISABLED)\n pr->size = 0;\n else\n pr->size = pr->org_size;\n pr->phys_mem = NULL;\n pr->dirty_bits = NULL;\n return pr;\n}\n\nstatic PhysMemoryRange *default_register_ram(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n\n pr = register_ram_entry(s, addr, size, devram_flags);\n\n pr->phys_mem = mallocz(size);\n if (!pr->phys_mem) {\n fprintf(stderr, \"Could not allocate VM memory\\n\");\n exit(1);\n }\n\n if (devram_flags & DEVRAM_FLAG_DIRTY_BITS) {\n size_t nb_pages;\n int i;\n nb_pages = size >> DEVRAM_PAGE_SIZE_LOG2;\n pr->dirty_bits_size = ((nb_pages + 31) / 32) * sizeof(uint32_t);\n pr->dirty_bits_index = 0;\n for(i = 0; i < 2; i++) {\n pr->dirty_bits_tab[i] = mallocz(pr->dirty_bits_size);\n }\n pr->dirty_bits = pr->dirty_bits_tab[pr->dirty_bits_index];\n }\n return pr;\n}\n\n/* return a pointer to the bitmap of dirty bits and reset them */\nstatic const uint32_t *default_get_dirty_bits(PhysMemoryMap *map,\n PhysMemoryRange *pr)\n{\n uint32_t *dirty_bits;\n BOOL has_dirty_bits;\n size_t n, i;\n \n dirty_bits = pr->dirty_bits;\n\n has_dirty_bits = FALSE;\n n = pr->dirty_bits_size / sizeof(uint32_t);\n for(i = 0; i < n; i++) {\n if (dirty_bits[i] != 0) {\n has_dirty_bits = TRUE;\n break;\n }\n }\n if (has_dirty_bits && pr->size != 0) {\n /* invalidate the corresponding CPU write TLBs */\n map->flush_tlb_write_range(map->opaque, pr->phys_mem, pr->org_size);\n }\n \n pr->dirty_bits_index ^= 1;\n pr->dirty_bits = pr->dirty_bits_tab[pr->dirty_bits_index];\n memset(pr->dirty_bits, 0, pr->dirty_bits_size);\n return dirty_bits;\n}\n\n/* reset the dirty bit of one page at 'offset' inside 'pr' */\nvoid phys_mem_reset_dirty_bit(PhysMemoryRange *pr, size_t offset)\n{\n size_t page_index;\n uint32_t mask, *dirty_bits_ptr;\n PhysMemoryMap *map;\n if (pr->dirty_bits) {\n page_index = offset >> DEVRAM_PAGE_SIZE_LOG2;\n mask = 1 << (page_index & 0x1f);\n dirty_bits_ptr = pr->dirty_bits + (page_index >> 5);\n if (*dirty_bits_ptr & mask) {\n *dirty_bits_ptr &= ~mask;\n /* invalidate the corresponding CPU write TLBs */\n map = pr->map;\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem + (offset & ~(DEVRAM_PAGE_SIZE - 1)),\n DEVRAM_PAGE_SIZE);\n }\n }\n}\n\nstatic void default_free_ram(PhysMemoryMap *s, PhysMemoryRange *pr)\n{\n free(pr->phys_mem);\n}\n\nPhysMemoryRange *cpu_register_device(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, void *opaque,\n DeviceReadFunc *read_func, DeviceWriteFunc *write_func,\n int devio_flags)\n{\n PhysMemoryRange *pr;\n assert(s->n_phys_mem_range < PHYS_MEM_RANGE_MAX);\n assert(size <= 0xffffffff);\n pr = &s->phys_mem_range[s->n_phys_mem_range++];\n pr->map = s;\n pr->addr = addr;\n pr->org_size = size;\n if (devio_flags & DEVIO_DISABLED)\n pr->size = 0;\n else\n pr->size = pr->org_size;\n pr->is_ram = FALSE;\n pr->opaque = opaque;\n pr->read_func = read_func;\n pr->write_func = write_func;\n pr->devio_flags = devio_flags;\n return pr;\n}\n\nstatic void default_set_addr(PhysMemoryMap *map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n if (enabled) {\n if (pr->size == 0 || pr->addr != addr) {\n /* enable or move mapping */\n if (pr->is_ram) {\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem, pr->org_size);\n }\n pr->addr = addr;\n pr->size = pr->org_size;\n }\n } else {\n if (pr->size != 0) {\n /* disable mapping */\n if (pr->is_ram) {\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem, pr->org_size);\n }\n pr->addr = 0;\n pr->size = 0;\n }\n }\n}\n\nvoid phys_mem_set_addr(PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n PhysMemoryMap *map = pr->map;\n if (!pr->is_ram) {\n default_set_addr(map, pr, addr, enabled);\n } else {\n return map->set_ram_addr(map, pr, addr, enabled);\n }\n}\n\n/* return NULL if no valid RAM page. The access can only be done in the page */\nuint8_t *phys_mem_get_ram_ptr(PhysMemoryMap *map, uint64_t paddr, BOOL is_rw)\n{\n PhysMemoryRange *pr = get_phys_mem_range(map, paddr);\n uintptr_t offset;\n if (!pr || !pr->is_ram)\n return NULL;\n offset = paddr - pr->addr;\n if (is_rw)\n phys_mem_set_dirty_bit(pr, offset);\n return pr->phys_mem + (uintptr_t)offset;\n}\n\n/* IRQ support */\n\nvoid irq_init(IRQSignal *irq, SetIRQFunc *set_irq, void *opaque, int irq_num)\n{\n irq->set_irq = set_irq;\n irq->opaque = opaque;\n irq->irq_num = irq_num;\n}\n"], ["/linuxpdf/tinyemu/json.c", "/*\n * Pseudo JSON parser\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"json.h\"\n#include \"fs_utils.h\"\n\nstatic JSONValue parse_string(const char **pp)\n{\n char buf[4096], *q;\n const char *p;\n int c, h;\n \n q = buf;\n p = *pp;\n p++;\n for(;;) {\n c = *p++;\n if (c == '\\0' || c == '\\n') {\n return json_error_new(\"unterminated string\");\n } else if (c == '\\\"') {\n break;\n } else if (c == '\\\\') {\n c = *p++;\n switch(c) {\n case '\\'':\n case '\\\"':\n case '\\\\':\n goto add_char;\n case 'n':\n c = '\\n';\n goto add_char;\n case 'r':\n c = '\\r';\n goto add_char;\n case 't':\n c = '\\t';\n goto add_char;\n case 'x':\n h = from_hex(*p++);\n if (h < 0)\n return json_error_new(\"invalig hex digit\");\n c = h << 4;\n h = from_hex(*p++);\n if (h < 0)\n return json_error_new(\"invalig hex digit\");\n c |= h;\n goto add_char;\n default:\n return json_error_new(\"unknown escape code\");\n }\n } else {\n add_char:\n if (q >= buf + sizeof(buf) - 1)\n return json_error_new(\"string too long\");\n *q++ = c;\n }\n }\n *q = '\\0';\n *pp = p;\n return json_string_new(buf);\n}\n\nstatic JSONProperty *json_object_get2(JSONObject *obj, const char *name)\n{\n JSONProperty *f;\n int i;\n for(i = 0; i < obj->len; i++) {\n f = &obj->props[i];\n if (!strcmp(f->name.u.str->data, name))\n return f;\n }\n return NULL;\n}\n\nJSONValue json_object_get(JSONValue val, const char *name)\n{\n JSONProperty *f;\n JSONObject *obj;\n \n if (val.type != JSON_OBJ)\n return json_undefined_new();\n obj = val.u.obj;\n f = json_object_get2(obj, name);\n if (!f)\n return json_undefined_new();\n return f->value;\n}\n\nint json_object_set(JSONValue val, const char *name, JSONValue prop_val)\n{\n JSONObject *obj;\n JSONProperty *f;\n int new_size;\n \n if (val.type != JSON_OBJ)\n return -1;\n obj = val.u.obj;\n f = json_object_get2(obj, name);\n if (f) {\n json_free(f->value);\n f->value = prop_val;\n } else {\n if (obj->len >= obj->size) {\n new_size = max_int(obj->len + 1, obj->size * 3 / 2);\n obj->props = realloc(obj->props, new_size * sizeof(JSONProperty));\n obj->size = new_size;\n }\n f = &obj->props[obj->len++];\n f->name = json_string_new(name);\n f->value = prop_val;\n }\n return 0;\n}\n\nJSONValue json_array_get(JSONValue val, unsigned int idx)\n{\n JSONArray *array;\n \n if (val.type != JSON_ARRAY)\n return json_undefined_new();\n array = val.u.array;\n if (idx < array->len) {\n return array->tab[idx];\n } else {\n return json_undefined_new();\n }\n}\n\nint json_array_set(JSONValue val, unsigned int idx, JSONValue prop_val)\n{\n JSONArray *array;\n int new_size;\n \n if (val.type != JSON_ARRAY)\n return -1;\n array = val.u.array;\n if (idx < array->len) {\n json_free(array->tab[idx]);\n array->tab[idx] = prop_val;\n } else if (idx == array->len) {\n if (array->len >= array->size) {\n new_size = max_int(array->len + 1, array->size * 3 / 2);\n array->tab = realloc(array->tab, new_size * sizeof(JSONValue));\n array->size = new_size;\n }\n array->tab[array->len++] = prop_val;\n } else {\n return -1;\n }\n return 0;\n}\n\nconst char *json_get_str(JSONValue val)\n{\n if (val.type != JSON_STR)\n return NULL;\n return val.u.str->data;\n}\n\nconst char *json_get_error(JSONValue val)\n{\n if (val.type != JSON_EXCEPTION)\n return NULL;\n return val.u.str->data;\n}\n\nJSONValue json_string_new2(const char *str, int len)\n{\n JSONValue val;\n JSONString *str1;\n\n str1 = malloc(sizeof(JSONString) + len + 1);\n str1->len = len;\n memcpy(str1->data, str, len + 1);\n val.type = JSON_STR;\n val.u.str = str1;\n return val;\n}\n\nJSONValue json_string_new(const char *str)\n{\n return json_string_new2(str, strlen(str));\n}\n\nJSONValue __attribute__((format(printf, 1, 2))) json_error_new(const char *fmt, ...)\n{\n JSONValue val;\n va_list ap;\n char buf[256];\n \n va_start(ap, fmt);\n vsnprintf(buf, sizeof(buf), fmt, ap);\n va_end(ap);\n val = json_string_new(buf);\n val.type = JSON_EXCEPTION;\n return val;\n}\n\nJSONValue json_object_new(void)\n{\n JSONValue val;\n JSONObject *obj;\n obj = mallocz(sizeof(JSONObject));\n val.type = JSON_OBJ;\n val.u.obj = obj;\n return val;\n}\n\nJSONValue json_array_new(void)\n{\n JSONValue val;\n JSONArray *array;\n array = mallocz(sizeof(JSONArray));\n val.type = JSON_ARRAY;\n val.u.array = array;\n return val;\n}\n\nvoid json_free(JSONValue val)\n{\n switch(val.type) {\n case JSON_STR:\n case JSON_EXCEPTION:\n free(val.u.str);\n break;\n case JSON_INT:\n case JSON_BOOL:\n case JSON_NULL:\n case JSON_UNDEFINED:\n break;\n case JSON_ARRAY:\n {\n JSONArray *array = val.u.array;\n int i;\n \n for(i = 0; i < array->len; i++) {\n json_free(array->tab[i]);\n }\n free(array);\n }\n break;\n case JSON_OBJ:\n {\n JSONObject *obj = val.u.obj;\n JSONProperty *f;\n int i;\n \n for(i = 0; i < obj->len; i++) {\n f = &obj->props[i];\n json_free(f->name);\n json_free(f->value);\n }\n free(obj);\n }\n break;\n default:\n abort();\n }\n}\n\nstatic void skip_spaces(const char **pp)\n{\n const char *p;\n p = *pp;\n for(;;) {\n if (isspace(*p)) {\n p++;\n } else if (p[0] == '/' && p[1] == '/') {\n p += 2;\n while (*p != '\\0' && *p != '\\n')\n p++;\n } else if (p[0] == '/' && p[1] == '*') {\n p += 2;\n while (*p != '\\0' && (p[0] != '*' || p[1] != '/'))\n p++;\n if (*p != '\\0')\n p += 2;\n } else {\n break;\n }\n }\n *pp = p;\n}\n\nstatic inline BOOL is_ident_first(int c)\n{\n return (c >= 'a' && c <= 'z') ||\n (c >= 'A' && c <= 'Z') ||\n c == '_' || c == '$';\n}\n\nstatic int parse_ident(char *buf, int buf_size, const char **pp)\n{\n char *q;\n const char *p;\n p = *pp;\n q = buf;\n *q++ = *p++; /* first char is already tested */\n while (is_ident_first(*p) || isdigit(*p)) {\n if ((q - buf) >= buf_size - 1)\n return -1;\n *q++ = *p++;\n }\n *pp = p;\n *q = '\\0';\n return 0;\n}\n\nJSONValue json_parse_value2(const char **pp)\n{\n char buf[128];\n const char *p;\n JSONValue val, val1, tag;\n \n p = *pp;\n skip_spaces(&p);\n if (*p == '\\0') {\n return json_error_new(\"unexpected end of file\");\n }\n if (isdigit(*p)) {\n val = json_int32_new(strtol(p, (char **)&p, 0));\n } else if (*p == '\"') {\n val = parse_string(&p);\n } else if (*p == '{') {\n p++;\n val = json_object_new();\n for(;;) {\n skip_spaces(&p);\n if (*p == '}') {\n p++;\n break;\n }\n if (*p == '\"') {\n tag = parse_string(&p);\n if (json_is_error(tag))\n return tag;\n } else if (is_ident_first(*p)) {\n if (parse_ident(buf, sizeof(buf), &p) < 0)\n goto invalid_prop;\n tag = json_string_new(buf);\n } else {\n goto invalid_prop;\n }\n // printf(\"property: %s\\n\", json_get_str(tag));\n if (tag.u.str->len == 0) {\n invalid_prop:\n return json_error_new(\"Invalid property name\");\n }\n skip_spaces(&p);\n if (*p != ':') {\n return json_error_new(\"':' expected\");\n }\n p++;\n \n val1 = json_parse_value2(&p);\n json_object_set(val, tag.u.str->data, val1);\n\n skip_spaces(&p);\n if (*p == ',') {\n p++;\n } else if (*p != '}') {\n return json_error_new(\"expecting ',' or '}'\");\n }\n }\n } else if (*p == '[') {\n int idx;\n \n p++;\n val = json_array_new();\n idx = 0;\n for(;;) {\n skip_spaces(&p);\n if (*p == ']') {\n p++;\n break;\n }\n val1 = json_parse_value2(&p);\n json_array_set(val, idx++, val1);\n\n skip_spaces(&p);\n if (*p == ',') {\n p++;\n } else if (*p != ']') {\n return json_error_new(\"expecting ',' or ']'\");\n }\n }\n } else if (is_ident_first(*p)) {\n if (parse_ident(buf, sizeof(buf), &p) < 0)\n goto unknown_id;\n if (!strcmp(buf, \"null\")) {\n val = json_null_new();\n } else if (!strcmp(buf, \"true\")) {\n val = json_bool_new(TRUE);\n } else if (!strcmp(buf, \"false\")) {\n val = json_bool_new(FALSE);\n } else {\n unknown_id:\n return json_error_new(\"unknown identifier: '%s'\", buf);\n }\n } else {\n return json_error_new(\"unexpected character\");\n }\n *pp = p;\n return val;\n}\n\nJSONValue json_parse_value(const char *p)\n{\n JSONValue val;\n val = json_parse_value2(&p); \n if (json_is_error(val))\n return val;\n skip_spaces(&p);\n if (*p != '\\0') {\n json_free(val);\n return json_error_new(\"unexpected characters at the end\");\n }\n return val;\n}\n\nJSONValue json_parse_value_len(const char *p, int len)\n{\n char *str;\n JSONValue val;\n str = malloc(len + 1);\n memcpy(str, p, len);\n str[len] = '\\0';\n val = json_parse_value(str);\n free(str);\n return val;\n}\n"], ["/linuxpdf/tinyemu/fs_utils.c", "/*\n * Misc FS utilities\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs_utils.h\"\n\n/* last byte is the version */\nconst uint8_t encrypted_file_magic[4] = { 0xfb, 0xa2, 0xe9, 0x01 };\n\nchar *compose_path(const char *path, const char *name)\n{\n int path_len, name_len;\n char *d, *q;\n\n if (path[0] == '\\0') {\n d = strdup(name);\n } else {\n path_len = strlen(path);\n name_len = strlen(name);\n d = malloc(path_len + 1 + name_len + 1);\n q = d;\n memcpy(q, path, path_len);\n q += path_len;\n if (path[path_len - 1] != '/')\n *q++ = '/';\n memcpy(q, name, name_len + 1);\n }\n return d;\n}\n\nchar *compose_url(const char *base_url, const char *name)\n{\n if (strchr(name, ':')) {\n return strdup(name);\n } else {\n return compose_path(base_url, name);\n }\n}\n\nvoid skip_line(const char **pp)\n{\n const char *p;\n p = *pp;\n while (*p != '\\n' && *p != '\\0')\n p++;\n if (*p == '\\n')\n p++;\n *pp = p;\n}\n\nchar *quoted_str(const char *str)\n{\n const char *s;\n char *q;\n int c;\n char *buf;\n\n if (str[0] == '\\0')\n goto use_quote;\n s = str;\n while (*s != '\\0') {\n if (*s <= ' ' || *s > '~')\n goto use_quote;\n s++;\n }\n return strdup(str);\n use_quote:\n buf = malloc(strlen(str) * 4 + 2 + 1);\n q = buf;\n s = str;\n *q++ = '\"';\n while (*s != '\\0') {\n c = *(uint8_t *)s;\n if (c < ' ' || c == 127) {\n q += sprintf(q, \"\\\\x%02x\", c);\n } else if (c == '\\\\' || c == '\\\"') {\n q += sprintf(q, \"\\\\%c\", c);\n } else {\n *q++ = c;\n }\n s++;\n }\n *q++ = '\"';\n *q = '\\0';\n return buf;\n}\n\nint parse_fname(char *buf, int buf_size, const char **pp)\n{\n const char *p;\n char *q;\n int c, h;\n \n p = *pp;\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\0')\n return -1;\n q = buf;\n if (*p == '\"') {\n p++;\n for(;;) {\n c = *p++;\n if (c == '\\0' || c == '\\n') {\n return -1;\n } else if (c == '\\\"') {\n break;\n } else if (c == '\\\\') {\n c = *p++;\n switch(c) {\n case '\\'':\n case '\\\"':\n case '\\\\':\n goto add_char;\n case 'n':\n c = '\\n';\n goto add_char;\n case 'r':\n c = '\\r';\n goto add_char;\n case 't':\n c = '\\t';\n goto add_char;\n case 'x':\n h = from_hex(*p++);\n if (h < 0)\n return -1;\n c = h << 4;\n h = from_hex(*p++);\n if (h < 0)\n return -1;\n c |= h;\n goto add_char;\n default:\n return -1;\n }\n } else {\n add_char:\n if (q >= buf + buf_size - 1)\n return -1;\n *q++ = c;\n }\n }\n } else {\n while (!isspace_nolf(*p) && *p != '\\0' && *p != '\\n') {\n if (q >= buf + buf_size - 1)\n return -1;\n *q++ = *p++;\n }\n }\n *q = '\\0';\n *pp = p;\n return 0;\n}\n\nint parse_uint32_base(uint32_t *pval, const char **pp, int base)\n{\n const char *p, *p1;\n p = *pp;\n while (isspace_nolf(*p))\n p++;\n *pval = strtoul(p, (char **)&p1, base);\n if (p1 == p)\n return -1;\n *pp = p1;\n return 0;\n}\n\nint parse_uint64_base(uint64_t *pval, const char **pp, int base)\n{\n const char *p, *p1;\n p = *pp;\n while (isspace_nolf(*p))\n p++;\n *pval = strtoull(p, (char **)&p1, base);\n if (p1 == p)\n return -1;\n *pp = p1;\n return 0;\n}\n\nint parse_uint64(uint64_t *pval, const char **pp)\n{\n return parse_uint64_base(pval, pp, 0);\n}\n\nint parse_uint32(uint32_t *pval, const char **pp)\n{\n return parse_uint32_base(pval, pp, 0);\n}\n\nint parse_time(uint32_t *psec, uint32_t *pnsec, const char **pp)\n{\n const char *p;\n uint32_t v, m;\n p = *pp;\n if (parse_uint32(psec, &p) < 0)\n return -1;\n v = 0;\n if (*p == '.') {\n p++;\n /* XXX: inefficient */\n m = 1000000000;\n v = 0;\n while (*p >= '0' && *p <= '9') {\n m /= 10;\n v += (*p - '0') * m;\n p++;\n }\n }\n *pnsec = v;\n *pp = p;\n return 0;\n}\n\nint parse_file_id(FSFileID *pval, const char **pp)\n{\n return parse_uint64_base(pval, pp, 16);\n}\n\nchar *file_id_to_filename(char *buf, FSFileID file_id)\n{\n sprintf(buf, \"%016\" PRIx64, file_id);\n return buf;\n}\n\nvoid encode_hex(char *str, const uint8_t *buf, int len)\n{\n int i;\n for(i = 0; i < len; i++)\n sprintf(str + 2 * i, \"%02x\", buf[i]);\n}\n\nint decode_hex(uint8_t *buf, const char *str, int len)\n{\n int h0, h1, i;\n\n for(i = 0; i < len; i++) {\n h0 = from_hex(str[2 * i]);\n if (h0 < 0)\n return -1;\n h1 = from_hex(str[2 * i + 1]);\n if (h1 < 0)\n return -1;\n buf[i] = (h0 << 4) | h1;\n }\n return 0;\n}\n\n/* return NULL if no end of header found */\nconst char *skip_header(const char *p)\n{\n p = strstr(p, \"\\n\\n\");\n if (!p)\n return NULL;\n return p + 2;\n}\n\n/* return 0 if OK, < 0 if error */\nint parse_tag(char *buf, int buf_size, const char *str, const char *tag)\n{\n char tagname[128], *q;\n const char *p, *p1;\n int len;\n \n p = str;\n for(;;) {\n if (*p == '\\0' || *p == '\\n')\n break;\n q = tagname;\n while (*p != ':' && *p != '\\n' && *p != '\\0') {\n if ((q - tagname) < sizeof(tagname) - 1)\n *q++ = *p;\n p++;\n }\n *q = '\\0';\n if (*p != ':')\n return -1;\n p++;\n while (isspace_nolf(*p))\n p++;\n p1 = p;\n p = strchr(p, '\\n');\n if (!p)\n len = strlen(p1);\n else\n len = p - p1;\n if (!strcmp(tagname, tag)) {\n if (len > buf_size - 1)\n len = buf_size - 1;\n memcpy(buf, p1, len);\n buf[len] = '\\0';\n return 0;\n }\n if (!p)\n break;\n else\n p++;\n }\n return -1;\n}\n\nint parse_tag_uint64(uint64_t *pval, const char *str, const char *tag)\n{\n char buf[64];\n const char *p;\n if (parse_tag(buf, sizeof(buf), str, tag))\n return -1;\n p = buf;\n return parse_uint64(pval, &p);\n}\n\nint parse_tag_file_id(FSFileID *pval, const char *str, const char *tag)\n{\n char buf[64];\n const char *p;\n if (parse_tag(buf, sizeof(buf), str, tag))\n return -1;\n p = buf;\n return parse_uint64_base(pval, &p, 16);\n}\n\nint parse_tag_version(const char *str)\n{\n uint64_t version;\n if (parse_tag_uint64(&version, str, \"Version\"))\n return -1;\n return version;\n}\n\nBOOL is_url(const char *path)\n{\n return (strstart(path, \"http:\", NULL) ||\n strstart(path, \"https:\", NULL) ||\n strstart(path, \"file:\", NULL));\n}\n"], ["/linuxpdf/tinyemu/vmmouse.c", "/*\n * VM mouse emulation\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n\n#define VMPORT_MAGIC 0x564D5868\n\n#define REG_EAX 0\n#define REG_EBX 1\n#define REG_ECX 2\n#define REG_EDX 3\n#define REG_ESI 4\n#define REG_EDI 5\n\n#define FIFO_SIZE (4 * 16)\n\nstruct VMMouseState {\n PS2MouseState *ps2_mouse;\n int fifo_count, fifo_rindex, fifo_windex;\n BOOL enabled;\n BOOL absolute;\n uint32_t fifo_buf[FIFO_SIZE];\n};\n\nstatic void put_queue(VMMouseState *s, uint32_t val)\n{\n if (s->fifo_count >= FIFO_SIZE)\n return;\n s->fifo_buf[s->fifo_windex] = val;\n if (++s->fifo_windex == FIFO_SIZE)\n s->fifo_windex = 0;\n s->fifo_count++;\n}\n\nstatic void read_data(VMMouseState *s, uint32_t *regs, int size)\n{\n int i;\n if (size > 6 || size > s->fifo_count) {\n // printf(\"vmmouse: read error req=%d count=%d\\n\", size, s->fifo_count);\n s->enabled = FALSE;\n return;\n }\n for(i = 0; i < size; i++) {\n regs[i] = s->fifo_buf[s->fifo_rindex];\n if (++s->fifo_rindex == FIFO_SIZE)\n s->fifo_rindex = 0;\n }\n s->fifo_count -= size;\n}\n\nvoid vmmouse_send_mouse_event(VMMouseState *s, int x, int y, int dz,\n int buttons)\n{\n int state;\n\n if (!s->enabled) {\n ps2_mouse_event(s->ps2_mouse, x, y, dz, buttons);\n return;\n }\n\n if ((s->fifo_count + 4) > FIFO_SIZE)\n return;\n\n state = 0;\n if (buttons & 1)\n state |= 0x20;\n if (buttons & 2)\n state |= 0x10;\n if (buttons & 4)\n state |= 0x08;\n if (s->absolute) {\n /* range = 0 ... 65535 */\n x *= 2; \n y *= 2;\n }\n\n put_queue(s, state);\n put_queue(s, x);\n put_queue(s, y);\n put_queue(s, -dz);\n\n /* send PS/2 mouse event */\n ps2_mouse_event(s->ps2_mouse, 1, 0, 0, 0);\n}\n\nvoid vmmouse_handler(VMMouseState *s, uint32_t *regs)\n{\n uint32_t cmd;\n \n cmd = regs[REG_ECX] & 0xff;\n switch(cmd) {\n case 10: /* get version */\n regs[REG_EBX] = VMPORT_MAGIC;\n break;\n case 39: /* VMMOUSE_DATA */\n read_data(s, regs, regs[REG_EBX]);\n break;\n case 40: /* VMMOUSE_STATUS */\n regs[REG_EAX] = ((s->enabled ? 0 : 0xffff) << 16) | s->fifo_count;\n break;\n case 41: /* VMMOUSE_COMMAND */\n switch(regs[REG_EBX]) {\n case 0x45414552: /* read id */\n if (s->fifo_count < FIFO_SIZE) {\n put_queue(s, 0x3442554a);\n s->enabled = TRUE;\n }\n break;\n case 0x000000f5: /* disable */\n s->enabled = FALSE;\n break;\n case 0x4c455252: /* set relative */\n s->absolute = 0;\n break;\n case 0x53424152: /* set absolute */\n s->absolute = 1;\n break;\n }\n break;\n }\n}\n\nBOOL vmmouse_is_absolute(VMMouseState *s)\n{\n return s->absolute;\n}\n\nVMMouseState *vmmouse_init(PS2MouseState *ps2_mouse)\n{\n VMMouseState *s;\n s = mallocz(sizeof(*s));\n s->ps2_mouse = ps2_mouse;\n return s;\n}\n"], ["/linuxpdf/tinyemu/cutils.c", "/*\n * Misc C utilities\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n\nvoid *mallocz(size_t size)\n{\n void *ptr;\n ptr = malloc(size);\n if (!ptr)\n return NULL;\n memset(ptr, 0, size);\n return ptr;\n}\n\nvoid pstrcpy(char *buf, int buf_size, const char *str)\n{\n int c;\n char *q = buf;\n\n if (buf_size <= 0)\n return;\n\n for(;;) {\n c = *str++;\n if (c == 0 || q >= buf + buf_size - 1)\n break;\n *q++ = c;\n }\n *q = '\\0';\n}\n\nchar *pstrcat(char *buf, int buf_size, const char *s)\n{\n int len;\n len = strlen(buf);\n if (len < buf_size)\n pstrcpy(buf + len, buf_size - len, s);\n return buf;\n}\n\nint strstart(const char *str, const char *val, const char **ptr)\n{\n const char *p, *q;\n p = str;\n q = val;\n while (*q != '\\0') {\n if (*p != *q)\n return 0;\n p++;\n q++;\n }\n if (ptr)\n *ptr = p;\n return 1;\n}\n\nvoid dbuf_init(DynBuf *s)\n{\n memset(s, 0, sizeof(*s));\n}\n\nvoid dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len)\n{\n size_t end, new_size;\n new_size = end = offset + len;\n if (new_size > s->allocated_size) {\n new_size = max_int(new_size, s->allocated_size * 3 / 2);\n s->buf = realloc(s->buf, new_size);\n s->allocated_size = new_size;\n }\n memcpy(s->buf + offset, data, len);\n if (end > s->size)\n s->size = end;\n}\n\nvoid dbuf_putc(DynBuf *s, uint8_t c)\n{\n dbuf_write(s, s->size, &c, 1);\n}\n\nvoid dbuf_putstr(DynBuf *s, const char *str)\n{\n dbuf_write(s, s->size, (const uint8_t *)str, strlen(str));\n}\n\nvoid dbuf_free(DynBuf *s)\n{\n free(s->buf);\n memset(s, 0, sizeof(*s));\n}\n"], ["/linuxpdf/tinyemu/simplefb.c", "/*\n * Simple frame buffer\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n//#define DEBUG_VBE\n\n#define FB_ALLOC_ALIGN 65536\n\nstruct SimpleFBState {\n FBDevice *fb_dev;\n int fb_page_count;\n PhysMemoryRange *mem_range;\n};\n\n#define MAX_MERGE_DISTANCE 3\n\nvoid simplefb_refresh(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque,\n PhysMemoryRange *mem_range,\n int fb_page_count)\n{\n const uint32_t *dirty_bits;\n uint32_t dirty_val;\n int y0, y1, page_y0, page_y1, byte_pos, page_index, bit_pos;\n\n dirty_bits = phys_mem_get_dirty_bits(mem_range);\n \n page_index = 0;\n y0 = y1 = 0;\n while (page_index < fb_page_count) {\n dirty_val = dirty_bits[page_index >> 5];\n if (dirty_val != 0) {\n bit_pos = 0;\n while (dirty_val != 0) {\n while (((dirty_val >> bit_pos) & 1) == 0)\n bit_pos++;\n dirty_val &= ~(1 << bit_pos);\n\n byte_pos = (page_index + bit_pos) * DEVRAM_PAGE_SIZE;\n page_y0 = byte_pos / fb_dev->stride;\n page_y1 = ((byte_pos + DEVRAM_PAGE_SIZE - 1) / fb_dev->stride) + 1;\n page_y1 = min_int(page_y1, fb_dev->height);\n if (y0 == y1) {\n y0 = page_y0;\n y1 = page_y1;\n } else if (page_y0 <= (y1 + MAX_MERGE_DISTANCE)) {\n /* union with current region */\n y1 = page_y1;\n } else {\n /* flush */\n redraw_func(fb_dev, opaque,\n 0, y0, fb_dev->width, y1 - y0);\n y0 = page_y0;\n y1 = page_y1;\n }\n }\n }\n page_index += 32;\n }\n\n if (y0 != y1) {\n redraw_func(fb_dev, opaque,\n 0, y0, fb_dev->width, y1 - y0);\n }\n}\n\nstatic void simplefb_refresh1(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n SimpleFBState *s = fb_dev->device_opaque;\n simplefb_refresh(fb_dev, redraw_func, opaque, s->mem_range,\n s->fb_page_count);\n}\n\nSimpleFBState *simplefb_init(PhysMemoryMap *map, uint64_t phys_addr,\n FBDevice *fb_dev, int width, int height)\n{\n SimpleFBState *s;\n \n s = mallocz(sizeof(*s));\n s->fb_dev = fb_dev;\n\n fb_dev->width = width;\n fb_dev->height = height;\n fb_dev->stride = width * 4;\n fb_dev->fb_size = (height * fb_dev->stride + FB_ALLOC_ALIGN - 1) & ~(FB_ALLOC_ALIGN - 1);\n s->fb_page_count = fb_dev->fb_size >> DEVRAM_PAGE_SIZE_LOG2;\n\n s->mem_range = cpu_register_ram(map, phys_addr, fb_dev->fb_size,\n DEVRAM_FLAG_DIRTY_BITS);\n \n fb_dev->fb_data = s->mem_range->phys_mem;\n fb_dev->device_opaque = s;\n fb_dev->refresh = simplefb_refresh1;\n return s;\n}\n"], ["/linuxpdf/tinyemu/splitimg.c", "/*\n * Disk image splitter\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n int blocksize, ret, i;\n const char *infilename, *outpath;\n FILE *f, *fo;\n char buf1[1024];\n uint8_t *buf;\n\n if ((optind + 1) >= argc) {\n printf(\"splitimg version \" CONFIG_VERSION \", Copyright (c) 2011-2016 Fabrice Bellard\\n\"\n \"usage: splitimg infile outpath [blocksize]\\n\"\n \"Create a multi-file disk image for the RISCVEMU HTTP block device\\n\"\n \"\\n\"\n \"outpath must be a directory\\n\"\n \"blocksize is the block size in KB\\n\");\n exit(1);\n }\n\n infilename = argv[optind++];\n outpath = argv[optind++];\n blocksize = 256;\n if (optind < argc)\n blocksize = strtol(argv[optind++], NULL, 0);\n\n blocksize *= 1024;\n \n buf = malloc(blocksize);\n\n f = fopen(infilename, \"rb\");\n if (!f) {\n perror(infilename);\n exit(1);\n }\n i = 0;\n for(;;) {\n ret = fread(buf, 1, blocksize, f);\n if (ret < 0) {\n perror(\"fread\");\n exit(1);\n }\n if (ret == 0)\n break;\n if (ret < blocksize) {\n printf(\"warning: last block is not full\\n\");\n memset(buf + ret, 0, blocksize - ret);\n }\n snprintf(buf1, sizeof(buf1), \"%s/blk%09u.bin\", outpath, i);\n fo = fopen(buf1, \"wb\");\n if (!fo) {\n perror(buf1);\n exit(1);\n }\n fwrite(buf, 1, blocksize, fo);\n fclose(fo);\n i++;\n }\n fclose(f);\n printf(\"%d blocks\\n\", i);\n\n snprintf(buf1, sizeof(buf1), \"%s/blk.txt\", outpath);\n fo = fopen(buf1, \"wb\");\n if (!fo) {\n perror(buf1);\n exit(1);\n }\n fprintf(fo, \"{\\n\");\n fprintf(fo, \" block_size: %d,\\n\", blocksize / 1024);\n fprintf(fo, \" n_block: %d,\\n\", i);\n fprintf(fo, \"}\\n\");\n fclose(fo);\n return 0;\n}\n"], ["/linuxpdf/tinyemu/fs.c", "/*\n * Filesystem utilities\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"fs.h\"\n\nFSFile *fs_dup(FSDevice *fs, FSFile *f)\n{\n FSQID qid;\n fs->fs_walk(fs, &f, &qid, f, 0, NULL);\n return f;\n}\n\nFSFile *fs_walk_path1(FSDevice *fs, FSFile *f, const char *path,\n char **pname)\n{\n const char *p;\n char *name;\n FSFile *f1;\n FSQID qid;\n int len, ret;\n BOOL is_last, is_first;\n\n if (path[0] == '/')\n path++;\n \n is_first = TRUE;\n for(;;) {\n p = strchr(path, '/');\n if (!p) {\n name = (char *)path;\n if (pname) {\n *pname = name;\n if (is_first) {\n ret = fs->fs_walk(fs, &f, &qid, f, 0, NULL);\n if (ret < 0)\n f = NULL;\n }\n return f;\n }\n is_last = TRUE;\n } else {\n len = p - path;\n name = malloc(len + 1);\n memcpy(name, path, len);\n name[len] = '\\0';\n is_last = FALSE;\n }\n ret = fs->fs_walk(fs, &f1, &qid, f, 1, &name);\n if (!is_last)\n free(name);\n if (!is_first)\n fs->fs_delete(fs, f);\n f = f1;\n is_first = FALSE;\n if (ret <= 0) {\n fs->fs_delete(fs, f);\n f = NULL;\n break;\n } else if (is_last) {\n break;\n }\n path = p + 1;\n }\n return f;\n}\n\nFSFile *fs_walk_path(FSDevice *fs, FSFile *f, const char *path)\n{\n return fs_walk_path1(fs, f, path, NULL);\n}\n\nvoid fs_end(FSDevice *fs)\n{\n fs->fs_end(fs);\n free(fs);\n}\n"], ["/linuxpdf/tinyemu/x86_cpu.c", "/*\n * x86 CPU emulator stub\n * \n * Copyright (c) 2011-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"x86_cpu.h\"\n\nX86CPUState *x86_cpu_init(PhysMemoryMap *mem_map)\n{\n fprintf(stderr, \"x86 emulator is not supported\\n\");\n exit(1);\n}\n\nvoid x86_cpu_end(X86CPUState *s)\n{\n}\n\nvoid x86_cpu_interp(X86CPUState *s, int max_cycles1)\n{\n}\n\nvoid x86_cpu_set_irq(X86CPUState *s, BOOL set)\n{\n}\n\nvoid x86_cpu_set_reg(X86CPUState *s, int reg, uint32_t val)\n{\n}\n\nuint32_t x86_cpu_get_reg(X86CPUState *s, int reg)\n{\n return 0;\n}\n\nvoid x86_cpu_set_seg(X86CPUState *s, int seg, const X86CPUSeg *sd)\n{\n}\n\nvoid x86_cpu_set_get_hard_intno(X86CPUState *s,\n int (*get_hard_intno)(void *opaque),\n void *opaque)\n{\n}\n\nvoid x86_cpu_set_get_tsc(X86CPUState *s,\n uint64_t (*get_tsc)(void *opaque),\n void *opaque)\n{\n}\n\nvoid x86_cpu_set_port_io(X86CPUState *s, \n DeviceReadFunc *port_read, DeviceWriteFunc *port_write,\n void *opaque)\n{\n}\n\nint64_t x86_cpu_get_cycles(X86CPUState *s)\n{\n return 0;\n}\n\nBOOL x86_cpu_get_power_down(X86CPUState *s)\n{\n return FALSE;\n}\n\nvoid x86_cpu_flush_tlb_write_range_ram(X86CPUState *s,\n uint8_t *ram_ptr, size_t ram_size)\n{\n}\n"], ["/linuxpdf/tinyemu/softfp.c", "/*\n * SoftFP Library\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"softfp.h\"\n\nstatic inline int clz32(uint32_t a)\n{\n int r;\n if (a == 0) {\n r = 32;\n } else {\n r = __builtin_clz(a);\n }\n return r;\n}\n\nstatic inline int clz64(uint64_t a)\n{\n int r;\n if (a == 0) {\n r = 64;\n } else \n {\n r = __builtin_clzll(a);\n }\n return r;\n}\n\n#ifdef HAVE_INT128\nstatic inline int clz128(uint128_t a)\n{\n int r;\n if (a == 0) {\n r = 128;\n } else \n {\n uint64_t ah, al;\n ah = a >> 64;\n al = a;\n if (ah != 0)\n r = __builtin_clzll(ah);\n else\n r = __builtin_clzll(al) + 64;\n }\n return r;\n}\n#endif\n\n#define F_SIZE 32\n#include \"softfp_template.h\"\n\n#define F_SIZE 64\n#include \"softfp_template.h\"\n\n#ifdef HAVE_INT128\n\n#define F_SIZE 128\n#include \"softfp_template.h\"\n\n#endif\n\n"]], "task_instance_info": {"created_time": "2025-08-20 17:59:23", "created_task_model": "DeepSeek-R1", "function_skeleton": "int sosendto(struct socket *so, struct mbuf *m) {}", "code_description": "This code segment functions to: Transmit data packets to a specified network destination through a socket, resolve virtual network addressing for internal services, and update connection state tracking for persistent communication channels."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c\n[TASK_BEGIN]\nint sosendto(struct socket *so, struct mbuf *m)\n{\n struct sockaddr_in addr;\n int ret;\n\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr = so->so_faddr;\n addr.sin_port = so->so_fport;\n\n ret = sendto(so->s, m->m_data, m->m_len, 0,\n (struct sockaddr *)&addr, sizeof(addr));\n if (ret < 0) {\n return -1;\n }\n return ret;\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 18-00-25"}, "editdistance_info": {"edit_distance": 24.2604, "calculate_time": "2025-08-20 18:00:25", "true_code_clean": "int\nsosendto(struct socket *so, struct mbuf *m)\n{\n\tSlirp *slirp = so->slirp;\n\tint ret;\n\tstruct sockaddr_in addr;\n\tDEBUG_CALL(\"sosendto\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n addr.sin_family = AF_INET;\n\tif ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n\t slirp->vnetwork_addr.s_addr) {\n\t if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\t if (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n\t } else {\n\t addr.sin_addr = loopback_addr;\n\t }\n\t} else\n\t addr.sin_addr = so->so_faddr;\n\taddr.sin_port = so->so_fport;\n\tDEBUG_MISC((dfd, \" sendto()ing, addr.sin_port=%d, addr.sin_addr.s_addr=%.16s\\n\", ntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));\n\tret = sendto(so->s, m->m_data, m->m_len, 0,\n\t\t (struct sockaddr *)&addr, sizeof (struct sockaddr));\n\tif (ret < 0)\n\t\treturn -1;\n\tif (so->so_expire)\n\t\tso->so_expire = curtime + SO_EXPIRE;\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= SS_ISFCONNECTED; \n\treturn 0;\n}", "predict_code_clean": "int sosendto(struct socket *so, struct mbuf *m)\n{\n struct sockaddr_in addr;\n int ret;\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr = so->so_faddr;\n addr.sin_port = so->so_fport;\n ret = sendto(so->s, m->m_data, m->m_len, 0,\n (struct sockaddr *)&addr, sizeof(addr));\n if (ret < 0) {\n return -1;\n }\n return ret;\n}"}} {"repo_name": "linuxpdf", "file_name": "/linuxpdf/tinyemu/jsemu.c", "inference_info": {"prefix_code": "/*\n * JS emulator main\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#include \"list.h\"\n#include \"fbuf.h\"\n\nint virt_machine_run(void *opaque);\n\n/* provided in lib.js */\nextern void console_write(void *opaque, const uint8_t *buf, int len);\nextern void console_get_size(int *pw, int *ph);\nextern void fb_refresh(void *opaque, void *data,\n int x, int y, int w, int h, int stride);\nextern void net_recv_packet(EthernetDevice *bs,\n const uint8_t *buf, int len);\n\nstatic uint8_t console_fifo[1024];\nstatic int console_fifo_windex;\nstatic int console_fifo_rindex;\nstatic int console_fifo_count;\nstatic BOOL console_resize_pending;\n\nstatic int global_width;\nstatic int global_height;\nstatic VirtMachine *global_vm;\nstatic BOOL global_carrier_state;\n\nstatic int console_read(void *opaque, uint8_t *buf, int len)\n{\n int out_len, l;\n len = min_int(len, console_fifo_count);\n console_fifo_count -= len;\n out_len = 0;\n while (len != 0) {\n l = min_int(len, sizeof(console_fifo) - console_fifo_rindex);\n memcpy(buf + out_len, console_fifo + console_fifo_rindex, l);\n len -= l;\n out_len += l;\n console_fifo_rindex += l;\n if (console_fifo_rindex == sizeof(console_fifo))\n console_fifo_rindex = 0;\n }\n return out_len;\n}\n\n/* called from JS */\nvoid console_queue_char(int c)\n{\n if (console_fifo_count < sizeof(console_fifo)) {\n console_fifo[console_fifo_windex] = c;\n if (++console_fifo_windex == sizeof(console_fifo))\n console_fifo_windex = 0;\n console_fifo_count++;\n }\n}\n\n/* called from JS */\nvoid display_key_event(int is_down, int key_code)\n{\n if (global_vm) {\n vm_send_key_event(global_vm, is_down, key_code);\n }\n}\n\n/* called from JS */\nstatic int mouse_last_x, mouse_last_y, mouse_last_buttons;\n\nvoid display_mouse_event(int dx, int dy, int buttons)\n{\n if (global_vm) {\n if (vm_mouse_is_absolute(global_vm) || 1) {\n dx = min_int(dx, global_width - 1);\n dy = min_int(dy, global_height - 1);\n dx = (dx * VIRTIO_INPUT_ABS_SCALE) / global_width;\n dy = (dy * VIRTIO_INPUT_ABS_SCALE) / global_height;\n } else {\n /* relative mouse is not supported */\n dx = 0;\n dy = 0;\n }\n mouse_last_x = dx;\n mouse_last_y = dy;\n mouse_last_buttons = buttons;\n vm_send_mouse_event(global_vm, dx, dy, 0, buttons);\n }\n}\n\n/* called from JS */\nvoid display_wheel_event(int dz)\n{\n if (global_vm) {\n vm_send_mouse_event(global_vm, mouse_last_x, mouse_last_y, dz,\n mouse_last_buttons);\n }\n}\n\n/* called from JS */\nvoid net_write_packet(const uint8_t *buf, int buf_len)\n{\n EthernetDevice *net = global_vm->net;\n if (net) {\n net->device_write_packet(net, buf, buf_len);\n }\n}\n\n/* called from JS */\nvoid net_set_carrier(BOOL carrier_state)\n{\n EthernetDevice *net;\n global_carrier_state = carrier_state;\n if (global_vm && global_vm->net) {\n net = global_vm->net;\n net->device_set_carrier(net, carrier_state);\n }\n}\n\nstatic void fb_refresh1(FBDevice *fb_dev, void *opaque,\n int x, int y, int w, int h)\n{\n int stride = fb_dev->stride;\n fb_refresh(opaque, fb_dev->fb_data + y * stride + x * 4, x, y, w, h,\n stride);\n}\n\nstatic CharacterDevice *console_init(void)\n{\n CharacterDevice *dev;\n console_resize_pending = TRUE;\n dev = mallocz(sizeof(*dev));\n dev->write_data = console_write;\n dev->read_data = console_read;\n return dev;\n}\n\ntypedef struct {\n VirtMachineParams *p;\n int ram_size;\n char *cmdline;\n BOOL has_network;\n char *pwd;\n} VMStartState;\n\nstatic void init_vm(void *arg);\nstatic void init_vm_fs(void *arg);\nstatic void init_vm_drive(void *arg);\n\nvoid vm_start(const char *url, int ram_size, const char *cmdline,\n const char *pwd, int width, int height, BOOL has_network)\n{\n VMStartState *s;\n\n s = mallocz(sizeof(*s));\n s->ram_size = ram_size;\n s->cmdline = strdup(cmdline);\n if (pwd)\n s->pwd = strdup(pwd);\n global_width = width;\n global_height = height;\n s->has_network = has_network;\n s->p = mallocz(sizeof(VirtMachineParams));\n virt_machine_set_defaults(s->p);\n virt_machine_load_config_file(s->p, url, init_vm_fs, s);\n}\n\nstatic void init_vm_fs(void *arg)\n{\n VMStartState *s = arg;\n VirtMachineParams *p = s->p;\n\n if (p->fs_count > 0) {\n assert(p->fs_count == 1);\n p->tab_fs[0].fs_dev = fs_net_init(p->tab_fs[0].filename,\n init_vm_drive, s);\n if (s->pwd) {\n fs_net_set_pwd(p->tab_fs[0].fs_dev, s->pwd);\n }\n } else {\n init_vm_drive(s);\n }\n}\n\nstatic void init_vm_drive(void *arg)\n{\n VMStartState *s = arg;\n VirtMachineParams *p = s->p;\n\n if (p->drive_count > 0) {\n assert(p->drive_count == 1);\n p->tab_drive[0].block_dev =\n block_device_init_http(p->tab_drive[0].filename,\n 131072,\n init_vm, s);\n } else {\n init_vm(s);\n }\n}\n\nstatic void init_vm(void *arg)\n{\n VMStartState *s = arg;\n VirtMachine *m;\n VirtMachineParams *p = s->p;\n int i;\n \n p->rtc_real_time = TRUE;\n p->ram_size = s->ram_size << 20;\n if (s->cmdline && s->cmdline[0] != '\\0') {\n vm_add_cmdline(s->p, s->cmdline);\n }\n\n if (global_width > 0 && global_height > 0) {\n /* enable graphic output if needed */\n if (!p->display_device)\n p->display_device = strdup(\"simplefb\");\n p->width = global_width;\n p->height = global_height;\n } else {\n p->console = console_init();\n }\n \n if (p->eth_count > 0 && !s->has_network) {\n /* remove the interfaces */\n for(i = 0; i < p->eth_count; i++) {\n free(p->tab_eth[i].ifname);\n free(p->tab_eth[i].driver);\n }\n p->eth_count = 0;\n }\n\n if (p->eth_count > 0) {\n EthernetDevice *net;\n int i;\n assert(p->eth_count == 1);\n net = mallocz(sizeof(EthernetDevice));\n net->mac_addr[0] = 0x02;\n for(i = 1; i < 6; i++)\n net->mac_addr[i] = (int)(emscripten_random() * 256);\n net->write_packet = net_recv_packet;\n net->opaque = NULL;\n p->tab_eth[0].net = net;\n }\n\n m = virt_machine_init(p);\n global_vm = m;\n\n virt_machine_free_config(s->p);\n\n if (m->net) {\n m->net->device_set_carrier(m->net, global_carrier_state);\n }\n \n free(s->p);\n free(s->cmdline);\n if (s->pwd) {\n memset(s->pwd, 0, strlen(s->pwd));\n free(s->pwd);\n }\n free(s);\n \n EM_ASM({\n start_machine_interval($0);\n }, m);\n}\n\n/* need to be long enough to hide the non zero delay of setTimeout(_, 0) */\n#define MAX_EXEC_TOTAL_CYCLE 100000\n#define MAX_EXEC_CYCLE 1000\n\n#define MAX_SLEEP_TIME 10 /* in ms */\n\n", "suffix_code": "\n\n", "middle_code": "int virt_machine_run(void *opaque)\n{\n VirtMachine *m = opaque;\n int delay, i;\n FBDevice *fb_dev;\n if (m->console_dev && virtio_console_can_write_data(m->console_dev)) {\n uint8_t buf[128];\n int ret, len;\n len = virtio_console_get_write_len(m->console_dev);\n len = min_int(len, sizeof(buf));\n ret = m->console->read_data(m->console->opaque, buf, len);\n if (ret > 0)\n virtio_console_write_data(m->console_dev, buf, ret);\n if (console_resize_pending) {\n int w, h;\n console_get_size(&w, &h);\n virtio_console_resize_event(m->console_dev, w, h);\n console_resize_pending = FALSE;\n }\n }\n fb_dev = m->fb_dev;\n if (fb_dev) {\n fb_dev->refresh(fb_dev, fb_refresh1, NULL);\n }\n i = 0;\n for(;;) {\n delay = virt_machine_get_sleep_duration(m, MAX_SLEEP_TIME);\n if (delay != 0 || i >= MAX_EXEC_TOTAL_CYCLE / MAX_EXEC_CYCLE)\n break;\n virt_machine_interp(m, MAX_EXEC_CYCLE);\n i++;\n }\n return i * MAX_EXEC_CYCLE;\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c", "sub_task_type": null}, "context_code": [["/linuxpdf/tinyemu/temu.c", "/*\n * TinyEMU\n * \n * Copyright (c) 2016-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifndef _WIN32\n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#ifdef CONFIG_FS_NET\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n#endif\n#ifdef CONFIG_SLIRP\n#include \"slirp/libslirp.h\"\n#endif\n\n#ifndef _WIN32\n\ntypedef struct {\n int stdin_fd;\n int console_esc_state;\n BOOL resize_pending;\n} STDIODevice;\n\nstatic struct termios oldtty;\nstatic int old_fd0_flags;\nstatic STDIODevice *global_stdio_device;\n\nstatic void term_exit(void)\n{\n tcsetattr (0, TCSANOW, &oldtty);\n fcntl(0, F_SETFL, old_fd0_flags);\n}\n\nstatic void term_init(BOOL allow_ctrlc)\n{\n struct termios tty;\n\n memset(&tty, 0, sizeof(tty));\n tcgetattr (0, &tty);\n oldtty = tty;\n old_fd0_flags = fcntl(0, F_GETFL);\n\n tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP\n |INLCR|IGNCR|ICRNL|IXON);\n tty.c_oflag |= OPOST;\n tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);\n if (!allow_ctrlc)\n tty.c_lflag &= ~ISIG;\n tty.c_cflag &= ~(CSIZE|PARENB);\n tty.c_cflag |= CS8;\n tty.c_cc[VMIN] = 1;\n tty.c_cc[VTIME] = 0;\n\n tcsetattr (0, TCSANOW, &tty);\n\n atexit(term_exit);\n}\n\nstatic void console_write(void *opaque, const uint8_t *buf, int len)\n{\n fwrite(buf, 1, len, stdout);\n fflush(stdout);\n}\n\nstatic int console_read(void *opaque, uint8_t *buf, int len)\n{\n STDIODevice *s = opaque;\n int ret, i, j;\n uint8_t ch;\n \n if (len <= 0)\n return 0;\n\n ret = read(s->stdin_fd, buf, len);\n if (ret < 0)\n return 0;\n if (ret == 0) {\n /* EOF */\n exit(1);\n }\n\n j = 0;\n for(i = 0; i < ret; i++) {\n ch = buf[i];\n if (s->console_esc_state) {\n s->console_esc_state = 0;\n switch(ch) {\n case 'x':\n printf(\"Terminated\\n\");\n exit(0);\n case 'h':\n printf(\"\\n\"\n \"C-a h print this help\\n\"\n \"C-a x exit emulator\\n\"\n \"C-a C-a send C-a\\n\"\n );\n break;\n case 1:\n goto output_char;\n default:\n break;\n }\n } else {\n if (ch == 1) {\n s->console_esc_state = 1;\n } else {\n output_char:\n buf[j++] = ch;\n }\n }\n }\n return j;\n}\n\nstatic void term_resize_handler(int sig)\n{\n if (global_stdio_device)\n global_stdio_device->resize_pending = TRUE;\n}\n\nstatic void console_get_size(STDIODevice *s, int *pw, int *ph)\n{\n struct winsize ws;\n int width, height;\n /* default values */\n width = 80;\n height = 25;\n if (ioctl(s->stdin_fd, TIOCGWINSZ, &ws) == 0 &&\n ws.ws_col >= 4 && ws.ws_row >= 4) {\n width = ws.ws_col;\n height = ws.ws_row;\n }\n *pw = width;\n *ph = height;\n}\n\nCharacterDevice *console_init(BOOL allow_ctrlc)\n{\n CharacterDevice *dev;\n STDIODevice *s;\n struct sigaction sig;\n\n term_init(allow_ctrlc);\n\n dev = mallocz(sizeof(*dev));\n s = mallocz(sizeof(*s));\n s->stdin_fd = 0;\n /* Note: the glibc does not properly tests the return value of\n write() in printf, so some messages on stdout may be lost */\n fcntl(s->stdin_fd, F_SETFL, O_NONBLOCK);\n\n s->resize_pending = TRUE;\n global_stdio_device = s;\n \n /* use a signal to get the host terminal resize events */\n sig.sa_handler = term_resize_handler;\n sigemptyset(&sig.sa_mask);\n sig.sa_flags = 0;\n sigaction(SIGWINCH, &sig, NULL);\n \n dev->opaque = s;\n dev->write_data = console_write;\n dev->read_data = console_read;\n return dev;\n}\n\n#endif /* !_WIN32 */\n\ntypedef enum {\n BF_MODE_RO,\n BF_MODE_RW,\n BF_MODE_SNAPSHOT,\n} BlockDeviceModeEnum;\n\n#define SECTOR_SIZE 512\n\ntypedef struct BlockDeviceFile {\n FILE *f;\n int64_t nb_sectors;\n BlockDeviceModeEnum mode;\n uint8_t **sector_table;\n} BlockDeviceFile;\n\nstatic int64_t bf_get_sector_count(BlockDevice *bs)\n{\n BlockDeviceFile *bf = bs->opaque;\n return bf->nb_sectors;\n}\n\n//#define DUMP_BLOCK_READ\n\nstatic int bf_read_async(BlockDevice *bs,\n uint64_t sector_num, uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceFile *bf = bs->opaque;\n // printf(\"bf_read_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n#ifdef DUMP_BLOCK_READ\n {\n static FILE *f;\n if (!f)\n f = fopen(\"/tmp/read_sect.txt\", \"wb\");\n fprintf(f, \"%\" PRId64 \" %d\\n\", sector_num, n);\n }\n#endif\n if (!bf->f)\n return -1;\n if (bf->mode == BF_MODE_SNAPSHOT) {\n int i;\n for(i = 0; i < n; i++) {\n if (!bf->sector_table[sector_num]) {\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fread(buf, 1, SECTOR_SIZE, bf->f);\n } else {\n memcpy(buf, bf->sector_table[sector_num], SECTOR_SIZE);\n }\n sector_num++;\n buf += SECTOR_SIZE;\n }\n } else {\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fread(buf, 1, n * SECTOR_SIZE, bf->f);\n }\n /* synchronous read */\n return 0;\n}\n\nstatic int bf_write_async(BlockDevice *bs,\n uint64_t sector_num, const uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceFile *bf = bs->opaque;\n int ret;\n\n switch(bf->mode) {\n case BF_MODE_RO:\n ret = -1; /* error */\n break;\n case BF_MODE_RW:\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fwrite(buf, 1, n * SECTOR_SIZE, bf->f);\n ret = 0;\n break;\n case BF_MODE_SNAPSHOT:\n {\n int i;\n if ((sector_num + n) > bf->nb_sectors)\n return -1;\n for(i = 0; i < n; i++) {\n if (!bf->sector_table[sector_num]) {\n bf->sector_table[sector_num] = malloc(SECTOR_SIZE);\n }\n memcpy(bf->sector_table[sector_num], buf, SECTOR_SIZE);\n sector_num++;\n buf += SECTOR_SIZE;\n }\n ret = 0;\n }\n break;\n default:\n abort();\n }\n\n return ret;\n}\n\nstatic BlockDevice *block_device_init(const char *filename,\n BlockDeviceModeEnum mode)\n{\n BlockDevice *bs;\n BlockDeviceFile *bf;\n int64_t file_size;\n FILE *f;\n const char *mode_str;\n\n if (mode == BF_MODE_RW) {\n mode_str = \"r+b\";\n } else {\n mode_str = \"rb\";\n }\n \n f = fopen(filename, mode_str);\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n file_size = ftello(f);\n\n bs = mallocz(sizeof(*bs));\n bf = mallocz(sizeof(*bf));\n\n bf->mode = mode;\n bf->nb_sectors = file_size / 512;\n bf->f = f;\n\n if (mode == BF_MODE_SNAPSHOT) {\n bf->sector_table = mallocz(sizeof(bf->sector_table[0]) *\n bf->nb_sectors);\n }\n \n bs->opaque = bf;\n bs->get_sector_count = bf_get_sector_count;\n bs->read_async = bf_read_async;\n bs->write_async = bf_write_async;\n return bs;\n}\n\n#ifndef _WIN32\n\ntypedef struct {\n int fd;\n BOOL select_filled;\n} TunState;\n\nstatic void tun_write_packet(EthernetDevice *net,\n const uint8_t *buf, int len)\n{\n TunState *s = net->opaque;\n write(s->fd, buf, len);\n}\n\nstatic void tun_select_fill(EthernetDevice *net, int *pfd_max,\n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *pdelay)\n{\n TunState *s = net->opaque;\n int net_fd = s->fd;\n\n s->select_filled = net->device_can_write_packet(net);\n if (s->select_filled) {\n FD_SET(net_fd, rfds);\n *pfd_max = max_int(*pfd_max, net_fd);\n }\n}\n\nstatic void tun_select_poll(EthernetDevice *net, \n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int select_ret)\n{\n TunState *s = net->opaque;\n int net_fd = s->fd;\n uint8_t buf[2048];\n int ret;\n \n if (select_ret <= 0)\n return;\n if (s->select_filled && FD_ISSET(net_fd, rfds)) {\n ret = read(net_fd, buf, sizeof(buf));\n if (ret > 0)\n net->device_write_packet(net, buf, ret);\n }\n \n}\n\n/* configure with:\n# bridge configuration (connect tap0 to bridge interface br0)\n ip link add br0 type bridge\n ip tuntap add dev tap0 mode tap [user x] [group x]\n ip link set tap0 master br0\n ip link set dev br0 up\n ip link set dev tap0 up\n\n# NAT configuration (eth1 is the interface connected to internet)\n ifconfig br0 192.168.3.1\n echo 1 > /proc/sys/net/ipv4/ip_forward\n iptables -D FORWARD 1\n iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE\n\n In the VM:\n ifconfig eth0 192.168.3.2\n route add -net 0.0.0.0 netmask 0.0.0.0 gw 192.168.3.1\n*/\nstatic EthernetDevice *tun_open(const char *ifname)\n{\n struct ifreq ifr;\n int fd, ret;\n EthernetDevice *net;\n TunState *s;\n \n fd = open(\"/dev/net/tun\", O_RDWR);\n if (fd < 0) {\n fprintf(stderr, \"Error: could not open /dev/net/tun\\n\");\n return NULL;\n }\n memset(&ifr, 0, sizeof(ifr));\n ifr.ifr_flags = IFF_TAP | IFF_NO_PI;\n pstrcpy(ifr.ifr_name, sizeof(ifr.ifr_name), ifname);\n ret = ioctl(fd, TUNSETIFF, (void *) &ifr);\n if (ret != 0) {\n fprintf(stderr, \"Error: could not configure /dev/net/tun\\n\");\n close(fd);\n return NULL;\n }\n fcntl(fd, F_SETFL, O_NONBLOCK);\n\n net = mallocz(sizeof(*net));\n net->mac_addr[0] = 0x02;\n net->mac_addr[1] = 0x00;\n net->mac_addr[2] = 0x00;\n net->mac_addr[3] = 0x00;\n net->mac_addr[4] = 0x00;\n net->mac_addr[5] = 0x01;\n s = mallocz(sizeof(*s));\n s->fd = fd;\n net->opaque = s;\n net->write_packet = tun_write_packet;\n net->select_fill = tun_select_fill;\n net->select_poll = tun_select_poll;\n return net;\n}\n\n#endif /* !_WIN32 */\n\n#ifdef CONFIG_SLIRP\n\n/*******************************************************/\n/* slirp */\n\nstatic Slirp *slirp_state;\n\nstatic void slirp_write_packet(EthernetDevice *net,\n const uint8_t *buf, int len)\n{\n Slirp *slirp_state = net->opaque;\n slirp_input(slirp_state, buf, len);\n}\n\nint slirp_can_output(void *opaque)\n{\n EthernetDevice *net = opaque;\n return net->device_can_write_packet(net);\n}\n\nvoid slirp_output(void *opaque, const uint8_t *pkt, int pkt_len)\n{\n EthernetDevice *net = opaque;\n return net->device_write_packet(net, pkt, pkt_len);\n}\n\nstatic void slirp_select_fill1(EthernetDevice *net, int *pfd_max,\n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *pdelay)\n{\n Slirp *slirp_state = net->opaque;\n slirp_select_fill(slirp_state, pfd_max, rfds, wfds, efds);\n}\n\nstatic void slirp_select_poll1(EthernetDevice *net, \n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int select_ret)\n{\n Slirp *slirp_state = net->opaque;\n slirp_select_poll(slirp_state, rfds, wfds, efds, (select_ret <= 0));\n}\n\nstatic EthernetDevice *slirp_open(void)\n{\n EthernetDevice *net;\n struct in_addr net_addr = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */\n struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */\n struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */\n struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */\n struct in_addr dns = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */\n const char *bootfile = NULL;\n const char *vhostname = NULL;\n int restricted = 0;\n \n if (slirp_state) {\n fprintf(stderr, \"Only a single slirp instance is allowed\\n\");\n return NULL;\n }\n net = mallocz(sizeof(*net));\n\n slirp_state = slirp_init(restricted, net_addr, mask, host, vhostname,\n \"\", bootfile, dhcp, dns, net);\n \n net->mac_addr[0] = 0x02;\n net->mac_addr[1] = 0x00;\n net->mac_addr[2] = 0x00;\n net->mac_addr[3] = 0x00;\n net->mac_addr[4] = 0x00;\n net->mac_addr[5] = 0x01;\n net->opaque = slirp_state;\n net->write_packet = slirp_write_packet;\n net->select_fill = slirp_select_fill1;\n net->select_poll = slirp_select_poll1;\n \n return net;\n}\n\n#endif /* CONFIG_SLIRP */\n\n#define MAX_EXEC_CYCLE 500000\n#define MAX_SLEEP_TIME 10 /* in ms */\n\nvoid virt_machine_run(VirtMachine *m)\n{\n fd_set rfds, wfds, efds;\n int fd_max, ret, delay;\n struct timeval tv;\n#ifndef _WIN32\n int stdin_fd;\n#endif\n \n delay = virt_machine_get_sleep_duration(m, MAX_SLEEP_TIME);\n \n /* wait for an event */\n FD_ZERO(&rfds);\n FD_ZERO(&wfds);\n FD_ZERO(&efds);\n fd_max = -1;\n#ifndef _WIN32\n if (m->console_dev && virtio_console_can_write_data(m->console_dev)) {\n STDIODevice *s = m->console->opaque;\n stdin_fd = s->stdin_fd;\n FD_SET(stdin_fd, &rfds);\n fd_max = stdin_fd;\n\n if (s->resize_pending) {\n int width, height;\n console_get_size(s, &width, &height);\n virtio_console_resize_event(m->console_dev, width, height);\n s->resize_pending = FALSE;\n }\n }\n#endif\n if (m->net) {\n m->net->select_fill(m->net, &fd_max, &rfds, &wfds, &efds, &delay);\n }\n#ifdef CONFIG_FS_NET\n fs_net_set_fdset(&fd_max, &rfds, &wfds, &efds, &delay);\n#endif\n tv.tv_sec = delay / 1000;\n tv.tv_usec = (delay % 1000) * 1000;\n ret = select(fd_max + 1, &rfds, &wfds, &efds, &tv);\n if (m->net) {\n m->net->select_poll(m->net, &rfds, &wfds, &efds, ret);\n }\n if (ret > 0) {\n#ifndef _WIN32\n if (m->console_dev && FD_ISSET(stdin_fd, &rfds)) {\n uint8_t buf[128];\n int ret, len;\n len = virtio_console_get_write_len(m->console_dev);\n len = min_int(len, sizeof(buf));\n ret = m->console->read_data(m->console->opaque, buf, len);\n if (ret > 0) {\n virtio_console_write_data(m->console_dev, buf, ret);\n }\n }\n#endif\n }\n\n#ifdef CONFIG_SDL\n sdl_refresh(m);\n#endif\n \n virt_machine_interp(m, MAX_EXEC_CYCLE);\n}\n\n/*******************************************************/\n\nstatic struct option options[] = {\n { \"help\", no_argument, NULL, 'h' },\n { \"ctrlc\", no_argument },\n { \"rw\", no_argument },\n { \"ro\", no_argument },\n { \"append\", required_argument },\n { \"no-accel\", no_argument },\n { \"build-preload\", required_argument },\n { NULL },\n};\n\nvoid help(void)\n{\n printf(\"temu version \" CONFIG_VERSION \", Copyright (c) 2016-2018 Fabrice Bellard\\n\"\n \"usage: riscvemu [options] config_file\\n\"\n \"options are:\\n\"\n \"-m ram_size set the RAM size in MB\\n\"\n \"-rw allow write access to the disk image (default=snapshot)\\n\"\n \"-ctrlc the C-c key stops the emulator instead of being sent to the\\n\"\n \" emulated software\\n\"\n \"-append cmdline append cmdline to the kernel command line\\n\"\n \"-no-accel disable VM acceleration (KVM, x86 machine only)\\n\"\n \"\\n\"\n \"Console keys:\\n\"\n \"Press C-a x to exit the emulator, C-a h to get some help.\\n\");\n exit(1);\n}\n\n#ifdef CONFIG_FS_NET\nstatic BOOL net_completed;\n\nstatic void net_start_cb(void *arg)\n{\n net_completed = TRUE;\n}\n\nstatic BOOL net_poll_cb(void *arg)\n{\n return net_completed;\n}\n\n#endif\n\nint main(int argc, char **argv)\n{\n VirtMachine *s;\n const char *path, *cmdline, *build_preload_file;\n int c, option_index, i, ram_size, accel_enable;\n BOOL allow_ctrlc;\n BlockDeviceModeEnum drive_mode;\n VirtMachineParams p_s, *p = &p_s;\n\n ram_size = -1;\n allow_ctrlc = FALSE;\n (void)allow_ctrlc;\n drive_mode = BF_MODE_SNAPSHOT;\n accel_enable = -1;\n cmdline = NULL;\n build_preload_file = NULL;\n for(;;) {\n c = getopt_long_only(argc, argv, \"hm:\", options, &option_index);\n if (c == -1)\n break;\n switch(c) {\n case 0:\n switch(option_index) {\n case 1: /* ctrlc */\n allow_ctrlc = TRUE;\n break;\n case 2: /* rw */\n drive_mode = BF_MODE_RW;\n break;\n case 3: /* ro */\n drive_mode = BF_MODE_RO;\n break;\n case 4: /* append */\n cmdline = optarg;\n break;\n case 5: /* no-accel */\n accel_enable = FALSE;\n break;\n case 6: /* build-preload */\n build_preload_file = optarg;\n break;\n default:\n fprintf(stderr, \"unknown option index: %d\\n\", option_index);\n exit(1);\n }\n break;\n case 'h':\n help();\n break;\n case 'm':\n ram_size = strtoul(optarg, NULL, 0);\n break;\n default:\n exit(1);\n }\n }\n\n if (optind >= argc) {\n help();\n }\n\n path = argv[optind++];\n\n virt_machine_set_defaults(p);\n#ifdef CONFIG_FS_NET\n fs_wget_init();\n#endif\n virt_machine_load_config_file(p, path, NULL, NULL);\n#ifdef CONFIG_FS_NET\n fs_net_event_loop(NULL, NULL);\n#endif\n\n /* override some config parameters */\n\n if (ram_size > 0) {\n p->ram_size = (uint64_t)ram_size << 20;\n }\n if (accel_enable != -1)\n p->accel_enable = accel_enable;\n if (cmdline) {\n vm_add_cmdline(p, cmdline);\n }\n \n /* open the files & devices */\n for(i = 0; i < p->drive_count; i++) {\n BlockDevice *drive;\n char *fname;\n fname = get_file_path(p->cfg_filename, p->tab_drive[i].filename);\n#ifdef CONFIG_FS_NET\n if (is_url(fname)) {\n net_completed = FALSE;\n drive = block_device_init_http(fname, 128 * 1024,\n net_start_cb, NULL);\n /* wait until the drive is initialized */\n fs_net_event_loop(net_poll_cb, NULL);\n } else\n#endif\n {\n drive = block_device_init(fname, drive_mode);\n }\n free(fname);\n p->tab_drive[i].block_dev = drive;\n }\n\n for(i = 0; i < p->fs_count; i++) {\n FSDevice *fs;\n const char *path;\n path = p->tab_fs[i].filename;\n#ifdef CONFIG_FS_NET\n if (is_url(path)) {\n fs = fs_net_init(path, NULL, NULL);\n if (!fs)\n exit(1);\n if (build_preload_file)\n fs_dump_cache_load(fs, build_preload_file);\n fs_net_event_loop(NULL, NULL);\n } else\n#endif\n {\n#ifdef _WIN32\n fprintf(stderr, \"Filesystem access not supported yet\\n\");\n exit(1);\n#else\n char *fname;\n fname = get_file_path(p->cfg_filename, path);\n fs = fs_disk_init(fname);\n if (!fs) {\n fprintf(stderr, \"%s: must be a directory\\n\", fname);\n exit(1);\n }\n free(fname);\n#endif\n }\n p->tab_fs[i].fs_dev = fs;\n }\n\n for(i = 0; i < p->eth_count; i++) {\n#ifdef CONFIG_SLIRP\n if (!strcmp(p->tab_eth[i].driver, \"user\")) {\n p->tab_eth[i].net = slirp_open();\n if (!p->tab_eth[i].net)\n exit(1);\n } else\n#endif\n#ifndef _WIN32\n if (!strcmp(p->tab_eth[i].driver, \"tap\")) {\n p->tab_eth[i].net = tun_open(p->tab_eth[i].ifname);\n if (!p->tab_eth[i].net)\n exit(1);\n } else\n#endif\n {\n fprintf(stderr, \"Unsupported network driver '%s'\\n\",\n p->tab_eth[i].driver);\n exit(1);\n }\n }\n \n#ifdef CONFIG_SDL\n if (p->display_device) {\n sdl_init(p->width, p->height);\n } else\n#endif\n {\n#ifdef _WIN32\n fprintf(stderr, \"Console not supported yet\\n\");\n exit(1);\n#else\n p->console = console_init(allow_ctrlc);\n#endif\n }\n p->rtc_real_time = TRUE;\n\n s = virt_machine_init(p);\n if (!s)\n exit(1);\n \n virt_machine_free_config(p);\n\n if (s->net) {\n s->net->device_set_carrier(s->net, TRUE);\n }\n \n for(;;) {\n virt_machine_run(s);\n }\n virt_machine_end(s);\n return 0;\n}\n"], ["/linuxpdf/tinyemu/x86_machine.c", "/*\n * PC emulator\n * \n * Copyright (c) 2011-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"x86_cpu.h\"\n#include \"machine.h\"\n#include \"pci.h\"\n#include \"ide.h\"\n#include \"ps2.h\"\n\n#if defined(__linux__) && (defined(__i386__) || defined(__x86_64__))\n#define USE_KVM\n#endif\n\n#ifdef USE_KVM\n#include \n#include \n#include \n#include \n#include \n#endif\n\n//#define DEBUG_BIOS\n//#define DUMP_IOPORT\n\n/***********************************************************/\n/* cmos emulation */\n\n//#define DEBUG_CMOS\n\n#define RTC_SECONDS 0\n#define RTC_SECONDS_ALARM 1\n#define RTC_MINUTES 2\n#define RTC_MINUTES_ALARM 3\n#define RTC_HOURS 4\n#define RTC_HOURS_ALARM 5\n#define RTC_ALARM_DONT_CARE 0xC0\n\n#define RTC_DAY_OF_WEEK 6\n#define RTC_DAY_OF_MONTH 7\n#define RTC_MONTH 8\n#define RTC_YEAR 9\n\n#define RTC_REG_A 10\n#define RTC_REG_B 11\n#define RTC_REG_C 12\n#define RTC_REG_D 13\n\n#define REG_A_UIP 0x80\n\n#define REG_B_SET 0x80\n#define REG_B_PIE 0x40\n#define REG_B_AIE 0x20\n#define REG_B_UIE 0x10\n\ntypedef struct {\n uint8_t cmos_index;\n uint8_t cmos_data[128];\n IRQSignal *irq;\n BOOL use_local_time;\n /* used for the periodic irq */\n uint32_t irq_timeout;\n uint32_t irq_period;\n} CMOSState;\n\nstatic void cmos_write(void *opaque, uint32_t offset,\n uint32_t data, int size_log2);\nstatic uint32_t cmos_read(void *opaque, uint32_t offset, int size_log2);\n\nstatic int to_bcd(CMOSState *s, unsigned int a)\n{\n if (s->cmos_data[RTC_REG_B] & 0x04) {\n return a;\n } else {\n return ((a / 10) << 4) | (a % 10);\n }\n}\n\nstatic void cmos_update_time(CMOSState *s, BOOL set_century)\n{\n struct timeval tv;\n struct tm tm;\n time_t ti;\n int val;\n \n gettimeofday(&tv, NULL);\n ti = tv.tv_sec;\n if (s->use_local_time) {\n localtime_r(&ti, &tm);\n } else {\n gmtime_r(&ti, &tm);\n }\n \n s->cmos_data[RTC_SECONDS] = to_bcd(s, tm.tm_sec);\n s->cmos_data[RTC_MINUTES] = to_bcd(s, tm.tm_min);\n if (s->cmos_data[RTC_REG_B] & 0x02) {\n s->cmos_data[RTC_HOURS] = to_bcd(s, tm.tm_hour);\n } else {\n s->cmos_data[RTC_HOURS] = to_bcd(s, tm.tm_hour % 12);\n if (tm.tm_hour >= 12)\n s->cmos_data[RTC_HOURS] |= 0x80;\n }\n s->cmos_data[RTC_DAY_OF_WEEK] = to_bcd(s, tm.tm_wday);\n s->cmos_data[RTC_DAY_OF_MONTH] = to_bcd(s, tm.tm_mday);\n s->cmos_data[RTC_MONTH] = to_bcd(s, tm.tm_mon + 1);\n s->cmos_data[RTC_YEAR] = to_bcd(s, tm.tm_year % 100);\n\n if (set_century) {\n /* not set by the hardware, but easier to do it here */\n val = to_bcd(s, (tm.tm_year / 100) + 19);\n s->cmos_data[0x32] = val;\n s->cmos_data[0x37] = val;\n }\n \n /* update in progress flag: 8/32768 seconds after change */\n if (tv.tv_usec < 244) {\n s->cmos_data[RTC_REG_A] |= REG_A_UIP;\n } else {\n s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;\n }\n}\n\nCMOSState *cmos_init(PhysMemoryMap *port_map, int addr,\n IRQSignal *irq, BOOL use_local_time)\n{\n CMOSState *s;\n \n s = mallocz(sizeof(*s));\n s->use_local_time = use_local_time;\n \n s->cmos_index = 0;\n\n s->cmos_data[RTC_REG_A] = 0x26;\n s->cmos_data[RTC_REG_B] = 0x02;\n s->cmos_data[RTC_REG_C] = 0x00;\n s->cmos_data[RTC_REG_D] = 0x80;\n\n cmos_update_time(s, TRUE);\n \n s->irq = irq;\n \n cpu_register_device(port_map, addr, 2, s, cmos_read, cmos_write, \n DEVIO_SIZE8);\n return s;\n}\n\n#define CMOS_FREQ 32768\n\nstatic uint32_t cmos_get_timer(CMOSState *s)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint32_t)ts.tv_sec * CMOS_FREQ +\n ((uint64_t)ts.tv_nsec * CMOS_FREQ / 1000000000);\n}\n\nstatic void cmos_update_timer(CMOSState *s)\n{\n int period_code;\n\n period_code = s->cmos_data[RTC_REG_A] & 0x0f;\n if ((s->cmos_data[RTC_REG_B] & REG_B_PIE) &&\n period_code != 0) {\n if (period_code <= 2)\n period_code += 7;\n s->irq_period = 1 << (period_code - 1);\n s->irq_timeout = (cmos_get_timer(s) + s->irq_period) &\n ~(s->irq_period - 1);\n }\n}\n\n/* XXX: could return a delay, but we don't need high precision\n (Windows 2000 uses it for delay calibration) */\nstatic void cmos_update_irq(CMOSState *s)\n{\n uint32_t d;\n if (s->cmos_data[RTC_REG_B] & REG_B_PIE) {\n d = cmos_get_timer(s) - s->irq_timeout;\n if ((int32_t)d >= 0) {\n /* this is not what the real RTC does. Here we sent the IRQ\n immediately */\n s->cmos_data[RTC_REG_C] |= 0xc0;\n set_irq(s->irq, 1);\n /* update for the next irq */\n s->irq_timeout += s->irq_period;\n }\n }\n}\n\nstatic void cmos_write(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n CMOSState *s = opaque;\n\n if (offset == 0) {\n s->cmos_index = data & 0x7f;\n } else {\n#ifdef DEBUG_CMOS\n printf(\"cmos_write: reg=0x%02x val=0x%02x\\n\", s->cmos_index, data);\n#endif\n switch(s->cmos_index) {\n case RTC_REG_A:\n s->cmos_data[RTC_REG_A] = (data & ~REG_A_UIP) |\n (s->cmos_data[RTC_REG_A] & REG_A_UIP);\n cmos_update_timer(s);\n break;\n case RTC_REG_B:\n s->cmos_data[s->cmos_index] = data;\n cmos_update_timer(s);\n break;\n default:\n s->cmos_data[s->cmos_index] = data;\n break;\n }\n }\n}\n\nstatic uint32_t cmos_read(void *opaque, uint32_t offset, int size_log2)\n{\n CMOSState *s = opaque;\n int ret;\n\n if (offset == 0) {\n return 0xff;\n } else {\n switch(s->cmos_index) {\n case RTC_SECONDS:\n case RTC_MINUTES:\n case RTC_HOURS:\n case RTC_DAY_OF_WEEK:\n case RTC_DAY_OF_MONTH:\n case RTC_MONTH:\n case RTC_YEAR:\n case RTC_REG_A:\n cmos_update_time(s, FALSE);\n ret = s->cmos_data[s->cmos_index];\n break;\n case RTC_REG_C:\n ret = s->cmos_data[s->cmos_index];\n s->cmos_data[RTC_REG_C] = 0x00;\n set_irq(s->irq, 0);\n break;\n default:\n ret = s->cmos_data[s->cmos_index];\n }\n#ifdef DEBUG_CMOS\n printf(\"cmos_read: reg=0x%02x val=0x%02x\\n\", s->cmos_index, ret);\n#endif\n return ret;\n }\n}\n\n/***********************************************************/\n/* 8259 pic emulation */\n\n//#define DEBUG_PIC\n\ntypedef void PICUpdateIRQFunc(void *opaque);\n\ntypedef struct {\n uint8_t last_irr; /* edge detection */\n uint8_t irr; /* interrupt request register */\n uint8_t imr; /* interrupt mask register */\n uint8_t isr; /* interrupt service register */\n uint8_t priority_add; /* used to compute irq priority */\n uint8_t irq_base;\n uint8_t read_reg_select;\n uint8_t special_mask;\n uint8_t init_state;\n uint8_t auto_eoi;\n uint8_t rotate_on_autoeoi;\n uint8_t init4; /* true if 4 byte init */\n uint8_t elcr; /* PIIX edge/trigger selection*/\n uint8_t elcr_mask;\n PICUpdateIRQFunc *update_irq;\n void *opaque;\n} PICState;\n\nstatic void pic_reset(PICState *s);\nstatic void pic_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pic_read(void *opaque, uint32_t offset, int size_log2);\nstatic void pic_elcr_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pic_elcr_read(void *opaque, uint32_t offset, int size_log2);\n\nPICState *pic_init(PhysMemoryMap *port_map, int port, int elcr_port,\n int elcr_mask,\n PICUpdateIRQFunc *update_irq, void *opaque)\n{\n PICState *s;\n\n s = mallocz(sizeof(*s));\n s->elcr_mask = elcr_mask;\n s->update_irq = update_irq;\n s->opaque = opaque;\n cpu_register_device(port_map, port, 2, s,\n pic_read, pic_write, DEVIO_SIZE8);\n cpu_register_device(port_map, elcr_port, 1, s,\n pic_elcr_read, pic_elcr_write, DEVIO_SIZE8);\n pic_reset(s);\n return s;\n}\n\nstatic void pic_reset(PICState *s)\n{\n /* all 8 bit registers */\n s->last_irr = 0; /* edge detection */\n s->irr = 0; /* interrupt request register */\n s->imr = 0; /* interrupt mask register */\n s->isr = 0; /* interrupt service register */\n s->priority_add = 0; /* used to compute irq priority */\n s->irq_base = 0;\n s->read_reg_select = 0;\n s->special_mask = 0;\n s->init_state = 0;\n s->auto_eoi = 0;\n s->rotate_on_autoeoi = 0;\n s->init4 = 0; /* true if 4 byte init */\n}\n\n/* set irq level. If an edge is detected, then the IRR is set to 1 */\nstatic void pic_set_irq1(PICState *s, int irq, int level)\n{\n int mask;\n mask = 1 << irq;\n if (s->elcr & mask) {\n /* level triggered */\n if (level) {\n s->irr |= mask;\n s->last_irr |= mask;\n } else {\n s->irr &= ~mask;\n s->last_irr &= ~mask;\n }\n } else {\n /* edge triggered */\n if (level) {\n if ((s->last_irr & mask) == 0)\n s->irr |= mask;\n s->last_irr |= mask;\n } else {\n s->last_irr &= ~mask;\n }\n }\n}\n \nstatic int pic_get_priority(PICState *s, int mask)\n{\n int priority;\n if (mask == 0)\n return -1;\n priority = 7;\n while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)\n priority--;\n return priority;\n}\n\n/* return the pic wanted interrupt. return -1 if none */\nstatic int pic_get_irq(PICState *s)\n{\n int mask, cur_priority, priority;\n\n mask = s->irr & ~s->imr;\n priority = pic_get_priority(s, mask);\n if (priority < 0)\n return -1;\n /* compute current priority */\n cur_priority = pic_get_priority(s, s->isr);\n if (priority > cur_priority) {\n /* higher priority found: an irq should be generated */\n return priority;\n } else {\n return -1;\n }\n}\n \n/* acknowledge interrupt 'irq' */\nstatic void pic_intack(PICState *s, int irq)\n{\n if (s->auto_eoi) {\n if (s->rotate_on_autoeoi)\n s->priority_add = (irq + 1) & 7;\n } else {\n s->isr |= (1 << irq);\n }\n /* We don't clear a level sensitive interrupt here */\n if (!(s->elcr & (1 << irq)))\n s->irr &= ~(1 << irq);\n}\n\nstatic void pic_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PICState *s = opaque;\n int priority, addr;\n \n addr = offset & 1;\n#ifdef DEBUG_PIC\n console.log(\"pic_write: addr=\" + toHex2(addr) + \" val=\" + toHex2(val));\n#endif\n if (addr == 0) {\n if (val & 0x10) {\n /* init */\n pic_reset(s);\n s->init_state = 1;\n s->init4 = val & 1;\n if (val & 0x02)\n abort(); /* \"single mode not supported\" */\n if (val & 0x08)\n abort(); /* \"level sensitive irq not supported\" */\n } else if (val & 0x08) {\n if (val & 0x02)\n s->read_reg_select = val & 1;\n if (val & 0x40)\n s->special_mask = (val >> 5) & 1;\n } else {\n switch(val) {\n case 0x00:\n case 0x80:\n s->rotate_on_autoeoi = val >> 7;\n break;\n case 0x20: /* end of interrupt */\n case 0xa0:\n priority = pic_get_priority(s, s->isr);\n if (priority >= 0) {\n s->isr &= ~(1 << ((priority + s->priority_add) & 7));\n }\n if (val == 0xa0)\n s->priority_add = (s->priority_add + 1) & 7;\n break;\n case 0x60:\n case 0x61:\n case 0x62:\n case 0x63:\n case 0x64:\n case 0x65:\n case 0x66:\n case 0x67:\n priority = val & 7;\n s->isr &= ~(1 << priority);\n break;\n case 0xc0:\n case 0xc1:\n case 0xc2:\n case 0xc3:\n case 0xc4:\n case 0xc5:\n case 0xc6:\n case 0xc7:\n s->priority_add = (val + 1) & 7;\n break;\n case 0xe0:\n case 0xe1:\n case 0xe2:\n case 0xe3:\n case 0xe4:\n case 0xe5:\n case 0xe6:\n case 0xe7:\n priority = val & 7;\n s->isr &= ~(1 << priority);\n s->priority_add = (priority + 1) & 7;\n break;\n }\n }\n } else {\n switch(s->init_state) {\n case 0:\n /* normal mode */\n s->imr = val;\n s->update_irq(s->opaque);\n break;\n case 1:\n s->irq_base = val & 0xf8;\n s->init_state = 2;\n break;\n case 2:\n if (s->init4) {\n s->init_state = 3;\n } else {\n s->init_state = 0;\n }\n break;\n case 3:\n s->auto_eoi = (val >> 1) & 1;\n s->init_state = 0;\n break;\n }\n }\n}\n\nstatic uint32_t pic_read(void *opaque, uint32_t offset, int size_log2)\n{\n PICState *s = opaque;\n int addr, ret;\n\n addr = offset & 1;\n if (addr == 0) {\n if (s->read_reg_select)\n ret = s->isr;\n else\n ret = s->irr;\n } else {\n ret = s->imr;\n }\n#ifdef DEBUG_PIC\n console.log(\"pic_read: addr=\" + toHex2(addr1) + \" val=\" + toHex2(ret));\n#endif\n return ret;\n}\n\nstatic void pic_elcr_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PICState *s = opaque;\n s->elcr = val & s->elcr_mask;\n}\n\nstatic uint32_t pic_elcr_read(void *opaque, uint32_t offset, int size_log2)\n{\n PICState *s = opaque;\n return s->elcr;\n}\n\ntypedef struct {\n PICState *pics[2];\n int irq_requested;\n void (*cpu_set_irq)(void *opaque, int level);\n void *opaque;\n#if defined(DEBUG_PIC)\n uint8_t irq_level[16];\n#endif\n IRQSignal *irqs;\n} PIC2State;\n\nstatic void pic2_update_irq(void *opaque);\nstatic void pic2_set_irq(void *opaque, int irq, int level);\n\nPIC2State *pic2_init(PhysMemoryMap *port_map, uint32_t addr0, uint32_t addr1,\n uint32_t elcr_addr0, uint32_t elcr_addr1, \n void (*cpu_set_irq)(void *opaque, int level),\n void *opaque, IRQSignal *irqs)\n{\n PIC2State *s;\n int i;\n \n s = mallocz(sizeof(*s));\n\n for(i = 0; i < 16; i++) {\n irq_init(&irqs[i], pic2_set_irq, s, i);\n }\n s->cpu_set_irq = cpu_set_irq;\n s->opaque = opaque;\n s->pics[0] = pic_init(port_map, addr0, elcr_addr0, 0xf8, pic2_update_irq, s);\n s->pics[1] = pic_init(port_map, addr1, elcr_addr1, 0xde, pic2_update_irq, s);\n s->irq_requested = 0;\n return s;\n}\n\nvoid pic2_set_elcr(PIC2State *s, const uint8_t *elcr)\n{\n int i;\n for(i = 0; i < 2; i++) {\n s->pics[i]->elcr = elcr[i] & s->pics[i]->elcr_mask;\n }\n}\n\n/* raise irq to CPU if necessary. must be called every time the active\n irq may change */\nstatic void pic2_update_irq(void *opaque)\n{\n PIC2State *s = opaque;\n int irq2, irq;\n\n /* first look at slave pic */\n irq2 = pic_get_irq(s->pics[1]);\n if (irq2 >= 0) {\n /* if irq request by slave pic, signal master PIC */\n pic_set_irq1(s->pics[0], 2, 1);\n pic_set_irq1(s->pics[0], 2, 0);\n }\n /* look at requested irq */\n irq = pic_get_irq(s->pics[0]);\n#if 0\n console.log(\"irr=\" + toHex2(s->pics[0].irr) + \" imr=\" + toHex2(s->pics[0].imr) + \" isr=\" + toHex2(s->pics[0].isr) + \" irq=\"+ irq);\n#endif\n if (irq >= 0) {\n /* raise IRQ request on the CPU */\n s->cpu_set_irq(s->opaque, 1);\n } else {\n /* lower irq */\n s->cpu_set_irq(s->opaque, 0);\n }\n}\n\nstatic void pic2_set_irq(void *opaque, int irq, int level)\n{\n PIC2State *s = opaque;\n#if defined(DEBUG_PIC)\n if (irq != 0 && level != s->irq_level[irq]) {\n console.log(\"pic_set_irq: irq=\" + irq + \" level=\" + level);\n s->irq_level[irq] = level;\n }\n#endif\n pic_set_irq1(s->pics[irq >> 3], irq & 7, level);\n pic2_update_irq(s);\n}\n\n/* called from the CPU to get the hardware interrupt number */\nstatic int pic2_get_hard_intno(PIC2State *s)\n{\n int irq, irq2, intno;\n\n irq = pic_get_irq(s->pics[0]);\n if (irq >= 0) {\n pic_intack(s->pics[0], irq);\n if (irq == 2) {\n irq2 = pic_get_irq(s->pics[1]);\n if (irq2 >= 0) {\n pic_intack(s->pics[1], irq2);\n } else {\n /* spurious IRQ on slave controller */\n irq2 = 7;\n }\n intno = s->pics[1]->irq_base + irq2;\n irq = irq2 + 8;\n } else {\n intno = s->pics[0]->irq_base + irq;\n }\n } else {\n /* spurious IRQ on host controller */\n irq = 7;\n intno = s->pics[0]->irq_base + irq;\n }\n pic2_update_irq(s);\n\n#if defined(DEBUG_PIC)\n if (irq != 0 && irq != 14)\n printf(\"pic_interrupt: irq=%d\\n\", irq);\n#endif\n return intno;\n}\n\n/***********************************************************/\n/* 8253 PIT emulation */\n\n#define PIT_FREQ 1193182\n\n#define RW_STATE_LSB 0\n#define RW_STATE_MSB 1\n#define RW_STATE_WORD0 2\n#define RW_STATE_WORD1 3\n#define RW_STATE_LATCHED_WORD0 4\n#define RW_STATE_LATCHED_WORD1 5\n\n//#define DEBUG_PIT\n\ntypedef int64_t PITGetTicksFunc(void *opaque);\n\ntypedef struct PITState PITState;\n\ntypedef struct {\n PITState *pit_state;\n uint32_t count;\n uint32_t latched_count;\n uint8_t rw_state;\n uint8_t mode;\n uint8_t bcd;\n uint8_t gate;\n int64_t count_load_time;\n int64_t last_irq_time;\n} PITChannel;\n\nstruct PITState {\n PITChannel pit_channels[3];\n uint8_t speaker_data_on;\n PITGetTicksFunc *get_ticks;\n IRQSignal *irq;\n void *opaque;\n};\n\nstatic void pit_load_count(PITChannel *pc, int val);\nstatic void pit_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pit_read(void *opaque, uint32_t offset, int size_log2);\nstatic void speaker_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t speaker_read(void *opaque, uint32_t offset, int size_log2);\n\nPITState *pit_init(PhysMemoryMap *port_map, int addr0, int addr1,\n IRQSignal *irq,\n PITGetTicksFunc *get_ticks, void *opaque)\n{\n PITState *s;\n PITChannel *pc;\n int i;\n\n s = mallocz(sizeof(*s));\n\n s->irq = irq;\n s->get_ticks = get_ticks;\n s->opaque = opaque;\n \n for(i = 0; i < 3; i++) {\n pc = &s->pit_channels[i];\n pc->pit_state = s;\n pc->mode = 3;\n pc->gate = (i != 2) >> 0;\n pit_load_count(pc, 0);\n }\n s->speaker_data_on = 0;\n\n cpu_register_device(port_map, addr0, 4, s, pit_read, pit_write, \n DEVIO_SIZE8);\n\n cpu_register_device(port_map, addr1, 1, s, speaker_read, speaker_write, \n DEVIO_SIZE8);\n return s;\n}\n\n/* unit = PIT frequency */\nstatic int64_t pit_get_time(PITChannel *pc)\n{\n PITState *s = pc->pit_state;\n return s->get_ticks(s->opaque);\n}\n\nstatic uint32_t pit_get_count(PITChannel *pc)\n{\n uint32_t counter;\n uint64_t d;\n \n d = pit_get_time(pc) - pc->count_load_time;\n switch(pc->mode) {\n case 0:\n case 1:\n case 4:\n case 5:\n counter = (pc->count - d) & 0xffff;\n break;\n default:\n counter = pc->count - (d % pc->count);\n break;\n }\n return counter;\n}\n\n/* get pit output bit */\nstatic int pit_get_out(PITChannel *pc)\n{\n int out;\n int64_t d;\n \n d = pit_get_time(pc) - pc->count_load_time;\n switch(pc->mode) {\n default:\n case 0:\n out = (d >= pc->count) >> 0;\n break;\n case 1:\n out = (d < pc->count) >> 0;\n break;\n case 2:\n /* mode used by Linux */\n if ((d % pc->count) == 0 && d != 0)\n out = 1;\n else\n out = 0;\n break;\n case 3:\n out = ((d % pc->count) < (pc->count >> 1)) >> 0;\n break;\n case 4:\n case 5:\n out = (d == pc->count) >> 0;\n break;\n }\n return out;\n}\n\nstatic void pit_load_count(PITChannel *s, int val)\n{\n if (val == 0)\n val = 0x10000;\n s->count_load_time = pit_get_time(s);\n s->last_irq_time = 0;\n s->count = val;\n}\n\nstatic void pit_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PITState *pit = opaque;\n int channel, access, addr;\n PITChannel *s;\n\n addr = offset & 3;\n#ifdef DEBUG_PIT\n printf(\"pit_write: off=%d val=0x%02x\\n\", addr, val);\n#endif\n if (addr == 3) {\n channel = val >> 6;\n if (channel == 3)\n return;\n s = &pit->pit_channels[channel];\n access = (val >> 4) & 3;\n switch(access) {\n case 0:\n s->latched_count = pit_get_count(s);\n s->rw_state = RW_STATE_LATCHED_WORD0;\n break;\n default:\n s->mode = (val >> 1) & 7;\n s->bcd = val & 1;\n s->rw_state = access - 1 + RW_STATE_LSB;\n break;\n }\n } else {\n s = &pit->pit_channels[addr];\n switch(s->rw_state) {\n case RW_STATE_LSB:\n pit_load_count(s, val);\n break;\n case RW_STATE_MSB:\n pit_load_count(s, val << 8);\n break;\n case RW_STATE_WORD0:\n case RW_STATE_WORD1:\n if (s->rw_state & 1) {\n pit_load_count(s, (s->latched_count & 0xff) | (val << 8));\n } else {\n s->latched_count = val;\n }\n s->rw_state ^= 1;\n break;\n }\n }\n}\n\nstatic uint32_t pit_read(void *opaque, uint32_t offset, int size_log2)\n{\n PITState *pit = opaque;\n PITChannel *s;\n int ret, count, addr;\n \n addr = offset & 3;\n if (addr == 3)\n return 0xff;\n\n s = &pit->pit_channels[addr];\n switch(s->rw_state) {\n case RW_STATE_LSB:\n case RW_STATE_MSB:\n case RW_STATE_WORD0:\n case RW_STATE_WORD1:\n count = pit_get_count(s);\n if (s->rw_state & 1)\n ret = (count >> 8) & 0xff;\n else\n ret = count & 0xff;\n if (s->rw_state & 2)\n s->rw_state ^= 1;\n break;\n default:\n case RW_STATE_LATCHED_WORD0:\n case RW_STATE_LATCHED_WORD1:\n if (s->rw_state & 1)\n ret = s->latched_count >> 8;\n else\n ret = s->latched_count & 0xff;\n s->rw_state ^= 1;\n break;\n }\n#ifdef DEBUG_PIT\n printf(\"pit_read: off=%d val=0x%02x\\n\", addr, ret);\n#endif\n return ret;\n}\n\nstatic void speaker_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PITState *pit = opaque;\n pit->speaker_data_on = (val >> 1) & 1;\n pit->pit_channels[2].gate = val & 1;\n}\n\nstatic uint32_t speaker_read(void *opaque, uint32_t offset, int size_log2)\n{\n PITState *pit = opaque;\n PITChannel *s;\n int out, val;\n\n s = &pit->pit_channels[2];\n out = pit_get_out(s);\n val = (pit->speaker_data_on << 1) | s->gate | (out << 5);\n#ifdef DEBUG_PIT\n // console.log(\"speaker_read: addr=\" + toHex2(addr) + \" val=\" + toHex2(val));\n#endif\n return val;\n}\n\n/* set the IRQ if necessary and return the delay in ms until the next\n IRQ. Note: The code does not handle all the PIT configurations. */\nstatic int pit_update_irq(PITState *pit)\n{\n PITChannel *s;\n int64_t d, delay;\n \n s = &pit->pit_channels[0];\n \n delay = PIT_FREQ; /* could be infinity delay */\n \n d = pit_get_time(s) - s->count_load_time;\n switch(s->mode) {\n default:\n case 0:\n case 1:\n case 4:\n case 5:\n if (s->last_irq_time == 0) {\n delay = s->count - d;\n if (delay <= 0) {\n set_irq(pit->irq, 1);\n set_irq(pit->irq, 0);\n s->last_irq_time = d;\n }\n }\n break;\n case 2: /* mode used by Linux */\n case 3:\n delay = s->last_irq_time + s->count - d;\n if (delay <= 0) {\n set_irq(pit->irq, 1);\n set_irq(pit->irq, 0);\n s->last_irq_time += s->count;\n }\n break;\n }\n\n if (delay <= 0)\n return 0;\n else\n return delay / (PIT_FREQ / 1000);\n}\n \n/***********************************************************/\n/* serial port emulation */\n\n#define UART_LCR_DLAB\t0x80\t/* Divisor latch access bit */\n\n#define UART_IER_MSI\t0x08\t/* Enable Modem status interrupt */\n#define UART_IER_RLSI\t0x04\t/* Enable receiver line status interrupt */\n#define UART_IER_THRI\t0x02\t/* Enable Transmitter holding register int. */\n#define UART_IER_RDI\t0x01\t/* Enable receiver data interrupt */\n\n#define UART_IIR_NO_INT\t0x01\t/* No interrupts pending */\n#define UART_IIR_ID\t0x06\t/* Mask for the interrupt ID */\n\n#define UART_IIR_MSI\t0x00\t/* Modem status interrupt */\n#define UART_IIR_THRI\t0x02\t/* Transmitter holding register empty */\n#define UART_IIR_RDI\t0x04\t/* Receiver data interrupt */\n#define UART_IIR_RLSI\t0x06\t/* Receiver line status interrupt */\n#define UART_IIR_FE 0xC0 /* Fifo enabled */\n\n#define UART_LSR_TEMT\t0x40\t/* Transmitter empty */\n#define UART_LSR_THRE\t0x20\t/* Transmit-hold-register empty */\n#define UART_LSR_BI\t0x10\t/* Break interrupt indicator */\n#define UART_LSR_FE\t0x08\t/* Frame error indicator */\n#define UART_LSR_PE\t0x04\t/* Parity error indicator */\n#define UART_LSR_OE\t0x02\t/* Overrun error indicator */\n#define UART_LSR_DR\t0x01\t/* Receiver data ready */\n\n#define UART_FCR_XFR 0x04 /* XMIT Fifo Reset */\n#define UART_FCR_RFR 0x02 /* RCVR Fifo Reset */\n#define UART_FCR_FE 0x01 /* FIFO Enable */\n\n#define UART_FIFO_LENGTH 16 /* 16550A Fifo Length */\n\ntypedef struct {\n uint8_t divider; \n uint8_t rbr; /* receive register */\n uint8_t ier;\n uint8_t iir; /* read only */\n uint8_t lcr;\n uint8_t mcr;\n uint8_t lsr; /* read only */\n uint8_t msr;\n uint8_t scr;\n uint8_t fcr;\n IRQSignal *irq;\n void (*write_func)(void *opaque, const uint8_t *buf, int buf_len);\n void *opaque;\n} SerialState;\n\nstatic void serial_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t serial_read(void *opaque, uint32_t offset, int size_log2);\n\nSerialState *serial_init(PhysMemoryMap *port_map, int addr,\n IRQSignal *irq,\n void (*write_func)(void *opaque, const uint8_t *buf, int buf_len), void *opaque)\n{\n SerialState *s;\n s = mallocz(sizeof(*s));\n \n /* all 8 bit registers */\n s->divider = 0; \n s->rbr = 0; /* receive register */\n s->ier = 0;\n s->iir = UART_IIR_NO_INT; /* read only */\n s->lcr = 0;\n s->mcr = 0;\n s->lsr = UART_LSR_TEMT | UART_LSR_THRE; /* read only */\n s->msr = 0;\n s->scr = 0;\n s->fcr = 0;\n\n s->irq = irq;\n s->write_func = write_func;\n s->opaque = opaque;\n\n cpu_register_device(port_map, addr, 8, s, serial_read, serial_write, \n DEVIO_SIZE8);\n return s;\n}\n\nstatic void serial_update_irq(SerialState *s)\n{\n if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {\n s->iir = UART_IIR_RDI;\n } else if ((s->lsr & UART_LSR_THRE) && (s->ier & UART_IER_THRI)) {\n s->iir = UART_IIR_THRI;\n } else {\n s->iir = UART_IIR_NO_INT;\n }\n if (s->iir != UART_IIR_NO_INT) {\n set_irq(s->irq, 1);\n } else {\n set_irq(s->irq, 0);\n }\n}\n\n#if 0\n/* send remainining chars in fifo */\nSerial.prototype.write_tx_fifo = function()\n{\n if (s->tx_fifo != \"\") {\n s->write_func(s->tx_fifo);\n s->tx_fifo = \"\";\n \n s->lsr |= UART_LSR_THRE;\n s->lsr |= UART_LSR_TEMT;\n s->update_irq();\n }\n}\n#endif\n \nstatic void serial_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n SerialState *s = opaque;\n int addr;\n\n addr = offset & 7;\n switch(addr) {\n default:\n case 0:\n if (s->lcr & UART_LCR_DLAB) {\n s->divider = (s->divider & 0xff00) | val;\n } else {\n#if 0\n if (s->fcr & UART_FCR_FE) {\n s->tx_fifo += String.fromCharCode(val);\n s->lsr &= ~UART_LSR_THRE;\n serial_update_irq(s);\n if (s->tx_fifo.length >= UART_FIFO_LENGTH) {\n /* write to the terminal */\n s->write_tx_fifo();\n }\n } else\n#endif\n {\n uint8_t ch;\n s->lsr &= ~UART_LSR_THRE;\n serial_update_irq(s);\n \n /* write to the terminal */\n ch = val;\n s->write_func(s->opaque, &ch, 1);\n s->lsr |= UART_LSR_THRE;\n s->lsr |= UART_LSR_TEMT;\n serial_update_irq(s);\n }\n }\n break;\n case 1:\n if (s->lcr & UART_LCR_DLAB) {\n s->divider = (s->divider & 0x00ff) | (val << 8);\n } else {\n s->ier = val;\n serial_update_irq(s);\n }\n break;\n case 2:\n#if 0\n if ((s->fcr ^ val) & UART_FCR_FE) {\n /* clear fifos */\n val |= UART_FCR_XFR | UART_FCR_RFR;\n }\n if (val & UART_FCR_XFR)\n s->tx_fifo = \"\";\n if (val & UART_FCR_RFR)\n s->rx_fifo = \"\";\n s->fcr = val & UART_FCR_FE;\n#endif\n break;\n case 3:\n s->lcr = val;\n break;\n case 4:\n s->mcr = val;\n break;\n case 5:\n break;\n case 6:\n s->msr = val;\n break;\n case 7:\n s->scr = val;\n break;\n }\n}\n\nstatic uint32_t serial_read(void *opaque, uint32_t offset, int size_log2)\n{\n SerialState *s = opaque;\n int ret, addr;\n\n addr = offset & 7;\n switch(addr) {\n default:\n case 0:\n if (s->lcr & UART_LCR_DLAB) {\n ret = s->divider & 0xff; \n } else {\n ret = s->rbr;\n s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);\n serial_update_irq(s);\n#if 0\n /* try to receive next chars */\n s->send_char_from_fifo();\n#endif\n }\n break;\n case 1:\n if (s->lcr & UART_LCR_DLAB) {\n ret = (s->divider >> 8) & 0xff;\n } else {\n ret = s->ier;\n }\n break;\n case 2:\n ret = s->iir;\n if (s->fcr & UART_FCR_FE)\n ret |= UART_IIR_FE;\n break;\n case 3:\n ret = s->lcr;\n break;\n case 4:\n ret = s->mcr;\n break;\n case 5:\n ret = s->lsr;\n break;\n case 6:\n ret = s->msr;\n break;\n case 7:\n ret = s->scr;\n break;\n }\n return ret;\n}\n\nvoid serial_send_break(SerialState *s)\n{\n s->rbr = 0;\n s->lsr |= UART_LSR_BI | UART_LSR_DR;\n serial_update_irq(s);\n}\n\n#if 0\nstatic void serial_send_char(SerialState *s, int ch)\n{\n s->rbr = ch;\n s->lsr |= UART_LSR_DR;\n serial_update_irq(s);\n}\n\nSerial.prototype.send_char_from_fifo = function()\n{\n var fifo;\n\n fifo = s->rx_fifo;\n if (fifo != \"\" && !(s->lsr & UART_LSR_DR)) {\n s->send_char(fifo.charCodeAt(0));\n s->rx_fifo = fifo.substr(1, fifo.length - 1);\n }\n}\n\n/* queue the string in the UART receive fifo and send it ASAP */\nSerial.prototype.send_chars = function(str)\n{\n s->rx_fifo += str;\n s->send_char_from_fifo();\n}\n \n#endif\n\n#ifdef DEBUG_BIOS\nstatic void bios_debug_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n#ifdef EMSCRIPTEN\n static char line_buf[256];\n static int line_buf_index;\n line_buf[line_buf_index++] = val;\n if (val == '\\n' || line_buf_index >= sizeof(line_buf) - 1) {\n line_buf[line_buf_index] = '\\0';\n printf(\"%s\", line_buf);\n line_buf_index = 0;\n }\n#else\n putchar(val & 0xff);\n#endif\n}\n\nstatic uint32_t bios_debug_read(void *opaque, uint32_t offset, int size_log2)\n{\n return 0;\n}\n#endif\n\ntypedef struct PCMachine {\n VirtMachine common;\n uint64_t ram_size;\n PhysMemoryMap *mem_map;\n PhysMemoryMap *port_map;\n \n X86CPUState *cpu_state;\n PIC2State *pic_state;\n IRQSignal pic_irq[16];\n PITState *pit_state;\n I440FXState *i440fx_state;\n CMOSState *cmos_state;\n SerialState *serial_state;\n\n /* input */\n VIRTIODevice *keyboard_dev;\n VIRTIODevice *mouse_dev;\n KBDState *kbd_state;\n PS2MouseState *ps2_mouse;\n VMMouseState *vm_mouse;\n PS2KbdState *ps2_kbd;\n\n#ifdef USE_KVM\n BOOL kvm_enabled;\n int kvm_fd;\n int vm_fd;\n int vcpu_fd;\n int kvm_run_size;\n struct kvm_run *kvm_run;\n#endif\n} PCMachine;\n\nstatic void copy_kernel(PCMachine *s, const uint8_t *buf, int buf_len,\n const char *cmd_line);\n\nstatic void port80_write(void *opaque, uint32_t offset,\n uint32_t val64, int size_log2)\n{\n}\n\nstatic uint32_t port80_read(void *opaque, uint32_t offset, int size_log2)\n{\n return 0xff;\n}\n\nstatic void port92_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n}\n\nstatic uint32_t port92_read(void *opaque, uint32_t offset, int size_log2)\n{\n int a20 = 1; /* A20=0 is not supported */\n return a20 << 1;\n}\n\n#define VMPORT_MAGIC 0x564D5868\n#define REG_EAX 0\n#define REG_EBX 1\n#define REG_ECX 2\n#define REG_EDX 3\n#define REG_ESI 4\n#define REG_EDI 5\n\nstatic uint32_t vmport_read(void *opaque, uint32_t addr, int size_log2)\n{\n PCMachine *s = opaque;\n uint32_t regs[6];\n\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n struct kvm_regs r;\n\n ioctl(s->vcpu_fd, KVM_GET_REGS, &r);\n regs[REG_EAX] = r.rax;\n regs[REG_EBX] = r.rbx;\n regs[REG_ECX] = r.rcx;\n regs[REG_EDX] = r.rdx;\n regs[REG_ESI] = r.rsi;\n regs[REG_EDI] = r.rdi;\n\n if (regs[REG_EAX] == VMPORT_MAGIC) {\n \n vmmouse_handler(s->vm_mouse, regs);\n \n /* Note: in 64 bits the high parts are reset to zero\n in all cases. */\n r.rax = regs[REG_EAX];\n r.rbx = regs[REG_EBX];\n r.rcx = regs[REG_ECX];\n r.rdx = regs[REG_EDX];\n r.rsi = regs[REG_ESI];\n r.rdi = regs[REG_EDI];\n ioctl(s->vcpu_fd, KVM_SET_REGS, &r);\n }\n } else\n#endif\n {\n regs[REG_EAX] = x86_cpu_get_reg(s->cpu_state, 0);\n regs[REG_EBX] = x86_cpu_get_reg(s->cpu_state, 3);\n regs[REG_ECX] = x86_cpu_get_reg(s->cpu_state, 1);\n regs[REG_EDX] = x86_cpu_get_reg(s->cpu_state, 2);\n regs[REG_ESI] = x86_cpu_get_reg(s->cpu_state, 6);\n regs[REG_EDI] = x86_cpu_get_reg(s->cpu_state, 7);\n\n if (regs[REG_EAX] == VMPORT_MAGIC) {\n vmmouse_handler(s->vm_mouse, regs);\n\n x86_cpu_set_reg(s->cpu_state, 0, regs[REG_EAX]);\n x86_cpu_set_reg(s->cpu_state, 3, regs[REG_EBX]);\n x86_cpu_set_reg(s->cpu_state, 1, regs[REG_ECX]);\n x86_cpu_set_reg(s->cpu_state, 2, regs[REG_EDX]);\n x86_cpu_set_reg(s->cpu_state, 6, regs[REG_ESI]);\n x86_cpu_set_reg(s->cpu_state, 7, regs[REG_EDI]);\n }\n }\n return regs[REG_EAX];\n}\n\nstatic void vmport_write(void *opaque, uint32_t addr, uint32_t val,\n int size_log2)\n{\n}\n\nstatic void pic_set_irq_cb(void *opaque, int level)\n{\n PCMachine *s = opaque;\n x86_cpu_set_irq(s->cpu_state, level);\n}\n\nstatic void serial_write_cb(void *opaque, const uint8_t *buf, int buf_len)\n{\n PCMachine *s = opaque;\n if (s->common.console) {\n s->common.console->write_data(s->common.console->opaque, buf, buf_len);\n }\n}\n\nstatic int get_hard_intno_cb(void *opaque)\n{\n PCMachine *s = opaque;\n return pic2_get_hard_intno(s->pic_state);\n}\n\nstatic int64_t pit_get_ticks_cb(void *opaque)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * PIT_FREQ +\n ((uint64_t)ts.tv_nsec * PIT_FREQ / 1000000000);\n}\n\n#define FRAMEBUFFER_BASE_ADDR 0xf0400000\n\nstatic uint8_t *get_ram_ptr(PCMachine *s, uint64_t paddr)\n{\n PhysMemoryRange *pr;\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr || !pr->is_ram)\n return NULL;\n return pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n}\n\n#ifdef DUMP_IOPORT\nstatic BOOL dump_port(int port)\n{\n return !((port >= 0x1f0 && port <= 0x1f7) ||\n (port >= 0x20 && port <= 0x21) ||\n (port >= 0xa0 && port <= 0xa1));\n}\n#endif\n\nstatic void st_port(void *opaque, uint32_t port, uint32_t val, int size_log2)\n{\n PCMachine *s = opaque;\n PhysMemoryRange *pr;\n#ifdef DUMP_IOPORT\n if (dump_port(port))\n printf(\"write port=0x%x val=0x%x s=%d\\n\", port, val, 1 << size_log2);\n#endif\n pr = get_phys_mem_range(s->port_map, port);\n if (!pr) {\n return;\n }\n port -= pr->addr;\n if ((pr->devio_flags >> size_log2) & 1) {\n pr->write_func(pr->opaque, port, (uint32_t)val, size_log2);\n } else if (size_log2 == 1 && (pr->devio_flags & DEVIO_SIZE8)) {\n pr->write_func(pr->opaque, port, val & 0xff, 0);\n pr->write_func(pr->opaque, port + 1, (val >> 8) & 0xff, 0);\n }\n}\n\nstatic uint32_t ld_port(void *opaque, uint32_t port1, int size_log2)\n{\n PCMachine *s = opaque;\n PhysMemoryRange *pr;\n uint32_t val, port;\n \n port = port1;\n pr = get_phys_mem_range(s->port_map, port);\n if (!pr) {\n val = -1;\n } else {\n port -= pr->addr;\n if ((pr->devio_flags >> size_log2) & 1) {\n val = pr->read_func(pr->opaque, port, size_log2);\n } else if (size_log2 == 1 && (pr->devio_flags & DEVIO_SIZE8)) {\n val = pr->read_func(pr->opaque, port, 0) & 0xff;\n val |= (pr->read_func(pr->opaque, port + 1, 0) & 0xff) << 8;\n } else {\n val = -1;\n }\n }\n#ifdef DUMP_IOPORT\n if (dump_port(port1))\n printf(\"read port=0x%x val=0x%x s=%d\\n\", port1, val, 1 << size_log2);\n#endif\n return val;\n}\n\nstatic void pc_machine_set_defaults(VirtMachineParams *p)\n{\n p->accel_enable = TRUE;\n}\n\n#ifdef USE_KVM\n\nstatic void sigalrm_handler(int sig)\n{\n}\n\n#define CPUID_APIC (1 << 9)\n#define CPUID_ACPI (1 << 22)\n\nstatic void kvm_set_cpuid(PCMachine *s)\n{\n struct kvm_cpuid2 *kvm_cpuid;\n int n_ent_max, i;\n struct kvm_cpuid_entry2 *ent;\n \n n_ent_max = 128;\n kvm_cpuid = mallocz(sizeof(struct kvm_cpuid2) + n_ent_max * sizeof(kvm_cpuid->entries[0]));\n \n kvm_cpuid->nent = n_ent_max;\n if (ioctl(s->kvm_fd, KVM_GET_SUPPORTED_CPUID, kvm_cpuid) < 0) {\n perror(\"KVM_GET_SUPPORTED_CPUID\");\n exit(1);\n }\n\n for(i = 0; i < kvm_cpuid->nent; i++) {\n ent = &kvm_cpuid->entries[i];\n /* remove the APIC & ACPI to be in sync with the emulator */\n if (ent->function == 1 || ent->function == 0x80000001) {\n ent->edx &= ~(CPUID_APIC | CPUID_ACPI);\n }\n }\n \n if (ioctl(s->vcpu_fd, KVM_SET_CPUID2, kvm_cpuid) < 0) {\n perror(\"KVM_SET_CPUID2\");\n exit(1);\n }\n free(kvm_cpuid);\n}\n\n/* XXX: should check overlapping mappings */\nstatic void kvm_map_ram(PhysMemoryMap *mem_map, PhysMemoryRange *pr)\n{\n PCMachine *s = mem_map->opaque;\n struct kvm_userspace_memory_region region;\n int flags;\n\n region.slot = pr - mem_map->phys_mem_range;\n flags = 0;\n if (pr->devram_flags & DEVRAM_FLAG_ROM)\n flags |= KVM_MEM_READONLY;\n if (pr->devram_flags & DEVRAM_FLAG_DIRTY_BITS)\n flags |= KVM_MEM_LOG_DIRTY_PAGES;\n region.flags = flags;\n region.guest_phys_addr = pr->addr;\n region.memory_size = pr->size;\n#if 0\n printf(\"map slot %d: %08lx %08lx\\n\",\n region.slot, pr->addr, pr->size);\n#endif\n region.userspace_addr = (uintptr_t)pr->phys_mem;\n if (ioctl(s->vm_fd, KVM_SET_USER_MEMORY_REGION, ®ion) < 0) {\n perror(\"KVM_SET_USER_MEMORY_REGION\");\n exit(1);\n }\n}\n\n/* XXX: just for one region */\nstatic PhysMemoryRange *kvm_register_ram(PhysMemoryMap *mem_map, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n uint8_t *phys_mem;\n \n pr = register_ram_entry(mem_map, addr, size, devram_flags);\n\n phys_mem = mmap(NULL, size, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n if (!phys_mem)\n return NULL;\n pr->phys_mem = phys_mem;\n if (devram_flags & DEVRAM_FLAG_DIRTY_BITS) {\n int n_pages = size >> 12;\n pr->dirty_bits_size = ((n_pages + 63) / 64) * 8;\n pr->dirty_bits = mallocz(pr->dirty_bits_size);\n }\n\n if (pr->size != 0) {\n kvm_map_ram(mem_map, pr);\n }\n return pr;\n}\n\nstatic void kvm_set_ram_addr(PhysMemoryMap *mem_map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n if (enabled) {\n if (pr->size == 0 || addr != pr->addr) {\n /* move or create the region */\n pr->size = pr->org_size;\n pr->addr = addr;\n kvm_map_ram(mem_map, pr);\n }\n } else {\n if (pr->size != 0) {\n pr->addr = 0;\n pr->size = 0;\n /* map a zero size region to disable */\n kvm_map_ram(mem_map, pr);\n }\n }\n}\n\nstatic const uint32_t *kvm_get_dirty_bits(PhysMemoryMap *mem_map,\n PhysMemoryRange *pr)\n{\n PCMachine *s = mem_map->opaque;\n struct kvm_dirty_log dlog;\n \n if (pr->size == 0) {\n /* not mapped: we assume no modification was made */\n memset(pr->dirty_bits, 0, pr->dirty_bits_size);\n } else {\n dlog.slot = pr - mem_map->phys_mem_range;\n dlog.dirty_bitmap = pr->dirty_bits;\n if (ioctl(s->vm_fd, KVM_GET_DIRTY_LOG, &dlog) < 0) {\n perror(\"KVM_GET_DIRTY_LOG\");\n exit(1);\n }\n }\n return pr->dirty_bits;\n}\n\nstatic void kvm_free_ram(PhysMemoryMap *mem_map, PhysMemoryRange *pr)\n{\n /* XXX: do it */\n munmap(pr->phys_mem, pr->org_size);\n free(pr->dirty_bits);\n}\n\nstatic void kvm_pic_set_irq(void *opaque, int irq_num, int level)\n{\n PCMachine *s = opaque;\n struct kvm_irq_level irq_level;\n irq_level.irq = irq_num;\n irq_level.level = level;\n if (ioctl(s->vm_fd, KVM_IRQ_LINE, &irq_level) < 0) {\n perror(\"KVM_IRQ_LINE\");\n exit(1);\n }\n}\n\nstatic void kvm_init(PCMachine *s)\n{\n int ret, i;\n struct sigaction act;\n struct kvm_pit_config pit_config;\n uint64_t base_addr;\n \n s->kvm_enabled = FALSE;\n s->kvm_fd = open(\"/dev/kvm\", O_RDWR);\n if (s->kvm_fd < 0) {\n fprintf(stderr, \"KVM not available\\n\");\n return;\n }\n ret = ioctl(s->kvm_fd, KVM_GET_API_VERSION, 0);\n if (ret < 0) {\n perror(\"KVM_GET_API_VERSION\");\n exit(1);\n }\n if (ret != 12) {\n fprintf(stderr, \"Unsupported KVM version\\n\");\n close(s->kvm_fd);\n s->kvm_fd = -1;\n return;\n }\n s->vm_fd = ioctl(s->kvm_fd, KVM_CREATE_VM, 0);\n if (s->vm_fd < 0) {\n perror(\"KVM_CREATE_VM\");\n exit(1);\n }\n\n /* just before the BIOS */\n base_addr = 0xfffbc000;\n if (ioctl(s->vm_fd, KVM_SET_IDENTITY_MAP_ADDR, &base_addr) < 0) {\n perror(\"KVM_SET_IDENTITY_MAP_ADDR\");\n exit(1);\n }\n \n if (ioctl(s->vm_fd, KVM_SET_TSS_ADDR, (long)(base_addr + 0x1000)) < 0) {\n perror(\"KVM_SET_TSS_ADDR\");\n exit(1);\n }\n \n if (ioctl(s->vm_fd, KVM_CREATE_IRQCHIP, 0) < 0) {\n perror(\"KVM_CREATE_IRQCHIP\");\n exit(1);\n }\n\n memset(&pit_config, 0, sizeof(pit_config));\n pit_config.flags = KVM_PIT_SPEAKER_DUMMY;\n if (ioctl(s->vm_fd, KVM_CREATE_PIT2, &pit_config)) {\n perror(\"KVM_CREATE_PIT2\");\n exit(1);\n }\n \n s->vcpu_fd = ioctl(s->vm_fd, KVM_CREATE_VCPU, 0);\n if (s->vcpu_fd < 0) {\n perror(\"KVM_CREATE_VCPU\");\n exit(1);\n }\n\n kvm_set_cpuid(s);\n \n /* map the kvm_run structure */\n s->kvm_run_size = ioctl(s->kvm_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);\n if (s->kvm_run_size < 0) {\n perror(\"KVM_GET_VCPU_MMAP_SIZE\");\n exit(1);\n }\n\n s->kvm_run = mmap(NULL, s->kvm_run_size, PROT_READ | PROT_WRITE,\n MAP_SHARED, s->vcpu_fd, 0);\n if (!s->kvm_run) {\n perror(\"mmap kvm_run\");\n exit(1);\n }\n\n for(i = 0; i < 16; i++) {\n irq_init(&s->pic_irq[i], kvm_pic_set_irq, s, i);\n }\n\n act.sa_handler = sigalrm_handler;\n sigemptyset(&act.sa_mask);\n act.sa_flags = 0;\n sigaction(SIGALRM, &act, NULL);\n\n s->kvm_enabled = TRUE;\n\n s->mem_map->register_ram = kvm_register_ram;\n s->mem_map->free_ram = kvm_free_ram;\n s->mem_map->get_dirty_bits = kvm_get_dirty_bits;\n s->mem_map->set_ram_addr = kvm_set_ram_addr;\n s->mem_map->opaque = s;\n}\n\nstatic void kvm_exit_io(PCMachine *s, struct kvm_run *run)\n{\n uint8_t *ptr;\n int i;\n \n ptr = (uint8_t *)run + run->io.data_offset;\n // printf(\"port: addr=%04x\\n\", run->io.port);\n \n for(i = 0; i < run->io.count; i++) {\n if (run->io.direction == KVM_EXIT_IO_OUT) {\n switch(run->io.size) {\n case 1:\n st_port(s, run->io.port, *(uint8_t *)ptr, 0);\n break;\n case 2:\n st_port(s, run->io.port, *(uint16_t *)ptr, 1);\n break;\n case 4:\n st_port(s, run->io.port, *(uint32_t *)ptr, 2);\n break;\n default:\n abort();\n }\n } else {\n switch(run->io.size) {\n case 1:\n *(uint8_t *)ptr = ld_port(s, run->io.port, 0);\n break;\n case 2:\n *(uint16_t *)ptr = ld_port(s, run->io.port, 1);\n break;\n case 4:\n *(uint32_t *)ptr = ld_port(s, run->io.port, 2);\n break;\n default:\n abort();\n }\n }\n ptr += run->io.size;\n }\n}\n\nstatic void kvm_exit_mmio(PCMachine *s, struct kvm_run *run)\n{\n uint8_t *data = run->mmio.data;\n PhysMemoryRange *pr;\n uint64_t addr;\n \n pr = get_phys_mem_range(s->mem_map, run->mmio.phys_addr);\n if (run->mmio.is_write) {\n if (!pr || pr->is_ram)\n return;\n addr = run->mmio.phys_addr - pr->addr;\n switch(run->mmio.len) {\n case 1:\n if (pr->devio_flags & DEVIO_SIZE8) {\n pr->write_func(pr->opaque, addr, *(uint8_t *)data, 0);\n }\n break;\n case 2:\n if (pr->devio_flags & DEVIO_SIZE16) {\n pr->write_func(pr->opaque, addr, *(uint16_t *)data, 1);\n }\n break;\n case 4:\n if (pr->devio_flags & DEVIO_SIZE32) {\n pr->write_func(pr->opaque, addr, *(uint32_t *)data, 2);\n }\n break;\n case 8:\n if (pr->devio_flags & DEVIO_SIZE32) {\n pr->write_func(pr->opaque, addr, *(uint32_t *)data, 2);\n pr->write_func(pr->opaque, addr + 4, *(uint32_t *)(data + 4), 2);\n }\n break;\n default:\n abort();\n }\n } else {\n if (!pr || pr->is_ram)\n goto no_dev;\n addr = run->mmio.phys_addr - pr->addr;\n switch(run->mmio.len) {\n case 1:\n if (!(pr->devio_flags & DEVIO_SIZE8))\n goto no_dev;\n *(uint8_t *)data = pr->read_func(pr->opaque, addr, 0);\n break;\n case 2:\n if (!(pr->devio_flags & DEVIO_SIZE16))\n goto no_dev;\n *(uint16_t *)data = pr->read_func(pr->opaque, addr, 1);\n break;\n case 4:\n if (!(pr->devio_flags & DEVIO_SIZE32))\n goto no_dev;\n *(uint32_t *)data = pr->read_func(pr->opaque, addr, 2);\n break;\n case 8:\n if (pr->devio_flags & DEVIO_SIZE32) {\n *(uint32_t *)data =\n pr->read_func(pr->opaque, addr, 2);\n *(uint32_t *)(data + 4) =\n pr->read_func(pr->opaque, addr + 4, 2);\n } else {\n no_dev:\n memset(run->mmio.data, 0, run->mmio.len);\n }\n break;\n default:\n abort();\n }\n \n }\n}\n\nstatic void kvm_exec(PCMachine *s)\n{\n struct kvm_run *run = s->kvm_run;\n struct itimerval ival;\n int ret;\n \n /* Not efficient but simple: we use a timer to interrupt the\n execution after a given time */\n ival.it_interval.tv_sec = 0;\n ival.it_interval.tv_usec = 0;\n ival.it_value.tv_sec = 0;\n ival.it_value.tv_usec = 10 * 1000; /* 10 ms max */\n setitimer(ITIMER_REAL, &ival, NULL);\n\n ret = ioctl(s->vcpu_fd, KVM_RUN, 0);\n if (ret < 0) {\n if (errno == EINTR || errno == EAGAIN) {\n /* timeout */\n return;\n }\n perror(\"KVM_RUN\");\n exit(1);\n }\n // printf(\"exit=%d\\n\", run->exit_reason);\n switch(run->exit_reason) {\n case KVM_EXIT_HLT:\n break;\n case KVM_EXIT_IO:\n kvm_exit_io(s, run);\n break;\n case KVM_EXIT_MMIO:\n kvm_exit_mmio(s, run);\n break;\n case KVM_EXIT_FAIL_ENTRY:\n fprintf(stderr, \"KVM_EXIT_FAIL_ENTRY: reason=0x%\" PRIx64 \"\\n\",\n (uint64_t)run->fail_entry.hardware_entry_failure_reason);\n#if 0\n {\n struct kvm_regs regs;\n if (ioctl(s->vcpu_fd, KVM_GET_REGS, ®s) < 0) {\n perror(\"KVM_SET_REGS\");\n exit(1);\n }\n printf(\"RIP=%016\" PRIx64 \"\\n\", (uint64_t)regs.rip);\n }\n#endif\n exit(1);\n case KVM_EXIT_INTERNAL_ERROR:\n fprintf(stderr, \"KVM_EXIT_INTERNAL_ERROR: suberror=0x%x\\n\",\n (uint32_t)run->internal.suberror);\n exit(1);\n default:\n fprintf(stderr, \"KVM: unsupported exit_reason=%d\\n\", run->exit_reason);\n exit(1);\n }\n}\n#endif\n\n#if defined(EMSCRIPTEN)\n/* with Javascript clock_gettime() is not enough precise enough to\n have a reliable TSC counter. XXX: increment the cycles during the\n power down time */\nstatic uint64_t cpu_get_tsc(void *opaque)\n{\n PCMachine *s = opaque;\n uint64_t c;\n c = x86_cpu_get_cycles(s->cpu_state);\n return c;\n}\n#else\n\n#define TSC_FREQ 100000000\n\nstatic uint64_t cpu_get_tsc(void *opaque)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * TSC_FREQ +\n (ts.tv_nsec / (1000000000 / TSC_FREQ));\n}\n#endif\n\nstatic void pc_flush_tlb_write_range(void *opaque, uint8_t *ram_addr,\n size_t ram_size)\n{\n PCMachine *s = opaque;\n x86_cpu_flush_tlb_write_range_ram(s->cpu_state, ram_addr, ram_size);\n}\n\nstatic VirtMachine *pc_machine_init(const VirtMachineParams *p)\n{\n PCMachine *s;\n int i, piix3_devfn;\n PCIBus *pci_bus;\n VIRTIOBusDef vbus_s, *vbus = &vbus_s;\n \n if (strcmp(p->machine_name, \"pc\") != 0) {\n vm_error(\"unsupported machine: %s\\n\", p->machine_name);\n return NULL;\n }\n\n assert(p->ram_size >= (1 << 20));\n\n s = mallocz(sizeof(*s));\n s->common.vmc = p->vmc;\n s->ram_size = p->ram_size;\n \n s->port_map = phys_mem_map_init();\n s->mem_map = phys_mem_map_init();\n\n#ifdef USE_KVM\n if (p->accel_enable) {\n kvm_init(s);\n }\n#endif\n\n#ifdef USE_KVM\n if (!s->kvm_enabled)\n#endif\n {\n s->cpu_state = x86_cpu_init(s->mem_map);\n x86_cpu_set_get_tsc(s->cpu_state, cpu_get_tsc, s);\n x86_cpu_set_port_io(s->cpu_state, ld_port, st_port, s);\n \n /* needed to handle the RAM dirty bits */\n s->mem_map->opaque = s;\n s->mem_map->flush_tlb_write_range = pc_flush_tlb_write_range;\n }\n\n /* set the RAM mapping and leave the VGA addresses empty */\n cpu_register_ram(s->mem_map, 0xc0000, p->ram_size - 0xc0000, 0);\n cpu_register_ram(s->mem_map, 0, 0xa0000, 0);\n \n /* devices */\n cpu_register_device(s->port_map, 0x80, 2, s, port80_read, port80_write, \n DEVIO_SIZE8);\n cpu_register_device(s->port_map, 0x92, 2, s, port92_read, port92_write, \n DEVIO_SIZE8);\n \n /* setup the bios */\n if (p->files[VM_FILE_BIOS].len > 0) {\n int bios_size, bios_size1;\n uint8_t *bios_buf, *ptr;\n uint32_t bios_addr;\n \n bios_size = p->files[VM_FILE_BIOS].len;\n bios_buf = p->files[VM_FILE_BIOS].buf;\n assert((bios_size % 65536) == 0 && bios_size != 0);\n bios_addr = -bios_size;\n /* at the top of the 4GB memory */\n cpu_register_ram(s->mem_map, bios_addr, bios_size, DEVRAM_FLAG_ROM);\n ptr = get_ram_ptr(s, bios_addr);\n memcpy(ptr, bios_buf, bios_size);\n /* in the lower 1MB memory (currently set as RAM) */\n bios_size1 = min_int(bios_size, 128 * 1024);\n ptr = get_ram_ptr(s, 0x100000 - bios_size1);\n memcpy(ptr, bios_buf + bios_size - bios_size1, bios_size1);\n#ifdef DEBUG_BIOS\n cpu_register_device(s->port_map, 0x402, 2, s,\n bios_debug_read, bios_debug_write, \n DEVIO_SIZE8);\n#endif\n }\n\n#ifdef USE_KVM\n if (!s->kvm_enabled)\n#endif\n {\n s->pic_state = pic2_init(s->port_map, 0x20, 0xa0,\n 0x4d0, 0x4d1,\n pic_set_irq_cb, s,\n s->pic_irq);\n x86_cpu_set_get_hard_intno(s->cpu_state, get_hard_intno_cb, s);\n s->pit_state = pit_init(s->port_map, 0x40, 0x61, &s->pic_irq[0],\n pit_get_ticks_cb, s);\n }\n\n s->cmos_state = cmos_init(s->port_map, 0x70, &s->pic_irq[8],\n p->rtc_local_time);\n\n /* various cmos data */\n {\n int size;\n /* memory size */\n size = min_int((s->ram_size - (1 << 20)) >> 10, 65535);\n put_le16(s->cmos_state->cmos_data + 0x30, size);\n if (s->ram_size >= (16 << 20)) {\n size = min_int((s->ram_size - (16 << 20)) >> 16, 65535);\n put_le16(s->cmos_state->cmos_data + 0x34, size);\n }\n s->cmos_state->cmos_data[0x14] = 0x06; /* mouse + FPU present */\n }\n \n s->i440fx_state = i440fx_init(&pci_bus, &piix3_devfn, s->mem_map,\n s->port_map, s->pic_irq);\n \n s->common.console = p->console;\n /* serial console */\n if (0) {\n s->serial_state = serial_init(s->port_map, 0x3f8, &s->pic_irq[4],\n serial_write_cb, s);\n }\n \n memset(vbus, 0, sizeof(*vbus));\n vbus->pci_bus = pci_bus;\n\n if (p->console) {\n /* virtio console */\n s->common.console_dev = virtio_console_init(vbus, p->console);\n }\n \n /* block devices */\n for(i = 0; i < p->drive_count;) {\n const VMDriveEntry *de = &p->tab_drive[i];\n\n if (!de->device || !strcmp(de->device, \"virtio\")) {\n virtio_block_init(vbus, p->tab_drive[i].block_dev);\n i++;\n } else if (!strcmp(de->device, \"ide\")) {\n BlockDevice *tab_bs[2];\n \n tab_bs[0] = p->tab_drive[i++].block_dev;\n tab_bs[1] = NULL;\n if (i < p->drive_count)\n tab_bs[1] = p->tab_drive[i++].block_dev;\n ide_init(s->port_map, 0x1f0, 0x3f6, &s->pic_irq[14], tab_bs);\n piix3_ide_init(pci_bus, piix3_devfn + 1);\n }\n }\n \n /* virtio filesystem */\n for(i = 0; i < p->fs_count; i++) {\n virtio_9p_init(vbus, p->tab_fs[i].fs_dev,\n p->tab_fs[i].tag);\n }\n\n if (p->display_device) {\n FBDevice *fb_dev;\n\n fb_dev = mallocz(sizeof(*fb_dev));\n s->common.fb_dev = fb_dev;\n if (!strcmp(p->display_device, \"vga\")) {\n int bios_size;\n uint8_t *bios_buf;\n bios_size = p->files[VM_FILE_VGA_BIOS].len;\n bios_buf = p->files[VM_FILE_VGA_BIOS].buf;\n pci_vga_init(pci_bus, fb_dev, p->width, p->height,\n bios_buf, bios_size);\n } else if (!strcmp(p->display_device, \"simplefb\")) {\n simplefb_init(s->mem_map,\n FRAMEBUFFER_BASE_ADDR,\n fb_dev, p->width, p->height);\n } else {\n vm_error(\"unsupported display device: %s\\n\", p->display_device);\n exit(1);\n }\n }\n\n if (p->input_device) {\n if (!strcmp(p->input_device, \"virtio\")) {\n s->keyboard_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_KEYBOARD);\n \n s->mouse_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_TABLET);\n } else if (!strcmp(p->input_device, \"ps2\")) {\n s->kbd_state = i8042_init(&s->ps2_kbd, &s->ps2_mouse,\n s->port_map,\n &s->pic_irq[1], &s->pic_irq[12], 0x60);\n /* vmmouse */\n cpu_register_device(s->port_map, 0x5658, 1, s,\n vmport_read, vmport_write, \n DEVIO_SIZE32);\n s->vm_mouse = vmmouse_init(s->ps2_mouse);\n } else {\n vm_error(\"unsupported input device: %s\\n\", p->input_device);\n exit(1);\n }\n }\n \n /* virtio net device */\n for(i = 0; i < p->eth_count; i++) {\n virtio_net_init(vbus, p->tab_eth[i].net);\n s->common.net = p->tab_eth[i].net;\n }\n\n if (p->files[VM_FILE_KERNEL].buf) {\n copy_kernel(s, p->files[VM_FILE_KERNEL].buf,\n p->files[VM_FILE_KERNEL].len,\n p->cmdline ? p->cmdline : \"\");\n }\n\n return (VirtMachine *)s;\n}\n\nstatic void pc_machine_end(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n /* XXX: free all */\n if (s->cpu_state) {\n x86_cpu_end(s->cpu_state);\n }\n phys_mem_map_end(s->mem_map);\n phys_mem_map_end(s->port_map);\n free(s);\n}\n\nstatic void pc_vm_send_key_event(VirtMachine *s1, BOOL is_down, uint16_t key_code)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->keyboard_dev) {\n virtio_input_send_key_event(s->keyboard_dev, is_down, key_code);\n } else if (s->ps2_kbd) {\n ps2_put_keycode(s->ps2_kbd, is_down, key_code);\n }\n}\n\nstatic BOOL pc_vm_mouse_is_absolute(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->mouse_dev) {\n return TRUE;\n } else if (s->vm_mouse) {\n return vmmouse_is_absolute(s->vm_mouse);\n } else {\n return FALSE;\n }\n}\n\nstatic void pc_vm_send_mouse_event(VirtMachine *s1, int dx, int dy, int dz,\n unsigned int buttons)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->mouse_dev) {\n virtio_input_send_mouse_event(s->mouse_dev, dx, dy, dz, buttons);\n } else if (s->vm_mouse) {\n vmmouse_send_mouse_event(s->vm_mouse, dx, dy, dz, buttons);\n }\n}\n\nstruct screen_info {\n} __attribute__((packed));\n\n/* from plex86 (BSD license) */\nstruct __attribute__ ((packed)) linux_params {\n /* screen_info structure */\n uint8_t orig_x;\t\t/* 0x00 */\n uint8_t orig_y;\t\t/* 0x01 */\n uint16_t ext_mem_k;\t/* 0x02 */\n uint16_t orig_video_page;\t/* 0x04 */\n uint8_t orig_video_mode;\t/* 0x06 */\n uint8_t orig_video_cols;\t/* 0x07 */\n uint8_t flags;\t\t/* 0x08 */\n uint8_t unused2;\t\t/* 0x09 */\n uint16_t orig_video_ega_bx;/* 0x0a */\n uint16_t unused3;\t\t/* 0x0c */\n uint8_t orig_video_lines;\t/* 0x0e */\n uint8_t orig_video_isVGA;\t/* 0x0f */\n uint16_t orig_video_points;/* 0x10 */\n \n /* VESA graphic mode -- linear frame buffer */\n uint16_t lfb_width;\t/* 0x12 */\n uint16_t lfb_height;\t/* 0x14 */\n uint16_t lfb_depth;\t/* 0x16 */\n uint32_t lfb_base;\t\t/* 0x18 */\n uint32_t lfb_size;\t\t/* 0x1c */\n uint16_t cl_magic, cl_offset; /* 0x20 */\n uint16_t lfb_linelength;\t/* 0x24 */\n uint8_t red_size;\t\t/* 0x26 */\n uint8_t red_pos;\t\t/* 0x27 */\n uint8_t green_size;\t/* 0x28 */\n uint8_t green_pos;\t/* 0x29 */\n uint8_t blue_size;\t/* 0x2a */\n uint8_t blue_pos;\t\t/* 0x2b */\n uint8_t rsvd_size;\t/* 0x2c */\n uint8_t rsvd_pos;\t\t/* 0x2d */\n uint16_t vesapm_seg;\t/* 0x2e */\n uint16_t vesapm_off;\t/* 0x30 */\n uint16_t pages;\t\t/* 0x32 */\n uint16_t vesa_attributes;\t/* 0x34 */\n uint32_t capabilities; /* 0x36 */\n uint32_t ext_lfb_base;\t/* 0x3a */\n uint8_t _reserved[2];\t/* 0x3e */\n \n /* 0x040 */ uint8_t apm_bios_info[20]; // struct apm_bios_info\n /* 0x054 */ uint8_t pad2[0x80 - 0x54];\n\n // Following 2 from 'struct drive_info_struct' in drivers/block/cciss.h.\n // Might be truncated?\n /* 0x080 */ uint8_t hd0_info[16]; // hd0-disk-parameter from intvector 0x41\n /* 0x090 */ uint8_t hd1_info[16]; // hd1-disk-parameter from intvector 0x46\n\n // System description table truncated to 16 bytes\n // From 'struct sys_desc_table_struct' in linux/arch/i386/kernel/setup.c.\n /* 0x0a0 */ uint16_t sys_description_len;\n /* 0x0a2 */ uint8_t sys_description_table[14];\n // [0] machine id\n // [1] machine submodel id\n // [2] BIOS revision\n // [3] bit1: MCA bus\n\n /* 0x0b0 */ uint8_t pad3[0x1e0 - 0xb0];\n /* 0x1e0 */ uint32_t alt_mem_k;\n /* 0x1e4 */ uint8_t pad4[4];\n /* 0x1e8 */ uint8_t e820map_entries;\n /* 0x1e9 */ uint8_t eddbuf_entries; // EDD_NR\n /* 0x1ea */ uint8_t pad5[0x1f1 - 0x1ea];\n /* 0x1f1 */ uint8_t setup_sects; // size of setup.S, number of sectors\n /* 0x1f2 */ uint16_t mount_root_rdonly; // MOUNT_ROOT_RDONLY (if !=0)\n /* 0x1f4 */ uint16_t sys_size; // size of compressed kernel-part in the\n // (b)zImage-file (in 16 byte units, rounded up)\n /* 0x1f6 */ uint16_t swap_dev; // (unused AFAIK)\n /* 0x1f8 */ uint16_t ramdisk_flags;\n /* 0x1fa */ uint16_t vga_mode; // (old one)\n /* 0x1fc */ uint16_t orig_root_dev; // (high=Major, low=minor)\n /* 0x1fe */ uint8_t pad6[1];\n /* 0x1ff */ uint8_t aux_device_info;\n /* 0x200 */ uint16_t jump_setup; // Jump to start of setup code,\n // aka \"reserved\" field.\n /* 0x202 */ uint8_t setup_signature[4]; // Signature for SETUP-header, =\"HdrS\"\n /* 0x206 */ uint16_t header_format_version; // Version number of header format;\n /* 0x208 */ uint8_t setup_S_temp0[8]; // Used by setup.S for communication with\n // boot loaders, look there.\n /* 0x210 */ uint8_t loader_type;\n // 0 for old one.\n // else 0xTV:\n // T=0: LILO\n // T=1: Loadlin\n // T=2: bootsect-loader\n // T=3: SYSLINUX\n // T=4: ETHERBOOT\n // V=version\n /* 0x211 */ uint8_t loadflags;\n // bit0 = 1: kernel is loaded high (bzImage)\n // bit7 = 1: Heap and pointer (see below) set by boot\n // loader.\n /* 0x212 */ uint16_t setup_S_temp1;\n /* 0x214 */ uint32_t kernel_start;\n /* 0x218 */ uint32_t initrd_start;\n /* 0x21c */ uint32_t initrd_size;\n /* 0x220 */ uint8_t setup_S_temp2[4];\n /* 0x224 */ uint16_t setup_S_heap_end_pointer;\n /* 0x226 */ uint16_t pad70;\n /* 0x228 */ uint32_t cmd_line_ptr;\n /* 0x22c */ uint8_t pad7[0x2d0 - 0x22c];\n\n /* 0x2d0 : Int 15, ax=e820 memory map. */\n // (linux/include/asm-i386/e820.h, 'struct e820entry')\n#define E820MAX 32\n#define E820_RAM 1\n#define E820_RESERVED 2\n#define E820_ACPI 3 /* usable as RAM once ACPI tables have been read */\n#define E820_NVS 4\n struct {\n uint64_t addr;\n uint64_t size;\n uint32_t type;\n } e820map[E820MAX];\n\n /* 0x550 */ uint8_t pad8[0x600 - 0x550];\n\n // BIOS Enhanced Disk Drive Services.\n // (From linux/include/asm-i386/edd.h, 'struct edd_info')\n // Each 'struct edd_info is 78 bytes, times a max of 6 structs in array.\n /* 0x600 */ uint8_t eddbuf[0x7d4 - 0x600];\n\n /* 0x7d4 */ uint8_t pad9[0x800 - 0x7d4];\n /* 0x800 */ uint8_t commandline[0x800];\n\n uint64_t gdt_table[4];\n};\n\n#define KERNEL_PARAMS_ADDR 0x00090000\n\nstatic void copy_kernel(PCMachine *s, const uint8_t *buf, int buf_len,\n const char *cmd_line)\n{\n uint8_t *ram_ptr;\n int setup_sects, header_len, copy_len, setup_hdr_start, setup_hdr_end;\n uint32_t load_address;\n struct linux_params *params;\n FBDevice *fb_dev;\n \n if (buf_len < 1024) {\n too_small:\n fprintf(stderr, \"Kernel too small\\n\");\n exit(1);\n }\n if (buf[0x1fe] != 0x55 || buf[0x1ff] != 0xaa) {\n fprintf(stderr, \"Invalid kernel magic\\n\");\n exit(1);\n }\n setup_sects = buf[0x1f1];\n if (setup_sects == 0)\n setup_sects = 4;\n header_len = (setup_sects + 1) * 512;\n if (buf_len < header_len)\n goto too_small;\n if (memcmp(buf + 0x202, \"HdrS\", 4) != 0) {\n fprintf(stderr, \"Kernel too old\\n\");\n exit(1);\n }\n load_address = 0x100000; /* we don't support older protocols */\n\n ram_ptr = get_ram_ptr(s, load_address);\n copy_len = buf_len - header_len;\n if (copy_len > (s->ram_size - load_address)) {\n fprintf(stderr, \"Not enough RAM\\n\");\n exit(1);\n }\n memcpy(ram_ptr, buf + header_len, copy_len);\n\n params = (void *)get_ram_ptr(s, KERNEL_PARAMS_ADDR);\n \n memset(params, 0, sizeof(struct linux_params));\n\n /* copy the setup header */\n setup_hdr_start = 0x1f1;\n setup_hdr_end = 0x202 + buf[0x201];\n memcpy((uint8_t *)params + setup_hdr_start, buf + setup_hdr_start,\n setup_hdr_end - setup_hdr_start);\n\n strcpy((char *)params->commandline, cmd_line);\n\n params->mount_root_rdonly = 0;\n params->cmd_line_ptr = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, commandline);\n params->alt_mem_k = (s->ram_size / 1024) - 1024;\n params->loader_type = 0x01;\n#if 0\n if (initrd_size > 0) {\n params->initrd_start = INITRD_LOAD_ADDR;\n params->initrd_size = initrd_size;\n }\n#endif\n params->orig_video_lines = 0;\n params->orig_video_cols = 0;\n\n fb_dev = s->common.fb_dev;\n if (fb_dev) {\n \n params->orig_video_isVGA = 0x23; /* VIDEO_TYPE_VLFB */\n\n params->lfb_depth = 32;\n params->red_size = 8;\n params->red_pos = 16;\n params->green_size = 8;\n params->green_pos = 8;\n params->blue_size = 8;\n params->blue_pos = 0;\n params->rsvd_size = 8;\n params->rsvd_pos = 24;\n\n params->lfb_width = fb_dev->width;\n params->lfb_height = fb_dev->height;\n params->lfb_linelength = fb_dev->stride;\n params->lfb_size = fb_dev->fb_size;\n params->lfb_base = FRAMEBUFFER_BASE_ADDR;\n }\n \n params->gdt_table[2] = 0x00cf9b000000ffffLL; /* CS */\n params->gdt_table[3] = 0x00cf93000000ffffLL; /* DS */\n \n#ifdef USE_KVM\n if (s->kvm_enabled) {\n struct kvm_sregs sregs;\n struct kvm_segment seg;\n struct kvm_regs regs;\n \n /* init flat protected mode */\n\n if (ioctl(s->vcpu_fd, KVM_GET_SREGS, &sregs) < 0) {\n perror(\"KVM_GET_SREGS\");\n exit(1);\n }\n\n sregs.cr0 |= (1 << 0); /* CR0_PE */\n sregs.gdt.base = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, gdt_table);\n sregs.gdt.limit = sizeof(params->gdt_table) - 1;\n \n memset(&seg, 0, sizeof(seg));\n seg.limit = 0xffffffff;\n seg.present = 1;\n seg.db = 1;\n seg.s = 1; /* code/data */\n seg.g = 1; /* 4KB granularity */\n\n seg.type = 0xb; /* code */\n seg.selector = 2 << 3;\n sregs.cs = seg;\n\n seg.type = 0x3; /* data */\n seg.selector = 3 << 3;\n sregs.ds = seg;\n sregs.es = seg;\n sregs.ss = seg;\n sregs.fs = seg;\n sregs.gs = seg;\n \n if (ioctl(s->vcpu_fd, KVM_SET_SREGS, &sregs) < 0) {\n perror(\"KVM_SET_SREGS\");\n exit(1);\n }\n \n memset(®s, 0, sizeof(regs));\n regs.rip = load_address;\n regs.rsi = KERNEL_PARAMS_ADDR;\n regs.rflags = 0x2;\n if (ioctl(s->vcpu_fd, KVM_SET_REGS, ®s) < 0) {\n perror(\"KVM_SET_REGS\");\n exit(1);\n }\n } else\n#endif\n {\n int i;\n X86CPUSeg sd;\n uint32_t val;\n val = x86_cpu_get_reg(s->cpu_state, X86_CPU_REG_CR0);\n x86_cpu_set_reg(s->cpu_state, X86_CPU_REG_CR0, val | (1 << 0));\n \n sd.base = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, gdt_table);\n sd.limit = sizeof(params->gdt_table) - 1;\n x86_cpu_set_seg(s->cpu_state, X86_CPU_SEG_GDT, &sd);\n sd.sel = 2 << 3;\n sd.base = 0;\n sd.limit = 0xffffffff;\n sd.flags = 0xc09b;\n x86_cpu_set_seg(s->cpu_state, X86_CPU_SEG_CS, &sd);\n sd.sel = 3 << 3;\n sd.flags = 0xc093;\n for(i = 0; i < 6; i++) {\n if (i != X86_CPU_SEG_CS) {\n x86_cpu_set_seg(s->cpu_state, i, &sd);\n }\n }\n \n x86_cpu_set_reg(s->cpu_state, X86_CPU_REG_EIP, load_address);\n x86_cpu_set_reg(s->cpu_state, 6, KERNEL_PARAMS_ADDR); /* esi */\n }\n\n /* map PCI interrupts (no BIOS, so we must do it) */\n {\n uint8_t elcr[2];\n static const uint8_t pci_irqs[4] = { 9, 10, 11, 12 };\n\n i440fx_map_interrupts(s->i440fx_state, elcr, pci_irqs);\n /* XXX: KVM support */\n if (s->pic_state) {\n pic2_set_elcr(s->pic_state, elcr);\n }\n }\n}\n\n/* in ms */\nstatic int pc_machine_get_sleep_duration(VirtMachine *s1, int delay)\n{\n PCMachine *s = (PCMachine *)s1;\n\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n /* XXX: improve */\n cmos_update_irq(s->cmos_state);\n delay = 0;\n } else\n#endif\n {\n cmos_update_irq(s->cmos_state);\n delay = min_int(delay, pit_update_irq(s->pit_state));\n if (!x86_cpu_get_power_down(s->cpu_state))\n delay = 0;\n }\n return delay;\n}\n\nstatic void pc_machine_interp(VirtMachine *s1, int max_exec_cycles)\n{\n PCMachine *s = (PCMachine *)s1;\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n kvm_exec(s);\n } else \n#endif\n {\n x86_cpu_interp(s->cpu_state, max_exec_cycles);\n }\n}\n\nconst VirtMachineClass pc_machine_class = {\n \"pc\",\n pc_machine_set_defaults,\n pc_machine_init,\n pc_machine_end,\n pc_machine_get_sleep_duration,\n pc_machine_interp,\n pc_vm_mouse_is_absolute,\n pc_vm_send_mouse_event,\n pc_vm_send_key_event,\n};\n"], ["/linuxpdf/tinyemu/riscv_machine.c", "/*\n * RISCV machine\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"riscv_cpu.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n/* RISCV machine */\n\ntypedef struct RISCVMachine {\n VirtMachine common;\n PhysMemoryMap *mem_map;\n int max_xlen;\n RISCVCPUState *cpu_state;\n uint64_t ram_size;\n /* RTC */\n BOOL rtc_real_time;\n uint64_t rtc_start_time;\n uint64_t timecmp;\n /* PLIC */\n uint32_t plic_pending_irq, plic_served_irq;\n IRQSignal plic_irq[32]; /* IRQ 0 is not used */\n /* HTIF */\n uint64_t htif_tohost, htif_fromhost;\n\n VIRTIODevice *keyboard_dev;\n VIRTIODevice *mouse_dev;\n\n int virtio_count;\n} RISCVMachine;\n\n#define LOW_RAM_SIZE 0x00010000 /* 64KB */\n#define RAM_BASE_ADDR 0x80000000\n#define CLINT_BASE_ADDR 0x02000000\n#define CLINT_SIZE 0x000c0000\n#define HTIF_BASE_ADDR 0x40008000\n#define IDE_BASE_ADDR 0x40009000\n#define VIRTIO_BASE_ADDR 0x40010000\n#define VIRTIO_SIZE 0x1000\n#define VIRTIO_IRQ 1\n#define PLIC_BASE_ADDR 0x40100000\n#define PLIC_SIZE 0x00400000\n#define FRAMEBUFFER_BASE_ADDR 0x41000000\n\n#define RTC_FREQ 10000000\n#define RTC_FREQ_DIV 16 /* arbitrary, relative to CPU freq to have a\n 10 MHz frequency */\n\nstatic uint64_t rtc_get_real_time(RISCVMachine *s)\n{\n struct timespec ts;\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * RTC_FREQ +\n (ts.tv_nsec / (1000000000 / RTC_FREQ));\n}\n\nstatic uint64_t rtc_get_time(RISCVMachine *m)\n{\n uint64_t val;\n if (m->rtc_real_time) {\n val = rtc_get_real_time(m) - m->rtc_start_time;\n } else {\n val = riscv_cpu_get_cycles(m->cpu_state) / RTC_FREQ_DIV;\n }\n // printf(\"rtc_time=%\" PRId64 \"\\n\", val);\n return val;\n}\n\nstatic uint32_t htif_read(void *opaque, uint32_t offset,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n uint32_t val;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0:\n val = s->htif_tohost;\n break;\n case 4:\n val = s->htif_tohost >> 32;\n break;\n case 8:\n val = s->htif_fromhost;\n break;\n case 12:\n val = s->htif_fromhost >> 32;\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n\nstatic void htif_handle_cmd(RISCVMachine *s)\n{\n uint32_t device, cmd;\n\n device = s->htif_tohost >> 56;\n cmd = (s->htif_tohost >> 48) & 0xff;\n if (s->htif_tohost == 1) {\n /* shuthost */\n printf(\"\\nPower off.\\n\");\n exit(0);\n } else if (device == 1 && cmd == 1) {\n uint8_t buf[1];\n buf[0] = s->htif_tohost & 0xff;\n s->common.console->write_data(s->common.console->opaque, buf, 1);\n s->htif_tohost = 0;\n s->htif_fromhost = ((uint64_t)device << 56) | ((uint64_t)cmd << 48);\n } else if (device == 1 && cmd == 0) {\n /* request keyboard interrupt */\n s->htif_tohost = 0;\n } else {\n printf(\"HTIF: unsupported tohost=0x%016\" PRIx64 \"\\n\", s->htif_tohost);\n }\n}\n\nstatic void htif_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0:\n s->htif_tohost = (s->htif_tohost & ~0xffffffff) | val;\n break;\n case 4:\n s->htif_tohost = (s->htif_tohost & 0xffffffff) | ((uint64_t)val << 32);\n htif_handle_cmd(s);\n break;\n case 8:\n s->htif_fromhost = (s->htif_fromhost & ~0xffffffff) | val;\n break;\n case 12:\n s->htif_fromhost = (s->htif_fromhost & 0xffffffff) |\n (uint64_t)val << 32;\n break;\n default:\n break;\n }\n}\n\n#if 0\nstatic void htif_poll(RISCVMachine *s)\n{\n uint8_t buf[1];\n int ret;\n\n if (s->htif_fromhost == 0) {\n ret = s->console->read_data(s->console->opaque, buf, 1);\n if (ret == 1) {\n s->htif_fromhost = ((uint64_t)1 << 56) | ((uint64_t)0 << 48) |\n buf[0];\n }\n }\n}\n#endif\n\nstatic uint32_t clint_read(void *opaque, uint32_t offset, int size_log2)\n{\n RISCVMachine *m = opaque;\n uint32_t val;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0xbff8:\n val = rtc_get_time(m);\n break;\n case 0xbffc:\n val = rtc_get_time(m) >> 32;\n break;\n case 0x4000:\n val = m->timecmp;\n break;\n case 0x4004:\n val = m->timecmp >> 32;\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n \nstatic void clint_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *m = opaque;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0x4000:\n m->timecmp = (m->timecmp & ~0xffffffff) | val;\n riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP);\n break;\n case 0x4004:\n m->timecmp = (m->timecmp & 0xffffffff) | ((uint64_t)val << 32);\n riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP);\n break;\n default:\n break;\n }\n}\n\nstatic void plic_update_mip(RISCVMachine *s)\n{\n RISCVCPUState *cpu = s->cpu_state;\n uint32_t mask;\n mask = s->plic_pending_irq & ~s->plic_served_irq;\n if (mask) {\n riscv_cpu_set_mip(cpu, MIP_MEIP | MIP_SEIP);\n } else {\n riscv_cpu_reset_mip(cpu, MIP_MEIP | MIP_SEIP);\n }\n}\n\n#define PLIC_HART_BASE 0x200000\n#define PLIC_HART_SIZE 0x1000\n\nstatic uint32_t plic_read(void *opaque, uint32_t offset, int size_log2)\n{\n RISCVMachine *s = opaque;\n uint32_t val, mask;\n int i;\n assert(size_log2 == 2);\n switch(offset) {\n case PLIC_HART_BASE:\n val = 0;\n break;\n case PLIC_HART_BASE + 4:\n mask = s->plic_pending_irq & ~s->plic_served_irq;\n if (mask != 0) {\n i = ctz32(mask);\n s->plic_served_irq |= 1 << i;\n plic_update_mip(s);\n val = i + 1;\n } else {\n val = 0;\n }\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n\nstatic void plic_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n \n assert(size_log2 == 2);\n switch(offset) {\n case PLIC_HART_BASE + 4:\n val--;\n if (val < 32) {\n s->plic_served_irq &= ~(1 << val);\n plic_update_mip(s);\n }\n break;\n default:\n break;\n }\n}\n\nstatic void plic_set_irq(void *opaque, int irq_num, int state)\n{\n RISCVMachine *s = opaque;\n uint32_t mask;\n\n mask = 1 << (irq_num - 1);\n if (state) \n s->plic_pending_irq |= mask;\n else\n s->plic_pending_irq &= ~mask;\n plic_update_mip(s);\n}\n\nstatic uint8_t *get_ram_ptr(RISCVMachine *s, uint64_t paddr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(s->mem_map, paddr, is_rw);\n}\n\n/* FDT machine description */\n\n#define FDT_MAGIC\t0xd00dfeed\n#define FDT_VERSION\t17\n\nstruct fdt_header {\n uint32_t magic;\n uint32_t totalsize;\n uint32_t off_dt_struct;\n uint32_t off_dt_strings;\n uint32_t off_mem_rsvmap;\n uint32_t version;\n uint32_t last_comp_version; /* <= 17 */\n uint32_t boot_cpuid_phys;\n uint32_t size_dt_strings;\n uint32_t size_dt_struct;\n};\n\nstruct fdt_reserve_entry {\n uint64_t address;\n uint64_t size;\n};\n\n#define FDT_BEGIN_NODE\t1\n#define FDT_END_NODE\t2\n#define FDT_PROP\t3\n#define FDT_NOP\t\t4\n#define FDT_END\t\t9\n\ntypedef struct {\n uint32_t *tab;\n int tab_len;\n int tab_size;\n int open_node_count;\n \n char *string_table;\n int string_table_len;\n int string_table_size;\n} FDTState;\n\nstatic FDTState *fdt_init(void)\n{\n FDTState *s;\n s = mallocz(sizeof(*s));\n return s;\n}\n\nstatic void fdt_alloc_len(FDTState *s, int len)\n{\n int new_size;\n if (unlikely(len > s->tab_size)) {\n new_size = max_int(len, s->tab_size * 3 / 2);\n s->tab = realloc(s->tab, new_size * sizeof(uint32_t));\n s->tab_size = new_size;\n }\n}\n\nstatic void fdt_put32(FDTState *s, int v)\n{\n fdt_alloc_len(s, s->tab_len + 1);\n s->tab[s->tab_len++] = cpu_to_be32(v);\n}\n\n/* the data is zero padded */\nstatic void fdt_put_data(FDTState *s, const uint8_t *data, int len)\n{\n int len1;\n \n len1 = (len + 3) / 4;\n fdt_alloc_len(s, s->tab_len + len1);\n memcpy(s->tab + s->tab_len, data, len);\n memset((uint8_t *)(s->tab + s->tab_len) + len, 0, -len & 3);\n s->tab_len += len1;\n}\n\nstatic void fdt_begin_node(FDTState *s, const char *name)\n{\n fdt_put32(s, FDT_BEGIN_NODE);\n fdt_put_data(s, (uint8_t *)name, strlen(name) + 1);\n s->open_node_count++;\n}\n\nstatic void fdt_begin_node_num(FDTState *s, const char *name, uint64_t n)\n{\n char buf[256];\n snprintf(buf, sizeof(buf), \"%s@%\" PRIx64, name, n);\n fdt_begin_node(s, buf);\n}\n\nstatic void fdt_end_node(FDTState *s)\n{\n fdt_put32(s, FDT_END_NODE);\n s->open_node_count--;\n}\n\nstatic int fdt_get_string_offset(FDTState *s, const char *name)\n{\n int pos, new_size, name_size, new_len;\n\n pos = 0;\n while (pos < s->string_table_len) {\n if (!strcmp(s->string_table + pos, name))\n return pos;\n pos += strlen(s->string_table + pos) + 1;\n }\n /* add a new string */\n name_size = strlen(name) + 1;\n new_len = s->string_table_len + name_size;\n if (new_len > s->string_table_size) {\n new_size = max_int(new_len, s->string_table_size * 3 / 2);\n s->string_table = realloc(s->string_table, new_size);\n s->string_table_size = new_size;\n }\n pos = s->string_table_len;\n memcpy(s->string_table + pos, name, name_size);\n s->string_table_len = new_len;\n return pos;\n}\n\nstatic void fdt_prop(FDTState *s, const char *prop_name,\n const void *data, int data_len)\n{\n fdt_put32(s, FDT_PROP);\n fdt_put32(s, data_len);\n fdt_put32(s, fdt_get_string_offset(s, prop_name));\n fdt_put_data(s, data, data_len);\n}\n\nstatic void fdt_prop_tab_u32(FDTState *s, const char *prop_name,\n uint32_t *tab, int tab_len)\n{\n int i;\n fdt_put32(s, FDT_PROP);\n fdt_put32(s, tab_len * sizeof(uint32_t));\n fdt_put32(s, fdt_get_string_offset(s, prop_name));\n for(i = 0; i < tab_len; i++)\n fdt_put32(s, tab[i]);\n}\n\nstatic void fdt_prop_u32(FDTState *s, const char *prop_name, uint32_t val)\n{\n fdt_prop_tab_u32(s, prop_name, &val, 1);\n}\n\nstatic void fdt_prop_tab_u64(FDTState *s, const char *prop_name,\n uint64_t v0)\n{\n uint32_t tab[2];\n tab[0] = v0 >> 32;\n tab[1] = v0;\n fdt_prop_tab_u32(s, prop_name, tab, 2);\n}\n\nstatic void fdt_prop_tab_u64_2(FDTState *s, const char *prop_name,\n uint64_t v0, uint64_t v1)\n{\n uint32_t tab[4];\n tab[0] = v0 >> 32;\n tab[1] = v0;\n tab[2] = v1 >> 32;\n tab[3] = v1;\n fdt_prop_tab_u32(s, prop_name, tab, 4);\n}\n\nstatic void fdt_prop_str(FDTState *s, const char *prop_name,\n const char *str)\n{\n fdt_prop(s, prop_name, str, strlen(str) + 1);\n}\n\n/* NULL terminated string list */\nstatic void fdt_prop_tab_str(FDTState *s, const char *prop_name,\n ...)\n{\n va_list ap;\n int size, str_size;\n char *ptr, *tab;\n\n va_start(ap, prop_name);\n size = 0;\n for(;;) {\n ptr = va_arg(ap, char *);\n if (!ptr)\n break;\n str_size = strlen(ptr) + 1;\n size += str_size;\n }\n va_end(ap);\n \n tab = malloc(size);\n va_start(ap, prop_name);\n size = 0;\n for(;;) {\n ptr = va_arg(ap, char *);\n if (!ptr)\n break;\n str_size = strlen(ptr) + 1;\n memcpy(tab + size, ptr, str_size);\n size += str_size;\n }\n va_end(ap);\n \n fdt_prop(s, prop_name, tab, size);\n free(tab);\n}\n\n/* write the FDT to 'dst1'. return the FDT size in bytes */\nint fdt_output(FDTState *s, uint8_t *dst)\n{\n struct fdt_header *h;\n struct fdt_reserve_entry *re;\n int dt_struct_size;\n int dt_strings_size;\n int pos;\n\n assert(s->open_node_count == 0);\n \n fdt_put32(s, FDT_END);\n \n dt_struct_size = s->tab_len * sizeof(uint32_t);\n dt_strings_size = s->string_table_len;\n\n h = (struct fdt_header *)dst;\n h->magic = cpu_to_be32(FDT_MAGIC);\n h->version = cpu_to_be32(FDT_VERSION);\n h->last_comp_version = cpu_to_be32(16);\n h->boot_cpuid_phys = cpu_to_be32(0);\n h->size_dt_strings = cpu_to_be32(dt_strings_size);\n h->size_dt_struct = cpu_to_be32(dt_struct_size);\n\n pos = sizeof(struct fdt_header);\n\n h->off_dt_struct = cpu_to_be32(pos);\n memcpy(dst + pos, s->tab, dt_struct_size);\n pos += dt_struct_size;\n\n /* align to 8 */\n while ((pos & 7) != 0) {\n dst[pos++] = 0;\n }\n h->off_mem_rsvmap = cpu_to_be32(pos);\n re = (struct fdt_reserve_entry *)(dst + pos);\n re->address = 0; /* no reserved entry */\n re->size = 0;\n pos += sizeof(struct fdt_reserve_entry);\n\n h->off_dt_strings = cpu_to_be32(pos);\n memcpy(dst + pos, s->string_table, dt_strings_size);\n pos += dt_strings_size;\n\n /* align to 8, just in case */\n while ((pos & 7) != 0) {\n dst[pos++] = 0;\n }\n\n h->totalsize = cpu_to_be32(pos);\n return pos;\n}\n\nvoid fdt_end(FDTState *s)\n{\n free(s->tab);\n free(s->string_table);\n free(s);\n}\n\nstatic int riscv_build_fdt(RISCVMachine *m, uint8_t *dst,\n uint64_t kernel_start, uint64_t kernel_size,\n uint64_t initrd_start, uint64_t initrd_size,\n const char *cmd_line)\n{\n FDTState *s;\n int size, max_xlen, i, cur_phandle, intc_phandle, plic_phandle;\n char isa_string[128], *q;\n uint32_t misa;\n uint32_t tab[4];\n FBDevice *fb_dev;\n \n s = fdt_init();\n\n cur_phandle = 1;\n \n fdt_begin_node(s, \"\");\n fdt_prop_u32(s, \"#address-cells\", 2);\n fdt_prop_u32(s, \"#size-cells\", 2);\n fdt_prop_str(s, \"compatible\", \"ucbbar,riscvemu-bar_dev\");\n fdt_prop_str(s, \"model\", \"ucbbar,riscvemu-bare\");\n\n /* CPU list */\n fdt_begin_node(s, \"cpus\");\n fdt_prop_u32(s, \"#address-cells\", 1);\n fdt_prop_u32(s, \"#size-cells\", 0);\n fdt_prop_u32(s, \"timebase-frequency\", RTC_FREQ);\n\n /* cpu */\n fdt_begin_node_num(s, \"cpu\", 0);\n fdt_prop_str(s, \"device_type\", \"cpu\");\n fdt_prop_u32(s, \"reg\", 0);\n fdt_prop_str(s, \"status\", \"okay\");\n fdt_prop_str(s, \"compatible\", \"riscv\");\n\n max_xlen = m->max_xlen;\n misa = riscv_cpu_get_misa(m->cpu_state);\n q = isa_string;\n q += snprintf(isa_string, sizeof(isa_string), \"rv%d\", max_xlen);\n for(i = 0; i < 26; i++) {\n if (misa & (1 << i))\n *q++ = 'a' + i;\n }\n *q = '\\0';\n fdt_prop_str(s, \"riscv,isa\", isa_string);\n \n fdt_prop_str(s, \"mmu-type\", max_xlen <= 32 ? \"riscv,sv32\" : \"riscv,sv48\");\n fdt_prop_u32(s, \"clock-frequency\", 2000000000);\n\n fdt_begin_node(s, \"interrupt-controller\");\n fdt_prop_u32(s, \"#interrupt-cells\", 1);\n fdt_prop(s, \"interrupt-controller\", NULL, 0);\n fdt_prop_str(s, \"compatible\", \"riscv,cpu-intc\");\n intc_phandle = cur_phandle++;\n fdt_prop_u32(s, \"phandle\", intc_phandle);\n fdt_end_node(s); /* interrupt-controller */\n \n fdt_end_node(s); /* cpu */\n \n fdt_end_node(s); /* cpus */\n\n fdt_begin_node_num(s, \"memory\", RAM_BASE_ADDR);\n fdt_prop_str(s, \"device_type\", \"memory\");\n tab[0] = (uint64_t)RAM_BASE_ADDR >> 32;\n tab[1] = RAM_BASE_ADDR;\n tab[2] = m->ram_size >> 32;\n tab[3] = m->ram_size;\n fdt_prop_tab_u32(s, \"reg\", tab, 4);\n \n fdt_end_node(s); /* memory */\n\n fdt_begin_node(s, \"htif\");\n fdt_prop_str(s, \"compatible\", \"ucb,htif0\");\n fdt_end_node(s); /* htif */\n\n fdt_begin_node(s, \"soc\");\n fdt_prop_u32(s, \"#address-cells\", 2);\n fdt_prop_u32(s, \"#size-cells\", 2);\n fdt_prop_tab_str(s, \"compatible\",\n \"ucbbar,riscvemu-bar-soc\", \"simple-bus\", NULL);\n fdt_prop(s, \"ranges\", NULL, 0);\n\n fdt_begin_node_num(s, \"clint\", CLINT_BASE_ADDR);\n fdt_prop_str(s, \"compatible\", \"riscv,clint0\");\n\n tab[0] = intc_phandle;\n tab[1] = 3; /* M IPI irq */\n tab[2] = intc_phandle;\n tab[3] = 7; /* M timer irq */\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 4);\n\n fdt_prop_tab_u64_2(s, \"reg\", CLINT_BASE_ADDR, CLINT_SIZE);\n \n fdt_end_node(s); /* clint */\n\n fdt_begin_node_num(s, \"plic\", PLIC_BASE_ADDR);\n fdt_prop_u32(s, \"#interrupt-cells\", 1);\n fdt_prop(s, \"interrupt-controller\", NULL, 0);\n fdt_prop_str(s, \"compatible\", \"riscv,plic0\");\n fdt_prop_u32(s, \"riscv,ndev\", 31);\n fdt_prop_tab_u64_2(s, \"reg\", PLIC_BASE_ADDR, PLIC_SIZE);\n\n tab[0] = intc_phandle;\n tab[1] = 9; /* S ext irq */\n tab[2] = intc_phandle;\n tab[3] = 11; /* M ext irq */\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 4);\n\n plic_phandle = cur_phandle++;\n fdt_prop_u32(s, \"phandle\", plic_phandle);\n\n fdt_end_node(s); /* plic */\n \n for(i = 0; i < m->virtio_count; i++) {\n fdt_begin_node_num(s, \"virtio\", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE);\n fdt_prop_str(s, \"compatible\", \"virtio,mmio\");\n fdt_prop_tab_u64_2(s, \"reg\", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE,\n VIRTIO_SIZE);\n tab[0] = plic_phandle;\n tab[1] = VIRTIO_IRQ + i;\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 2);\n fdt_end_node(s); /* virtio */\n }\n\n fb_dev = m->common.fb_dev;\n if (fb_dev) {\n fdt_begin_node_num(s, \"framebuffer\", FRAMEBUFFER_BASE_ADDR);\n fdt_prop_str(s, \"compatible\", \"simple-framebuffer\");\n fdt_prop_tab_u64_2(s, \"reg\", FRAMEBUFFER_BASE_ADDR, fb_dev->fb_size);\n fdt_prop_u32(s, \"width\", fb_dev->width);\n fdt_prop_u32(s, \"height\", fb_dev->height);\n fdt_prop_u32(s, \"stride\", fb_dev->stride);\n fdt_prop_str(s, \"format\", \"a8r8g8b8\");\n fdt_end_node(s); /* framebuffer */\n }\n \n fdt_end_node(s); /* soc */\n\n fdt_begin_node(s, \"chosen\");\n fdt_prop_str(s, \"bootargs\", cmd_line ? cmd_line : \"\");\n if (kernel_size > 0) {\n fdt_prop_tab_u64(s, \"riscv,kernel-start\", kernel_start);\n fdt_prop_tab_u64(s, \"riscv,kernel-end\", kernel_start + kernel_size);\n }\n if (initrd_size > 0) {\n fdt_prop_tab_u64(s, \"linux,initrd-start\", initrd_start);\n fdt_prop_tab_u64(s, \"linux,initrd-end\", initrd_start + initrd_size);\n }\n \n\n fdt_end_node(s); /* chosen */\n \n fdt_end_node(s); /* / */\n\n size = fdt_output(s, dst);\n#if 0\n {\n FILE *f;\n f = fopen(\"/tmp/riscvemu.dtb\", \"wb\");\n fwrite(dst, 1, size, f);\n fclose(f);\n }\n#endif\n fdt_end(s);\n return size;\n}\n\nstatic void copy_bios(RISCVMachine *s, const uint8_t *buf, int buf_len,\n const uint8_t *kernel_buf, int kernel_buf_len,\n const uint8_t *initrd_buf, int initrd_buf_len,\n const char *cmd_line)\n{\n uint32_t fdt_addr, align, kernel_base, initrd_base;\n uint8_t *ram_ptr;\n uint32_t *q;\n\n if (buf_len > s->ram_size) {\n vm_error(\"BIOS too big\\n\");\n exit(1);\n }\n\n ram_ptr = get_ram_ptr(s, RAM_BASE_ADDR, TRUE);\n memcpy(ram_ptr, buf, buf_len);\n\n kernel_base = 0;\n if (kernel_buf_len > 0) {\n /* copy the kernel if present */\n if (s->max_xlen == 32)\n align = 4 << 20; /* 4 MB page align */\n else\n align = 2 << 20; /* 2 MB page align */\n kernel_base = (buf_len + align - 1) & ~(align - 1);\n memcpy(ram_ptr + kernel_base, kernel_buf, kernel_buf_len);\n if (kernel_buf_len + kernel_base > s->ram_size) {\n vm_error(\"kernel too big\");\n exit(1);\n }\n }\n\n initrd_base = 0;\n if (initrd_buf_len > 0) {\n /* same allocation as QEMU */\n initrd_base = s->ram_size / 2;\n if (initrd_base > (128 << 20))\n initrd_base = 128 << 20;\n memcpy(ram_ptr + initrd_base, initrd_buf, initrd_buf_len);\n if (initrd_buf_len + initrd_base > s->ram_size) {\n vm_error(\"initrd too big\");\n exit(1);\n }\n }\n \n ram_ptr = get_ram_ptr(s, 0, TRUE);\n \n fdt_addr = 0x1000 + 8 * 8;\n\n riscv_build_fdt(s, ram_ptr + fdt_addr,\n RAM_BASE_ADDR + kernel_base, kernel_buf_len,\n RAM_BASE_ADDR + initrd_base, initrd_buf_len,\n cmd_line);\n\n /* jump_addr = 0x80000000 */\n \n q = (uint32_t *)(ram_ptr + 0x1000);\n q[0] = 0x297 + 0x80000000 - 0x1000; /* auipc t0, jump_addr */\n q[1] = 0x597; /* auipc a1, dtb */\n q[2] = 0x58593 + ((fdt_addr - 4) << 20); /* addi a1, a1, dtb */\n q[3] = 0xf1402573; /* csrr a0, mhartid */\n q[4] = 0x00028067; /* jalr zero, t0, jump_addr */\n}\n\nstatic void riscv_flush_tlb_write_range(void *opaque, uint8_t *ram_addr,\n size_t ram_size)\n{\n RISCVMachine *s = opaque;\n riscv_cpu_flush_tlb_write_range_ram(s->cpu_state, ram_addr, ram_size);\n}\n\nstatic void riscv_machine_set_defaults(VirtMachineParams *p)\n{\n}\n\nstatic VirtMachine *riscv_machine_init(const VirtMachineParams *p)\n{\n RISCVMachine *s;\n VIRTIODevice *blk_dev;\n int irq_num, i, max_xlen, ram_flags;\n VIRTIOBusDef vbus_s, *vbus = &vbus_s;\n\n\n if (!strcmp(p->machine_name, \"riscv32\")) {\n max_xlen = 32;\n } else if (!strcmp(p->machine_name, \"riscv64\")) {\n max_xlen = 64;\n } else if (!strcmp(p->machine_name, \"riscv128\")) {\n max_xlen = 128;\n } else {\n vm_error(\"unsupported machine: %s\\n\", p->machine_name);\n return NULL;\n }\n \n s = mallocz(sizeof(*s));\n s->common.vmc = p->vmc;\n s->ram_size = p->ram_size;\n s->max_xlen = max_xlen;\n s->mem_map = phys_mem_map_init();\n /* needed to handle the RAM dirty bits */\n s->mem_map->opaque = s;\n s->mem_map->flush_tlb_write_range = riscv_flush_tlb_write_range;\n\n s->cpu_state = riscv_cpu_init(s->mem_map, max_xlen);\n if (!s->cpu_state) {\n vm_error(\"unsupported max_xlen=%d\\n\", max_xlen);\n /* XXX: should free resources */\n return NULL;\n }\n /* RAM */\n ram_flags = 0;\n cpu_register_ram(s->mem_map, RAM_BASE_ADDR, p->ram_size, ram_flags);\n cpu_register_ram(s->mem_map, 0x00000000, LOW_RAM_SIZE, 0);\n s->rtc_real_time = p->rtc_real_time;\n if (p->rtc_real_time) {\n s->rtc_start_time = rtc_get_real_time(s);\n }\n \n cpu_register_device(s->mem_map, CLINT_BASE_ADDR, CLINT_SIZE, s,\n clint_read, clint_write, DEVIO_SIZE32);\n cpu_register_device(s->mem_map, PLIC_BASE_ADDR, PLIC_SIZE, s,\n plic_read, plic_write, DEVIO_SIZE32);\n for(i = 1; i < 32; i++) {\n irq_init(&s->plic_irq[i], plic_set_irq, s, i);\n }\n\n cpu_register_device(s->mem_map, HTIF_BASE_ADDR, 16,\n s, htif_read, htif_write, DEVIO_SIZE32);\n s->common.console = p->console;\n\n memset(vbus, 0, sizeof(*vbus));\n vbus->mem_map = s->mem_map;\n vbus->addr = VIRTIO_BASE_ADDR;\n irq_num = VIRTIO_IRQ;\n \n /* virtio console */\n if (p->console) {\n vbus->irq = &s->plic_irq[irq_num];\n s->common.console_dev = virtio_console_init(vbus, p->console);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n \n /* virtio net device */\n for(i = 0; i < p->eth_count; i++) {\n vbus->irq = &s->plic_irq[irq_num];\n virtio_net_init(vbus, p->tab_eth[i].net);\n s->common.net = p->tab_eth[i].net;\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n /* virtio block device */\n for(i = 0; i < p->drive_count; i++) {\n vbus->irq = &s->plic_irq[irq_num];\n blk_dev = virtio_block_init(vbus, p->tab_drive[i].block_dev);\n (void)blk_dev;\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n /* virtio filesystem */\n for(i = 0; i < p->fs_count; i++) {\n VIRTIODevice *fs_dev;\n vbus->irq = &s->plic_irq[irq_num];\n fs_dev = virtio_9p_init(vbus, p->tab_fs[i].fs_dev,\n p->tab_fs[i].tag);\n (void)fs_dev;\n // virtio_set_debug(fs_dev, VIRTIO_DEBUG_9P);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n if (p->display_device) {\n FBDevice *fb_dev;\n fb_dev = mallocz(sizeof(*fb_dev));\n s->common.fb_dev = fb_dev;\n if (!strcmp(p->display_device, \"simplefb\")) {\n simplefb_init(s->mem_map,\n FRAMEBUFFER_BASE_ADDR,\n fb_dev,\n p->width, p->height);\n \n } else {\n vm_error(\"unsupported display device: %s\\n\", p->display_device);\n exit(1);\n }\n }\n\n if (p->input_device) {\n if (!strcmp(p->input_device, \"virtio\")) {\n vbus->irq = &s->plic_irq[irq_num];\n s->keyboard_dev = virtio_input_init(vbus,\n VIRTIO_INPUT_TYPE_KEYBOARD);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n\n vbus->irq = &s->plic_irq[irq_num];\n s->mouse_dev = virtio_input_init(vbus,\n VIRTIO_INPUT_TYPE_TABLET);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n } else {\n vm_error(\"unsupported input device: %s\\n\", p->input_device);\n exit(1);\n }\n }\n \n if (!p->files[VM_FILE_BIOS].buf) {\n vm_error(\"No bios found\");\n }\n\n copy_bios(s, p->files[VM_FILE_BIOS].buf, p->files[VM_FILE_BIOS].len,\n p->files[VM_FILE_KERNEL].buf, p->files[VM_FILE_KERNEL].len,\n p->files[VM_FILE_INITRD].buf, p->files[VM_FILE_INITRD].len,\n p->cmdline);\n \n return (VirtMachine *)s;\n}\n\nstatic void riscv_machine_end(VirtMachine *s1)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n /* XXX: stop all */\n riscv_cpu_end(s->cpu_state);\n phys_mem_map_end(s->mem_map);\n free(s);\n}\n\n/* in ms */\nstatic int riscv_machine_get_sleep_duration(VirtMachine *s1, int delay)\n{\n RISCVMachine *m = (RISCVMachine *)s1;\n RISCVCPUState *s = m->cpu_state;\n int64_t delay1;\n \n /* wait for an event: the only asynchronous event is the RTC timer */\n if (!(riscv_cpu_get_mip(s) & MIP_MTIP)) {\n delay1 = m->timecmp - rtc_get_time(m);\n if (delay1 <= 0) {\n riscv_cpu_set_mip(s, MIP_MTIP);\n delay = 0;\n } else {\n /* convert delay to ms */\n delay1 = delay1 / (RTC_FREQ / 1000);\n if (delay1 < delay)\n delay = delay1;\n }\n }\n if (!riscv_cpu_get_power_down(s))\n delay = 0;\n return delay;\n}\n\nstatic void riscv_machine_interp(VirtMachine *s1, int max_exec_cycle)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n riscv_cpu_interp(s->cpu_state, max_exec_cycle);\n}\n\nstatic void riscv_vm_send_key_event(VirtMachine *s1, BOOL is_down,\n uint16_t key_code)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n if (s->keyboard_dev) {\n virtio_input_send_key_event(s->keyboard_dev, is_down, key_code);\n }\n}\n\nstatic BOOL riscv_vm_mouse_is_absolute(VirtMachine *s)\n{\n return TRUE;\n}\n\nstatic void riscv_vm_send_mouse_event(VirtMachine *s1, int dx, int dy, int dz,\n unsigned int buttons)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n if (s->mouse_dev) {\n virtio_input_send_mouse_event(s->mouse_dev, dx, dy, dz, buttons);\n }\n}\n\nconst VirtMachineClass riscv_machine_class = {\n \"riscv32,riscv64,riscv128\",\n riscv_machine_set_defaults,\n riscv_machine_init,\n riscv_machine_end,\n riscv_machine_get_sleep_duration,\n riscv_machine_interp,\n riscv_vm_mouse_is_absolute,\n riscv_vm_send_mouse_event,\n riscv_vm_send_key_event,\n};\n"], ["/linuxpdf/tinyemu/virtio.c", "/*\n * VIRTIO driver\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"virtio.h\"\n\n//#define DEBUG_VIRTIO\n\n/* MMIO addresses - from the Linux kernel */\n#define VIRTIO_MMIO_MAGIC_VALUE\t\t0x000\n#define VIRTIO_MMIO_VERSION\t\t0x004\n#define VIRTIO_MMIO_DEVICE_ID\t\t0x008\n#define VIRTIO_MMIO_VENDOR_ID\t\t0x00c\n#define VIRTIO_MMIO_DEVICE_FEATURES\t0x010\n#define VIRTIO_MMIO_DEVICE_FEATURES_SEL\t0x014\n#define VIRTIO_MMIO_DRIVER_FEATURES\t0x020\n#define VIRTIO_MMIO_DRIVER_FEATURES_SEL\t0x024\n#define VIRTIO_MMIO_GUEST_PAGE_SIZE\t0x028 /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_SEL\t\t0x030\n#define VIRTIO_MMIO_QUEUE_NUM_MAX\t0x034\n#define VIRTIO_MMIO_QUEUE_NUM\t\t0x038\n#define VIRTIO_MMIO_QUEUE_ALIGN\t\t0x03c /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_PFN\t\t0x040 /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_READY\t\t0x044\n#define VIRTIO_MMIO_QUEUE_NOTIFY\t0x050\n#define VIRTIO_MMIO_INTERRUPT_STATUS\t0x060\n#define VIRTIO_MMIO_INTERRUPT_ACK\t0x064\n#define VIRTIO_MMIO_STATUS\t\t0x070\n#define VIRTIO_MMIO_QUEUE_DESC_LOW\t0x080\n#define VIRTIO_MMIO_QUEUE_DESC_HIGH\t0x084\n#define VIRTIO_MMIO_QUEUE_AVAIL_LOW\t0x090\n#define VIRTIO_MMIO_QUEUE_AVAIL_HIGH\t0x094\n#define VIRTIO_MMIO_QUEUE_USED_LOW\t0x0a0\n#define VIRTIO_MMIO_QUEUE_USED_HIGH\t0x0a4\n#define VIRTIO_MMIO_CONFIG_GENERATION\t0x0fc\n#define VIRTIO_MMIO_CONFIG\t\t0x100\n\n/* PCI registers */\n#define VIRTIO_PCI_DEVICE_FEATURE_SEL\t0x000\n#define VIRTIO_PCI_DEVICE_FEATURE\t0x004\n#define VIRTIO_PCI_GUEST_FEATURE_SEL\t0x008\n#define VIRTIO_PCI_GUEST_FEATURE\t0x00c\n#define VIRTIO_PCI_MSIX_CONFIG 0x010\n#define VIRTIO_PCI_NUM_QUEUES 0x012\n#define VIRTIO_PCI_DEVICE_STATUS 0x014\n#define VIRTIO_PCI_CONFIG_GENERATION 0x015\n#define VIRTIO_PCI_QUEUE_SEL\t\t0x016\n#define VIRTIO_PCI_QUEUE_SIZE\t 0x018\n#define VIRTIO_PCI_QUEUE_MSIX_VECTOR 0x01a\n#define VIRTIO_PCI_QUEUE_ENABLE 0x01c\n#define VIRTIO_PCI_QUEUE_NOTIFY_OFF 0x01e\n#define VIRTIO_PCI_QUEUE_DESC_LOW\t0x020\n#define VIRTIO_PCI_QUEUE_DESC_HIGH\t0x024\n#define VIRTIO_PCI_QUEUE_AVAIL_LOW\t0x028\n#define VIRTIO_PCI_QUEUE_AVAIL_HIGH\t0x02c\n#define VIRTIO_PCI_QUEUE_USED_LOW\t0x030\n#define VIRTIO_PCI_QUEUE_USED_HIGH\t0x034\n\n#define VIRTIO_PCI_CFG_OFFSET 0x0000\n#define VIRTIO_PCI_ISR_OFFSET 0x1000\n#define VIRTIO_PCI_CONFIG_OFFSET 0x2000\n#define VIRTIO_PCI_NOTIFY_OFFSET 0x3000\n\n#define VIRTIO_PCI_CAP_LEN 16\n\n#define MAX_QUEUE 8\n#define MAX_CONFIG_SPACE_SIZE 256\n#define MAX_QUEUE_NUM 16\n\ntypedef struct {\n uint32_t ready; /* 0 or 1 */\n uint32_t num;\n uint16_t last_avail_idx;\n virtio_phys_addr_t desc_addr;\n virtio_phys_addr_t avail_addr;\n virtio_phys_addr_t used_addr;\n BOOL manual_recv; /* if TRUE, the device_recv() callback is not called */\n} QueueState;\n\n#define VRING_DESC_F_NEXT\t1\n#define VRING_DESC_F_WRITE\t2\n#define VRING_DESC_F_INDIRECT\t4\n\ntypedef struct {\n uint64_t addr;\n uint32_t len;\n uint16_t flags; /* VRING_DESC_F_x */\n uint16_t next;\n} VIRTIODesc;\n\n/* return < 0 to stop the notification (it must be manually restarted\n later), 0 if OK */\ntypedef int VIRTIODeviceRecvFunc(VIRTIODevice *s1, int queue_idx,\n int desc_idx, int read_size,\n int write_size);\n\n/* return NULL if no RAM at this address. The mapping is valid for one page */\ntypedef uint8_t *VIRTIOGetRAMPtrFunc(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw);\n\nstruct VIRTIODevice {\n PhysMemoryMap *mem_map;\n PhysMemoryRange *mem_range;\n /* PCI only */\n PCIDevice *pci_dev;\n /* MMIO only */\n IRQSignal *irq;\n VIRTIOGetRAMPtrFunc *get_ram_ptr;\n int debug;\n\n uint32_t int_status;\n uint32_t status;\n uint32_t device_features_sel;\n uint32_t queue_sel; /* currently selected queue */\n QueueState queue[MAX_QUEUE];\n\n /* device specific */\n uint32_t device_id;\n uint32_t vendor_id;\n uint32_t device_features;\n VIRTIODeviceRecvFunc *device_recv;\n void (*config_write)(VIRTIODevice *s); /* called after the config\n is written */\n uint32_t config_space_size; /* in bytes, must be multiple of 4 */\n uint8_t config_space[MAX_CONFIG_SPACE_SIZE];\n};\n\nstatic uint32_t virtio_mmio_read(void *opaque, uint32_t offset1, int size_log2);\nstatic void virtio_mmio_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t virtio_pci_read(void *opaque, uint32_t offset, int size_log2);\nstatic void virtio_pci_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\n\nstatic void virtio_reset(VIRTIODevice *s)\n{\n int i;\n\n s->status = 0;\n s->queue_sel = 0;\n s->device_features_sel = 0;\n s->int_status = 0;\n for(i = 0; i < MAX_QUEUE; i++) {\n QueueState *qs = &s->queue[i];\n qs->ready = 0;\n qs->num = MAX_QUEUE_NUM;\n qs->desc_addr = 0;\n qs->avail_addr = 0;\n qs->used_addr = 0;\n qs->last_avail_idx = 0;\n }\n}\n\nstatic uint8_t *virtio_pci_get_ram_ptr(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw)\n{\n return pci_device_get_dma_ptr(s->pci_dev, paddr, is_rw);\n}\n\nstatic uint8_t *virtio_mmio_get_ram_ptr(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(s->mem_map, paddr, is_rw);\n}\n\nstatic void virtio_add_pci_capability(VIRTIODevice *s, int cfg_type,\n int bar, uint32_t offset, uint32_t len,\n uint32_t mult)\n{\n uint8_t cap[20];\n int cap_len;\n if (cfg_type == 2)\n cap_len = 20;\n else\n cap_len = 16;\n memset(cap, 0, cap_len);\n cap[0] = 0x09; /* vendor specific */\n cap[2] = cap_len; /* set by pci_add_capability() */\n cap[3] = cfg_type;\n cap[4] = bar;\n put_le32(cap + 8, offset);\n put_le32(cap + 12, len);\n if (cfg_type == 2)\n put_le32(cap + 16, mult);\n pci_add_capability(s->pci_dev, cap, cap_len);\n}\n\nstatic void virtio_pci_bar_set(void *opaque, int bar_num,\n uint32_t addr, BOOL enabled)\n{\n VIRTIODevice *s = opaque;\n phys_mem_set_addr(s->mem_range, addr, enabled);\n}\n\nstatic void virtio_init(VIRTIODevice *s, VIRTIOBusDef *bus,\n uint32_t device_id, int config_space_size,\n VIRTIODeviceRecvFunc *device_recv)\n{\n memset(s, 0, sizeof(*s));\n\n if (bus->pci_bus) {\n uint16_t pci_device_id, class_id;\n char name[32];\n int bar_num;\n \n switch(device_id) {\n case 1:\n pci_device_id = 0x1000; /* net */\n class_id = 0x0200;\n break;\n case 2:\n pci_device_id = 0x1001; /* block */\n class_id = 0x0100; /* XXX: check it */\n break;\n case 3:\n pci_device_id = 0x1003; /* console */\n class_id = 0x0780;\n break;\n case 9:\n pci_device_id = 0x1040 + device_id; /* use new device ID */\n class_id = 0x2;\n break;\n case 18:\n pci_device_id = 0x1040 + device_id; /* use new device ID */\n class_id = 0x0980;\n break;\n default:\n abort();\n }\n snprintf(name, sizeof(name), \"virtio_%04x\", pci_device_id);\n s->pci_dev = pci_register_device(bus->pci_bus, name, -1,\n 0x1af4, pci_device_id, 0x00,\n class_id);\n pci_device_set_config16(s->pci_dev, 0x2c, 0x1af4);\n pci_device_set_config16(s->pci_dev, 0x2e, device_id);\n pci_device_set_config8(s->pci_dev, PCI_INTERRUPT_PIN, 1);\n\n bar_num = 4;\n virtio_add_pci_capability(s, 1, bar_num,\n VIRTIO_PCI_CFG_OFFSET, 0x1000, 0); /* common */\n virtio_add_pci_capability(s, 3, bar_num,\n VIRTIO_PCI_ISR_OFFSET, 0x1000, 0); /* isr */\n virtio_add_pci_capability(s, 4, bar_num,\n VIRTIO_PCI_CONFIG_OFFSET, 0x1000, 0); /* config */\n virtio_add_pci_capability(s, 2, bar_num,\n VIRTIO_PCI_NOTIFY_OFFSET, 0x1000, 0); /* notify */\n \n s->get_ram_ptr = virtio_pci_get_ram_ptr;\n s->irq = pci_device_get_irq(s->pci_dev, 0);\n s->mem_map = pci_device_get_mem_map(s->pci_dev);\n s->mem_range = cpu_register_device(s->mem_map, 0, 0x4000, s,\n virtio_pci_read, virtio_pci_write,\n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32 | DEVIO_DISABLED);\n pci_register_bar(s->pci_dev, bar_num, 0x4000, PCI_ADDRESS_SPACE_MEM,\n s, virtio_pci_bar_set);\n } else {\n /* MMIO case */\n s->mem_map = bus->mem_map;\n s->irq = bus->irq;\n s->mem_range = cpu_register_device(s->mem_map, bus->addr, VIRTIO_PAGE_SIZE,\n s, virtio_mmio_read, virtio_mmio_write,\n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32);\n s->get_ram_ptr = virtio_mmio_get_ram_ptr;\n }\n\n s->device_id = device_id;\n s->vendor_id = 0xffff;\n s->config_space_size = config_space_size;\n s->device_recv = device_recv;\n virtio_reset(s);\n}\n\nstatic uint16_t virtio_read16(VIRTIODevice *s, virtio_phys_addr_t addr)\n{\n uint8_t *ptr;\n if (addr & 1)\n return 0; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, FALSE);\n if (!ptr)\n return 0;\n return *(uint16_t *)ptr;\n}\n\nstatic void virtio_write16(VIRTIODevice *s, virtio_phys_addr_t addr,\n uint16_t val)\n{\n uint8_t *ptr;\n if (addr & 1)\n return; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return;\n *(uint16_t *)ptr = val;\n}\n\nstatic void virtio_write32(VIRTIODevice *s, virtio_phys_addr_t addr,\n uint32_t val)\n{\n uint8_t *ptr;\n if (addr & 3)\n return; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return;\n *(uint32_t *)ptr = val;\n}\n\nstatic int virtio_memcpy_from_ram(VIRTIODevice *s, uint8_t *buf,\n virtio_phys_addr_t addr, int count)\n{\n uint8_t *ptr;\n int l;\n\n while (count > 0) {\n l = min_int(count, VIRTIO_PAGE_SIZE - (addr & (VIRTIO_PAGE_SIZE - 1)));\n ptr = s->get_ram_ptr(s, addr, FALSE);\n if (!ptr)\n return -1;\n memcpy(buf, ptr, l);\n addr += l;\n buf += l;\n count -= l;\n }\n return 0;\n}\n\nstatic int virtio_memcpy_to_ram(VIRTIODevice *s, virtio_phys_addr_t addr, \n const uint8_t *buf, int count)\n{\n uint8_t *ptr;\n int l;\n\n while (count > 0) {\n l = min_int(count, VIRTIO_PAGE_SIZE - (addr & (VIRTIO_PAGE_SIZE - 1)));\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return -1;\n memcpy(ptr, buf, l);\n addr += l;\n buf += l;\n count -= l;\n }\n return 0;\n}\n\nstatic int get_desc(VIRTIODevice *s, VIRTIODesc *desc, \n int queue_idx, int desc_idx)\n{\n QueueState *qs = &s->queue[queue_idx];\n return virtio_memcpy_from_ram(s, (void *)desc, qs->desc_addr +\n desc_idx * sizeof(VIRTIODesc),\n sizeof(VIRTIODesc));\n}\n\nstatic int memcpy_to_from_queue(VIRTIODevice *s, uint8_t *buf,\n int queue_idx, int desc_idx,\n int offset, int count, BOOL to_queue)\n{\n VIRTIODesc desc;\n int l, f_write_flag;\n\n if (count == 0)\n return 0;\n\n get_desc(s, &desc, queue_idx, desc_idx);\n\n if (to_queue) {\n f_write_flag = VRING_DESC_F_WRITE;\n /* find the first write descriptor */\n for(;;) {\n if ((desc.flags & VRING_DESC_F_WRITE) == f_write_flag)\n break;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n } else {\n f_write_flag = 0;\n }\n\n /* find the descriptor at offset */\n for(;;) {\n if ((desc.flags & VRING_DESC_F_WRITE) != f_write_flag)\n return -1;\n if (offset < desc.len)\n break;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n offset -= desc.len;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n\n for(;;) {\n l = min_int(count, desc.len - offset);\n if (to_queue)\n virtio_memcpy_to_ram(s, desc.addr + offset, buf, l);\n else\n virtio_memcpy_from_ram(s, buf, desc.addr + offset, l);\n count -= l;\n if (count == 0)\n break;\n offset += l;\n buf += l;\n if (offset == desc.len) {\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n if ((desc.flags & VRING_DESC_F_WRITE) != f_write_flag)\n return -1;\n offset = 0;\n }\n }\n return 0;\n}\n\nstatic int memcpy_from_queue(VIRTIODevice *s, void *buf,\n int queue_idx, int desc_idx,\n int offset, int count)\n{\n return memcpy_to_from_queue(s, buf, queue_idx, desc_idx, offset, count,\n FALSE);\n}\n\nstatic int memcpy_to_queue(VIRTIODevice *s,\n int queue_idx, int desc_idx,\n int offset, const void *buf, int count)\n{\n return memcpy_to_from_queue(s, (void *)buf, queue_idx, desc_idx, offset,\n count, TRUE);\n}\n\n/* signal that the descriptor has been consumed */\nstatic void virtio_consume_desc(VIRTIODevice *s,\n int queue_idx, int desc_idx, int desc_len)\n{\n QueueState *qs = &s->queue[queue_idx];\n virtio_phys_addr_t addr;\n uint32_t index;\n\n addr = qs->used_addr + 2;\n index = virtio_read16(s, addr);\n virtio_write16(s, addr, index + 1);\n\n addr = qs->used_addr + 4 + (index & (qs->num - 1)) * 8;\n virtio_write32(s, addr, desc_idx);\n virtio_write32(s, addr + 4, desc_len);\n\n s->int_status |= 1;\n set_irq(s->irq, 1);\n}\n\nstatic int get_desc_rw_size(VIRTIODevice *s, \n int *pread_size, int *pwrite_size,\n int queue_idx, int desc_idx)\n{\n VIRTIODesc desc;\n int read_size, write_size;\n\n read_size = 0;\n write_size = 0;\n get_desc(s, &desc, queue_idx, desc_idx);\n\n for(;;) {\n if (desc.flags & VRING_DESC_F_WRITE)\n break;\n read_size += desc.len;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n goto done;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n \n for(;;) {\n if (!(desc.flags & VRING_DESC_F_WRITE))\n return -1;\n write_size += desc.len;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n break;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n\n done:\n *pread_size = read_size;\n *pwrite_size = write_size;\n return 0;\n}\n\n/* XXX: test if the queue is ready ? */\nstatic void queue_notify(VIRTIODevice *s, int queue_idx)\n{\n QueueState *qs = &s->queue[queue_idx];\n uint16_t avail_idx;\n int desc_idx, read_size, write_size;\n\n if (qs->manual_recv)\n return;\n\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n while (qs->last_avail_idx != avail_idx) {\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (!get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx)) {\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"queue_notify: idx=%d read_size=%d write_size=%d\\n\",\n queue_idx, read_size, write_size);\n }\n#endif\n if (s->device_recv(s, queue_idx, desc_idx,\n read_size, write_size) < 0)\n break;\n }\n qs->last_avail_idx++;\n }\n}\n\nstatic uint32_t virtio_config_read(VIRTIODevice *s, uint32_t offset,\n int size_log2)\n{\n uint32_t val;\n switch(size_log2) {\n case 0:\n if (offset < s->config_space_size) {\n val = s->config_space[offset];\n } else {\n val = 0;\n }\n break;\n case 1:\n if (offset < (s->config_space_size - 1)) {\n val = get_le16(&s->config_space[offset]);\n } else {\n val = 0;\n }\n break;\n case 2:\n if (offset < (s->config_space_size - 3)) {\n val = get_le32(s->config_space + offset);\n } else {\n val = 0;\n }\n break;\n default:\n abort();\n }\n return val;\n}\n\nstatic void virtio_config_write(VIRTIODevice *s, uint32_t offset,\n uint32_t val, int size_log2)\n{\n switch(size_log2) {\n case 0:\n if (offset < s->config_space_size) {\n s->config_space[offset] = val;\n if (s->config_write)\n s->config_write(s);\n }\n break;\n case 1:\n if (offset < s->config_space_size - 1) {\n put_le16(s->config_space + offset, val);\n if (s->config_write)\n s->config_write(s);\n }\n break;\n case 2:\n if (offset < s->config_space_size - 3) {\n put_le32(s->config_space + offset, val);\n if (s->config_write)\n s->config_write(s);\n }\n break;\n }\n}\n\nstatic uint32_t virtio_mmio_read(void *opaque, uint32_t offset, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t val;\n\n if (offset >= VIRTIO_MMIO_CONFIG) {\n return virtio_config_read(s, offset - VIRTIO_MMIO_CONFIG, size_log2);\n }\n\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_MMIO_MAGIC_VALUE:\n val = 0x74726976;\n break;\n case VIRTIO_MMIO_VERSION:\n val = 2;\n break;\n case VIRTIO_MMIO_DEVICE_ID:\n val = s->device_id;\n break;\n case VIRTIO_MMIO_VENDOR_ID:\n val = s->vendor_id;\n break;\n case VIRTIO_MMIO_DEVICE_FEATURES:\n switch(s->device_features_sel) {\n case 0:\n val = s->device_features;\n break;\n case 1:\n val = 1; /* version 1 */\n break;\n default:\n val = 0;\n break;\n }\n break;\n case VIRTIO_MMIO_DEVICE_FEATURES_SEL:\n val = s->device_features_sel;\n break;\n case VIRTIO_MMIO_QUEUE_SEL:\n val = s->queue_sel;\n break;\n case VIRTIO_MMIO_QUEUE_NUM_MAX:\n val = MAX_QUEUE_NUM;\n break;\n case VIRTIO_MMIO_QUEUE_NUM:\n val = s->queue[s->queue_sel].num;\n break;\n case VIRTIO_MMIO_QUEUE_DESC_LOW:\n val = s->queue[s->queue_sel].desc_addr;\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_LOW:\n val = s->queue[s->queue_sel].avail_addr;\n break;\n case VIRTIO_MMIO_QUEUE_USED_LOW:\n val = s->queue[s->queue_sel].used_addr;\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_MMIO_QUEUE_DESC_HIGH:\n val = s->queue[s->queue_sel].desc_addr >> 32;\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_HIGH:\n val = s->queue[s->queue_sel].avail_addr >> 32;\n break;\n case VIRTIO_MMIO_QUEUE_USED_HIGH:\n val = s->queue[s->queue_sel].used_addr >> 32;\n break;\n#endif\n case VIRTIO_MMIO_QUEUE_READY:\n val = s->queue[s->queue_sel].ready;\n break;\n case VIRTIO_MMIO_INTERRUPT_STATUS:\n val = s->int_status;\n break;\n case VIRTIO_MMIO_STATUS:\n val = s->status;\n break;\n case VIRTIO_MMIO_CONFIG_GENERATION:\n val = 0;\n break;\n default:\n val = 0;\n break;\n }\n } else {\n val = 0;\n }\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_mmio_read: offset=0x%x val=0x%x size=%d\\n\", \n offset, val, 1 << size_log2);\n }\n#endif\n return val;\n}\n\n#if VIRTIO_ADDR_BITS == 64\nstatic void set_low32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = (*paddr & ~(virtio_phys_addr_t)0xffffffff) | val;\n}\n\nstatic void set_high32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = (*paddr & 0xffffffff) | ((virtio_phys_addr_t)val << 32);\n}\n#else\nstatic void set_low32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = val;\n}\n#endif\n\nstatic void virtio_mmio_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n VIRTIODevice *s = opaque;\n \n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_mmio_write: offset=0x%x val=0x%x size=%d\\n\",\n offset, val, 1 << size_log2);\n }\n#endif\n\n if (offset >= VIRTIO_MMIO_CONFIG) {\n virtio_config_write(s, offset - VIRTIO_MMIO_CONFIG, val, size_log2);\n return;\n }\n\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_MMIO_DEVICE_FEATURES_SEL:\n s->device_features_sel = val;\n break;\n case VIRTIO_MMIO_QUEUE_SEL:\n if (val < MAX_QUEUE)\n s->queue_sel = val;\n break;\n case VIRTIO_MMIO_QUEUE_NUM:\n if ((val & (val - 1)) == 0 && val > 0) {\n s->queue[s->queue_sel].num = val;\n }\n break;\n case VIRTIO_MMIO_QUEUE_DESC_LOW:\n set_low32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_LOW:\n set_low32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_USED_LOW:\n set_low32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_MMIO_QUEUE_DESC_HIGH:\n set_high32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_HIGH:\n set_high32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_USED_HIGH:\n set_high32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#endif\n case VIRTIO_MMIO_STATUS:\n s->status = val;\n if (val == 0) {\n /* reset */\n set_irq(s->irq, 0);\n virtio_reset(s);\n }\n break;\n case VIRTIO_MMIO_QUEUE_READY:\n s->queue[s->queue_sel].ready = val & 1;\n break;\n case VIRTIO_MMIO_QUEUE_NOTIFY:\n if (val < MAX_QUEUE)\n queue_notify(s, val);\n break;\n case VIRTIO_MMIO_INTERRUPT_ACK:\n s->int_status &= ~val;\n if (s->int_status == 0) {\n set_irq(s->irq, 0);\n }\n break;\n }\n }\n}\n\nstatic uint32_t virtio_pci_read(void *opaque, uint32_t offset1, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t offset;\n uint32_t val = 0;\n\n offset = offset1 & 0xfff;\n switch(offset1 >> 12) {\n case VIRTIO_PCI_CFG_OFFSET >> 12:\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_FEATURE:\n switch(s->device_features_sel) {\n case 0:\n val = s->device_features;\n break;\n case 1:\n val = 1; /* version 1 */\n break;\n default:\n val = 0;\n break;\n }\n break;\n case VIRTIO_PCI_DEVICE_FEATURE_SEL:\n val = s->device_features_sel;\n break;\n case VIRTIO_PCI_QUEUE_DESC_LOW:\n val = s->queue[s->queue_sel].desc_addr;\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_LOW:\n val = s->queue[s->queue_sel].avail_addr;\n break;\n case VIRTIO_PCI_QUEUE_USED_LOW:\n val = s->queue[s->queue_sel].used_addr;\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_PCI_QUEUE_DESC_HIGH:\n val = s->queue[s->queue_sel].desc_addr >> 32;\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_HIGH:\n val = s->queue[s->queue_sel].avail_addr >> 32;\n break;\n case VIRTIO_PCI_QUEUE_USED_HIGH:\n val = s->queue[s->queue_sel].used_addr >> 32;\n break;\n#endif\n }\n } else if (size_log2 == 1) {\n switch(offset) {\n case VIRTIO_PCI_NUM_QUEUES:\n val = MAX_QUEUE_NUM;\n break;\n case VIRTIO_PCI_QUEUE_SEL:\n val = s->queue_sel;\n break;\n case VIRTIO_PCI_QUEUE_SIZE:\n val = s->queue[s->queue_sel].num;\n break;\n case VIRTIO_PCI_QUEUE_ENABLE:\n val = s->queue[s->queue_sel].ready;\n break;\n case VIRTIO_PCI_QUEUE_NOTIFY_OFF:\n val = 0;\n break;\n }\n } else if (size_log2 == 0) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_STATUS:\n val = s->status;\n break;\n }\n }\n break;\n case VIRTIO_PCI_ISR_OFFSET >> 12:\n if (offset == 0 && size_log2 == 0) {\n val = s->int_status;\n s->int_status = 0;\n set_irq(s->irq, 0);\n }\n break;\n case VIRTIO_PCI_CONFIG_OFFSET >> 12:\n val = virtio_config_read(s, offset, size_log2);\n break;\n }\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_pci_read: offset=0x%x val=0x%x size=%d\\n\", \n offset1, val, 1 << size_log2);\n }\n#endif\n return val;\n}\n\nstatic void virtio_pci_write(void *opaque, uint32_t offset1,\n uint32_t val, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t offset;\n \n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_pci_write: offset=0x%x val=0x%x size=%d\\n\",\n offset1, val, 1 << size_log2);\n }\n#endif\n offset = offset1 & 0xfff;\n switch(offset1 >> 12) {\n case VIRTIO_PCI_CFG_OFFSET >> 12:\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_FEATURE_SEL:\n s->device_features_sel = val;\n break;\n case VIRTIO_PCI_QUEUE_DESC_LOW:\n set_low32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_LOW:\n set_low32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_USED_LOW:\n set_low32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_PCI_QUEUE_DESC_HIGH:\n set_high32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_HIGH:\n set_high32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_USED_HIGH:\n set_high32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#endif\n }\n } else if (size_log2 == 1) {\n switch(offset) {\n case VIRTIO_PCI_QUEUE_SEL:\n if (val < MAX_QUEUE)\n s->queue_sel = val;\n break;\n case VIRTIO_PCI_QUEUE_SIZE:\n if ((val & (val - 1)) == 0 && val > 0) {\n s->queue[s->queue_sel].num = val;\n }\n break;\n case VIRTIO_PCI_QUEUE_ENABLE:\n s->queue[s->queue_sel].ready = val & 1;\n break;\n }\n } else if (size_log2 == 0) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_STATUS:\n s->status = val;\n if (val == 0) {\n /* reset */\n set_irq(s->irq, 0);\n virtio_reset(s);\n }\n break;\n }\n }\n break;\n case VIRTIO_PCI_CONFIG_OFFSET >> 12:\n virtio_config_write(s, offset, val, size_log2);\n break;\n case VIRTIO_PCI_NOTIFY_OFFSET >> 12:\n if (val < MAX_QUEUE)\n queue_notify(s, val);\n break;\n }\n}\n\nvoid virtio_set_debug(VIRTIODevice *s, int debug)\n{\n s->debug = debug;\n}\n\nstatic void virtio_config_change_notify(VIRTIODevice *s)\n{\n /* INT_CONFIG interrupt */\n s->int_status |= 2;\n set_irq(s->irq, 1);\n}\n\n/*********************************************************************/\n/* block device */\n\ntypedef struct {\n uint32_t type;\n uint8_t *buf;\n int write_size;\n int queue_idx;\n int desc_idx;\n} BlockRequest;\n\ntypedef struct VIRTIOBlockDevice {\n VIRTIODevice common;\n BlockDevice *bs;\n\n BOOL req_in_progress;\n BlockRequest req; /* request in progress */\n} VIRTIOBlockDevice;\n\ntypedef struct {\n uint32_t type;\n uint32_t ioprio;\n uint64_t sector_num;\n} BlockRequestHeader;\n\n#define VIRTIO_BLK_T_IN 0\n#define VIRTIO_BLK_T_OUT 1\n#define VIRTIO_BLK_T_FLUSH 4\n#define VIRTIO_BLK_T_FLUSH_OUT 5\n\n#define VIRTIO_BLK_S_OK 0\n#define VIRTIO_BLK_S_IOERR 1\n#define VIRTIO_BLK_S_UNSUPP 2\n\n#define SECTOR_SIZE 512\n\nstatic void virtio_block_req_end(VIRTIODevice *s, int ret)\n{\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n int write_size;\n int queue_idx = s1->req.queue_idx;\n int desc_idx = s1->req.desc_idx;\n uint8_t *buf, buf1[1];\n\n switch(s1->req.type) {\n case VIRTIO_BLK_T_IN:\n write_size = s1->req.write_size;\n buf = s1->req.buf;\n if (ret < 0) {\n buf[write_size - 1] = VIRTIO_BLK_S_IOERR;\n } else {\n buf[write_size - 1] = VIRTIO_BLK_S_OK;\n }\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, write_size);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, write_size);\n break;\n case VIRTIO_BLK_T_OUT:\n if (ret < 0)\n buf1[0] = VIRTIO_BLK_S_IOERR;\n else\n buf1[0] = VIRTIO_BLK_S_OK;\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf1, sizeof(buf1));\n virtio_consume_desc(s, queue_idx, desc_idx, 1);\n break;\n default:\n abort();\n }\n}\n\nstatic void virtio_block_req_cb(void *opaque, int ret)\n{\n VIRTIODevice *s = opaque;\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n\n virtio_block_req_end(s, ret);\n \n s1->req_in_progress = FALSE;\n\n /* handle next requests */\n queue_notify((VIRTIODevice *)s, s1->req.queue_idx);\n}\n\n/* XXX: handle async I/O */\nstatic int virtio_block_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n BlockDevice *bs = s1->bs;\n BlockRequestHeader h;\n uint8_t *buf;\n int len, ret;\n\n if (s1->req_in_progress)\n return -1;\n \n if (memcpy_from_queue(s, &h, queue_idx, desc_idx, 0, sizeof(h)) < 0)\n return 0;\n s1->req.type = h.type;\n s1->req.queue_idx = queue_idx;\n s1->req.desc_idx = desc_idx;\n switch(h.type) {\n case VIRTIO_BLK_T_IN:\n s1->req.buf = malloc(write_size);\n s1->req.write_size = write_size;\n ret = bs->read_async(bs, h.sector_num, s1->req.buf, \n (write_size - 1) / SECTOR_SIZE,\n virtio_block_req_cb, s);\n if (ret > 0) {\n /* asyncronous read */\n s1->req_in_progress = TRUE;\n } else {\n virtio_block_req_end(s, ret);\n }\n break;\n case VIRTIO_BLK_T_OUT:\n assert(write_size >= 1);\n len = read_size - sizeof(h);\n buf = malloc(len);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, sizeof(h), len);\n ret = bs->write_async(bs, h.sector_num, buf, len / SECTOR_SIZE,\n virtio_block_req_cb, s);\n free(buf);\n if (ret > 0) {\n /* asyncronous write */\n s1->req_in_progress = TRUE;\n } else {\n virtio_block_req_end(s, ret);\n }\n break;\n default:\n break;\n }\n return 0;\n}\n\nVIRTIODevice *virtio_block_init(VIRTIOBusDef *bus, BlockDevice *bs)\n{\n VIRTIOBlockDevice *s;\n uint64_t nb_sectors;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 2, 8, virtio_block_recv_request);\n s->bs = bs;\n \n nb_sectors = bs->get_sector_count(bs);\n put_le32(s->common.config_space, nb_sectors);\n put_le32(s->common.config_space + 4, nb_sectors >> 32);\n\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* network device */\n\ntypedef struct VIRTIONetDevice {\n VIRTIODevice common;\n EthernetDevice *es;\n int header_size;\n} VIRTIONetDevice;\n\ntypedef struct {\n uint8_t flags;\n uint8_t gso_type;\n uint16_t hdr_len;\n uint16_t gso_size;\n uint16_t csum_start;\n uint16_t csum_offset;\n uint16_t num_buffers;\n} VIRTIONetHeader;\n\nstatic int virtio_net_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIONetDevice *s1 = (VIRTIONetDevice *)s;\n EthernetDevice *es = s1->es;\n VIRTIONetHeader h;\n uint8_t *buf;\n int len;\n\n if (queue_idx == 1) {\n /* send to network */\n if (memcpy_from_queue(s, &h, queue_idx, desc_idx, 0, s1->header_size) < 0)\n return 0;\n len = read_size - s1->header_size;\n buf = malloc(len);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, s1->header_size, len);\n es->write_packet(es, buf, len);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\nstatic BOOL virtio_net_can_write_packet(EthernetDevice *es)\n{\n VIRTIODevice *s = es->device_opaque;\n QueueState *qs = &s->queue[0];\n uint16_t avail_idx;\n\n if (!qs->ready)\n return FALSE;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n return qs->last_avail_idx != avail_idx;\n}\n\nstatic void virtio_net_write_packet(EthernetDevice *es, const uint8_t *buf, int buf_len)\n{\n VIRTIODevice *s = es->device_opaque;\n VIRTIONetDevice *s1 = (VIRTIONetDevice *)s;\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n VIRTIONetHeader h;\n int len, read_size, write_size;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx))\n return;\n len = s1->header_size + buf_len; \n if (len > write_size)\n return;\n memset(&h, 0, s1->header_size);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, &h, s1->header_size);\n memcpy_to_queue(s, queue_idx, desc_idx, s1->header_size, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, len);\n qs->last_avail_idx++;\n}\n\nstatic void virtio_net_set_carrier(EthernetDevice *es, BOOL carrier_state)\n{\n#if 0\n VIRTIODevice *s1 = es->device_opaque;\n VIRTIONetDevice *s = (VIRTIONetDevice *)s1;\n int cur_carrier_state;\n\n // printf(\"virtio_net_set_carrier: %d\\n\", carrier_state);\n cur_carrier_state = s->common.config_space[6] & 1;\n if (cur_carrier_state != carrier_state) {\n s->common.config_space[6] = (carrier_state << 0);\n virtio_config_change_notify(s1);\n }\n#endif\n}\n\nVIRTIODevice *virtio_net_init(VIRTIOBusDef *bus, EthernetDevice *es)\n{\n VIRTIONetDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 1, 6 + 2, virtio_net_recv_request);\n /* VIRTIO_NET_F_MAC, VIRTIO_NET_F_STATUS */\n s->common.device_features = (1 << 5) /* | (1 << 16) */;\n s->common.queue[0].manual_recv = TRUE;\n s->es = es;\n memcpy(s->common.config_space, es->mac_addr, 6);\n /* status */\n s->common.config_space[6] = 0;\n s->common.config_space[7] = 0;\n\n s->header_size = sizeof(VIRTIONetHeader);\n \n es->device_opaque = s;\n es->device_can_write_packet = virtio_net_can_write_packet;\n es->device_write_packet = virtio_net_write_packet;\n es->device_set_carrier = virtio_net_set_carrier;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* console device */\n\ntypedef struct VIRTIOConsoleDevice {\n VIRTIODevice common;\n CharacterDevice *cs;\n} VIRTIOConsoleDevice;\n\nstatic int virtio_console_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIOConsoleDevice *s1 = (VIRTIOConsoleDevice *)s;\n CharacterDevice *cs = s1->cs;\n uint8_t *buf;\n\n if (queue_idx == 1) {\n /* send to console */\n buf = malloc(read_size);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, 0, read_size);\n cs->write_data(cs->opaque, buf, read_size);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\nBOOL virtio_console_can_write_data(VIRTIODevice *s)\n{\n QueueState *qs = &s->queue[0];\n uint16_t avail_idx;\n\n if (!qs->ready)\n return FALSE;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n return qs->last_avail_idx != avail_idx;\n}\n\nint virtio_console_get_write_len(VIRTIODevice *s)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n int read_size, write_size;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return 0;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return 0;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx))\n return 0;\n return write_size;\n}\n\nint virtio_console_write_data(VIRTIODevice *s, const uint8_t *buf, int buf_len)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return 0;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return 0;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, buf_len);\n qs->last_avail_idx++;\n return buf_len;\n}\n\n/* send a resize event */\nvoid virtio_console_resize_event(VIRTIODevice *s, int width, int height)\n{\n /* indicate the console size */\n put_le16(s->config_space + 0, width);\n put_le16(s->config_space + 2, height);\n\n virtio_config_change_notify(s);\n}\n\nVIRTIODevice *virtio_console_init(VIRTIOBusDef *bus, CharacterDevice *cs)\n{\n VIRTIOConsoleDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 3, 4, virtio_console_recv_request);\n s->common.device_features = (1 << 0); /* VIRTIO_CONSOLE_F_SIZE */\n s->common.queue[0].manual_recv = TRUE;\n \n s->cs = cs;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* input device */\n\nenum {\n VIRTIO_INPUT_CFG_UNSET = 0x00,\n VIRTIO_INPUT_CFG_ID_NAME = 0x01,\n VIRTIO_INPUT_CFG_ID_SERIAL = 0x02,\n VIRTIO_INPUT_CFG_ID_DEVIDS = 0x03,\n VIRTIO_INPUT_CFG_PROP_BITS = 0x10,\n VIRTIO_INPUT_CFG_EV_BITS = 0x11,\n VIRTIO_INPUT_CFG_ABS_INFO = 0x12,\n};\n\n#define VIRTIO_INPUT_EV_SYN 0x00\n#define VIRTIO_INPUT_EV_KEY 0x01\n#define VIRTIO_INPUT_EV_REL 0x02\n#define VIRTIO_INPUT_EV_ABS 0x03\n#define VIRTIO_INPUT_EV_REP 0x14\n\n#define BTN_LEFT 0x110\n#define BTN_RIGHT 0x111\n#define BTN_MIDDLE 0x112\n#define BTN_GEAR_DOWN 0x150\n#define BTN_GEAR_UP 0x151\n\n#define REL_X 0x00\n#define REL_Y 0x01\n#define REL_Z 0x02\n#define REL_WHEEL 0x08\n\n#define ABS_X 0x00\n#define ABS_Y 0x01\n#define ABS_Z 0x02\n\ntypedef struct VIRTIOInputDevice {\n VIRTIODevice common;\n VirtioInputTypeEnum type;\n uint32_t buttons_state;\n} VIRTIOInputDevice;\n\nstatic const uint16_t buttons_list[] = {\n BTN_LEFT, BTN_RIGHT, BTN_MIDDLE\n};\n\nstatic int virtio_input_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n if (queue_idx == 1) {\n /* led & keyboard updates */\n // printf(\"%s: write_size=%d\\n\", __func__, write_size);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\n/* return < 0 if could not send key event */\nstatic int virtio_input_queue_event(VIRTIODevice *s,\n uint16_t type, uint16_t code,\n uint32_t value)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx, buf_len;\n uint16_t avail_idx;\n uint8_t buf[8];\n\n if (!qs->ready)\n return -1;\n\n put_le16(buf, type);\n put_le16(buf + 2, code);\n put_le32(buf + 4, value);\n buf_len = 8;\n \n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return -1;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n // printf(\"send: queue_idx=%d desc_idx=%d\\n\", queue_idx, desc_idx);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, buf_len);\n qs->last_avail_idx++;\n return 0;\n}\n\nint virtio_input_send_key_event(VIRTIODevice *s, BOOL is_down,\n uint16_t key_code)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n int ret;\n \n if (s1->type != VIRTIO_INPUT_TYPE_KEYBOARD)\n return -1;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_KEY, key_code, is_down);\n if (ret)\n return ret;\n return virtio_input_queue_event(s, VIRTIO_INPUT_EV_SYN, 0, 0);\n}\n\n/* also used for the tablet */\nint virtio_input_send_mouse_event(VIRTIODevice *s, int dx, int dy, int dz,\n unsigned int buttons)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n int ret, i, b, last_b;\n\n if (s1->type != VIRTIO_INPUT_TYPE_MOUSE &&\n s1->type != VIRTIO_INPUT_TYPE_TABLET)\n return -1;\n if (s1->type == VIRTIO_INPUT_TYPE_MOUSE) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_X, dx);\n if (ret != 0)\n return ret;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_Y, dy);\n if (ret != 0)\n return ret;\n } else {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_ABS, ABS_X, dx);\n if (ret != 0)\n return ret;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_ABS, ABS_Y, dy);\n if (ret != 0)\n return ret;\n }\n if (dz != 0) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_WHEEL, dz);\n if (ret != 0)\n return ret;\n }\n\n if (buttons != s1->buttons_state) {\n for(i = 0; i < countof(buttons_list); i++) {\n b = (buttons >> i) & 1;\n last_b = (s1->buttons_state >> i) & 1;\n if (b != last_b) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_KEY,\n buttons_list[i], b);\n if (ret != 0)\n return ret;\n }\n }\n s1->buttons_state = buttons;\n }\n\n return virtio_input_queue_event(s, VIRTIO_INPUT_EV_SYN, 0, 0);\n}\n\nstatic void set_bit(uint8_t *tab, int k)\n{\n tab[k >> 3] |= 1 << (k & 7);\n}\n\nstatic void virtio_input_config_write(VIRTIODevice *s)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n uint8_t *config = s->config_space;\n int i;\n \n // printf(\"config_write: %02x %02x\\n\", config[0], config[1]);\n switch(config[0]) {\n case VIRTIO_INPUT_CFG_UNSET:\n break;\n case VIRTIO_INPUT_CFG_ID_NAME:\n {\n const char *name;\n int len;\n switch(s1->type) {\n case VIRTIO_INPUT_TYPE_KEYBOARD:\n name = \"virtio_keyboard\";\n break;\n case VIRTIO_INPUT_TYPE_MOUSE:\n name = \"virtio_mouse\";\n break;\n case VIRTIO_INPUT_TYPE_TABLET:\n name = \"virtio_tablet\";\n break;\n default:\n abort();\n }\n len = strlen(name);\n config[2] = len;\n memcpy(config + 8, name, len);\n }\n break;\n default:\n case VIRTIO_INPUT_CFG_ID_SERIAL:\n case VIRTIO_INPUT_CFG_ID_DEVIDS:\n case VIRTIO_INPUT_CFG_PROP_BITS:\n config[2] = 0; /* size of reply */\n break;\n case VIRTIO_INPUT_CFG_EV_BITS:\n config[2] = 0;\n switch(s1->type) {\n case VIRTIO_INPUT_TYPE_KEYBOARD:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 128 / 8;\n memset(config + 8, 0xff, 128 / 8); /* bitmap */\n break;\n case VIRTIO_INPUT_EV_REP: /* allow key repetition */\n config[2] = 1;\n break;\n default:\n break;\n }\n break;\n case VIRTIO_INPUT_TYPE_MOUSE:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 512 / 8;\n memset(config + 8, 0, 512 / 8); /* bitmap */\n for(i = 0; i < countof(buttons_list); i++)\n set_bit(config + 8, buttons_list[i]);\n break;\n case VIRTIO_INPUT_EV_REL:\n config[2] = 2;\n config[8] = 0;\n config[9] = 0;\n set_bit(config + 8, REL_X);\n set_bit(config + 8, REL_Y);\n set_bit(config + 8, REL_WHEEL);\n break;\n default:\n break;\n }\n break;\n case VIRTIO_INPUT_TYPE_TABLET:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 512 / 8;\n memset(config + 8, 0, 512 / 8); /* bitmap */\n for(i = 0; i < countof(buttons_list); i++)\n set_bit(config + 8, buttons_list[i]);\n break;\n case VIRTIO_INPUT_EV_REL:\n config[2] = 2;\n config[8] = 0;\n config[9] = 0;\n set_bit(config + 8, REL_WHEEL);\n break;\n case VIRTIO_INPUT_EV_ABS:\n config[2] = 1;\n config[8] = 0;\n set_bit(config + 8, ABS_X);\n set_bit(config + 8, ABS_Y);\n break;\n default:\n break;\n }\n break;\n default:\n abort();\n }\n break;\n case VIRTIO_INPUT_CFG_ABS_INFO:\n if (s1->type == VIRTIO_INPUT_TYPE_TABLET && config[1] <= 1) {\n /* for ABS_X and ABS_Y */\n config[2] = 5 * 4;\n put_le32(config + 8, 0); /* min */\n put_le32(config + 12, VIRTIO_INPUT_ABS_SCALE - 1) ; /* max */\n put_le32(config + 16, 0); /* fuzz */\n put_le32(config + 20, 0); /* flat */\n put_le32(config + 24, 0); /* res */\n }\n break;\n }\n}\n\nVIRTIODevice *virtio_input_init(VIRTIOBusDef *bus, VirtioInputTypeEnum type)\n{\n VIRTIOInputDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 18, 256, virtio_input_recv_request);\n s->common.queue[0].manual_recv = TRUE;\n s->common.device_features = 0;\n s->common.config_write = virtio_input_config_write;\n s->type = type;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* 9p filesystem device */\n\ntypedef struct {\n struct list_head link;\n uint32_t fid;\n FSFile *fd;\n} FIDDesc;\n\ntypedef struct VIRTIO9PDevice {\n VIRTIODevice common;\n FSDevice *fs;\n int msize; /* maximum message size */\n struct list_head fid_list; /* list of FIDDesc */\n BOOL req_in_progress;\n} VIRTIO9PDevice;\n\nstatic FIDDesc *fid_find1(VIRTIO9PDevice *s, uint32_t fid)\n{\n struct list_head *el;\n FIDDesc *f;\n\n list_for_each(el, &s->fid_list) {\n f = list_entry(el, FIDDesc, link);\n if (f->fid == fid)\n return f;\n }\n return NULL;\n}\n\nstatic FSFile *fid_find(VIRTIO9PDevice *s, uint32_t fid)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (!f)\n return NULL;\n return f->fd;\n}\n\nstatic void fid_delete(VIRTIO9PDevice *s, uint32_t fid)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (f) {\n s->fs->fs_delete(s->fs, f->fd);\n list_del(&f->link);\n free(f);\n }\n}\n\nstatic void fid_set(VIRTIO9PDevice *s, uint32_t fid, FSFile *fd)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (f) {\n s->fs->fs_delete(s->fs, f->fd);\n f->fd = fd;\n } else {\n f = malloc(sizeof(*f));\n f->fid = fid;\n f->fd = fd;\n list_add(&f->link, &s->fid_list);\n }\n}\n\n#ifdef DEBUG_VIRTIO\n\ntypedef struct {\n uint8_t tag;\n const char *name;\n} Virtio9POPName;\n\nstatic const Virtio9POPName virtio_9p_op_names[] = {\n { 8, \"statfs\" },\n { 12, \"lopen\" },\n { 14, \"lcreate\" },\n { 16, \"symlink\" },\n { 18, \"mknod\" },\n { 22, \"readlink\" },\n { 24, \"getattr\" },\n { 26, \"setattr\" },\n { 30, \"xattrwalk\" },\n { 40, \"readdir\" },\n { 50, \"fsync\" },\n { 52, \"lock\" },\n { 54, \"getlock\" },\n { 70, \"link\" },\n { 72, \"mkdir\" },\n { 74, \"renameat\" },\n { 76, \"unlinkat\" },\n { 100, \"version\" },\n { 104, \"attach\" },\n { 108, \"flush\" },\n { 110, \"walk\" },\n { 116, \"read\" },\n { 118, \"write\" },\n { 120, \"clunk\" },\n { 0, NULL },\n};\n\nstatic const char *get_9p_op_name(int tag)\n{\n const Virtio9POPName *p;\n for(p = virtio_9p_op_names; p->name != NULL; p++) {\n if (p->tag == tag)\n return p->name;\n }\n return NULL;\n}\n\n#endif /* DEBUG_VIRTIO */\n\nstatic int marshall(VIRTIO9PDevice *s, \n uint8_t *buf1, int max_len, const char *fmt, ...)\n{\n va_list ap;\n int c;\n uint32_t val;\n uint64_t val64;\n uint8_t *buf, *buf_end;\n\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" ->\");\n#endif\n va_start(ap, fmt);\n buf = buf1;\n buf_end = buf1 + max_len;\n for(;;) {\n c = *fmt++;\n if (c == '\\0')\n break;\n switch(c) {\n case 'b':\n assert(buf + 1 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" b=%d\", val);\n#endif\n buf[0] = val;\n buf += 1;\n break;\n case 'h':\n assert(buf + 2 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" h=%d\", val);\n#endif\n put_le16(buf, val);\n buf += 2;\n break;\n case 'w':\n assert(buf + 4 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" w=%d\", val);\n#endif\n put_le32(buf, val);\n buf += 4;\n break;\n case 'd':\n assert(buf + 8 <= buf_end);\n val64 = va_arg(ap, uint64_t);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" d=%\" PRId64, val64);\n#endif\n put_le64(buf, val64);\n buf += 8;\n break;\n case 's':\n {\n char *str;\n int len;\n str = va_arg(ap, char *);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" s=\\\"%s\\\"\", str);\n#endif\n len = strlen(str);\n assert(len <= 65535);\n assert(buf + 2 + len <= buf_end);\n put_le16(buf, len);\n buf += 2;\n memcpy(buf, str, len);\n buf += len;\n }\n break;\n case 'Q':\n {\n FSQID *qid;\n assert(buf + 13 <= buf_end);\n qid = va_arg(ap, FSQID *);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" Q=%d:%d:%\" PRIu64, qid->type, qid->version, qid->path);\n#endif\n buf[0] = qid->type;\n put_le32(buf + 1, qid->version);\n put_le64(buf + 5, qid->path);\n buf += 13;\n }\n break;\n default:\n abort();\n }\n }\n va_end(ap);\n return buf - buf1;\n}\n\n/* return < 0 if error */\n/* XXX: free allocated strings in case of error */\nstatic int unmarshall(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, int *poffset, const char *fmt, ...)\n{\n VIRTIODevice *s1 = (VIRTIODevice *)s;\n va_list ap;\n int offset, c;\n uint8_t buf[16];\n\n offset = *poffset;\n va_start(ap, fmt);\n for(;;) {\n c = *fmt++;\n if (c == '\\0')\n break;\n switch(c) {\n case 'b':\n {\n uint8_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 1))\n return -1;\n ptr = va_arg(ap, uint8_t *);\n *ptr = buf[0];\n offset += 1;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" b=%d\", *ptr);\n#endif\n }\n break;\n case 'h':\n {\n uint16_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 2))\n return -1;\n ptr = va_arg(ap, uint16_t *);\n *ptr = get_le16(buf);\n offset += 2;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" h=%d\", *ptr);\n#endif\n }\n break;\n case 'w':\n {\n uint32_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 4))\n return -1;\n ptr = va_arg(ap, uint32_t *);\n *ptr = get_le32(buf);\n offset += 4;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" w=%d\", *ptr);\n#endif\n }\n break;\n case 'd':\n {\n uint64_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 8))\n return -1;\n ptr = va_arg(ap, uint64_t *);\n *ptr = get_le64(buf);\n offset += 8;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" d=%\" PRId64, *ptr);\n#endif\n }\n break;\n case 's':\n {\n char *str, **ptr;\n int len;\n\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 2))\n return -1;\n len = get_le16(buf);\n offset += 2;\n str = malloc(len + 1);\n if (memcpy_from_queue(s1, str, queue_idx, desc_idx, offset, len))\n return -1;\n str[len] = '\\0';\n offset += len;\n ptr = va_arg(ap, char **);\n *ptr = str;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" s=\\\"%s\\\"\", *ptr);\n#endif\n }\n break;\n default:\n abort();\n }\n }\n va_end(ap);\n *poffset = offset;\n return 0;\n}\n\nstatic void virtio_9p_send_reply(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, uint8_t id, uint16_t tag, \n uint8_t *buf, int buf_len)\n{\n uint8_t *buf1;\n int len;\n\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P) {\n if (id == 6)\n printf(\" (error)\");\n printf(\"\\n\");\n }\n#endif\n len = buf_len + 7;\n buf1 = malloc(len);\n put_le32(buf1, len);\n buf1[4] = id + 1;\n put_le16(buf1 + 5, tag);\n memcpy(buf1 + 7, buf, buf_len);\n memcpy_to_queue((VIRTIODevice *)s, queue_idx, desc_idx, 0, buf1, len);\n virtio_consume_desc((VIRTIODevice *)s, queue_idx, desc_idx, len);\n free(buf1);\n}\n\nstatic void virtio_9p_send_error(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, uint16_t tag, uint32_t error)\n{\n uint8_t buf[4];\n int buf_len;\n\n buf_len = marshall(s, buf, sizeof(buf), \"w\", -error);\n virtio_9p_send_reply(s, queue_idx, desc_idx, 6, tag, buf, buf_len);\n}\n\ntypedef struct {\n VIRTIO9PDevice *dev;\n int queue_idx;\n int desc_idx;\n uint16_t tag;\n} P9OpenInfo;\n\nstatic void virtio_9p_open_reply(FSDevice *fs, FSQID *qid, int err,\n P9OpenInfo *oi)\n{\n VIRTIO9PDevice *s = oi->dev;\n uint8_t buf[32];\n int buf_len;\n \n if (err < 0) {\n virtio_9p_send_error(s, oi->queue_idx, oi->desc_idx, oi->tag, err);\n } else {\n buf_len = marshall(s, buf, sizeof(buf),\n \"Qw\", qid, s->msize - 24);\n virtio_9p_send_reply(s, oi->queue_idx, oi->desc_idx, 12, oi->tag,\n buf, buf_len);\n }\n free(oi);\n}\n\nstatic void virtio_9p_open_cb(FSDevice *fs, FSQID *qid, int err,\n void *opaque)\n{\n P9OpenInfo *oi = opaque;\n VIRTIO9PDevice *s = oi->dev;\n int queue_idx = oi->queue_idx;\n \n virtio_9p_open_reply(fs, qid, err, oi);\n\n s->req_in_progress = FALSE;\n\n /* handle next requests */\n queue_notify((VIRTIODevice *)s, queue_idx);\n}\n\nstatic int virtio_9p_recv_request(VIRTIODevice *s1, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIO9PDevice *s = (VIRTIO9PDevice *)s1;\n int offset, header_len;\n uint8_t id;\n uint16_t tag;\n uint8_t buf[1024];\n int buf_len, err;\n FSDevice *fs = s->fs;\n\n if (queue_idx != 0)\n return 0;\n \n if (s->req_in_progress)\n return -1;\n \n offset = 0;\n header_len = 4 + 1 + 2;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, header_len)) {\n tag = 0;\n goto protocol_error;\n }\n //size = get_le32(buf);\n id = buf[4];\n tag = get_le16(buf + 5);\n offset += header_len;\n \n#ifdef DEBUG_VIRTIO\n if (s1->debug & VIRTIO_DEBUG_9P) {\n const char *name;\n name = get_9p_op_name(id);\n printf(\"9p: op=\");\n if (name)\n printf(\"%s\", name);\n else\n printf(\"%d\", id);\n }\n#endif\n /* Note: same subset as JOR1K */\n switch(id) {\n case 8: /* statfs */\n {\n FSStatFS st;\n\n fs->fs_statfs(fs, &st);\n buf_len = marshall(s, buf, sizeof(buf),\n \"wwddddddw\", \n 0,\n st.f_bsize,\n st.f_blocks,\n st.f_bfree,\n st.f_bavail,\n st.f_files,\n st.f_ffree,\n 0, /* id */\n 256 /* max filename length */\n );\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 12: /* lopen */\n {\n uint32_t fid, flags;\n FSFile *f;\n FSQID qid;\n P9OpenInfo *oi;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"ww\", &fid, &flags))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n oi = malloc(sizeof(*oi));\n oi->dev = s;\n oi->queue_idx = queue_idx;\n oi->desc_idx = desc_idx;\n oi->tag = tag;\n err = fs->fs_open(fs, &qid, f, flags, virtio_9p_open_cb, oi);\n if (err <= 0) {\n virtio_9p_open_reply(fs, &qid, err, oi);\n } else {\n s->req_in_progress = TRUE;\n }\n }\n break;\n case 14: /* lcreate */\n {\n uint32_t fid, flags, mode, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wswww\", &fid, &name, &flags, &mode, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_create(fs, &qid, f, name, flags, mode, gid);\n }\n free(name);\n if (err) \n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Qw\", &qid, s->msize - 24);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 16: /* symlink */\n {\n uint32_t fid, gid;\n char *name, *symgt;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wssw\", &fid, &name, &symgt, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_symlink(fs, &qid, f, name, symgt, gid);\n }\n free(name);\n free(symgt);\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 18: /* mknod */\n {\n uint32_t fid, mode, major, minor, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wswwww\", &fid, &name, &mode, &major, &minor, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_mknod(fs, &qid, f, name, mode, major, minor, gid);\n }\n free(name);\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 22: /* readlink */\n {\n uint32_t fid;\n char buf1[1024];\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"w\", &fid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_readlink(fs, buf1, sizeof(buf1), f);\n }\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"s\", buf1);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 24: /* getattr */\n {\n uint32_t fid;\n uint64_t mask;\n FSFile *f;\n FSStat st;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wd\", &fid, &mask))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_stat(fs, f, &st);\n if (err)\n goto error;\n\n buf_len = marshall(s, buf, sizeof(buf),\n \"dQwwwddddddddddddddd\", \n mask, &st.qid,\n st.st_mode, st.st_uid, st.st_gid,\n st.st_nlink, st.st_rdev, st.st_size,\n st.st_blksize, st.st_blocks,\n st.st_atime_sec, (uint64_t)st.st_atime_nsec,\n st.st_mtime_sec, (uint64_t)st.st_mtime_nsec,\n st.st_ctime_sec, (uint64_t)st.st_ctime_nsec,\n (uint64_t)0, (uint64_t)0,\n (uint64_t)0, (uint64_t)0);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 26: /* setattr */\n {\n uint32_t fid, mask, mode, uid, gid;\n uint64_t size, atime_sec, atime_nsec, mtime_sec, mtime_nsec;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wwwwwddddd\", &fid, &mask, &mode, &uid, &gid,\n &size, &atime_sec, &atime_nsec, \n &mtime_sec, &mtime_nsec))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_setattr(fs, f, mask, mode, uid, gid, size, atime_sec,\n atime_nsec, mtime_sec, mtime_nsec);\n if (err)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 30: /* xattrwalk */\n {\n /* not supported yet */\n err = -P9_ENOTSUP;\n goto error;\n }\n break;\n case 40: /* readdir */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf = malloc(count + 4);\n n = fs->fs_readdir(fs, f, offs, buf + 4, count);\n if (n < 0) {\n err = n;\n goto error;\n }\n put_le32(buf, n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, n + 4);\n free(buf);\n }\n break;\n case 50: /* fsync */\n {\n uint32_t fid;\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"w\", &fid))\n goto protocol_error;\n /* ignored */\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 52: /* lock */\n {\n uint32_t fid;\n FSFile *f;\n FSLock lock;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wbwddws\", &fid, &lock.type, &lock.flags,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n err = -P9_EPROTO;\n else\n err = fs->fs_lock(fs, f, &lock);\n free(lock.client_id);\n if (err < 0)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"b\", err);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 54: /* getlock */\n {\n uint32_t fid;\n FSFile *f;\n FSLock lock;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wbddws\", &fid, &lock.type,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n err = -P9_EPROTO;\n else\n err = fs->fs_getlock(fs, f, &lock);\n if (err < 0) {\n free(lock.client_id);\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"bddws\",\n &lock.type,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id);\n free(lock.client_id);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 70: /* link */\n {\n uint32_t dfid, fid;\n char *name;\n FSFile *f, *df;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wws\", &dfid, &fid, &name))\n goto protocol_error;\n df = fid_find(s, dfid);\n f = fid_find(s, fid);\n if (!df || !f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_link(fs, df, f, name);\n }\n free(name);\n if (err)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 72: /* mkdir */\n {\n uint32_t fid, mode, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsww\", &fid, &name, &mode, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_mkdir(fs, &qid, f, name, mode, gid);\n if (err != 0)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 74: /* renameat */\n {\n uint32_t fid, new_fid;\n char *name, *new_name;\n FSFile *f, *new_f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsws\", &fid, &name, &new_fid, &new_name))\n goto protocol_error;\n f = fid_find(s, fid);\n new_f = fid_find(s, new_fid);\n if (!f || !new_f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_renameat(fs, f, name, new_f, new_name);\n }\n free(name);\n free(new_name);\n if (err != 0)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 76: /* unlinkat */\n {\n uint32_t fid, flags;\n char *name;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsw\", &fid, &name, &flags))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_unlinkat(fs, f, name);\n }\n free(name);\n if (err != 0)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 100: /* version */\n {\n uint32_t msize;\n char *version;\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"ws\", &msize, &version))\n goto protocol_error;\n s->msize = msize;\n // printf(\"version: msize=%d version=%s\\n\", msize, version);\n free(version);\n buf_len = marshall(s, buf, sizeof(buf), \"ws\", s->msize, \"9P2000.L\");\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 104: /* attach */\n {\n uint32_t fid, afid, uid;\n char *uname, *aname;\n FSQID qid;\n FSFile *f;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"wwssw\", &fid, &afid, &uname, &aname, &uid))\n goto protocol_error;\n err = fs->fs_attach(fs, &f, &qid, uid, uname, aname);\n if (err != 0)\n goto error;\n fid_set(s, fid, f);\n free(uname);\n free(aname);\n buf_len = marshall(s, buf, sizeof(buf), \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 108: /* flush */\n {\n uint16_t oldtag;\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"h\", &oldtag))\n goto protocol_error;\n /* ignored */\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 110: /* walk */\n {\n uint32_t fid, newfid;\n uint16_t nwname;\n FSQID *qids;\n char **names;\n FSFile *f;\n int i;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"wwh\", &fid, &newfid, &nwname))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n names = mallocz(sizeof(names[0]) * nwname);\n qids = malloc(sizeof(qids[0]) * nwname);\n for(i = 0; i < nwname; i++) {\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"s\", &names[i])) {\n err = -P9_EPROTO;\n goto walk_done;\n }\n }\n err = fs->fs_walk(fs, &f, qids, f, nwname, names);\n walk_done:\n for(i = 0; i < nwname; i++) {\n free(names[i]);\n }\n free(names);\n if (err < 0) {\n free(qids);\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"h\", err);\n for(i = 0; i < err; i++) {\n buf_len += marshall(s, buf + buf_len, sizeof(buf) - buf_len,\n \"Q\", &qids[i]);\n }\n free(qids);\n fid_set(s, newfid, f);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 116: /* read */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf = malloc(count + 4);\n n = fs->fs_read(fs, f, offs, buf + 4, count);\n if (n < 0) {\n err = n;\n free(buf);\n goto error;\n }\n put_le32(buf, n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, n + 4);\n free(buf);\n }\n break;\n case 118: /* write */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf1;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf1 = malloc(count);\n if (memcpy_from_queue(s1, buf1, queue_idx, desc_idx, offset,\n count)) {\n free(buf1);\n goto protocol_error;\n }\n n = fs->fs_write(fs, f, offs, buf1, count);\n free(buf1);\n if (n < 0) {\n err = n;\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"w\", n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 120: /* clunk */\n {\n uint32_t fid;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"w\", &fid))\n goto protocol_error;\n fid_delete(s, fid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n default:\n printf(\"9p: unsupported operation id=%d\\n\", id);\n goto protocol_error;\n }\n return 0;\n error:\n virtio_9p_send_error(s, queue_idx, desc_idx, tag, err);\n return 0;\n protocol_error:\n fid_not_found:\n err = -P9_EPROTO;\n goto error;\n}\n\nVIRTIODevice *virtio_9p_init(VIRTIOBusDef *bus, FSDevice *fs,\n const char *mount_tag)\n\n{\n VIRTIO9PDevice *s;\n int len;\n uint8_t *cfg;\n\n len = strlen(mount_tag);\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 9, 2 + len, virtio_9p_recv_request);\n s->common.device_features = 1 << 0;\n\n /* set the mount tag */\n cfg = s->common.config_space;\n cfg[0] = len;\n cfg[1] = len >> 8;\n memcpy(cfg + 2, mount_tag, len);\n\n s->fs = fs;\n s->msize = 8192;\n init_list_head(&s->fid_list);\n \n return (VIRTIODevice *)s;\n}\n\n"], ["/linuxpdf/tinyemu/machine.c", "/*\n * VM utilities\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#include \"fs_utils.h\"\n#ifdef CONFIG_FS_NET\n#include \"fs_wget.h\"\n#endif\n\nvoid __attribute__((format(printf, 1, 2))) vm_error(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n#ifdef EMSCRIPTEN\n vprintf(fmt, ap);\n#else\n vfprintf(stderr, fmt, ap);\n#endif\n va_end(ap);\n}\n\nint vm_get_int(JSONValue obj, const char *name, int *pval)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n vm_error(\"expecting '%s' property\\n\", name);\n return -1;\n }\n if (val.type != JSON_INT) {\n vm_error(\"%s: integer expected\\n\", name);\n return -1;\n }\n *pval = val.u.int32;\n return 0;\n}\n\nint vm_get_int_opt(JSONValue obj, const char *name, int *pval, int def_val)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n *pval = def_val;\n return 0;\n }\n if (val.type != JSON_INT) {\n vm_error(\"%s: integer expected\\n\", name);\n return -1;\n }\n *pval = val.u.int32;\n return 0;\n}\n\nstatic int vm_get_str2(JSONValue obj, const char *name, const char **pstr,\n BOOL is_opt)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n if (is_opt) {\n *pstr = NULL;\n return 0;\n } else {\n vm_error(\"expecting '%s' property\\n\", name);\n return -1;\n }\n }\n if (val.type != JSON_STR) {\n vm_error(\"%s: string expected\\n\", name);\n return -1;\n }\n *pstr = val.u.str->data;\n return 0;\n}\n\nstatic int vm_get_str(JSONValue obj, const char *name, const char **pstr)\n{ \n return vm_get_str2(obj, name, pstr, FALSE);\n}\n\nstatic int vm_get_str_opt(JSONValue obj, const char *name, const char **pstr)\n{ \n return vm_get_str2(obj, name, pstr, TRUE);\n}\n\nstatic char *strdup_null(const char *str)\n{\n if (!str)\n return NULL;\n else\n return strdup(str);\n}\n\n/* currently only for \"TZ\" */\nstatic char *cmdline_subst(const char *cmdline)\n{\n DynBuf dbuf;\n const char *p;\n char var_name[32], *q, buf[32];\n \n dbuf_init(&dbuf);\n p = cmdline;\n while (*p != '\\0') {\n if (p[0] == '$' && p[1] == '{') {\n p += 2;\n q = var_name;\n while (*p != '\\0' && *p != '}') {\n if ((q - var_name) < sizeof(var_name) - 1)\n *q++ = *p;\n p++;\n }\n *q = '\\0';\n if (*p == '}')\n p++;\n if (!strcmp(var_name, \"TZ\")) {\n time_t ti;\n struct tm tm;\n int n, sg;\n /* get the offset to UTC */\n time(&ti);\n localtime_r(&ti, &tm);\n n = tm.tm_gmtoff / 60;\n sg = '-';\n if (n < 0) {\n sg = '+';\n n = -n;\n }\n snprintf(buf, sizeof(buf), \"UTC%c%02d:%02d\",\n sg, n / 60, n % 60);\n dbuf_putstr(&dbuf, buf);\n }\n } else {\n dbuf_putc(&dbuf, *p++);\n }\n }\n dbuf_putc(&dbuf, 0);\n return (char *)dbuf.buf;\n}\n\nstatic BOOL find_name(const char *name, const char *name_list)\n{\n size_t len;\n const char *p, *r;\n \n p = name_list;\n for(;;) {\n r = strchr(p, ',');\n if (!r) {\n if (!strcmp(name, p))\n return TRUE;\n break;\n } else {\n len = r - p;\n if (len == strlen(name) && !memcmp(name, p, len))\n return TRUE;\n p = r + 1;\n }\n }\n return FALSE;\n}\n\nstatic const VirtMachineClass *virt_machine_list[] = {\n#if defined(EMSCRIPTEN)\n /* only a single machine in the EMSCRIPTEN target */\n#ifndef CONFIG_X86EMU\n &riscv_machine_class,\n#endif \n#else\n &riscv_machine_class,\n#endif /* !EMSCRIPTEN */\n#ifdef CONFIG_X86EMU\n &pc_machine_class,\n#endif\n NULL,\n};\n\nstatic const VirtMachineClass *virt_machine_find_class(const char *machine_name)\n{\n const VirtMachineClass *vmc, **pvmc;\n \n for(pvmc = virt_machine_list; *pvmc != NULL; pvmc++) {\n vmc = *pvmc;\n if (find_name(machine_name, vmc->machine_names))\n return vmc;\n }\n return NULL;\n}\n\nstatic int virt_machine_parse_config(VirtMachineParams *p,\n char *config_file_str, int len)\n{\n int version, val;\n const char *tag_name, *str;\n char buf1[256];\n JSONValue cfg, obj, el;\n \n cfg = json_parse_value_len(config_file_str, len);\n if (json_is_error(cfg)) {\n vm_error(\"error: %s\\n\", json_get_error(cfg));\n json_free(cfg);\n return -1;\n }\n\n if (vm_get_int(cfg, \"version\", &version) < 0)\n goto tag_fail;\n if (version != VM_CONFIG_VERSION) {\n if (version > VM_CONFIG_VERSION) {\n vm_error(\"The emulator is too old to run this VM: please upgrade\\n\");\n return -1;\n } else {\n vm_error(\"The VM configuration file is too old for this emulator version: please upgrade the VM configuration file\\n\");\n return -1;\n }\n }\n \n if (vm_get_str(cfg, \"machine\", &str) < 0)\n goto tag_fail;\n p->machine_name = strdup(str);\n p->vmc = virt_machine_find_class(p->machine_name);\n if (!p->vmc) {\n vm_error(\"Unknown machine name: %s\\n\", p->machine_name);\n goto tag_fail;\n }\n p->vmc->virt_machine_set_defaults(p);\n\n tag_name = \"memory_size\";\n if (vm_get_int(cfg, tag_name, &val) < 0)\n goto tag_fail;\n p->ram_size = (uint64_t)val << 20;\n \n tag_name = \"bios\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_BIOS].filename = strdup(str);\n }\n\n tag_name = \"kernel\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_KERNEL].filename = strdup(str);\n }\n\n tag_name = \"initrd\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_INITRD].filename = strdup(str);\n }\n\n if (vm_get_str_opt(cfg, \"cmdline\", &str) < 0)\n goto tag_fail;\n if (str) {\n p->cmdline = cmdline_subst(str);\n }\n \n for(;;) {\n snprintf(buf1, sizeof(buf1), \"drive%d\", p->drive_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->drive_count >= MAX_DRIVE_DEVICE) {\n vm_error(\"Too many drives\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"file\", &str) < 0)\n goto tag_fail;\n p->tab_drive[p->drive_count].filename = strdup(str);\n if (vm_get_str_opt(obj, \"device\", &str) < 0)\n goto tag_fail;\n p->tab_drive[p->drive_count].device = strdup_null(str);\n p->drive_count++;\n }\n\n for(;;) {\n snprintf(buf1, sizeof(buf1), \"fs%d\", p->fs_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->fs_count >= MAX_DRIVE_DEVICE) {\n vm_error(\"Too many filesystems\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"file\", &str) < 0)\n goto tag_fail;\n p->tab_fs[p->fs_count].filename = strdup(str);\n if (vm_get_str_opt(obj, \"tag\", &str) < 0)\n goto tag_fail;\n if (!str) {\n if (p->fs_count == 0)\n strcpy(buf1, \"/dev/root\");\n else\n snprintf(buf1, sizeof(buf1), \"/dev/root%d\", p->fs_count);\n str = buf1;\n }\n p->tab_fs[p->fs_count].tag = strdup(str);\n p->fs_count++;\n }\n\n for(;;) {\n snprintf(buf1, sizeof(buf1), \"eth%d\", p->eth_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->eth_count >= MAX_ETH_DEVICE) {\n vm_error(\"Too many ethernet interfaces\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"driver\", &str) < 0)\n goto tag_fail;\n p->tab_eth[p->eth_count].driver = strdup(str);\n if (!strcmp(str, \"tap\")) {\n if (vm_get_str(obj, \"ifname\", &str) < 0)\n goto tag_fail;\n p->tab_eth[p->eth_count].ifname = strdup(str);\n }\n p->eth_count++;\n }\n\n p->display_device = NULL;\n obj = json_object_get(cfg, \"display0\");\n if (!json_is_undefined(obj)) {\n if (vm_get_str(obj, \"device\", &str) < 0)\n goto tag_fail;\n p->display_device = strdup(str);\n if (vm_get_int(obj, \"width\", &p->width) < 0)\n goto tag_fail;\n if (vm_get_int(obj, \"height\", &p->height) < 0)\n goto tag_fail;\n if (vm_get_str_opt(obj, \"vga_bios\", &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_VGA_BIOS].filename = strdup(str);\n }\n }\n\n if (vm_get_str_opt(cfg, \"input_device\", &str) < 0)\n goto tag_fail;\n p->input_device = strdup_null(str);\n\n if (vm_get_str_opt(cfg, \"accel\", &str) < 0)\n goto tag_fail;\n if (str) {\n if (!strcmp(str, \"none\")) {\n p->accel_enable = FALSE;\n } else if (!strcmp(str, \"auto\")) {\n p->accel_enable = TRUE;\n } else {\n vm_error(\"unsupported 'accel' config: %s\\n\", str);\n return -1;\n }\n }\n\n tag_name = \"rtc_local_time\";\n el = json_object_get(cfg, tag_name);\n if (!json_is_undefined(el)) {\n if (el.type != JSON_BOOL) {\n vm_error(\"%s: boolean expected\\n\", tag_name);\n goto tag_fail;\n }\n p->rtc_local_time = el.u.b;\n }\n \n json_free(cfg);\n return 0;\n tag_fail:\n json_free(cfg);\n return -1;\n}\n\ntypedef void FSLoadFileCB(void *opaque, uint8_t *buf, int buf_len);\n\ntypedef struct {\n VirtMachineParams *vm_params;\n void (*start_cb)(void *opaque);\n void *opaque;\n \n FSLoadFileCB *file_load_cb;\n void *file_load_opaque;\n int file_index;\n} VMConfigLoadState;\n\nstatic void config_file_loaded(void *opaque, uint8_t *buf, int buf_len);\nstatic void config_additional_file_load(VMConfigLoadState *s);\nstatic void config_additional_file_load_cb(void *opaque,\n uint8_t *buf, int buf_len);\n\n/* XXX: win32, URL */\nchar *get_file_path(const char *base_filename, const char *filename)\n{\n int len, len1;\n char *fname, *p;\n \n if (!base_filename)\n goto done;\n if (strchr(filename, ':'))\n goto done; /* full URL */\n if (filename[0] == '/')\n goto done;\n p = strrchr(base_filename, '/');\n if (!p) {\n done:\n return strdup(filename);\n }\n len = p + 1 - base_filename;\n len1 = strlen(filename);\n fname = malloc(len + len1 + 1);\n memcpy(fname, base_filename, len);\n memcpy(fname + len, filename, len1 + 1);\n return fname;\n}\n\n\n#ifdef EMSCRIPTEN\nstatic int load_file(uint8_t **pbuf, const char *filename)\n{\n abort();\n}\n#else\n/* return -1 if error. */\nstatic int load_file(uint8_t **pbuf, const char *filename)\n{\n FILE *f;\n int size;\n uint8_t *buf;\n \n f = fopen(filename, \"rb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n size = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = malloc(size);\n if (fread(buf, 1, size, f) != size) {\n fprintf(stderr, \"%s: read error\\n\", filename);\n exit(1);\n }\n fclose(f);\n *pbuf = buf;\n return size;\n}\n#endif\n\n#ifdef CONFIG_FS_NET\nstatic void config_load_file_cb(void *opaque, int err, void *data, size_t size)\n{\n VMConfigLoadState *s = opaque;\n \n // printf(\"err=%d data=%p size=%ld\\n\", err, data, size);\n if (err < 0) {\n vm_error(\"Error %d while loading file\\n\", -err);\n exit(1);\n }\n s->file_load_cb(s->file_load_opaque, data, size);\n}\n#endif\n\nstatic void config_load_file(VMConfigLoadState *s, const char *filename,\n FSLoadFileCB *cb, void *opaque)\n{\n // printf(\"loading %s\\n\", filename);\n#ifdef CONFIG_FS_NET\n if (is_url(filename)) {\n s->file_load_cb = cb;\n s->file_load_opaque = opaque;\n fs_wget(filename, NULL, NULL, s, config_load_file_cb, TRUE);\n } else\n#endif\n {\n uint8_t *buf;\n int size;\n size = load_file(&buf, filename);\n cb(opaque, buf, size);\n free(buf);\n }\n}\n\nvoid virt_machine_load_config_file(VirtMachineParams *p,\n const char *filename,\n void (*start_cb)(void *opaque),\n void *opaque)\n{\n VMConfigLoadState *s;\n \n s = mallocz(sizeof(*s));\n s->vm_params = p;\n s->start_cb = start_cb;\n s->opaque = opaque;\n p->cfg_filename = strdup(filename);\n\n config_load_file(s, filename, config_file_loaded, s);\n}\n\nstatic void config_file_loaded(void *opaque, uint8_t *buf, int buf_len)\n{\n VMConfigLoadState *s = opaque;\n VirtMachineParams *p = s->vm_params;\n\n if (virt_machine_parse_config(p, (char *)buf, buf_len) < 0)\n exit(1);\n \n /* load the additional files */\n s->file_index = 0;\n config_additional_file_load(s);\n}\n\nstatic void config_additional_file_load(VMConfigLoadState *s)\n{\n VirtMachineParams *p = s->vm_params;\n while (s->file_index < VM_FILE_COUNT &&\n p->files[s->file_index].filename == NULL) {\n s->file_index++;\n }\n if (s->file_index == VM_FILE_COUNT) {\n if (s->start_cb)\n s->start_cb(s->opaque);\n free(s);\n } else {\n char *fname;\n \n fname = get_file_path(p->cfg_filename,\n p->files[s->file_index].filename);\n config_load_file(s, fname,\n config_additional_file_load_cb, s);\n free(fname);\n }\n}\n\nstatic void config_additional_file_load_cb(void *opaque,\n uint8_t *buf, int buf_len)\n{\n VMConfigLoadState *s = opaque;\n VirtMachineParams *p = s->vm_params;\n\n p->files[s->file_index].buf = malloc(buf_len);\n memcpy(p->files[s->file_index].buf, buf, buf_len);\n p->files[s->file_index].len = buf_len;\n\n /* load the next files */\n s->file_index++;\n config_additional_file_load(s);\n}\n\nvoid vm_add_cmdline(VirtMachineParams *p, const char *cmdline)\n{\n char *new_cmdline, *old_cmdline;\n if (cmdline[0] == '!') {\n new_cmdline = strdup(cmdline + 1);\n } else {\n old_cmdline = p->cmdline;\n if (!old_cmdline)\n old_cmdline = \"\";\n new_cmdline = malloc(strlen(old_cmdline) + 1 + strlen(cmdline) + 1);\n strcpy(new_cmdline, old_cmdline);\n strcat(new_cmdline, \" \");\n strcat(new_cmdline, cmdline);\n }\n free(p->cmdline);\n p->cmdline = new_cmdline;\n}\n\nvoid virt_machine_free_config(VirtMachineParams *p)\n{\n int i;\n \n free(p->machine_name);\n free(p->cmdline);\n for(i = 0; i < VM_FILE_COUNT; i++) {\n free(p->files[i].filename);\n free(p->files[i].buf);\n }\n for(i = 0; i < p->drive_count; i++) {\n free(p->tab_drive[i].filename);\n free(p->tab_drive[i].device);\n }\n for(i = 0; i < p->fs_count; i++) {\n free(p->tab_fs[i].filename);\n free(p->tab_fs[i].tag);\n }\n for(i = 0; i < p->eth_count; i++) {\n free(p->tab_eth[i].driver);\n free(p->tab_eth[i].ifname);\n }\n free(p->input_device);\n free(p->display_device);\n free(p->cfg_filename);\n}\n\nVirtMachine *virt_machine_init(const VirtMachineParams *p)\n{\n const VirtMachineClass *vmc = p->vmc;\n return vmc->virt_machine_init(p);\n}\n\nvoid virt_machine_set_defaults(VirtMachineParams *p)\n{\n memset(p, 0, sizeof(*p));\n}\n\nvoid virt_machine_end(VirtMachine *s)\n{\n s->vmc->virt_machine_end(s);\n}\n"], ["/linuxpdf/tinyemu/sdl.c", "/*\n * SDL display driver\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"cutils.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n#define KEYCODE_MAX 127\n\nstatic SDL_Surface *screen;\nstatic SDL_Surface *fb_surface;\nstatic int screen_width, screen_height, fb_width, fb_height, fb_stride;\nstatic SDL_Cursor *sdl_cursor_hidden;\nstatic uint8_t key_pressed[KEYCODE_MAX + 1];\n\nstatic void sdl_update_fb_surface(FBDevice *fb_dev)\n{\n if (!fb_surface)\n goto force_alloc;\n if (fb_width != fb_dev->width ||\n fb_height != fb_dev->height ||\n fb_stride != fb_dev->stride) {\n force_alloc:\n if (fb_surface != NULL)\n SDL_FreeSurface(fb_surface);\n fb_width = fb_dev->width;\n fb_height = fb_dev->height;\n fb_stride = fb_dev->stride;\n fb_surface = SDL_CreateRGBSurfaceFrom(fb_dev->fb_data,\n fb_dev->width, fb_dev->height,\n 32, fb_dev->stride,\n 0x00ff0000,\n 0x0000ff00,\n 0x000000ff,\n 0x00000000);\n if (!fb_surface) {\n fprintf(stderr, \"Could not create SDL framebuffer surface\\n\");\n exit(1);\n }\n }\n}\n\nstatic void sdl_update(FBDevice *fb_dev, void *opaque,\n int x, int y, int w, int h)\n{\n SDL_Rect r;\n // printf(\"sdl_update: %d %d %d %d\\n\", x, y, w, h);\n r.x = x;\n r.y = y;\n r.w = w;\n r.h = h;\n SDL_BlitSurface(fb_surface, &r, screen, &r);\n SDL_UpdateRect(screen, r.x, r.y, r.w, r.h);\n}\n\n#if defined(_WIN32)\n\nstatic int sdl_get_keycode(const SDL_KeyboardEvent *ev)\n{\n return ev->keysym.scancode;\n}\n\n#else\n\n/* we assume Xorg is used with a PC keyboard. Return 0 if no keycode found. */\nstatic int sdl_get_keycode(const SDL_KeyboardEvent *ev)\n{\n int keycode;\n keycode = ev->keysym.scancode;\n if (keycode < 9) {\n keycode = 0;\n } else if (keycode < 127 + 8) {\n keycode -= 8;\n } else {\n keycode = 0;\n }\n return keycode;\n}\n\n#endif\n\n/* release all pressed keys */\nstatic void sdl_reset_keys(VirtMachine *m)\n{\n int i;\n \n for(i = 1; i <= KEYCODE_MAX; i++) {\n if (key_pressed[i]) {\n vm_send_key_event(m, FALSE, i);\n key_pressed[i] = FALSE;\n }\n }\n}\n\nstatic void sdl_handle_key_event(const SDL_KeyboardEvent *ev, VirtMachine *m)\n{\n int keycode, keypress;\n\n keycode = sdl_get_keycode(ev);\n if (keycode) {\n if (keycode == 0x3a || keycode ==0x45) {\n /* SDL does not generate key up for numlock & caps lock */\n vm_send_key_event(m, TRUE, keycode);\n vm_send_key_event(m, FALSE, keycode);\n } else {\n keypress = (ev->type == SDL_KEYDOWN);\n if (keycode <= KEYCODE_MAX)\n key_pressed[keycode] = keypress;\n vm_send_key_event(m, keypress, keycode);\n }\n } else if (ev->type == SDL_KEYUP) {\n /* workaround to reset the keyboard state (used when changing\n desktop with ctrl-alt-x on Linux) */\n sdl_reset_keys(m);\n }\n}\n\nstatic void sdl_send_mouse_event(VirtMachine *m, int x1, int y1,\n int dz, int state, BOOL is_absolute)\n{\n int buttons, x, y;\n\n buttons = 0;\n if (state & SDL_BUTTON(SDL_BUTTON_LEFT))\n buttons |= (1 << 0);\n if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))\n buttons |= (1 << 1);\n if (state & SDL_BUTTON(SDL_BUTTON_MIDDLE))\n buttons |= (1 << 2);\n if (is_absolute) {\n x = (x1 * 32768) / screen_width;\n y = (y1 * 32768) / screen_height;\n } else {\n x = x1;\n y = y1;\n }\n vm_send_mouse_event(m, x, y, dz, buttons);\n}\n\nstatic void sdl_handle_mouse_motion_event(const SDL_Event *ev, VirtMachine *m)\n{\n BOOL is_absolute = vm_mouse_is_absolute(m);\n int x, y;\n if (is_absolute) {\n x = ev->motion.x;\n y = ev->motion.y;\n } else {\n x = ev->motion.xrel;\n y = ev->motion.yrel;\n }\n sdl_send_mouse_event(m, x, y, 0, ev->motion.state, is_absolute);\n}\n\nstatic void sdl_handle_mouse_button_event(const SDL_Event *ev, VirtMachine *m)\n{\n BOOL is_absolute = vm_mouse_is_absolute(m);\n int state, dz;\n\n dz = 0;\n if (ev->type == SDL_MOUSEBUTTONDOWN) {\n if (ev->button.button == SDL_BUTTON_WHEELUP) {\n dz = 1;\n } else if (ev->button.button == SDL_BUTTON_WHEELDOWN) {\n dz = -1;\n }\n }\n \n state = SDL_GetMouseState(NULL, NULL);\n /* just in case */\n if (ev->type == SDL_MOUSEBUTTONDOWN)\n state |= SDL_BUTTON(ev->button.button);\n else\n state &= ~SDL_BUTTON(ev->button.button);\n\n if (is_absolute) {\n sdl_send_mouse_event(m, ev->button.x, ev->button.y,\n dz, state, is_absolute);\n } else {\n sdl_send_mouse_event(m, 0, 0, dz, state, is_absolute);\n }\n}\n\nvoid sdl_refresh(VirtMachine *m)\n{\n SDL_Event ev_s, *ev = &ev_s;\n\n if (!m->fb_dev)\n return;\n \n sdl_update_fb_surface(m->fb_dev);\n\n m->fb_dev->refresh(m->fb_dev, sdl_update, NULL);\n \n while (SDL_PollEvent(ev)) {\n switch (ev->type) {\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n sdl_handle_key_event(&ev->key, m);\n break;\n case SDL_MOUSEMOTION:\n sdl_handle_mouse_motion_event(ev, m);\n break;\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n sdl_handle_mouse_button_event(ev, m);\n break;\n case SDL_QUIT:\n exit(0);\n }\n }\n}\n\nstatic void sdl_hide_cursor(void)\n{\n uint8_t data = 0;\n sdl_cursor_hidden = SDL_CreateCursor(&data, &data, 8, 1, 0, 0);\n SDL_ShowCursor(1);\n SDL_SetCursor(sdl_cursor_hidden);\n}\n\nvoid sdl_init(int width, int height)\n{\n int flags;\n \n screen_width = width;\n screen_height = height;\n\n if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE)) {\n fprintf(stderr, \"Could not initialize SDL - exiting\\n\");\n exit(1);\n }\n\n flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;\n screen = SDL_SetVideoMode(width, height, 0, flags);\n if (!screen || !screen->pixels) {\n fprintf(stderr, \"Could not open SDL display\\n\");\n exit(1);\n }\n\n SDL_WM_SetCaption(\"TinyEMU\", \"TinyEMU\");\n\n sdl_hide_cursor();\n}\n\n"], ["/linuxpdf/tinyemu/vga.c", "/*\n * Dummy VGA device\n * \n * Copyright (c) 2003-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n//#define DEBUG_VBE\n\n#define MSR_COLOR_EMULATION 0x01\n#define MSR_PAGE_SELECT 0x20\n\n#define ST01_V_RETRACE 0x08\n#define ST01_DISP_ENABLE 0x01\n\n#define VBE_DISPI_INDEX_ID 0x0\n#define VBE_DISPI_INDEX_XRES 0x1\n#define VBE_DISPI_INDEX_YRES 0x2\n#define VBE_DISPI_INDEX_BPP 0x3\n#define VBE_DISPI_INDEX_ENABLE 0x4\n#define VBE_DISPI_INDEX_BANK 0x5\n#define VBE_DISPI_INDEX_VIRT_WIDTH 0x6\n#define VBE_DISPI_INDEX_VIRT_HEIGHT 0x7\n#define VBE_DISPI_INDEX_X_OFFSET 0x8\n#define VBE_DISPI_INDEX_Y_OFFSET 0x9\n#define VBE_DISPI_INDEX_VIDEO_MEMORY_64K 0xa\n#define VBE_DISPI_INDEX_NB 0xb\n\n#define VBE_DISPI_ID0 0xB0C0\n#define VBE_DISPI_ID1 0xB0C1\n#define VBE_DISPI_ID2 0xB0C2\n#define VBE_DISPI_ID3 0xB0C3\n#define VBE_DISPI_ID4 0xB0C4\n#define VBE_DISPI_ID5 0xB0C5\n\n#define VBE_DISPI_DISABLED 0x00\n#define VBE_DISPI_ENABLED 0x01\n#define VBE_DISPI_GETCAPS 0x02\n#define VBE_DISPI_8BIT_DAC 0x20\n#define VBE_DISPI_LFB_ENABLED 0x40\n#define VBE_DISPI_NOCLEARMEM 0x80\n\n#define FB_ALLOC_ALIGN (1 << 20)\n\n#define MAX_TEXT_WIDTH 132\n#define MAX_TEXT_HEIGHT 60\n\nstruct VGAState {\n FBDevice *fb_dev;\n int fb_page_count;\n PhysMemoryRange *mem_range;\n PhysMemoryRange *mem_range2;\n PCIDevice *pci_dev;\n PhysMemoryRange *rom_range;\n\n uint8_t *vga_ram; /* 128K at 0xa0000 */\n \n uint8_t sr_index;\n uint8_t sr[8];\n uint8_t gr_index;\n uint8_t gr[16];\n uint8_t ar_index;\n uint8_t ar[21];\n int ar_flip_flop;\n uint8_t cr_index;\n uint8_t cr[256]; /* CRT registers */\n uint8_t msr; /* Misc Output Register */\n uint8_t fcr; /* Feature Control Register */\n uint8_t st00; /* status 0 */\n uint8_t st01; /* status 1 */\n uint8_t dac_state;\n uint8_t dac_sub_index;\n uint8_t dac_read_index;\n uint8_t dac_write_index;\n uint8_t dac_cache[3]; /* used when writing */\n uint8_t palette[768];\n \n /* text mode state */\n uint32_t last_palette[16];\n uint16_t last_ch_attr[MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT];\n uint32_t last_width;\n uint32_t last_height;\n uint16_t last_line_offset;\n uint16_t last_start_addr;\n uint16_t last_cursor_offset;\n uint8_t last_cursor_start;\n uint8_t last_cursor_end;\n \n /* VBE extension */\n uint16_t vbe_index;\n uint16_t vbe_regs[VBE_DISPI_INDEX_NB];\n};\n\nstatic void vga_draw_glyph8(uint8_t *d, int linesize,\n const uint8_t *font_ptr, int h,\n uint32_t fgcol, uint32_t bgcol)\n{\n uint32_t font_data, xorcol;\n\n xorcol = bgcol ^ fgcol;\n do {\n font_data = font_ptr[0];\n ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol;\n ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[7] = (-((font_data >> 0) & 1) & xorcol) ^ bgcol;\n font_ptr++;\n d += linesize;\n } while (--h);\n}\n\nstatic void vga_draw_glyph9(uint8_t *d, int linesize,\n const uint8_t *font_ptr, int h,\n uint32_t fgcol, uint32_t bgcol,\n int dup9)\n{\n uint32_t font_data, xorcol, v;\n\n xorcol = bgcol ^ fgcol;\n do {\n font_data = font_ptr[0];\n ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol;\n ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol;\n v = (-((font_data >> 0) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[7] = v;\n if (dup9)\n ((uint32_t *)d)[8] = v;\n else\n ((uint32_t *)d)[8] = bgcol;\n font_ptr++;\n d += linesize;\n } while (--h);\n}\n\nstatic const uint8_t cursor_glyph[32] = {\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n};\n\nstatic inline int c6_to_8(int v)\n{\n int b;\n v &= 0x3f;\n b = v & 1;\n return (v << 2) | (b << 1) | b;\n}\n\nstatic int update_palette16(VGAState *s, uint32_t *palette)\n{\n int full_update, i;\n uint32_t v, col;\n\n full_update = 0;\n for(i = 0; i < 16; i++) {\n v = s->ar[i];\n if (s->ar[0x10] & 0x80)\n v = ((s->ar[0x14] & 0xf) << 4) | (v & 0xf);\n else\n v = ((s->ar[0x14] & 0xc) << 4) | (v & 0x3f);\n v = v * 3;\n col = (c6_to_8(s->palette[v]) << 16) |\n (c6_to_8(s->palette[v + 1]) << 8) |\n c6_to_8(s->palette[v + 2]);\n if (col != palette[i]) {\n full_update = 1;\n palette[i] = col;\n }\n }\n return full_update;\n}\n\n/* the text refresh is just for debugging and initial boot message, so\n it is very incomplete */\nstatic void vga_text_refresh(VGAState *s,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n FBDevice *fb_dev = s->fb_dev;\n int width, height, cwidth, cheight, cy, cx, x1, y1, width1, height1;\n int cx_min, cx_max, dup9;\n uint32_t ch_attr, line_offset, start_addr, ch_addr, ch_addr1, ch, cattr;\n uint8_t *vga_ram, *font_ptr, *dst;\n uint32_t fgcol, bgcol, cursor_offset, cursor_start, cursor_end;\n BOOL full_update;\n\n full_update = update_palette16(s, s->last_palette);\n\n vga_ram = s->vga_ram;\n \n line_offset = s->cr[0x13];\n line_offset <<= 3;\n line_offset >>= 1;\n\n start_addr = s->cr[0x0d] | (s->cr[0x0c] << 8);\n \n cheight = (s->cr[9] & 0x1f) + 1;\n cwidth = 8;\n if (!(s->sr[1] & 0x01))\n cwidth++;\n \n width = (s->cr[0x01] + 1);\n height = s->cr[0x12] |\n ((s->cr[0x07] & 0x02) << 7) |\n ((s->cr[0x07] & 0x40) << 3);\n height = (height + 1) / cheight;\n \n width1 = width * cwidth;\n height1 = height * cheight;\n if (fb_dev->width < width1 || fb_dev->height < height1 ||\n width > MAX_TEXT_WIDTH || height > MAX_TEXT_HEIGHT)\n return; /* not enough space */\n if (s->last_line_offset != line_offset ||\n s->last_start_addr != start_addr ||\n s->last_width != width ||\n s->last_height != height) {\n s->last_line_offset = line_offset;\n s->last_start_addr = start_addr;\n s->last_width = width;\n s->last_height = height;\n full_update = TRUE;\n }\n \n /* update cursor position */\n cursor_offset = ((s->cr[0x0e] << 8) | s->cr[0x0f]) - start_addr;\n cursor_start = s->cr[0xa];\n cursor_end = s->cr[0xb];\n if (cursor_offset != s->last_cursor_offset ||\n cursor_start != s->last_cursor_start ||\n cursor_end != s->last_cursor_end) {\n /* force refresh of characters with the cursor */\n if (s->last_cursor_offset < MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT)\n s->last_ch_attr[s->last_cursor_offset] = -1;\n if (cursor_offset < MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT)\n s->last_ch_attr[cursor_offset] = -1;\n s->last_cursor_offset = cursor_offset;\n s->last_cursor_start = cursor_start;\n s->last_cursor_end = cursor_end;\n }\n\n ch_addr1 = 0x18000 + (start_addr * 2);\n cursor_offset = 0x18000 + (start_addr + cursor_offset) * 2;\n \n x1 = (fb_dev->width - width1) / 2;\n y1 = (fb_dev->height - height1) / 2;\n#if 0\n printf(\"text refresh %dx%d font=%dx%d start_addr=0x%x line_offset=0x%x\\n\",\n width, height, cwidth, cheight, start_addr, line_offset);\n#endif\n for(cy = 0; cy < height; cy++) {\n ch_addr = ch_addr1;\n dst = fb_dev->fb_data + (y1 + cy * cheight) * fb_dev->stride + x1 * 4;\n cx_min = width;\n cx_max = -1;\n for(cx = 0; cx < width; cx++) {\n ch_attr = *(uint16_t *)(vga_ram + (ch_addr & 0x1fffe));\n if (full_update || ch_attr != s->last_ch_attr[cy * width + cx]) {\n s->last_ch_attr[cy * width + cx] = ch_attr;\n cx_min = min_int(cx_min, cx);\n cx_max = max_int(cx_max, cx);\n ch = ch_attr & 0xff;\n cattr = ch_attr >> 8;\n font_ptr = vga_ram + 32 * ch;\n bgcol = s->last_palette[cattr >> 4];\n fgcol = s->last_palette[cattr & 0x0f];\n if (cwidth == 8) {\n vga_draw_glyph8(dst, fb_dev->stride, font_ptr, cheight,\n fgcol, bgcol);\n } else {\n dup9 = 0;\n if (ch >= 0xb0 && ch <= 0xdf && (s->ar[0x10] & 0x04))\n dup9 = 1;\n vga_draw_glyph9(dst, fb_dev->stride, font_ptr, cheight,\n fgcol, bgcol, dup9);\n }\n /* cursor display */\n if (cursor_offset == ch_addr && !(cursor_start & 0x20)) {\n int line_start, line_last, h;\n uint8_t *dst1;\n line_start = cursor_start & 0x1f;\n line_last = min_int(cursor_end & 0x1f, cheight - 1);\n\n if (line_last >= line_start && line_start < cheight) {\n h = line_last - line_start + 1;\n dst1 = dst + fb_dev->stride * line_start;\n if (cwidth == 8) {\n vga_draw_glyph8(dst1, fb_dev->stride,\n cursor_glyph,\n h, fgcol, bgcol);\n } else {\n vga_draw_glyph9(dst1, fb_dev->stride,\n cursor_glyph,\n h, fgcol, bgcol, 1);\n }\n }\n }\n }\n ch_addr += 2;\n dst += 4 * cwidth;\n }\n if (cx_max >= cx_min) {\n // printf(\"redraw %d %d %d\\n\", cy, cx_min, cx_max);\n redraw_func(fb_dev, opaque,\n x1 + cx_min * cwidth, y1 + cy * cheight,\n (cx_max - cx_min + 1) * cwidth, cheight);\n }\n ch_addr1 += line_offset;\n }\n}\n\nstatic void vga_refresh(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n VGAState *s = fb_dev->device_opaque;\n\n if (!(s->ar_index & 0x20)) {\n /* blank */\n } else if (s->gr[0x06] & 1) {\n /* graphic mode (VBE) */\n simplefb_refresh(fb_dev, redraw_func, opaque, s->mem_range, s->fb_page_count);\n } else {\n /* text mode */\n vga_text_refresh(s, redraw_func, opaque);\n }\n}\n\n/* force some bits to zero */\nstatic const uint8_t sr_mask[8] = {\n (uint8_t)~0xfc,\n (uint8_t)~0xc2,\n (uint8_t)~0xf0,\n (uint8_t)~0xc0,\n (uint8_t)~0xf1,\n (uint8_t)~0xff,\n (uint8_t)~0xff,\n (uint8_t)~0x00,\n};\n\nstatic const uint8_t gr_mask[16] = {\n (uint8_t)~0xf0, /* 0x00 */\n (uint8_t)~0xf0, /* 0x01 */\n (uint8_t)~0xf0, /* 0x02 */\n (uint8_t)~0xe0, /* 0x03 */\n (uint8_t)~0xfc, /* 0x04 */\n (uint8_t)~0x84, /* 0x05 */\n (uint8_t)~0xf0, /* 0x06 */\n (uint8_t)~0xf0, /* 0x07 */\n (uint8_t)~0x00, /* 0x08 */\n (uint8_t)~0xff, /* 0x09 */\n (uint8_t)~0xff, /* 0x0a */\n (uint8_t)~0xff, /* 0x0b */\n (uint8_t)~0xff, /* 0x0c */\n (uint8_t)~0xff, /* 0x0d */\n (uint8_t)~0xff, /* 0x0e */\n (uint8_t)~0xff, /* 0x0f */\n};\n\nstatic uint32_t vga_ioport_read(VGAState *s, uint32_t addr)\n{\n int val, index;\n\n /* check port range access depending on color/monochrome mode */\n if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION)) ||\n (addr >= 0x3d0 && addr <= 0x3df && !(s->msr & MSR_COLOR_EMULATION))) {\n val = 0xff;\n } else {\n switch(addr) {\n case 0x3c0:\n if (s->ar_flip_flop == 0) {\n val = s->ar_index;\n } else {\n val = 0;\n }\n break;\n case 0x3c1:\n index = s->ar_index & 0x1f;\n if (index < 21)\n val = s->ar[index];\n else\n val = 0;\n break;\n case 0x3c2:\n val = s->st00;\n break;\n case 0x3c4:\n val = s->sr_index;\n break;\n case 0x3c5:\n val = s->sr[s->sr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n break;\n case 0x3c7:\n val = s->dac_state;\n break;\n\tcase 0x3c8:\n\t val = s->dac_write_index;\n\t break;\n case 0x3c9:\n val = s->palette[s->dac_read_index * 3 + s->dac_sub_index];\n if (++s->dac_sub_index == 3) {\n s->dac_sub_index = 0;\n s->dac_read_index++;\n }\n break;\n case 0x3ca:\n val = s->fcr;\n break;\n case 0x3cc:\n val = s->msr;\n break;\n case 0x3ce:\n val = s->gr_index;\n break;\n case 0x3cf:\n val = s->gr[s->gr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n break;\n case 0x3b4:\n case 0x3d4:\n val = s->cr_index;\n break;\n case 0x3b5:\n case 0x3d5:\n val = s->cr[s->cr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n break;\n case 0x3ba:\n case 0x3da:\n /* just toggle to fool polling */\n s->st01 ^= ST01_V_RETRACE | ST01_DISP_ENABLE;\n val = s->st01;\n s->ar_flip_flop = 0;\n break;\n default:\n val = 0x00;\n break;\n }\n }\n#if defined(DEBUG_VGA)\n printf(\"VGA: read addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n return val;\n}\n\nstatic void vga_ioport_write(VGAState *s, uint32_t addr, uint32_t val)\n{\n int index;\n\n /* check port range access depending on color/monochrome mode */\n if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION)) ||\n (addr >= 0x3d0 && addr <= 0x3df && !(s->msr & MSR_COLOR_EMULATION)))\n return;\n\n#ifdef DEBUG_VGA\n printf(\"VGA: write addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n\n switch(addr) {\n case 0x3c0:\n if (s->ar_flip_flop == 0) {\n val &= 0x3f;\n s->ar_index = val;\n } else {\n index = s->ar_index & 0x1f;\n switch(index) {\n case 0x00 ... 0x0f:\n s->ar[index] = val & 0x3f;\n break;\n case 0x10:\n s->ar[index] = val & ~0x10;\n break;\n case 0x11:\n s->ar[index] = val;\n break;\n case 0x12:\n s->ar[index] = val & ~0xc0;\n break;\n case 0x13:\n s->ar[index] = val & ~0xf0;\n break;\n case 0x14:\n s->ar[index] = val & ~0xf0;\n break;\n default:\n break;\n }\n }\n s->ar_flip_flop ^= 1;\n break;\n case 0x3c2:\n s->msr = val & ~0x10;\n break;\n case 0x3c4:\n s->sr_index = val & 7;\n break;\n case 0x3c5:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n s->sr[s->sr_index] = val & sr_mask[s->sr_index];\n break;\n case 0x3c7:\n s->dac_read_index = val;\n s->dac_sub_index = 0;\n s->dac_state = 3;\n break;\n case 0x3c8:\n s->dac_write_index = val;\n s->dac_sub_index = 0;\n s->dac_state = 0;\n break;\n case 0x3c9:\n s->dac_cache[s->dac_sub_index] = val;\n if (++s->dac_sub_index == 3) {\n memcpy(&s->palette[s->dac_write_index * 3], s->dac_cache, 3);\n s->dac_sub_index = 0;\n s->dac_write_index++;\n }\n break;\n case 0x3ce:\n s->gr_index = val & 0x0f;\n break;\n case 0x3cf:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n s->gr[s->gr_index] = val & gr_mask[s->gr_index];\n break;\n case 0x3b4:\n case 0x3d4:\n s->cr_index = val;\n break;\n case 0x3b5:\n case 0x3d5:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n /* handle CR0-7 protection */\n if ((s->cr[0x11] & 0x80) && s->cr_index <= 7) {\n /* can always write bit 4 of CR7 */\n if (s->cr_index == 7)\n s->cr[7] = (s->cr[7] & ~0x10) | (val & 0x10);\n return;\n }\n switch(s->cr_index) {\n case 0x01: /* horizontal display end */\n case 0x07:\n case 0x09:\n case 0x0c:\n case 0x0d:\n case 0x12: /* vertical display end */\n s->cr[s->cr_index] = val;\n break;\n default:\n s->cr[s->cr_index] = val;\n break;\n }\n break;\n case 0x3ba:\n case 0x3da:\n s->fcr = val & 0x10;\n break;\n }\n}\n\n#define VGA_IO(base) \\\nstatic uint32_t vga_read_ ## base(void *opaque, uint32_t addr, int size_log2)\\\n{\\\n return vga_ioport_read(opaque, base + addr);\\\n}\\\nstatic void vga_write_ ## base(void *opaque, uint32_t addr, uint32_t val, int size_log2)\\\n{\\\n return vga_ioport_write(opaque, base + addr, val);\\\n}\n\nVGA_IO(0x3c0)\nVGA_IO(0x3b4)\nVGA_IO(0x3d4)\nVGA_IO(0x3ba)\nVGA_IO(0x3da)\n\nstatic void vbe_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n VGAState *s = opaque;\n FBDevice *fb_dev = s->fb_dev;\n \n if (offset == 0) {\n s->vbe_index = val;\n } else {\n#ifdef DEBUG_VBE\n printf(\"VBE write: index=0x%04x val=0x%04x\\n\", s->vbe_index, val);\n#endif\n switch(s->vbe_index) {\n case VBE_DISPI_INDEX_ID:\n if (val >= VBE_DISPI_ID0 && val <= VBE_DISPI_ID5)\n s->vbe_regs[s->vbe_index] = val;\n break;\n case VBE_DISPI_INDEX_ENABLE:\n if ((val & VBE_DISPI_ENABLED) &&\n !(s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED)) {\n /* set graphic mode */\n /* XXX: resolution change not really supported */\n if (s->vbe_regs[VBE_DISPI_INDEX_XRES] <= 4096 &&\n s->vbe_regs[VBE_DISPI_INDEX_YRES] <= 4096 &&\n (s->vbe_regs[VBE_DISPI_INDEX_XRES] * 4 *\n s->vbe_regs[VBE_DISPI_INDEX_YRES]) <= fb_dev->fb_size) {\n fb_dev->width = s->vbe_regs[VBE_DISPI_INDEX_XRES];\n fb_dev->height = s->vbe_regs[VBE_DISPI_INDEX_YRES];\n fb_dev->stride = fb_dev->width * 4;\n }\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] =\n s->vbe_regs[VBE_DISPI_INDEX_XRES];\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_HEIGHT] =\n s->vbe_regs[VBE_DISPI_INDEX_YRES];\n s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET] = 0;\n s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET] = 0;\n }\n s->vbe_regs[s->vbe_index] = val;\n break;\n case VBE_DISPI_INDEX_XRES:\n case VBE_DISPI_INDEX_YRES:\n case VBE_DISPI_INDEX_BPP:\n case VBE_DISPI_INDEX_BANK:\n case VBE_DISPI_INDEX_VIRT_WIDTH:\n case VBE_DISPI_INDEX_VIRT_HEIGHT:\n case VBE_DISPI_INDEX_X_OFFSET:\n case VBE_DISPI_INDEX_Y_OFFSET:\n s->vbe_regs[s->vbe_index] = val;\n break;\n }\n }\n}\n\nstatic uint32_t vbe_read(void *opaque, uint32_t offset, int size_log2)\n{\n VGAState *s = opaque;\n uint32_t val;\n\n if (offset == 0) {\n val = s->vbe_index;\n } else {\n if (s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_GETCAPS) {\n switch(s->vbe_index) {\n case VBE_DISPI_INDEX_XRES:\n val = s->fb_dev->width;\n break;\n case VBE_DISPI_INDEX_YRES:\n val = s->fb_dev->height;\n break;\n case VBE_DISPI_INDEX_BPP:\n val = 32;\n break;\n default:\n goto read_reg;\n }\n } else {\n read_reg:\n if (s->vbe_index < VBE_DISPI_INDEX_NB)\n val = s->vbe_regs[s->vbe_index];\n else\n val = 0;\n }\n#ifdef DEBUG_VBE\n printf(\"VBE read: index=0x%04x val=0x%04x\\n\", s->vbe_index, val);\n#endif\n }\n return val;\n}\n\n\nstatic void simplefb_bar_set(void *opaque, int bar_num,\n uint32_t addr, BOOL enabled)\n{\n VGAState *s = opaque;\n if (bar_num == 0)\n phys_mem_set_addr(s->mem_range, addr, enabled);\n else\n phys_mem_set_addr(s->rom_range, addr, enabled);\n}\n\nVGAState *pci_vga_init(PCIBus *bus, FBDevice *fb_dev,\n int width, int height,\n const uint8_t *vga_rom_buf, int vga_rom_size)\n{\n VGAState *s;\n PCIDevice *d;\n uint32_t bar_size;\n PhysMemoryMap *mem_map, *port_map;\n \n d = pci_register_device(bus, \"VGA\", -1, 0x1234, 0x1111, 0x00, 0x0300);\n \n mem_map = pci_device_get_mem_map(d);\n port_map = pci_device_get_port_map(d);\n\n s = mallocz(sizeof(*s));\n s->fb_dev = fb_dev;\n \n fb_dev->width = width;\n fb_dev->height = height;\n fb_dev->stride = width * 4;\n\n fb_dev->fb_size = (height * fb_dev->stride + FB_ALLOC_ALIGN - 1) & ~(FB_ALLOC_ALIGN - 1);\n s->fb_page_count = fb_dev->fb_size >> DEVRAM_PAGE_SIZE_LOG2;\n\n s->mem_range =\n cpu_register_ram(mem_map, 0, fb_dev->fb_size,\n DEVRAM_FLAG_DIRTY_BITS | DEVRAM_FLAG_DISABLED);\n \n fb_dev->fb_data = s->mem_range->phys_mem;\n\n s->pci_dev = d;\n bar_size = 1;\n while (bar_size < fb_dev->fb_size)\n bar_size <<= 1;\n pci_register_bar(d, 0, bar_size, PCI_ADDRESS_SPACE_MEM, s,\n simplefb_bar_set);\n\n if (vga_rom_size > 0) {\n int rom_size;\n /* align to page size */\n rom_size = (vga_rom_size + DEVRAM_PAGE_SIZE - 1) & ~(DEVRAM_PAGE_SIZE - 1);\n s->rom_range = cpu_register_ram(mem_map, 0, rom_size,\n DEVRAM_FLAG_ROM | DEVRAM_FLAG_DISABLED);\n memcpy(s->rom_range->phys_mem, vga_rom_buf, vga_rom_size);\n\n bar_size = 1;\n while (bar_size < rom_size)\n bar_size <<= 1;\n pci_register_bar(d, PCI_ROM_SLOT, bar_size, PCI_ADDRESS_SPACE_MEM, s,\n simplefb_bar_set);\n }\n\n /* VGA memory (for simple text mode no need for callbacks) */\n s->mem_range2 = cpu_register_ram(mem_map, 0xa0000, 0x20000, 0);\n s->vga_ram = s->mem_range2->phys_mem;\n \n /* standard VGA ports */\n \n cpu_register_device(port_map, 0x3c0, 16, s, vga_read_0x3c0, vga_write_0x3c0,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3b4, 2, s, vga_read_0x3b4, vga_write_0x3b4,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3d4, 2, s, vga_read_0x3d4, vga_write_0x3d4,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3ba, 1, s, vga_read_0x3ba, vga_write_0x3ba,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3da, 1, s, vga_read_0x3da, vga_write_0x3da,\n DEVIO_SIZE8);\n \n /* VBE extension */\n cpu_register_device(port_map, 0x1ce, 2, s, vbe_read, vbe_write, \n DEVIO_SIZE16);\n \n s->vbe_regs[VBE_DISPI_INDEX_ID] = VBE_DISPI_ID5;\n s->vbe_regs[VBE_DISPI_INDEX_VIDEO_MEMORY_64K] = fb_dev->fb_size >> 16;\n\n fb_dev->device_opaque = s;\n fb_dev->refresh = vga_refresh;\n return s;\n}\n"], ["/linuxpdf/tinyemu/fs_net.c", "/*\n * Networked Filesystem using HTTP\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n#include \"fbuf.h\"\n\n#if defined(EMSCRIPTEN)\n#include \n#endif\n\n/*\n TODO:\n - implement fs_lock/fs_getlock\n - update fs_size with links ?\n - limit fs_size in dirent creation\n - limit filename length\n*/\n\n//#define DEBUG_CACHE\n#if !defined(EMSCRIPTEN)\n#define DUMP_CACHE_LOAD\n#endif\n\n#if defined(EMSCRIPTEN)\n#define DEFAULT_INODE_CACHE_SIZE (64 * 1024 * 1024)\n#else\n#define DEFAULT_INODE_CACHE_SIZE (256 * 1024 * 1024)\n#endif\n\ntypedef enum {\n FT_FIFO = 1,\n FT_CHR = 2,\n FT_DIR = 4,\n FT_BLK = 6,\n FT_REG = 8,\n FT_LNK = 10,\n FT_SOCK = 12,\n} FSINodeTypeEnum;\n\ntypedef enum {\n REG_STATE_LOCAL, /* local content */\n REG_STATE_UNLOADED, /* content not loaded */\n REG_STATE_LOADING, /* content is being loaded */\n REG_STATE_LOADED, /* loaded, not modified, stored in cached_inode_list */\n} FSINodeRegStateEnum;\n\ntypedef struct FSBaseURL {\n struct list_head link;\n int ref_count;\n char *base_url_id;\n char *url;\n char *user;\n char *password;\n BOOL encrypted;\n AES_KEY aes_state;\n} FSBaseURL;\n\ntypedef struct FSINode {\n struct list_head link;\n uint64_t inode_num; /* inode number */\n int32_t refcount;\n int32_t open_count;\n FSINodeTypeEnum type;\n uint32_t mode;\n uint32_t uid;\n uint32_t gid;\n uint32_t mtime_sec;\n uint32_t ctime_sec;\n uint32_t mtime_nsec;\n uint32_t ctime_nsec;\n union {\n struct {\n FSINodeRegStateEnum state;\n size_t size; /* real file size */\n FileBuffer fbuf;\n FSBaseURL *base_url;\n FSFileID file_id; /* network file ID */\n struct list_head link;\n struct FSOpenInfo *open_info; /* used in LOADING state */\n BOOL is_fscmd;\n#ifdef DUMP_CACHE_LOAD\n char *filename;\n#endif\n } reg;\n struct {\n struct list_head de_list; /* list of FSDirEntry */\n int size;\n } dir;\n struct {\n uint32_t major;\n uint32_t minor;\n } dev;\n struct {\n char *name;\n } symlink;\n } u;\n} FSINode;\n\ntypedef struct {\n struct list_head link;\n FSINode *inode;\n uint8_t mark; /* temporary use only */\n char name[0];\n} FSDirEntry;\n\ntypedef enum {\n FS_CMD_XHR,\n FS_CMD_PBKDF2,\n} FSCMDRequestEnum;\n\n#define FS_CMD_REPLY_LEN_MAX 64\n\ntypedef struct {\n FSCMDRequestEnum type;\n struct CmdXHRState *xhr_state;\n int reply_len;\n uint8_t reply_buf[FS_CMD_REPLY_LEN_MAX];\n} FSCMDRequest;\n\nstruct FSFile {\n uint32_t uid;\n FSINode *inode;\n BOOL is_opened;\n uint32_t open_flags;\n FSCMDRequest *req;\n};\n\ntypedef struct {\n struct list_head link;\n BOOL is_archive;\n const char *name;\n} PreloadFile;\n\ntypedef struct {\n struct list_head link;\n FSFileID file_id;\n struct list_head file_list; /* list of PreloadFile.link */\n} PreloadEntry;\n\ntypedef struct {\n struct list_head link;\n FSFileID file_id;\n uint64_t size;\n const char *name;\n} PreloadArchiveFile;\n\ntypedef struct {\n struct list_head link;\n const char *name;\n struct list_head file_list; /* list of PreloadArchiveFile.link */\n} PreloadArchive;\n\ntypedef struct FSDeviceMem {\n FSDevice common;\n\n struct list_head inode_list; /* list of FSINode */\n int64_t inode_count; /* current number of inodes */\n uint64_t inode_limit;\n int64_t fs_blocks;\n uint64_t fs_max_blocks;\n uint64_t inode_num_alloc;\n int block_size_log2;\n uint32_t block_size; /* for stat/statfs */\n FSINode *root_inode;\n struct list_head inode_cache_list; /* list of FSINode.u.reg.link */\n int64_t inode_cache_size;\n int64_t inode_cache_size_limit;\n struct list_head preload_list; /* list of PreloadEntry.link */\n struct list_head preload_archive_list; /* list of PreloadArchive.link */\n /* network */\n struct list_head base_url_list; /* list of FSBaseURL.link */\n char *import_dir;\n#ifdef DUMP_CACHE_LOAD\n BOOL dump_cache_load;\n BOOL dump_started;\n char *dump_preload_dir;\n FILE *dump_preload_file;\n FILE *dump_preload_archive_file;\n\n char *dump_archive_name;\n uint64_t dump_archive_size;\n FILE *dump_archive_file;\n\n int dump_archive_num;\n struct list_head dump_preload_list; /* list of PreloadFile.link */\n struct list_head dump_exclude_list; /* list of PreloadFile.link */\n#endif\n} FSDeviceMem;\n\ntypedef enum {\n FS_OPEN_WGET_REG,\n FS_OPEN_WGET_ARCHIVE,\n FS_OPEN_WGET_ARCHIVE_FILE,\n} FSOpenWgetEnum;\n\ntypedef struct FSOpenInfo {\n FSDevice *fs;\n FSOpenWgetEnum open_type;\n\n /* used for FS_OPEN_WGET_REG, FS_OPEN_WGET_ARCHIVE */\n XHRState *xhr;\n FSINode *n;\n DecryptFileState *dec_state;\n size_t cur_pos;\n\n struct list_head archive_link; /* FS_OPEN_WGET_ARCHIVE_FILE */\n uint64_t archive_offset; /* FS_OPEN_WGET_ARCHIVE_FILE */\n struct list_head archive_file_list; /* FS_OPEN_WGET_ARCHIVE */\n \n /* the following is set in case there is a fs_open callback */\n FSFile *f;\n FSOpenCompletionFunc *cb;\n void *opaque;\n} FSOpenInfo;\n\nstatic void fs_close(FSDevice *fs, FSFile *f);\nstatic void inode_decref(FSDevice *fs1, FSINode *n);\nstatic int fs_cmd_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int buf_len);\nstatic int fs_cmd_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int buf_len);\nstatic int fs_truncate(FSDevice *fs1, FSINode *n, uint64_t size);\nstatic void fs_open_end(FSOpenInfo *oi);\nstatic void fs_base_url_decref(FSDevice *fs, FSBaseURL *bu);\nstatic FSBaseURL *fs_net_set_base_url(FSDevice *fs1,\n const char *base_url_id,\n const char *url,\n const char *user, const char *password,\n AES_KEY *aes_state);\nstatic void fs_cmd_close(FSDevice *fs, FSFile *f);\nstatic void fs_error_archive(FSOpenInfo *oi);\n#ifdef DUMP_CACHE_LOAD\nstatic void dump_loaded_file(FSDevice *fs1, FSINode *n);\n#endif\n\n#if !defined(EMSCRIPTEN)\n/* file buffer (the content of the buffer can be stored elsewhere) */\nvoid file_buffer_init(FileBuffer *bs)\n{\n bs->data = NULL;\n bs->allocated_size = 0;\n}\n\nvoid file_buffer_reset(FileBuffer *bs)\n{\n free(bs->data);\n file_buffer_init(bs);\n}\n\nint file_buffer_resize(FileBuffer *bs, size_t new_size)\n{\n uint8_t *new_data;\n new_data = realloc(bs->data, new_size);\n if (!new_data && new_size != 0)\n return -1;\n bs->data = new_data;\n bs->allocated_size = new_size;\n return 0;\n}\n\nvoid file_buffer_write(FileBuffer *bs, size_t offset, const uint8_t *buf,\n size_t size)\n{\n memcpy(bs->data + offset, buf, size);\n}\n\nvoid file_buffer_set(FileBuffer *bs, size_t offset, int val, size_t size)\n{\n memset(bs->data + offset, val, size);\n}\n\nvoid file_buffer_read(FileBuffer *bs, size_t offset, uint8_t *buf,\n size_t size)\n{\n memcpy(buf, bs->data + offset, size);\n}\n#endif\n\nstatic int64_t to_blocks(FSDeviceMem *fs, uint64_t size)\n{\n return (size + fs->block_size - 1) >> fs->block_size_log2;\n}\n\nstatic FSINode *inode_incref(FSDevice *fs, FSINode *n)\n{\n n->refcount++;\n return n;\n}\n\nstatic FSINode *inode_inc_open(FSDevice *fs, FSINode *n)\n{\n n->open_count++;\n return n;\n}\n\nstatic void inode_free(FSDevice *fs1, FSINode *n)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n // printf(\"inode_free=%\" PRId64 \"\\n\", n->inode_num);\n assert(n->refcount == 0);\n assert(n->open_count == 0);\n switch(n->type) {\n case FT_REG:\n fs->fs_blocks -= to_blocks(fs, n->u.reg.size);\n assert(fs->fs_blocks >= 0);\n file_buffer_reset(&n->u.reg.fbuf);\n#ifdef DUMP_CACHE_LOAD\n free(n->u.reg.filename);\n#endif\n switch(n->u.reg.state) {\n case REG_STATE_LOADED:\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n fs_base_url_decref(fs1, n->u.reg.base_url);\n break;\n case REG_STATE_LOADING:\n {\n FSOpenInfo *oi = n->u.reg.open_info;\n if (oi->xhr)\n fs_wget_free(oi->xhr);\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE) {\n fs_error_archive(oi);\n }\n fs_open_end(oi);\n fs_base_url_decref(fs1, n->u.reg.base_url);\n }\n break;\n case REG_STATE_UNLOADED:\n fs_base_url_decref(fs1, n->u.reg.base_url);\n break;\n case REG_STATE_LOCAL:\n break;\n default:\n abort();\n }\n break;\n case FT_LNK:\n free(n->u.symlink.name);\n break;\n case FT_DIR:\n assert(list_empty(&n->u.dir.de_list));\n break;\n default:\n break;\n }\n list_del(&n->link);\n free(n);\n fs->inode_count--;\n assert(fs->inode_count >= 0);\n}\n\nstatic void inode_decref(FSDevice *fs1, FSINode *n)\n{\n assert(n->refcount >= 1);\n if (--n->refcount <= 0 && n->open_count <= 0) {\n inode_free(fs1, n);\n }\n}\n\nstatic void inode_dec_open(FSDevice *fs1, FSINode *n)\n{\n assert(n->open_count >= 1);\n if (--n->open_count <= 0 && n->refcount <= 0) {\n inode_free(fs1, n);\n }\n}\n\nstatic void inode_update_mtime(FSDevice *fs, FSINode *n)\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n n->mtime_sec = tv.tv_sec;\n n->mtime_nsec = tv.tv_usec * 1000;\n}\n\nstatic FSINode *inode_new(FSDevice *fs1, FSINodeTypeEnum type,\n uint32_t mode, uint32_t uid, uint32_t gid)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n;\n\n n = mallocz(sizeof(*n));\n n->refcount = 1;\n n->open_count = 0;\n n->inode_num = fs->inode_num_alloc;\n fs->inode_num_alloc++;\n n->type = type;\n n->mode = mode & 0xfff;\n n->uid = uid;\n n->gid = gid;\n\n switch(type) {\n case FT_REG:\n file_buffer_init(&n->u.reg.fbuf);\n break;\n case FT_DIR:\n init_list_head(&n->u.dir.de_list);\n break;\n default:\n break;\n }\n\n list_add(&n->link, &fs->inode_list);\n fs->inode_count++;\n\n inode_update_mtime(fs1, n);\n n->ctime_sec = n->mtime_sec;\n n->ctime_nsec = n->mtime_nsec;\n\n return n;\n}\n\n/* warning: the refcount of 'n1' is not incremented by this function */\n/* XXX: test FS max size */\nstatic FSDirEntry *inode_dir_add(FSDevice *fs1, FSINode *n, const char *name,\n FSINode *n1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSDirEntry *de;\n int name_len, dirent_size, new_size;\n assert(n->type == FT_DIR);\n\n name_len = strlen(name);\n de = mallocz(sizeof(*de) + name_len + 1);\n de->inode = n1;\n memcpy(de->name, name, name_len + 1);\n dirent_size = sizeof(*de) + name_len + 1;\n new_size = n->u.dir.size + dirent_size;\n fs->fs_blocks += to_blocks(fs, new_size) - to_blocks(fs, n->u.dir.size);\n n->u.dir.size = new_size;\n list_add_tail(&de->link, &n->u.dir.de_list);\n return de;\n}\n\nstatic FSDirEntry *inode_search(FSINode *n, const char *name)\n{\n struct list_head *el;\n FSDirEntry *de;\n \n if (n->type != FT_DIR)\n return NULL;\n\n list_for_each(el, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n if (!strcmp(de->name, name))\n return de;\n }\n return NULL;\n}\n\nstatic FSINode *inode_search_path1(FSDevice *fs, FSINode *n, const char *path)\n{\n char name[1024];\n const char *p, *p1;\n int len;\n FSDirEntry *de;\n \n p = path;\n if (*p == '/')\n p++;\n if (*p == '\\0')\n return n;\n for(;;) {\n p1 = strchr(p, '/');\n if (!p1) {\n len = strlen(p);\n } else {\n len = p1 - p;\n p1++;\n }\n if (len > sizeof(name) - 1)\n return NULL;\n memcpy(name, p, len);\n name[len] = '\\0';\n if (n->type != FT_DIR)\n return NULL;\n de = inode_search(n, name);\n if (!de)\n return NULL;\n n = de->inode;\n p = p1;\n if (!p)\n break;\n }\n return n;\n}\n\nstatic FSINode *inode_search_path(FSDevice *fs1, const char *path)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (!fs1)\n return NULL;\n return inode_search_path1(fs1, fs->root_inode, path);\n}\n\nstatic BOOL is_empty_dir(FSDevice *fs, FSINode *n)\n{\n struct list_head *el;\n FSDirEntry *de;\n\n list_for_each(el, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n if (strcmp(de->name, \".\") != 0 &&\n strcmp(de->name, \"..\") != 0)\n return FALSE;\n }\n return TRUE;\n}\n\nstatic void inode_dirent_delete_no_decref(FSDevice *fs1, FSINode *n, FSDirEntry *de)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int dirent_size, new_size;\n dirent_size = sizeof(*de) + strlen(de->name) + 1;\n\n new_size = n->u.dir.size - dirent_size;\n fs->fs_blocks += to_blocks(fs, new_size) - to_blocks(fs, n->u.dir.size);\n n->u.dir.size = new_size;\n assert(n->u.dir.size >= 0);\n assert(fs->fs_blocks >= 0);\n list_del(&de->link);\n free(de);\n}\n\nstatic void inode_dirent_delete(FSDevice *fs, FSINode *n, FSDirEntry *de)\n{\n FSINode *n1;\n n1 = de->inode;\n inode_dirent_delete_no_decref(fs, n, de);\n inode_decref(fs, n1);\n}\n\nstatic void flush_dir(FSDevice *fs, FSINode *n)\n{\n struct list_head *el, *el1;\n FSDirEntry *de;\n list_for_each_safe(el, el1, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n inode_dirent_delete(fs, n, de);\n }\n assert(n->u.dir.size == 0);\n}\n\nstatic void fs_delete(FSDevice *fs, FSFile *f)\n{\n fs_close(fs, f);\n inode_dec_open(fs, f->inode);\n free(f);\n}\n\nstatic FSFile *fid_create(FSDevice *fs1, FSINode *n, uint32_t uid)\n{\n FSFile *f;\n\n f = mallocz(sizeof(*f));\n f->inode = inode_inc_open(fs1, n);\n f->uid = uid;\n return f;\n}\n\nstatic void inode_to_qid(FSQID *qid, FSINode *n)\n{\n if (n->type == FT_DIR)\n qid->type = P9_QTDIR;\n else if (n->type == FT_LNK)\n qid->type = P9_QTSYMLINK;\n else\n qid->type = P9_QTFILE;\n qid->version = 0; /* no caching on client */\n qid->path = n->inode_num;\n}\n\nstatic void fs_statfs(FSDevice *fs1, FSStatFS *st)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n st->f_bsize = 1024;\n st->f_blocks = fs->fs_max_blocks <<\n (fs->block_size_log2 - 10);\n st->f_bfree = (fs->fs_max_blocks - fs->fs_blocks) <<\n (fs->block_size_log2 - 10);\n st->f_bavail = st->f_bfree;\n st->f_files = fs->inode_limit;\n st->f_ffree = fs->inode_limit - fs->inode_count;\n}\n\nstatic int fs_attach(FSDevice *fs1, FSFile **pf, FSQID *qid, uint32_t uid,\n const char *uname, const char *aname)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n *pf = fid_create(fs1, fs->root_inode, uid);\n inode_to_qid(qid, fs->root_inode);\n return 0;\n}\n\nstatic int fs_walk(FSDevice *fs, FSFile **pf, FSQID *qids,\n FSFile *f, int count, char **names)\n{\n int i;\n FSINode *n;\n FSDirEntry *de;\n\n n = f->inode;\n for(i = 0; i < count; i++) {\n de = inode_search(n, names[i]);\n if (!de)\n break;\n n = de->inode;\n inode_to_qid(&qids[i], n);\n }\n *pf = fid_create(fs, n, f->uid);\n return i;\n}\n\nstatic int fs_mkdir(FSDevice *fs, FSQID *qid, FSFile *f,\n const char *name, uint32_t mode, uint32_t gid)\n{\n FSINode *n, *n1;\n\n n = f->inode;\n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n if (inode_search(n, name))\n return -P9_EEXIST;\n n1 = inode_new(fs, FT_DIR, mode, f->uid, gid);\n inode_dir_add(fs, n1, \".\", inode_incref(fs, n1));\n inode_dir_add(fs, n1, \"..\", inode_incref(fs, n));\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\n/* remove elements in the cache considering that 'added_size' will be\n added */\nstatic void fs_trim_cache(FSDevice *fs1, int64_t added_size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el, *el1;\n FSINode *n;\n\n if ((fs->inode_cache_size + added_size) <= fs->inode_cache_size_limit)\n return;\n list_for_each_prev_safe(el, el1, &fs->inode_cache_list) {\n n = list_entry(el, FSINode, u.reg.link);\n assert(n->u.reg.state == REG_STATE_LOADED);\n /* cannot remove open files */\n // printf(\"open_count=%d\\n\", n->open_count);\n if (n->open_count != 0)\n continue;\n#ifdef DEBUG_CACHE\n printf(\"fs_trim_cache: remove '%s' size=%ld\\n\",\n n->u.reg.filename, (long)n->u.reg.size);\n#endif\n file_buffer_reset(&n->u.reg.fbuf);\n n->u.reg.state = REG_STATE_UNLOADED;\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n if ((fs->inode_cache_size + added_size) <= fs->inode_cache_size_limit)\n break;\n }\n}\n\nstatic void fs_open_end(FSOpenInfo *oi)\n{\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE_FILE) {\n list_del(&oi->archive_link);\n }\n if (oi->dec_state)\n decrypt_file_end(oi->dec_state);\n free(oi);\n}\n\nstatic int fs_open_write_cb(void *opaque, const uint8_t *data, size_t size)\n{\n FSOpenInfo *oi = opaque;\n size_t len;\n FSINode *n = oi->n;\n \n /* we ignore extraneous data */\n len = n->u.reg.size - oi->cur_pos;\n if (size < len)\n len = size;\n file_buffer_write(&n->u.reg.fbuf, oi->cur_pos, data, len);\n oi->cur_pos += len;\n return 0;\n}\n\nstatic void fs_wget_set_loaded(FSINode *n)\n{\n FSOpenInfo *oi;\n FSDeviceMem *fs;\n FSFile *f;\n FSQID qid;\n\n assert(n->u.reg.state == REG_STATE_LOADING);\n oi = n->u.reg.open_info;\n fs = (FSDeviceMem *)oi->fs;\n n->u.reg.state = REG_STATE_LOADED;\n list_add(&n->u.reg.link, &fs->inode_cache_list);\n fs->inode_cache_size += n->u.reg.size;\n \n if (oi->cb) {\n f = oi->f;\n f->is_opened = TRUE;\n inode_to_qid(&qid, n);\n oi->cb(oi->fs, &qid, 0, oi->opaque);\n }\n fs_open_end(oi);\n}\n\nstatic void fs_wget_set_error(FSINode *n)\n{\n FSOpenInfo *oi;\n assert(n->u.reg.state == REG_STATE_LOADING);\n oi = n->u.reg.open_info;\n n->u.reg.state = REG_STATE_UNLOADED;\n file_buffer_reset(&n->u.reg.fbuf);\n if (oi->cb) {\n oi->cb(oi->fs, NULL, -P9_EIO, oi->opaque);\n }\n fs_open_end(oi);\n}\n\nstatic void fs_read_archive(FSOpenInfo *oi)\n{\n FSINode *n = oi->n;\n uint64_t pos, pos1, l;\n uint8_t buf[1024];\n FSINode *n1;\n FSOpenInfo *oi1;\n struct list_head *el, *el1;\n \n list_for_each_safe(el, el1, &oi->archive_file_list) {\n oi1 = list_entry(el, FSOpenInfo, archive_link);\n n1 = oi1->n;\n /* copy the archive data to the file */\n pos = oi1->archive_offset;\n pos1 = 0;\n while (pos1 < n1->u.reg.size) {\n l = n1->u.reg.size - pos1;\n if (l > sizeof(buf))\n l = sizeof(buf);\n file_buffer_read(&n->u.reg.fbuf, pos, buf, l);\n file_buffer_write(&n1->u.reg.fbuf, pos1, buf, l);\n pos += l;\n pos1 += l;\n }\n fs_wget_set_loaded(n1);\n }\n}\n\nstatic void fs_error_archive(FSOpenInfo *oi)\n{\n FSOpenInfo *oi1;\n struct list_head *el, *el1;\n \n list_for_each_safe(el, el1, &oi->archive_file_list) {\n oi1 = list_entry(el, FSOpenInfo, archive_link);\n fs_wget_set_error(oi1->n);\n }\n}\n\nstatic void fs_open_cb(void *opaque, int err, void *data, size_t size)\n{\n FSOpenInfo *oi = opaque;\n FSINode *n = oi->n;\n \n // printf(\"open_cb: err=%d size=%ld\\n\", err, size);\n if (err < 0) {\n error:\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE)\n fs_error_archive(oi);\n fs_wget_set_error(n);\n } else {\n if (oi->dec_state) {\n if (decrypt_file(oi->dec_state, data, size) < 0)\n goto error;\n if (err == 0) {\n if (decrypt_file_flush(oi->dec_state) < 0)\n goto error;\n }\n } else {\n fs_open_write_cb(oi, data, size);\n }\n\n if (err == 0) {\n /* end of transfer */\n if (oi->cur_pos != n->u.reg.size)\n goto error;\n#ifdef DUMP_CACHE_LOAD\n dump_loaded_file(oi->fs, n);\n#endif\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE)\n fs_read_archive(oi);\n fs_wget_set_loaded(n);\n }\n }\n}\n\n\nstatic int fs_open_wget(FSDevice *fs1, FSINode *n, FSOpenWgetEnum open_type)\n{\n char *url;\n FSOpenInfo *oi;\n char fname[FILEID_SIZE_MAX];\n FSBaseURL *bu;\n\n assert(n->u.reg.state == REG_STATE_UNLOADED);\n \n fs_trim_cache(fs1, n->u.reg.size);\n \n if (file_buffer_resize(&n->u.reg.fbuf, n->u.reg.size) < 0)\n return -P9_EIO;\n n->u.reg.state = REG_STATE_LOADING;\n oi = mallocz(sizeof(*oi));\n oi->cur_pos = 0;\n oi->fs = fs1;\n oi->n = n;\n oi->open_type = open_type;\n if (open_type != FS_OPEN_WGET_ARCHIVE_FILE) {\n if (open_type == FS_OPEN_WGET_ARCHIVE)\n init_list_head(&oi->archive_file_list);\n file_id_to_filename(fname, n->u.reg.file_id);\n bu = n->u.reg.base_url;\n url = compose_path(bu->url, fname);\n if (bu->encrypted) {\n oi->dec_state = decrypt_file_init(&bu->aes_state, fs_open_write_cb, oi);\n }\n oi->xhr = fs_wget(url, bu->user, bu->password, oi, fs_open_cb, FALSE);\n }\n n->u.reg.open_info = oi;\n return 0;\n}\n\n\nstatic void fs_preload_file(FSDevice *fs1, const char *filename)\n{\n FSINode *n;\n\n n = inode_search_path(fs1, filename);\n if (n && n->type == FT_REG && n->u.reg.state == REG_STATE_UNLOADED) {\n#if defined(DEBUG_CACHE)\n printf(\"preload: %s\\n\", filename);\n#endif\n fs_open_wget(fs1, n, FS_OPEN_WGET_REG);\n }\n}\n\nstatic PreloadArchive *find_preload_archive(FSDeviceMem *fs,\n const char *filename)\n{\n PreloadArchive *pa;\n struct list_head *el;\n list_for_each(el, &fs->preload_archive_list) {\n pa = list_entry(el, PreloadArchive, link);\n if (!strcmp(pa->name, filename))\n return pa;\n }\n return NULL;\n}\n\nstatic void fs_preload_archive(FSDevice *fs1, const char *filename)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n PreloadArchive *pa;\n PreloadArchiveFile *paf;\n struct list_head *el;\n FSINode *n, *n1;\n uint64_t offset;\n BOOL has_unloaded;\n \n pa = find_preload_archive(fs, filename);\n if (!pa)\n return;\n#if defined(DEBUG_CACHE)\n printf(\"preload archive: %s\\n\", filename);\n#endif\n n = inode_search_path(fs1, filename);\n if (n && n->type == FT_REG && n->u.reg.state == REG_STATE_UNLOADED) {\n /* if all the files are loaded, no need to load the archive */\n offset = 0;\n has_unloaded = FALSE;\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n n1 = inode_search_path(fs1, paf->name);\n if (n1 && n1->type == FT_REG &&\n n1->u.reg.state == REG_STATE_UNLOADED) {\n has_unloaded = TRUE;\n }\n offset += paf->size;\n }\n if (!has_unloaded) {\n#if defined(DEBUG_CACHE)\n printf(\"archive files already loaded\\n\");\n#endif\n return;\n }\n /* check archive size consistency */\n if (offset != n->u.reg.size) {\n#if defined(DEBUG_CACHE)\n printf(\" inconsistent archive size: %\" PRId64 \" %\" PRId64 \"\\n\",\n offset, n->u.reg.size);\n#endif\n goto load_fallback;\n }\n\n /* start loading the archive */\n fs_open_wget(fs1, n, FS_OPEN_WGET_ARCHIVE);\n \n /* indicate that all the archive files are being loaded. Also\n check consistency of size and file id */\n offset = 0;\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n n1 = inode_search_path(fs1, paf->name);\n if (n1 && n1->type == FT_REG &&\n n1->u.reg.state == REG_STATE_UNLOADED) {\n if (n1->u.reg.size == paf->size &&\n n1->u.reg.file_id == paf->file_id) {\n fs_open_wget(fs1, n1, FS_OPEN_WGET_ARCHIVE_FILE);\n list_add_tail(&n1->u.reg.open_info->archive_link,\n &n->u.reg.open_info->archive_file_list);\n n1->u.reg.open_info->archive_offset = offset;\n } else {\n#if defined(DEBUG_CACHE)\n printf(\" inconsistent archive file: %s\\n\", paf->name);\n#endif\n /* fallback to file preload */\n fs_preload_file(fs1, paf->name);\n }\n }\n offset += paf->size;\n }\n } else {\n load_fallback:\n /* if the archive is already loaded or not loaded, we load the\n files separately (XXX: not optimal if the archive is\n already loaded, but it should not happen often) */\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n fs_preload_file(fs1, paf->name);\n }\n }\n}\n\nstatic void fs_preload_files(FSDevice *fs1, FSFileID file_id)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el;\n PreloadEntry *pe;\n PreloadFile *pf;\n \n list_for_each(el, &fs->preload_list) {\n pe = list_entry(el, PreloadEntry, link);\n if (pe->file_id == file_id)\n goto found;\n }\n return;\n found:\n list_for_each(el, &pe->file_list) {\n pf = list_entry(el, PreloadFile, link);\n if (pf->is_archive)\n fs_preload_archive(fs1, pf->name);\n else\n fs_preload_file(fs1, pf->name);\n }\n}\n\n/* return < 0 if error, 0 if OK, 1 if asynchronous completion */\n/* XXX: we don't support several simultaneous asynchronous open on the\n same inode */\nstatic int fs_open(FSDevice *fs1, FSQID *qid, FSFile *f, uint32_t flags,\n FSOpenCompletionFunc *cb, void *opaque)\n{\n FSINode *n = f->inode;\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int ret;\n \n fs_close(fs1, f);\n\n if (flags & P9_O_DIRECTORY) {\n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n } else {\n if (n->type != FT_REG && n->type != FT_DIR)\n return -P9_EINVAL; /* XXX */\n }\n f->open_flags = flags;\n if (n->type == FT_REG) {\n if ((flags & P9_O_TRUNC) && (flags & P9_O_NOACCESS) != P9_O_RDONLY) {\n fs_truncate(fs1, n, 0);\n }\n\n switch(n->u.reg.state) {\n case REG_STATE_UNLOADED:\n {\n FSOpenInfo *oi;\n /* need to load the file */\n fs_preload_files(fs1, n->u.reg.file_id);\n /* The state can be modified by the fs_preload_files */\n if (n->u.reg.state == REG_STATE_LOADING)\n goto handle_loading;\n ret = fs_open_wget(fs1, n, FS_OPEN_WGET_REG);\n if (ret)\n return ret;\n oi = n->u.reg.open_info;\n oi->f = f;\n oi->cb = cb;\n oi->opaque = opaque;\n return 1; /* completion callback will be called later */\n }\n break;\n case REG_STATE_LOADING:\n handle_loading:\n {\n FSOpenInfo *oi;\n /* we only handle the case where the file is being preloaded */\n oi = n->u.reg.open_info;\n if (oi->cb)\n return -P9_EIO;\n oi = n->u.reg.open_info;\n oi->f = f;\n oi->cb = cb;\n oi->opaque = opaque;\n return 1; /* completion callback will be called later */\n }\n break;\n case REG_STATE_LOCAL:\n goto do_open;\n case REG_STATE_LOADED:\n /* move to front */\n list_del(&n->u.reg.link);\n list_add(&n->u.reg.link, &fs->inode_cache_list);\n goto do_open;\n default:\n abort();\n }\n } else {\n do_open:\n f->is_opened = TRUE;\n inode_to_qid(qid, n);\n return 0;\n }\n}\n\nstatic int fs_create(FSDevice *fs, FSQID *qid, FSFile *f, const char *name, \n uint32_t flags, uint32_t mode, uint32_t gid)\n{\n FSINode *n1, *n = f->inode;\n \n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n if (inode_search(n, name)) {\n /* XXX: support it, but Linux does not seem to use this case */\n return -P9_EEXIST;\n } else {\n fs_close(fs, f);\n \n n1 = inode_new(fs, FT_REG, mode, f->uid, gid);\n inode_dir_add(fs, n, name, n1);\n \n inode_dec_open(fs, f->inode);\n f->inode = inode_inc_open(fs, n1);\n f->is_opened = TRUE;\n f->open_flags = flags;\n inode_to_qid(qid, n1);\n return 0;\n }\n}\n\nstatic int fs_readdir(FSDevice *fs, FSFile *f, uint64_t offset1,\n uint8_t *buf, int count)\n{\n FSINode *n1, *n = f->inode;\n int len, pos, name_len, type;\n struct list_head *el;\n FSDirEntry *de;\n uint64_t offset;\n\n if (!f->is_opened || n->type != FT_DIR)\n return -P9_EPROTO;\n \n el = n->u.dir.de_list.next;\n offset = 0;\n while (offset < offset1) {\n if (el == &n->u.dir.de_list)\n return 0; /* no more entries */\n offset++;\n el = el->next;\n }\n \n pos = 0;\n for(;;) {\n if (el == &n->u.dir.de_list)\n break;\n de = list_entry(el, FSDirEntry, link);\n name_len = strlen(de->name);\n len = 13 + 8 + 1 + 2 + name_len;\n if ((pos + len) > count)\n break;\n offset++;\n n1 = de->inode;\n if (n1->type == FT_DIR)\n type = P9_QTDIR;\n else if (n1->type == FT_LNK)\n type = P9_QTSYMLINK;\n else\n type = P9_QTFILE;\n buf[pos++] = type;\n put_le32(buf + pos, 0); /* version */\n pos += 4;\n put_le64(buf + pos, n1->inode_num);\n pos += 8;\n put_le64(buf + pos, offset);\n pos += 8;\n buf[pos++] = n1->type;\n put_le16(buf + pos, name_len);\n pos += 2;\n memcpy(buf + pos, de->name, name_len);\n pos += name_len;\n el = el->next;\n }\n return pos;\n}\n\nstatic int fs_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n FSINode *n = f->inode;\n uint64_t count1;\n\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n if ((f->open_flags & P9_O_NOACCESS) == P9_O_WRONLY)\n return -P9_EIO;\n if (n->u.reg.is_fscmd)\n return fs_cmd_read(fs, f, offset, buf, count);\n if (offset >= n->u.reg.size)\n return 0;\n count1 = n->u.reg.size - offset;\n if (count1 < count)\n count = count1;\n file_buffer_read(&n->u.reg.fbuf, offset, buf, count);\n return count;\n}\n\nstatic int fs_truncate(FSDevice *fs1, FSINode *n, uint64_t size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n intptr_t diff, diff_blocks;\n size_t new_allocated_size;\n \n if (n->type != FT_REG)\n return -P9_EINVAL;\n if (size > UINTPTR_MAX)\n return -P9_ENOSPC;\n diff = size - n->u.reg.size;\n if (diff == 0)\n return 0;\n diff_blocks = to_blocks(fs, size) - to_blocks(fs, n->u.reg.size);\n /* currently cannot resize while loading */\n switch(n->u.reg.state) {\n case REG_STATE_LOADING:\n return -P9_EIO;\n case REG_STATE_UNLOADED:\n if (size == 0) {\n /* now local content */\n n->u.reg.state = REG_STATE_LOCAL;\n }\n break;\n case REG_STATE_LOADED:\n case REG_STATE_LOCAL:\n if (diff > 0) {\n if ((fs->fs_blocks + diff_blocks) > fs->fs_max_blocks)\n return -P9_ENOSPC;\n if (size > n->u.reg.fbuf.allocated_size) {\n new_allocated_size = n->u.reg.fbuf.allocated_size * 5 / 4;\n if (size > new_allocated_size)\n new_allocated_size = size;\n if (file_buffer_resize(&n->u.reg.fbuf, new_allocated_size) < 0)\n return -P9_ENOSPC;\n }\n file_buffer_set(&n->u.reg.fbuf, n->u.reg.size, 0, diff);\n } else {\n new_allocated_size = n->u.reg.fbuf.allocated_size * 4 / 5;\n if (size <= new_allocated_size) {\n if (file_buffer_resize(&n->u.reg.fbuf, new_allocated_size) < 0)\n return -P9_ENOSPC;\n }\n }\n /* file is modified, so it is now local */\n if (n->u.reg.state == REG_STATE_LOADED) {\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n n->u.reg.state = REG_STATE_LOCAL;\n }\n break;\n default:\n abort();\n }\n fs->fs_blocks += diff_blocks;\n assert(fs->fs_blocks >= 0);\n n->u.reg.size = size;\n return 0;\n}\n\nstatic int fs_write(FSDevice *fs1, FSFile *f, uint64_t offset,\n const uint8_t *buf, int count)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n = f->inode;\n uint64_t end;\n int err;\n \n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n if ((f->open_flags & P9_O_NOACCESS) == P9_O_RDONLY)\n return -P9_EIO;\n if (count == 0)\n return 0;\n if (n->u.reg.is_fscmd) {\n return fs_cmd_write(fs1, f, offset, buf, count);\n }\n end = offset + count;\n if (end > n->u.reg.size) {\n err = fs_truncate(fs1, n, end);\n if (err)\n return err;\n }\n inode_update_mtime(fs1, n);\n /* file is modified, so it is now local */\n if (n->u.reg.state == REG_STATE_LOADED) {\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n n->u.reg.state = REG_STATE_LOCAL;\n }\n file_buffer_write(&n->u.reg.fbuf, offset, buf, count);\n return count;\n}\n\nstatic void fs_close(FSDevice *fs, FSFile *f)\n{\n if (f->is_opened) {\n f->is_opened = FALSE;\n }\n if (f->req)\n fs_cmd_close(fs, f);\n}\n\nstatic int fs_stat(FSDevice *fs1, FSFile *f, FSStat *st)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n = f->inode;\n\n inode_to_qid(&st->qid, n);\n st->st_mode = n->mode | (n->type << 12);\n st->st_uid = n->uid;\n st->st_gid = n->gid;\n st->st_nlink = n->refcount;\n if (n->type == FT_BLK || n->type == FT_CHR) {\n /* XXX: check */\n st->st_rdev = (n->u.dev.major << 8) | n->u.dev.minor;\n } else {\n st->st_rdev = 0;\n }\n st->st_blksize = fs->block_size;\n if (n->type == FT_REG) {\n st->st_size = n->u.reg.size;\n } else if (n->type == FT_LNK) {\n st->st_size = strlen(n->u.symlink.name);\n } else if (n->type == FT_DIR) {\n st->st_size = n->u.dir.size;\n } else {\n st->st_size = 0;\n }\n /* in 512 byte blocks */\n st->st_blocks = to_blocks(fs, st->st_size) << (fs->block_size_log2 - 9);\n \n /* Note: atime is not supported */\n st->st_atime_sec = n->mtime_sec;\n st->st_atime_nsec = n->mtime_nsec;\n st->st_mtime_sec = n->mtime_sec;\n st->st_mtime_nsec = n->mtime_nsec;\n st->st_ctime_sec = n->ctime_sec;\n st->st_ctime_nsec = n->ctime_nsec;\n return 0;\n}\n\nstatic int fs_setattr(FSDevice *fs1, FSFile *f, uint32_t mask,\n uint32_t mode, uint32_t uid, uint32_t gid,\n uint64_t size, uint64_t atime_sec, uint64_t atime_nsec,\n uint64_t mtime_sec, uint64_t mtime_nsec)\n{\n FSINode *n = f->inode;\n int ret;\n \n if (mask & P9_SETATTR_MODE) {\n n->mode = mode;\n }\n if (mask & P9_SETATTR_UID) {\n n->uid = uid;\n }\n if (mask & P9_SETATTR_GID) {\n n->gid = gid;\n }\n if (mask & P9_SETATTR_SIZE) {\n ret = fs_truncate(fs1, n, size);\n if (ret)\n return ret;\n }\n if (mask & P9_SETATTR_MTIME) {\n if (mask & P9_SETATTR_MTIME_SET) {\n n->mtime_sec = mtime_sec;\n n->mtime_nsec = mtime_nsec;\n } else {\n inode_update_mtime(fs1, n);\n }\n }\n if (mask & P9_SETATTR_CTIME) {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n n->ctime_sec = tv.tv_sec;\n n->ctime_nsec = tv.tv_usec * 1000;\n }\n return 0;\n}\n\nstatic int fs_link(FSDevice *fs, FSFile *df, FSFile *f, const char *name)\n{\n FSINode *n = df->inode;\n \n if (f->inode->type == FT_DIR)\n return -P9_EPERM;\n if (inode_search(n, name))\n return -P9_EEXIST;\n inode_dir_add(fs, n, name, inode_incref(fs, f->inode));\n return 0;\n}\n\nstatic int fs_symlink(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, const char *symgt, uint32_t gid)\n{\n FSINode *n1, *n = f->inode;\n \n if (inode_search(n, name))\n return -P9_EEXIST;\n\n n1 = inode_new(fs, FT_LNK, 0777, f->uid, gid);\n n1->u.symlink.name = strdup(symgt);\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\nstatic int fs_mknod(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, uint32_t mode, uint32_t major,\n uint32_t minor, uint32_t gid)\n{\n int type;\n FSINode *n1, *n = f->inode;\n\n type = (mode & P9_S_IFMT) >> 12;\n /* XXX: add FT_DIR support */\n if (type != FT_FIFO && type != FT_CHR && type != FT_BLK &&\n type != FT_REG && type != FT_SOCK)\n return -P9_EINVAL;\n if (inode_search(n, name))\n return -P9_EEXIST;\n n1 = inode_new(fs, type, mode, f->uid, gid);\n if (type == FT_CHR || type == FT_BLK) {\n n1->u.dev.major = major;\n n1->u.dev.minor = minor;\n }\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\nstatic int fs_readlink(FSDevice *fs, char *buf, int buf_size, FSFile *f)\n{\n FSINode *n = f->inode;\n int len;\n if (n->type != FT_LNK)\n return -P9_EIO;\n len = min_int(strlen(n->u.symlink.name), buf_size - 1);\n memcpy(buf, n->u.symlink.name, len);\n buf[len] = '\\0';\n return 0;\n}\n\nstatic int fs_renameat(FSDevice *fs, FSFile *f, const char *name, \n FSFile *new_f, const char *new_name)\n{\n FSDirEntry *de, *de1;\n FSINode *n1;\n \n de = inode_search(f->inode, name);\n if (!de)\n return -P9_ENOENT;\n de1 = inode_search(new_f->inode, new_name);\n n1 = NULL;\n if (de1) {\n n1 = de1->inode;\n if (n1->type == FT_DIR)\n return -P9_EEXIST; /* XXX: handle the case */\n inode_dirent_delete_no_decref(fs, new_f->inode, de1);\n }\n inode_dir_add(fs, new_f->inode, new_name, inode_incref(fs, de->inode));\n inode_dirent_delete(fs, f->inode, de);\n if (n1)\n inode_decref(fs, n1);\n return 0;\n}\n\nstatic int fs_unlinkat(FSDevice *fs, FSFile *f, const char *name)\n{\n FSDirEntry *de;\n FSINode *n;\n\n if (!strcmp(name, \".\") || !strcmp(name, \"..\"))\n return -P9_ENOENT;\n de = inode_search(f->inode, name);\n if (!de)\n return -P9_ENOENT;\n n = de->inode;\n if (n->type == FT_DIR) {\n if (!is_empty_dir(fs, n))\n return -P9_ENOTEMPTY;\n flush_dir(fs, n);\n }\n inode_dirent_delete(fs, f->inode, de);\n return 0;\n}\n\nstatic int fs_lock(FSDevice *fs, FSFile *f, const FSLock *lock)\n{\n FSINode *n = f->inode;\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n /* XXX: implement it */\n return P9_LOCK_SUCCESS;\n}\n\nstatic int fs_getlock(FSDevice *fs, FSFile *f, FSLock *lock)\n{\n FSINode *n = f->inode;\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n /* XXX: implement it */\n return 0;\n}\n\n/* XXX: only used with file lists, so not all the data is released */\nstatic void fs_mem_end(FSDevice *fs1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el, *el1, *el2, *el3;\n FSINode *n;\n FSDirEntry *de;\n\n list_for_each_safe(el, el1, &fs->inode_list) {\n n = list_entry(el, FSINode, link);\n n->refcount = 0;\n if (n->type == FT_DIR) {\n list_for_each_safe(el2, el3, &n->u.dir.de_list) {\n de = list_entry(el2, FSDirEntry, link);\n list_del(&de->link);\n free(de);\n }\n init_list_head(&n->u.dir.de_list);\n }\n inode_free(fs1, n);\n }\n assert(list_empty(&fs->inode_cache_list));\n free(fs->import_dir);\n}\n\nFSDevice *fs_mem_init(void)\n{\n FSDeviceMem *fs;\n FSDevice *fs1;\n FSINode *n;\n\n fs = mallocz(sizeof(*fs));\n fs1 = &fs->common;\n\n fs->common.fs_end = fs_mem_end;\n fs->common.fs_delete = fs_delete;\n fs->common.fs_statfs = fs_statfs;\n fs->common.fs_attach = fs_attach;\n fs->common.fs_walk = fs_walk;\n fs->common.fs_mkdir = fs_mkdir;\n fs->common.fs_open = fs_open;\n fs->common.fs_create = fs_create;\n fs->common.fs_stat = fs_stat;\n fs->common.fs_setattr = fs_setattr;\n fs->common.fs_close = fs_close;\n fs->common.fs_readdir = fs_readdir;\n fs->common.fs_read = fs_read;\n fs->common.fs_write = fs_write;\n fs->common.fs_link = fs_link;\n fs->common.fs_symlink = fs_symlink;\n fs->common.fs_mknod = fs_mknod;\n fs->common.fs_readlink = fs_readlink;\n fs->common.fs_renameat = fs_renameat;\n fs->common.fs_unlinkat = fs_unlinkat;\n fs->common.fs_lock = fs_lock;\n fs->common.fs_getlock = fs_getlock;\n\n init_list_head(&fs->inode_list);\n fs->inode_num_alloc = 1;\n fs->block_size_log2 = FS_BLOCK_SIZE_LOG2;\n fs->block_size = 1 << fs->block_size_log2;\n fs->inode_limit = 1 << 20; /* arbitrary */\n fs->fs_max_blocks = 1 << (30 - fs->block_size_log2); /* arbitrary */\n\n init_list_head(&fs->inode_cache_list);\n fs->inode_cache_size_limit = DEFAULT_INODE_CACHE_SIZE;\n\n init_list_head(&fs->preload_list);\n init_list_head(&fs->preload_archive_list);\n\n init_list_head(&fs->base_url_list);\n\n /* create the root inode */\n n = inode_new(fs1, FT_DIR, 0777, 0, 0);\n inode_dir_add(fs1, n, \".\", inode_incref(fs1, n));\n inode_dir_add(fs1, n, \"..\", inode_incref(fs1, n));\n fs->root_inode = n;\n\n return (FSDevice *)fs;\n}\n\nstatic BOOL fs_is_net(FSDevice *fs)\n{\n return (fs->fs_end == fs_mem_end);\n}\n\nstatic FSBaseURL *fs_find_base_url(FSDevice *fs1,\n const char *base_url_id)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el;\n FSBaseURL *bu;\n \n list_for_each(el, &fs->base_url_list) {\n bu = list_entry(el, FSBaseURL, link);\n if (!strcmp(bu->base_url_id, base_url_id))\n return bu;\n }\n return NULL;\n}\n\nstatic void fs_base_url_decref(FSDevice *fs, FSBaseURL *bu)\n{\n assert(bu->ref_count >= 1);\n if (--bu->ref_count == 0) {\n free(bu->base_url_id);\n free(bu->url);\n free(bu->user);\n free(bu->password);\n list_del(&bu->link);\n free(bu);\n }\n}\n\nstatic FSBaseURL *fs_net_set_base_url(FSDevice *fs1,\n const char *base_url_id,\n const char *url,\n const char *user, const char *password,\n AES_KEY *aes_state)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSBaseURL *bu;\n \n assert(fs_is_net(fs1));\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu) {\n bu = mallocz(sizeof(*bu));\n bu->base_url_id = strdup(base_url_id);\n bu->ref_count = 1;\n list_add_tail(&bu->link, &fs->base_url_list);\n } else {\n free(bu->url);\n free(bu->user);\n free(bu->password);\n }\n\n bu->url = strdup(url);\n if (user)\n bu->user = strdup(user);\n else\n bu->user = NULL;\n if (password)\n bu->password = strdup(password);\n else\n bu->password = NULL;\n if (aes_state) {\n bu->encrypted = TRUE;\n bu->aes_state = *aes_state;\n } else {\n bu->encrypted = FALSE;\n }\n return bu;\n}\n\nstatic int fs_net_reset_base_url(FSDevice *fs1,\n const char *base_url_id)\n{\n FSBaseURL *bu;\n \n assert(fs_is_net(fs1));\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu)\n return -P9_ENOENT;\n fs_base_url_decref(fs1, bu);\n return 0;\n}\n\nstatic void fs_net_set_fs_max_size(FSDevice *fs1, uint64_t fs_max_size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n assert(fs_is_net(fs1));\n fs->fs_max_blocks = to_blocks(fs, fs_max_size);\n}\n\nstatic int fs_net_set_url(FSDevice *fs1, FSINode *n,\n const char *base_url_id, FSFileID file_id, uint64_t size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSBaseURL *bu;\n\n assert(fs_is_net(fs1));\n\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu)\n return -P9_ENOENT;\n\n /* XXX: could accept more state */\n if (n->type != FT_REG ||\n n->u.reg.state != REG_STATE_LOCAL ||\n n->u.reg.fbuf.allocated_size != 0)\n return -P9_EIO;\n \n if (size > 0) {\n n->u.reg.state = REG_STATE_UNLOADED;\n n->u.reg.base_url = bu;\n bu->ref_count++;\n n->u.reg.size = size;\n fs->fs_blocks += to_blocks(fs, size);\n n->u.reg.file_id = file_id;\n }\n return 0;\n}\n\n#ifdef DUMP_CACHE_LOAD\n\n#include \"json.h\"\n\n#define ARCHIVE_SIZE_MAX (4 << 20)\n\nstatic void fs_dump_add_file(struct list_head *head, const char *name)\n{\n PreloadFile *pf;\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(name);\n list_add_tail(&pf->link, head);\n}\n\nstatic PreloadFile *fs_dump_find_file(struct list_head *head, const char *name)\n{\n PreloadFile *pf;\n struct list_head *el;\n list_for_each(el, head) {\n pf = list_entry(el, PreloadFile, link);\n if (!strcmp(pf->name, name))\n return pf;\n }\n return NULL;\n}\n\nstatic void dump_close_archive(FSDevice *fs1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (fs->dump_archive_file) {\n fclose(fs->dump_archive_file);\n }\n fs->dump_archive_file = NULL;\n fs->dump_archive_size = 0;\n}\n\nstatic void dump_loaded_file(FSDevice *fs1, FSINode *n)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char filename[1024];\n const char *fname, *p;\n \n if (!fs->dump_cache_load || !n->u.reg.filename)\n return;\n fname = n->u.reg.filename;\n \n if (fs_dump_find_file(&fs->dump_preload_list, fname)) {\n dump_close_archive(fs1);\n p = strrchr(fname, '/');\n if (!p)\n p = fname;\n else\n p++;\n free(fs->dump_archive_name);\n fs->dump_archive_name = strdup(p);\n fs->dump_started = TRUE;\n fs->dump_archive_num = 0;\n\n fprintf(fs->dump_preload_file, \"\\n%s :\\n\", fname);\n }\n if (!fs->dump_started)\n return;\n \n if (!fs->dump_archive_file) {\n snprintf(filename, sizeof(filename), \"%s/%s%d\",\n fs->dump_preload_dir, fs->dump_archive_name,\n fs->dump_archive_num);\n fs->dump_archive_file = fopen(filename, \"wb\");\n if (!fs->dump_archive_file) {\n perror(filename);\n exit(1);\n }\n fprintf(fs->dump_preload_archive_file, \"\\n@.preload2/%s%d :\\n\",\n fs->dump_archive_name, fs->dump_archive_num);\n fprintf(fs->dump_preload_file, \" @.preload2/%s%d\\n\",\n fs->dump_archive_name, fs->dump_archive_num);\n fflush(fs->dump_preload_file);\n fs->dump_archive_num++;\n }\n\n if (n->u.reg.size >= ARCHIVE_SIZE_MAX) {\n /* exclude large files from archive */\n /* add indicative size */\n fprintf(fs->dump_preload_file, \" %s %\" PRId64 \"\\n\",\n fname, n->u.reg.size);\n fflush(fs->dump_preload_file);\n } else {\n fprintf(fs->dump_preload_archive_file, \" %s %\" PRId64 \" %\" PRIx64 \"\\n\",\n n->u.reg.filename, n->u.reg.size, n->u.reg.file_id);\n fflush(fs->dump_preload_archive_file);\n fwrite(n->u.reg.fbuf.data, 1, n->u.reg.size, fs->dump_archive_file);\n fflush(fs->dump_archive_file);\n fs->dump_archive_size += n->u.reg.size;\n if (fs->dump_archive_size >= ARCHIVE_SIZE_MAX) {\n dump_close_archive(fs1);\n }\n }\n}\n\nstatic JSONValue json_load(const char *filename)\n{\n FILE *f;\n JSONValue val;\n size_t size;\n char *buf;\n \n f = fopen(filename, \"rb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n size = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = malloc(size + 1);\n fread(buf, 1, size, f);\n fclose(f);\n val = json_parse_value_len(buf, size);\n free(buf);\n return val;\n}\n\nvoid fs_dump_cache_load(FSDevice *fs1, const char *cfg_filename)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n JSONValue cfg, val, array;\n char *fname;\n const char *preload_dir, *name;\n int i;\n \n if (!fs_is_net(fs1))\n return;\n cfg = json_load(cfg_filename);\n if (json_is_error(cfg)) {\n fprintf(stderr, \"%s\\n\", json_get_error(cfg));\n exit(1);\n }\n\n val = json_object_get(cfg, \"preload_dir\");\n if (json_is_undefined(cfg)) {\n config_error:\n exit(1);\n }\n preload_dir = json_get_str(val);\n if (!preload_dir) {\n fprintf(stderr, \"expecting preload_filename\\n\");\n goto config_error;\n }\n fs->dump_preload_dir = strdup(preload_dir);\n \n init_list_head(&fs->dump_preload_list);\n init_list_head(&fs->dump_exclude_list);\n\n array = json_object_get(cfg, \"preload\");\n if (array.type != JSON_ARRAY) {\n fprintf(stderr, \"expecting preload array\\n\");\n goto config_error;\n }\n for(i = 0; i < array.u.array->len; i++) {\n val = json_array_get(array, i);\n name = json_get_str(val);\n if (!name) {\n fprintf(stderr, \"expecting a string\\n\");\n goto config_error;\n }\n fs_dump_add_file(&fs->dump_preload_list, name);\n }\n json_free(cfg);\n\n fname = compose_path(fs->dump_preload_dir, \"preload.txt\");\n fs->dump_preload_file = fopen(fname, \"w\");\n if (!fs->dump_preload_file) {\n perror(fname);\n exit(1);\n }\n free(fname);\n\n fname = compose_path(fs->dump_preload_dir, \"preload_archive.txt\");\n fs->dump_preload_archive_file = fopen(fname, \"w\");\n if (!fs->dump_preload_archive_file) {\n perror(fname);\n exit(1);\n }\n free(fname);\n\n fs->dump_cache_load = TRUE;\n}\n#else\nvoid fs_dump_cache_load(FSDevice *fs1, const char *cfg_filename)\n{\n}\n#endif\n\n/***********************************************/\n/* file list processing */\n\nstatic int filelist_load_rec(FSDevice *fs1, const char **pp, FSINode *dir,\n const char *path)\n{\n // FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char fname[1024], lname[1024];\n int ret;\n const char *p;\n FSINodeTypeEnum type;\n uint32_t mode, uid, gid;\n uint64_t size;\n FSINode *n;\n\n p = *pp;\n for(;;) {\n /* skip comments or empty lines */\n if (*p == '\\0')\n break;\n if (*p == '#') {\n skip_line(&p);\n continue;\n }\n /* end of directory */\n if (*p == '.') {\n p++;\n skip_line(&p);\n break;\n }\n if (parse_uint32_base(&mode, &p, 8) < 0) {\n fprintf(stderr, \"invalid mode\\n\");\n return -1;\n }\n type = mode >> 12;\n mode &= 0xfff;\n \n if (parse_uint32(&uid, &p) < 0) {\n fprintf(stderr, \"invalid uid\\n\");\n return -1;\n }\n\n if (parse_uint32(&gid, &p) < 0) {\n fprintf(stderr, \"invalid gid\\n\");\n return -1;\n }\n\n n = inode_new(fs1, type, mode, uid, gid);\n \n size = 0;\n switch(type) {\n case FT_CHR:\n case FT_BLK:\n if (parse_uint32(&n->u.dev.major, &p) < 0) {\n fprintf(stderr, \"invalid major\\n\");\n return -1;\n }\n if (parse_uint32(&n->u.dev.minor, &p) < 0) {\n fprintf(stderr, \"invalid minor\\n\");\n return -1;\n }\n break;\n case FT_REG:\n if (parse_uint64(&size, &p) < 0) {\n fprintf(stderr, \"invalid size\\n\");\n return -1;\n }\n break;\n case FT_DIR:\n inode_dir_add(fs1, n, \".\", inode_incref(fs1, n));\n inode_dir_add(fs1, n, \"..\", inode_incref(fs1, dir));\n break;\n default:\n break;\n }\n \n /* modification time */\n if (parse_time(&n->mtime_sec, &n->mtime_nsec, &p) < 0) {\n fprintf(stderr, \"invalid mtime\\n\");\n return -1;\n }\n\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return -1;\n }\n inode_dir_add(fs1, dir, fname, n);\n \n if (type == FT_LNK) {\n if (parse_fname(lname, sizeof(lname), &p) < 0) {\n fprintf(stderr, \"invalid symlink name\\n\");\n return -1;\n }\n n->u.symlink.name = strdup(lname);\n } else if (type == FT_REG && size > 0) {\n FSFileID file_id;\n if (parse_file_id(&file_id, &p) < 0) {\n fprintf(stderr, \"invalid file id\\n\");\n return -1;\n }\n fs_net_set_url(fs1, n, \"/\", file_id, size);\n#ifdef DUMP_CACHE_LOAD\n {\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (fs->dump_cache_load\n#ifdef DEBUG_CACHE\n || 1\n#endif\n ) {\n n->u.reg.filename = compose_path(path, fname);\n } else {\n n->u.reg.filename = NULL;\n }\n }\n#endif\n }\n\n skip_line(&p);\n \n if (type == FT_DIR) {\n char *path1;\n path1 = compose_path(path, fname);\n ret = filelist_load_rec(fs1, &p, n, path1);\n free(path1);\n if (ret)\n return ret;\n }\n }\n *pp = p;\n return 0;\n}\n\nstatic int filelist_load(FSDevice *fs1, const char *str)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int ret;\n const char *p;\n \n if (parse_tag_version(str) != 1)\n return -1;\n p = skip_header(str);\n if (!p)\n return -1;\n ret = filelist_load_rec(fs1, &p, fs->root_inode, \"\");\n return ret;\n}\n\n/************************************************************/\n/* FS init from network */\n\nstatic void __attribute__((format(printf, 1, 2))) fatal_error(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n fprintf(stderr, \"Error: \");\n vfprintf(stderr, fmt, ap);\n fprintf(stderr, \"\\n\");\n va_end(ap);\n exit(1);\n}\n\nstatic void fs_create_cmd(FSDevice *fs)\n{\n FSFile *root_fd;\n FSQID qid;\n FSINode *n;\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\"));\n assert(!fs->fs_create(fs, &qid, root_fd, FSCMD_NAME, P9_O_RDWR | P9_O_TRUNC,\n 0666, 0));\n n = root_fd->inode;\n n->u.reg.is_fscmd = TRUE;\n fs->fs_delete(fs, root_fd);\n}\n\ntypedef struct {\n FSDevice *fs;\n char *url;\n void (*start_cb)(void *opaque);\n void *start_opaque;\n \n FSFile *root_fd;\n FSFile *fd;\n int file_index;\n \n} FSNetInitState;\n\nstatic void fs_initial_sync(FSDevice *fs,\n const char *url, void (*start_cb)(void *opaque),\n void *start_opaque);\nstatic void head_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque);\nstatic void filelist_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque);\nstatic void kernel_load_cb(FSDevice *fs, FSQID *qid, int err,\n void *opaque);\nstatic int preload_parse(FSDevice *fs, const char *fname, BOOL is_new);\n\n#ifdef EMSCRIPTEN\nstatic FSDevice *fs_import_fs;\n#endif\n\n#define DEFAULT_IMPORT_FILE_PATH \"/tmp\"\n\nFSDevice *fs_net_init(const char *url, void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n FSDevice *fs;\n FSDeviceMem *fs1;\n \n fs_wget_init();\n \n fs = fs_mem_init();\n#ifdef EMSCRIPTEN\n if (!fs_import_fs)\n fs_import_fs = fs;\n#endif\n fs1 = (FSDeviceMem *)fs;\n fs1->import_dir = strdup(DEFAULT_IMPORT_FILE_PATH);\n \n fs_create_cmd(fs);\n\n if (url) {\n fs_initial_sync(fs, url, start_cb, start_opaque);\n }\n return fs;\n}\n\nstatic void fs_initial_sync(FSDevice *fs,\n const char *url, void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n FSNetInitState *s;\n FSFile *head_fd;\n FSQID qid;\n char *head_url;\n char buf[128];\n struct timeval tv;\n \n s = mallocz(sizeof(*s));\n s->fs = fs;\n s->url = strdup(url);\n s->start_cb = start_cb;\n s->start_opaque = start_opaque;\n assert(!fs->fs_attach(fs, &s->root_fd, &qid, 0, \"\", \"\"));\n \n /* avoid using cached version */\n gettimeofday(&tv, NULL);\n snprintf(buf, sizeof(buf), HEAD_FILENAME \"?nocache=%\" PRId64,\n (int64_t)tv.tv_sec * 1000000 + tv.tv_usec);\n head_url = compose_url(s->url, buf);\n head_fd = fs_dup(fs, s->root_fd);\n assert(!fs->fs_create(fs, &qid, head_fd, \".head\",\n P9_O_RDWR | P9_O_TRUNC, 0644, 0));\n fs_wget_file2(fs, head_fd, head_url, NULL, NULL, NULL, 0,\n head_loaded, s, NULL);\n free(head_url);\n}\n\nstatic void head_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque)\n{\n FSNetInitState *s = opaque;\n char *buf, *root_url, *url;\n char fname[FILEID_SIZE_MAX];\n FSFileID root_id;\n FSFile *new_filelist_fd;\n FSQID qid;\n uint64_t fs_max_size;\n \n if (size < 0)\n fatal_error(\"could not load 'head' file (HTTP error=%d)\", -(int)size);\n \n buf = malloc(size + 1);\n fs->fs_read(fs, f, 0, (uint8_t *)buf, size);\n buf[size] = '\\0';\n fs->fs_delete(fs, f);\n fs->fs_unlinkat(fs, s->root_fd, \".head\");\n\n if (parse_tag_version(buf) != 1)\n fatal_error(\"invalid head version\");\n\n if (parse_tag_file_id(&root_id, buf, \"RootID\") < 0)\n fatal_error(\"expected RootID tag\");\n\n if (parse_tag_uint64(&fs_max_size, buf, \"FSMaxSize\") == 0 &&\n fs_max_size >= ((uint64_t)1 << 20)) {\n fs_net_set_fs_max_size(fs, fs_max_size);\n }\n \n /* set the Root URL in the filesystem */\n root_url = compose_url(s->url, ROOT_FILENAME);\n fs_net_set_base_url(fs, \"/\", root_url, NULL, NULL, NULL);\n \n new_filelist_fd = fs_dup(fs, s->root_fd);\n assert(!fs->fs_create(fs, &qid, new_filelist_fd, \".filelist.txt\",\n P9_O_RDWR | P9_O_TRUNC, 0644, 0));\n\n file_id_to_filename(fname, root_id);\n url = compose_url(root_url, fname);\n fs_wget_file2(fs, new_filelist_fd, url, NULL, NULL, NULL, 0,\n filelist_loaded, s, NULL);\n free(root_url);\n free(url);\n}\n\nstatic void filelist_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque)\n{\n FSNetInitState *s = opaque;\n uint8_t *buf;\n\n if (size < 0)\n fatal_error(\"could not load file list (HTTP error=%d)\", -(int)size);\n \n buf = malloc(size + 1);\n fs->fs_read(fs, f, 0, buf, size);\n buf[size] = '\\0';\n fs->fs_delete(fs, f);\n fs->fs_unlinkat(fs, s->root_fd, \".filelist.txt\");\n \n if (filelist_load(fs, (char *)buf) != 0)\n fatal_error(\"error while parsing file list\");\n\n /* try to load the kernel and the preload file */\n s->file_index = 0;\n kernel_load_cb(fs, NULL, 0, s);\n}\n\n\n#define FILE_LOAD_COUNT 2\n\nstatic const char *kernel_file_list[FILE_LOAD_COUNT] = {\n \".preload\",\n \".preload2/preload.txt\",\n};\n\nstatic void kernel_load_cb(FSDevice *fs, FSQID *qid1, int err,\n void *opaque)\n{\n FSNetInitState *s = opaque;\n FSQID qid;\n\n#ifdef DUMP_CACHE_LOAD\n /* disable preloading if dumping cache load */\n if (((FSDeviceMem *)fs)->dump_cache_load)\n return;\n#endif\n\n if (s->fd) {\n fs->fs_delete(fs, s->fd);\n s->fd = NULL;\n }\n \n if (s->file_index >= FILE_LOAD_COUNT) {\n /* all files are loaded */\n if (preload_parse(fs, \".preload2/preload.txt\", TRUE) < 0) { \n preload_parse(fs, \".preload\", FALSE);\n }\n fs->fs_delete(fs, s->root_fd);\n if (s->start_cb)\n s->start_cb(s->start_opaque);\n free(s);\n } else {\n s->fd = fs_walk_path(fs, s->root_fd, kernel_file_list[s->file_index++]);\n if (!s->fd)\n goto done;\n err = fs->fs_open(fs, &qid, s->fd, P9_O_RDONLY, kernel_load_cb, s);\n if (err <= 0) {\n done:\n kernel_load_cb(fs, NULL, 0, s);\n }\n }\n}\n\nstatic void preload_parse_str_old(FSDevice *fs1, const char *p)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char fname[1024];\n PreloadEntry *pe;\n PreloadFile *pf;\n FSINode *n;\n\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\n') {\n p++;\n continue;\n }\n if (*p == '\\0')\n break;\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n // printf(\"preload file='%s\\n\", fname);\n n = inode_search_path(fs1, fname);\n if (!n || n->type != FT_REG || n->u.reg.state == REG_STATE_LOCAL) {\n fprintf(stderr, \"invalid preload file: '%s'\\n\", fname);\n while (*p != '\\n' && *p != '\\0')\n p++;\n } else {\n pe = mallocz(sizeof(*pe));\n pe->file_id = n->u.reg.file_id;\n init_list_head(&pe->file_list);\n list_add_tail(&pe->link, &fs->preload_list);\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\0' || *p == '\\n')\n break;\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n // printf(\" adding '%s'\\n\", fname);\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(fname);\n list_add_tail(&pf->link, &pe->file_list); \n }\n }\n }\n}\n\nstatic void preload_parse_str(FSDevice *fs1, const char *p)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n PreloadEntry *pe;\n PreloadArchive *pa;\n FSINode *n;\n BOOL is_archive;\n char fname[1024];\n \n pe = NULL;\n pa = NULL;\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\n') {\n pe = NULL;\n p++;\n continue;\n }\n if (*p == '#')\n continue; /* comment */\n if (*p == '\\0')\n break;\n\n is_archive = FALSE;\n if (*p == '@') {\n is_archive = TRUE;\n p++;\n }\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n while (isspace_nolf(*p))\n p++;\n if (*p == ':') {\n p++;\n // printf(\"preload file='%s' archive=%d\\n\", fname, is_archive);\n n = inode_search_path(fs1, fname);\n pe = NULL;\n pa = NULL;\n if (!n || n->type != FT_REG || n->u.reg.state == REG_STATE_LOCAL) {\n fprintf(stderr, \"invalid preload file: '%s'\\n\", fname);\n while (*p != '\\n' && *p != '\\0')\n p++;\n } else if (is_archive) {\n pa = mallocz(sizeof(*pa));\n pa->name = strdup(fname);\n init_list_head(&pa->file_list);\n list_add_tail(&pa->link, &fs->preload_archive_list);\n } else {\n pe = mallocz(sizeof(*pe));\n pe->file_id = n->u.reg.file_id;\n init_list_head(&pe->file_list);\n list_add_tail(&pe->link, &fs->preload_list);\n }\n } else {\n if (!pe && !pa) {\n fprintf(stderr, \"filename without target: %s\\n\", fname);\n return;\n }\n if (pa) {\n PreloadArchiveFile *paf;\n FSFileID file_id;\n uint64_t size;\n\n if (parse_uint64(&size, &p) < 0) {\n fprintf(stderr, \"invalid size\\n\");\n return;\n }\n\n if (parse_file_id(&file_id, &p) < 0) {\n fprintf(stderr, \"invalid file id\\n\");\n return;\n }\n\n paf = mallocz(sizeof(*paf));\n paf->name = strdup(fname);\n paf->file_id = file_id;\n paf->size = size;\n list_add_tail(&paf->link, &pa->file_list);\n } else {\n PreloadFile *pf;\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(fname);\n pf->is_archive = is_archive;\n list_add_tail(&pf->link, &pe->file_list);\n }\n }\n /* skip the rest of the line */\n while (*p != '\\n' && *p != '\\0')\n p++;\n if (*p == '\\n')\n p++;\n }\n}\n\nstatic int preload_parse(FSDevice *fs, const char *fname, BOOL is_new)\n{\n FSINode *n;\n char *buf;\n size_t size;\n \n n = inode_search_path(fs, fname);\n if (!n || n->type != FT_REG || n->u.reg.state != REG_STATE_LOADED)\n return -1;\n /* transform to zero terminated string */\n size = n->u.reg.size;\n buf = malloc(size + 1);\n file_buffer_read(&n->u.reg.fbuf, 0, (uint8_t *)buf, size);\n buf[size] = '\\0';\n if (is_new)\n preload_parse_str(fs, buf);\n else\n preload_parse_str_old(fs, buf);\n free(buf);\n return 0;\n}\n\n\n\n/************************************************************/\n/* FS user interface */\n\ntypedef struct CmdXHRState {\n FSFile *req_fd;\n FSFile *root_fd;\n FSFile *fd;\n FSFile *post_fd;\n AES_KEY aes_state;\n} CmdXHRState;\n\nstatic void fs_cmd_xhr_on_load(FSDevice *fs, FSFile *f, int64_t size,\n void *opaque);\n\nstatic int parse_hex_buf(uint8_t *buf, int buf_size, const char **pp)\n{\n char buf1[1024];\n int len;\n \n if (parse_fname(buf1, sizeof(buf1), pp) < 0)\n return -1;\n len = strlen(buf1);\n if ((len & 1) != 0)\n return -1;\n len >>= 1;\n if (len > buf_size)\n return -1;\n if (decode_hex(buf, buf1, len) < 0)\n return -1;\n return len;\n}\n\nstatic int fs_cmd_xhr(FSDevice *fs, FSFile *f,\n const char *p, uint32_t uid, uint32_t gid)\n{\n char url[1024], post_filename[1024], filename[1024];\n char user_buf[128], *user;\n char password_buf[128], *password;\n FSQID qid;\n FSFile *fd, *root_fd, *post_fd;\n uint64_t post_data_len;\n int err, aes_key_len;\n CmdXHRState *s;\n char *name;\n AES_KEY *paes_state;\n uint8_t aes_key[FS_KEY_LEN];\n uint32_t flags;\n FSCMDRequest *req;\n\n /* a request is already done or in progress */\n if (f->req != NULL)\n return -P9_EIO;\n\n if (parse_fname(url, sizeof(url), &p) < 0)\n goto fail;\n if (parse_fname(user_buf, sizeof(user_buf), &p) < 0)\n goto fail;\n if (parse_fname(password_buf, sizeof(password_buf), &p) < 0)\n goto fail;\n if (parse_fname(post_filename, sizeof(post_filename), &p) < 0)\n goto fail;\n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n aes_key_len = parse_hex_buf(aes_key, FS_KEY_LEN, &p);\n if (aes_key_len < 0)\n goto fail;\n if (parse_uint32(&flags, &p) < 0)\n goto fail;\n if (aes_key_len != 0 && aes_key_len != FS_KEY_LEN)\n goto fail;\n\n if (user_buf[0] != '\\0')\n user = user_buf;\n else\n user = NULL;\n if (password_buf[0] != '\\0')\n password = password_buf;\n else\n password = NULL;\n\n // printf(\"url='%s' '%s' '%s' filename='%s'\\n\", url, user, password, filename);\n assert(!fs->fs_attach(fs, &root_fd, &qid, uid, \"\", \"\"));\n post_fd = NULL;\n\n fd = fs_walk_path1(fs, root_fd, filename, &name);\n if (!fd) {\n err = -P9_ENOENT;\n goto fail1;\n }\n /* XXX: until fs_create is fixed */\n fs->fs_unlinkat(fs, fd, name);\n\n err = fs->fs_create(fs, &qid, fd, name,\n P9_O_RDWR | P9_O_TRUNC, 0600, gid);\n if (err < 0) {\n goto fail1;\n }\n\n if (post_filename[0] != '\\0') {\n FSINode *n;\n \n post_fd = fs_walk_path(fs, root_fd, post_filename);\n if (!post_fd) {\n err = -P9_ENOENT;\n goto fail1;\n }\n err = fs->fs_open(fs, &qid, post_fd, P9_O_RDONLY, NULL, NULL);\n if (err < 0)\n goto fail1;\n n = post_fd->inode;\n assert(n->type == FT_REG && n->u.reg.state == REG_STATE_LOCAL);\n post_data_len = n->u.reg.size;\n } else {\n post_data_len = 0;\n }\n\n s = mallocz(sizeof(*s));\n s->root_fd = root_fd;\n s->fd = fd;\n s->post_fd = post_fd;\n if (aes_key_len != 0) {\n AES_set_decrypt_key(aes_key, FS_KEY_LEN * 8, &s->aes_state);\n paes_state = &s->aes_state;\n } else {\n paes_state = NULL;\n }\n\n req = mallocz(sizeof(*req));\n req->type = FS_CMD_XHR;\n req->reply_len = 0;\n req->xhr_state = s;\n s->req_fd = f;\n f->req = req;\n \n fs_wget_file2(fs, fd, url, user, password, post_fd, post_data_len,\n fs_cmd_xhr_on_load, s, paes_state);\n return 0;\n fail1:\n if (fd)\n fs->fs_delete(fs, fd);\n if (post_fd)\n fs->fs_delete(fs, post_fd);\n fs->fs_delete(fs, root_fd);\n return err;\n fail:\n return -P9_EIO;\n}\n\nstatic void fs_cmd_xhr_on_load(FSDevice *fs, FSFile *f, int64_t size,\n void *opaque)\n{\n CmdXHRState *s = opaque;\n FSCMDRequest *req;\n int ret;\n \n // printf(\"fs_cmd_xhr_on_load: size=%d\\n\", (int)size);\n\n if (s->fd)\n fs->fs_delete(fs, s->fd);\n if (s->post_fd)\n fs->fs_delete(fs, s->post_fd);\n fs->fs_delete(fs, s->root_fd);\n \n if (s->req_fd) {\n req = s->req_fd->req;\n if (size < 0) {\n ret = size;\n } else {\n ret = 0;\n }\n put_le32(req->reply_buf, ret);\n req->reply_len = sizeof(ret);\n req->xhr_state = NULL;\n }\n free(s);\n}\n\nstatic int fs_cmd_set_base_url(FSDevice *fs, const char *p)\n{\n // FSDeviceMem *fs1 = (FSDeviceMem *)fs;\n char url[1024], base_url_id[1024];\n char user_buf[128], *user;\n char password_buf[128], *password;\n AES_KEY aes_state, *paes_state;\n uint8_t aes_key[FS_KEY_LEN];\n int aes_key_len;\n \n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n if (parse_fname(url, sizeof(url), &p) < 0)\n goto fail;\n if (parse_fname(user_buf, sizeof(user_buf), &p) < 0)\n goto fail;\n if (parse_fname(password_buf, sizeof(password_buf), &p) < 0)\n goto fail;\n aes_key_len = parse_hex_buf(aes_key, FS_KEY_LEN, &p);\n if (aes_key_len < 0)\n goto fail;\n\n if (user_buf[0] != '\\0')\n user = user_buf;\n else\n user = NULL;\n if (password_buf[0] != '\\0')\n password = password_buf;\n else\n password = NULL;\n\n if (aes_key_len != 0) {\n if (aes_key_len != FS_KEY_LEN)\n goto fail;\n AES_set_decrypt_key(aes_key, FS_KEY_LEN * 8, &aes_state);\n paes_state = &aes_state;\n } else {\n paes_state = NULL;\n }\n\n fs_net_set_base_url(fs, base_url_id, url, user, password,\n paes_state);\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_reset_base_url(FSDevice *fs, const char *p)\n{\n char base_url_id[1024];\n \n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n fs_net_reset_base_url(fs, base_url_id);\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_set_url(FSDevice *fs, const char *p)\n{\n char base_url_id[1024];\n char filename[1024];\n FSFileID file_id;\n uint64_t size;\n FSINode *n;\n \n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n if (parse_file_id(&file_id, &p) < 0)\n goto fail;\n if (parse_uint64(&size, &p) < 0)\n goto fail;\n \n n = inode_search_path(fs, filename);\n if (!n) {\n return -P9_ENOENT;\n }\n return fs_net_set_url(fs, n, base_url_id, file_id, size);\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_export_file(FSDevice *fs, const char *p)\n{\n char filename[1024];\n FSINode *n;\n const char *name;\n uint8_t *buf;\n \n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n n = inode_search_path(fs, filename);\n if (!n)\n return -P9_ENOENT;\n if (n->type != FT_REG ||\n (n->u.reg.state != REG_STATE_LOCAL &&\n n->u.reg.state != REG_STATE_LOADED))\n goto fail;\n name = strrchr(filename, '/');\n if (name)\n name++;\n else\n name = filename;\n /* XXX: pass the buffer to JS to avoid the allocation */\n buf = malloc(n->u.reg.size);\n file_buffer_read(&n->u.reg.fbuf, 0, buf, n->u.reg.size);\n fs_export_file(name, buf, n->u.reg.size);\n free(buf);\n return 0;\n fail:\n return -P9_EIO;\n}\n\n/* PBKDF2 crypto acceleration */\nstatic int fs_cmd_pbkdf2(FSDevice *fs, FSFile *f, const char *p)\n{\n uint8_t pwd[1024];\n uint8_t salt[128];\n uint32_t iter, key_len;\n int pwd_len, salt_len;\n FSCMDRequest *req;\n \n /* a request is already done or in progress */\n if (f->req != NULL)\n return -P9_EIO;\n\n pwd_len = parse_hex_buf(pwd, sizeof(pwd), &p);\n if (pwd_len < 0)\n goto fail;\n salt_len = parse_hex_buf(salt, sizeof(salt), &p);\n if (pwd_len < 0)\n goto fail;\n if (parse_uint32(&iter, &p) < 0)\n goto fail;\n if (parse_uint32(&key_len, &p) < 0)\n goto fail;\n if (key_len > FS_CMD_REPLY_LEN_MAX ||\n key_len == 0)\n goto fail;\n req = mallocz(sizeof(*req));\n req->type = FS_CMD_PBKDF2;\n req->reply_len = key_len;\n pbkdf2_hmac_sha256(pwd, pwd_len, salt, salt_len, iter, key_len,\n req->reply_buf);\n f->req = req;\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_set_import_dir(FSDevice *fs, FSFile *f, const char *p)\n{\n FSDeviceMem *fs1 = (FSDeviceMem *)fs;\n char filename[1024];\n\n if (parse_fname(filename, sizeof(filename), &p) < 0)\n return -P9_EINVAL;\n free(fs1->import_dir);\n fs1->import_dir = strdup(filename);\n return 0;\n}\n\nstatic int fs_cmd_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int buf_len)\n{\n char *buf1;\n const char *p;\n char cmd[64];\n int err;\n \n /* transform into a string */\n buf1 = malloc(buf_len + 1);\n memcpy(buf1, buf, buf_len);\n buf1[buf_len] = '\\0';\n \n err = 0;\n p = buf1;\n if (parse_fname(cmd, sizeof(cmd), &p) < 0)\n goto fail;\n if (!strcmp(cmd, \"xhr\")) {\n err = fs_cmd_xhr(fs, f, p, f->uid, 0);\n } else if (!strcmp(cmd, \"set_base_url\")) {\n err = fs_cmd_set_base_url(fs, p);\n } else if (!strcmp(cmd, \"reset_base_url\")) {\n err = fs_cmd_reset_base_url(fs, p);\n } else if (!strcmp(cmd, \"set_url\")) {\n err = fs_cmd_set_url(fs, p);\n } else if (!strcmp(cmd, \"export_file\")) {\n err = fs_cmd_export_file(fs, p);\n } else if (!strcmp(cmd, \"pbkdf2\")) {\n err = fs_cmd_pbkdf2(fs, f, p);\n } else if (!strcmp(cmd, \"set_import_dir\")) {\n err = fs_cmd_set_import_dir(fs, f, p);\n } else {\n printf(\"unknown command: '%s'\\n\", cmd);\n fail:\n err = -P9_EIO;\n }\n free(buf1);\n if (err == 0)\n return buf_len;\n else\n return err;\n}\n\nstatic int fs_cmd_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int buf_len)\n{\n FSCMDRequest *req;\n int l;\n \n req = f->req;\n if (!req)\n return -P9_EIO;\n l = min_int(req->reply_len, buf_len);\n memcpy(buf, req->reply_buf, l);\n return l;\n}\n\nstatic void fs_cmd_close(FSDevice *fs, FSFile *f)\n{\n FSCMDRequest *req;\n req = f->req;\n\n if (req) {\n if (req->xhr_state) {\n req->xhr_state->req_fd = NULL;\n }\n free(req);\n f->req = NULL;\n }\n}\n\n/* Create a .fscmd_pwd file to avoid passing the password thru the\n Linux command line */\nvoid fs_net_set_pwd(FSDevice *fs, const char *pwd)\n{\n FSFile *root_fd;\n FSQID qid;\n \n assert(fs_is_net(fs));\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\"));\n assert(!fs->fs_create(fs, &qid, root_fd, \".fscmd_pwd\", P9_O_RDWR | P9_O_TRUNC,\n 0600, 0));\n fs->fs_write(fs, root_fd, 0, (uint8_t *)pwd, strlen(pwd));\n fs->fs_delete(fs, root_fd);\n}\n\n/* external file import */\n\n#ifdef EMSCRIPTEN\n\nvoid fs_import_file(const char *filename, uint8_t *buf, int buf_len)\n{\n FSDevice *fs;\n FSDeviceMem *fs1;\n FSFile *fd, *root_fd;\n FSQID qid;\n \n // printf(\"importing file: %s len=%d\\n\", filename, buf_len);\n fs = fs_import_fs;\n if (!fs) {\n free(buf);\n return;\n }\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 1000, \"\", \"\"));\n fs1 = (FSDeviceMem *)fs;\n fd = fs_walk_path(fs, root_fd, fs1->import_dir);\n if (!fd)\n goto fail;\n fs_unlinkat(fs, root_fd, filename);\n if (fs->fs_create(fs, &qid, fd, filename, P9_O_RDWR | P9_O_TRUNC,\n 0600, 0) < 0)\n goto fail;\n fs->fs_write(fs, fd, 0, buf, buf_len);\n fail:\n if (fd)\n fs->fs_delete(fs, fd);\n if (root_fd)\n fs->fs_delete(fs, root_fd);\n free(buf);\n}\n\n#else\n\nvoid fs_export_file(const char *filename,\n const uint8_t *buf, int buf_len)\n{\n}\n\n#endif\n"], ["/linuxpdf/tinyemu/fs_wget.c", "/*\n * HTTP file download\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n\n#if defined(EMSCRIPTEN)\n#include \n#else\n#include \n#endif\n\n/***********************************************/\n/* HTTP get */\n\n#ifdef EMSCRIPTEN\n\nstruct XHRState {\n void *opaque;\n WGetWriteCallback *cb;\n};\n\nstatic int downloading_count;\n\nvoid fs_wget_init(void)\n{\n}\n\nextern void fs_wget_update_downloading(int flag);\n\nstatic void fs_wget_update_downloading_count(int incr)\n{\n int prev_state, state;\n prev_state = (downloading_count > 0);\n downloading_count += incr;\n state = (downloading_count > 0);\n if (prev_state != state)\n fs_wget_update_downloading(state);\n}\n\nstatic void fs_wget_onerror(unsigned int handle, void *opaque, int status,\n const char *status_text)\n{\n XHRState *s = opaque;\n if (status <= 0)\n status = -404; /* HTTP not found error */\n else\n status = -status;\n fs_wget_update_downloading_count(-1);\n if (s->cb)\n s->cb(s->opaque, status, NULL, 0);\n}\n\nstatic void fs_wget_onload(unsigned int handle,\n void *opaque, void *data, unsigned int size)\n{\n XHRState *s = opaque;\n fs_wget_update_downloading_count(-1);\n if (s->cb)\n s->cb(s->opaque, 0, data, size);\n}\n\nextern int emscripten_async_wget3_data(const char* url, const char* requesttype, const char *user, const char *password, const uint8_t *post_data, int post_data_len, void *arg, int free, em_async_wget2_data_onload_func onload, em_async_wget2_data_onerror_func onerror, em_async_wget2_data_onprogress_func onprogress);\n\nXHRState *fs_wget2(const char *url, const char *user, const char *password,\n WGetReadCallback *read_cb, uint64_t post_data_len,\n void *opaque, WGetWriteCallback *cb, BOOL single_write)\n{\n XHRState *s;\n const char *request;\n uint8_t *post_data;\n \n s = mallocz(sizeof(*s));\n s->opaque = opaque;\n s->cb = cb;\n\n if (post_data_len != 0) {\n request = \"POST\";\n post_data = malloc(post_data_len);\n read_cb(opaque, post_data, post_data_len);\n } else {\n request = \"GET\";\n post_data = NULL;\n }\n fs_wget_update_downloading_count(1);\n\n emscripten_async_wget3_data(url, request, user, password,\n post_data, post_data_len, s, 1, fs_wget_onload,\n fs_wget_onerror, NULL);\n if (post_data_len != 0)\n free(post_data);\n return s;\n}\n\nvoid fs_wget_free(XHRState *s)\n{\n s->cb = NULL;\n s->opaque = NULL;\n}\n\n#else\n\nstruct XHRState {\n struct list_head link;\n CURL *eh;\n void *opaque;\n WGetWriteCallback *write_cb;\n WGetReadCallback *read_cb;\n\n BOOL single_write;\n DynBuf dbuf; /* used if single_write */\n};\n\ntypedef struct {\n struct list_head link;\n int64_t timeout;\n void (*cb)(void *opaque);\n void *opaque;\n} AsyncCallState;\n\nstatic CURLM *curl_multi_ctx;\nstatic struct list_head xhr_list; /* list of XHRState.link */\n\nvoid fs_wget_init(void)\n{\n if (curl_multi_ctx)\n return;\n curl_global_init(CURL_GLOBAL_ALL);\n curl_multi_ctx = curl_multi_init();\n init_list_head(&xhr_list);\n}\n\nvoid fs_wget_end(void)\n{\n curl_multi_cleanup(curl_multi_ctx);\n curl_global_cleanup();\n}\n\nstatic size_t fs_wget_write_cb(char *ptr, size_t size, size_t nmemb,\n void *userdata)\n{\n XHRState *s = userdata;\n size *= nmemb;\n\n if (s->single_write) {\n dbuf_write(&s->dbuf, s->dbuf.size, (void *)ptr, size);\n } else {\n s->write_cb(s->opaque, 1, ptr, size);\n }\n return size;\n}\n\nstatic size_t fs_wget_read_cb(char *ptr, size_t size, size_t nmemb,\n void *userdata)\n{\n XHRState *s = userdata;\n size *= nmemb;\n return s->read_cb(s->opaque, ptr, size);\n}\n\nXHRState *fs_wget2(const char *url, const char *user, const char *password,\n WGetReadCallback *read_cb, uint64_t post_data_len,\n void *opaque, WGetWriteCallback *write_cb, BOOL single_write)\n{\n XHRState *s;\n s = mallocz(sizeof(*s));\n s->eh = curl_easy_init();\n s->opaque = opaque;\n s->write_cb = write_cb;\n s->read_cb = read_cb;\n s->single_write = single_write;\n dbuf_init(&s->dbuf);\n \n curl_easy_setopt(s->eh, CURLOPT_PRIVATE, s);\n curl_easy_setopt(s->eh, CURLOPT_WRITEDATA, s);\n curl_easy_setopt(s->eh, CURLOPT_WRITEFUNCTION, fs_wget_write_cb);\n curl_easy_setopt(s->eh, CURLOPT_HEADER, 0);\n curl_easy_setopt(s->eh, CURLOPT_URL, url);\n curl_easy_setopt(s->eh, CURLOPT_VERBOSE, 0L);\n curl_easy_setopt(s->eh, CURLOPT_ACCEPT_ENCODING, \"\");\n if (user) {\n curl_easy_setopt(s->eh, CURLOPT_USERNAME, user);\n curl_easy_setopt(s->eh, CURLOPT_PASSWORD, password);\n }\n if (post_data_len != 0) {\n struct curl_slist *headers = NULL;\n headers = curl_slist_append(headers,\n \"Content-Type: application/octet-stream\");\n curl_easy_setopt(s->eh, CURLOPT_HTTPHEADER, headers);\n curl_easy_setopt(s->eh, CURLOPT_POST, 1L);\n curl_easy_setopt(s->eh, CURLOPT_POSTFIELDSIZE_LARGE,\n (curl_off_t)post_data_len);\n curl_easy_setopt(s->eh, CURLOPT_READDATA, s);\n curl_easy_setopt(s->eh, CURLOPT_READFUNCTION, fs_wget_read_cb);\n }\n curl_multi_add_handle(curl_multi_ctx, s->eh);\n list_add_tail(&s->link, &xhr_list);\n return s;\n}\n\nvoid fs_wget_free(XHRState *s)\n{\n dbuf_free(&s->dbuf);\n curl_easy_cleanup(s->eh);\n list_del(&s->link);\n free(s);\n}\n\n/* timeout is in ms */\nvoid fs_net_set_fdset(int *pfd_max, fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *ptimeout)\n{\n long timeout;\n int n, fd_max;\n CURLMsg *msg;\n \n if (!curl_multi_ctx)\n return;\n \n curl_multi_perform(curl_multi_ctx, &n);\n\n for(;;) {\n msg = curl_multi_info_read(curl_multi_ctx, &n);\n if (!msg)\n break;\n if (msg->msg == CURLMSG_DONE) {\n XHRState *s;\n long http_code;\n\n curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char **)&s);\n curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE,\n &http_code);\n /* signal the end of the transfer or error */\n if (http_code == 200) {\n if (s->single_write) {\n s->write_cb(s->opaque, 0, s->dbuf.buf, s->dbuf.size);\n } else {\n s->write_cb(s->opaque, 0, NULL, 0);\n }\n } else {\n s->write_cb(s->opaque, -http_code, NULL, 0);\n }\n curl_multi_remove_handle(curl_multi_ctx, s->eh);\n curl_easy_cleanup(s->eh);\n dbuf_free(&s->dbuf);\n list_del(&s->link);\n free(s);\n }\n }\n\n curl_multi_fdset(curl_multi_ctx, rfds, wfds, efds, &fd_max);\n *pfd_max = max_int(*pfd_max, fd_max);\n curl_multi_timeout(curl_multi_ctx, &timeout);\n if (timeout >= 0)\n *ptimeout = min_int(*ptimeout, timeout);\n}\n\nvoid fs_net_event_loop(FSNetEventLoopCompletionFunc *cb, void *opaque)\n{\n fd_set rfds, wfds, efds;\n int timeout, fd_max;\n struct timeval tv;\n \n if (!curl_multi_ctx)\n return;\n\n for(;;) {\n fd_max = -1;\n FD_ZERO(&rfds);\n FD_ZERO(&wfds);\n FD_ZERO(&efds);\n timeout = 10000;\n fs_net_set_fdset(&fd_max, &rfds, &wfds, &efds, &timeout);\n if (cb) {\n if (cb(opaque))\n break;\n } else {\n if (list_empty(&xhr_list))\n break;\n }\n tv.tv_sec = timeout / 1000;\n tv.tv_usec = (timeout % 1000) * 1000;\n select(fd_max + 1, &rfds, &wfds, &efds, &tv);\n }\n}\n\n#endif /* !EMSCRIPTEN */\n\nXHRState *fs_wget(const char *url, const char *user, const char *password,\n void *opaque, WGetWriteCallback *cb, BOOL single_write)\n{\n return fs_wget2(url, user, password, NULL, 0, opaque, cb, single_write);\n}\n\n/***********************************************/\n/* file decryption */\n\n#define ENCRYPTED_FILE_HEADER_SIZE (4 + AES_BLOCK_SIZE)\n\n#define DEC_BUF_SIZE (256 * AES_BLOCK_SIZE)\n\nstruct DecryptFileState {\n DecryptFileCB *write_cb;\n void *opaque;\n int dec_state;\n int dec_buf_pos;\n AES_KEY *aes_state;\n uint8_t iv[AES_BLOCK_SIZE];\n uint8_t dec_buf[DEC_BUF_SIZE];\n};\n\nDecryptFileState *decrypt_file_init(AES_KEY *aes_state,\n DecryptFileCB *write_cb,\n void *opaque)\n{\n DecryptFileState *s;\n s = mallocz(sizeof(*s));\n s->write_cb = write_cb;\n s->opaque = opaque;\n s->aes_state = aes_state;\n return s;\n}\n \nint decrypt_file(DecryptFileState *s, const uint8_t *data,\n size_t size)\n{\n int l, len, ret;\n\n while (size != 0) {\n switch(s->dec_state) {\n case 0:\n l = min_int(size, ENCRYPTED_FILE_HEADER_SIZE - s->dec_buf_pos);\n memcpy(s->dec_buf + s->dec_buf_pos, data, l);\n s->dec_buf_pos += l;\n if (s->dec_buf_pos >= ENCRYPTED_FILE_HEADER_SIZE) {\n if (memcmp(s->dec_buf, encrypted_file_magic, 4) != 0)\n return -1;\n memcpy(s->iv, s->dec_buf + 4, AES_BLOCK_SIZE);\n s->dec_state = 1;\n s->dec_buf_pos = 0;\n }\n break;\n case 1:\n l = min_int(size, DEC_BUF_SIZE - s->dec_buf_pos);\n memcpy(s->dec_buf + s->dec_buf_pos, data, l);\n s->dec_buf_pos += l;\n if (s->dec_buf_pos >= DEC_BUF_SIZE) {\n /* keep one block in case it is the padding */\n len = s->dec_buf_pos - AES_BLOCK_SIZE;\n AES_cbc_encrypt(s->dec_buf, s->dec_buf, len,\n s->aes_state, s->iv, FALSE);\n ret = s->write_cb(s->opaque, s->dec_buf, len);\n if (ret < 0)\n return ret;\n memcpy(s->dec_buf, s->dec_buf + s->dec_buf_pos - AES_BLOCK_SIZE,\n AES_BLOCK_SIZE);\n s->dec_buf_pos = AES_BLOCK_SIZE;\n }\n break;\n default:\n abort();\n }\n data += l;\n size -= l;\n }\n return 0;\n}\n\n/* write last blocks */\nint decrypt_file_flush(DecryptFileState *s)\n{\n int len, pad_len, ret;\n\n if (s->dec_state != 1)\n return -1;\n len = s->dec_buf_pos;\n if (len == 0 || \n (len % AES_BLOCK_SIZE) != 0)\n return -1;\n AES_cbc_encrypt(s->dec_buf, s->dec_buf, len,\n s->aes_state, s->iv, FALSE);\n pad_len = s->dec_buf[s->dec_buf_pos - 1];\n if (pad_len < 1 || pad_len > AES_BLOCK_SIZE)\n return -1;\n len -= pad_len;\n if (len != 0) {\n ret = s->write_cb(s->opaque, s->dec_buf, len);\n if (ret < 0)\n return ret;\n }\n return 0;\n}\n\nvoid decrypt_file_end(DecryptFileState *s)\n{\n free(s);\n}\n\n/* XHR file */\n\ntypedef struct {\n FSDevice *fs;\n FSFile *f;\n int64_t pos;\n FSWGetFileCB *cb;\n void *opaque;\n FSFile *posted_file;\n int64_t read_pos;\n DecryptFileState *dec_state;\n} FSWGetFileState;\n\nstatic int fs_wget_file_write_cb(void *opaque, const uint8_t *data,\n size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n\n ret = fs->fs_write(fs, s->f, s->pos, data, size);\n if (ret < 0)\n return ret;\n s->pos += ret;\n return ret;\n}\n\nstatic void fs_wget_file_on_load(void *opaque, int err, void *data, size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n int64_t ret_size;\n \n // printf(\"err=%d size=%ld\\n\", err, size);\n if (err < 0) {\n ret_size = err;\n goto done;\n } else {\n if (s->dec_state) {\n ret = decrypt_file(s->dec_state, data, size);\n if (ret >= 0 && err == 0) {\n /* handle the end of file */\n decrypt_file_flush(s->dec_state);\n }\n } else {\n ret = fs_wget_file_write_cb(s, data, size);\n }\n if (ret < 0) {\n ret_size = ret;\n goto done;\n } else if (err == 0) {\n /* end of transfer */\n ret_size = s->pos;\n done:\n s->cb(fs, s->f, ret_size, s->opaque);\n if (s->dec_state)\n decrypt_file_end(s->dec_state);\n free(s);\n }\n }\n}\n\nstatic size_t fs_wget_file_read_cb(void *opaque, void *data, size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n \n if (!s->posted_file)\n return 0;\n ret = fs->fs_read(fs, s->posted_file, s->read_pos, data, size);\n if (ret < 0)\n return 0;\n s->read_pos += ret;\n return ret;\n}\n\nvoid fs_wget_file2(FSDevice *fs, FSFile *f, const char *url,\n const char *user, const char *password,\n FSFile *posted_file, uint64_t post_data_len,\n FSWGetFileCB *cb, void *opaque,\n AES_KEY *aes_state)\n{\n FSWGetFileState *s;\n s = mallocz(sizeof(*s));\n s->fs = fs;\n s->f = f;\n s->pos = 0;\n s->cb = cb;\n s->opaque = opaque;\n s->posted_file = posted_file;\n s->read_pos = 0;\n if (aes_state) {\n s->dec_state = decrypt_file_init(aes_state, fs_wget_file_write_cb, s);\n }\n \n fs_wget2(url, user, password, fs_wget_file_read_cb, post_data_len,\n s, fs_wget_file_on_load, FALSE);\n}\n\n/***********************************************/\n/* PBKDF2 */\n\n#ifdef USE_BUILTIN_CRYPTO\n\n#define HMAC_BLOCK_SIZE 64\n\ntypedef struct {\n SHA256_CTX ctx;\n uint8_t K[HMAC_BLOCK_SIZE + SHA256_DIGEST_LENGTH];\n} HMAC_SHA256_CTX;\n\nvoid hmac_sha256_init(HMAC_SHA256_CTX *s, const uint8_t *key, int key_len)\n{\n int i, l;\n \n if (key_len > HMAC_BLOCK_SIZE) {\n SHA256(key, key_len, s->K);\n l = SHA256_DIGEST_LENGTH;\n } else {\n memcpy(s->K, key, key_len);\n l = key_len;\n }\n memset(s->K + l, 0, HMAC_BLOCK_SIZE - l);\n for(i = 0; i < HMAC_BLOCK_SIZE; i++)\n s->K[i] ^= 0x36;\n SHA256_Init(&s->ctx);\n SHA256_Update(&s->ctx, s->K, HMAC_BLOCK_SIZE);\n}\n\nvoid hmac_sha256_update(HMAC_SHA256_CTX *s, const uint8_t *buf, int len)\n{\n SHA256_Update(&s->ctx, buf, len);\n}\n\n/* out has a length of SHA256_DIGEST_LENGTH */\nvoid hmac_sha256_final(HMAC_SHA256_CTX *s, uint8_t *out)\n{\n int i;\n \n SHA256_Final(s->K + HMAC_BLOCK_SIZE, &s->ctx);\n for(i = 0; i < HMAC_BLOCK_SIZE; i++)\n s->K[i] ^= (0x36 ^ 0x5c);\n SHA256(s->K, HMAC_BLOCK_SIZE + SHA256_DIGEST_LENGTH, out);\n}\n\n#define SALT_LEN_MAX 32\n\nvoid pbkdf2_hmac_sha256(const uint8_t *pwd, int pwd_len,\n const uint8_t *salt, int salt_len,\n int iter, int key_len, uint8_t *out)\n{\n uint8_t F[SHA256_DIGEST_LENGTH], U[SALT_LEN_MAX + 4];\n HMAC_SHA256_CTX ctx;\n int it, U_len, j, l;\n uint32_t i;\n \n assert(salt_len <= SALT_LEN_MAX);\n i = 1;\n while (key_len > 0) {\n memset(F, 0, SHA256_DIGEST_LENGTH);\n memcpy(U, salt, salt_len);\n U[salt_len] = i >> 24;\n U[salt_len + 1] = i >> 16;\n U[salt_len + 2] = i >> 8;\n U[salt_len + 3] = i;\n U_len = salt_len + 4;\n for(it = 0; it < iter; it++) {\n hmac_sha256_init(&ctx, pwd, pwd_len);\n hmac_sha256_update(&ctx, U, U_len);\n hmac_sha256_final(&ctx, U);\n for(j = 0; j < SHA256_DIGEST_LENGTH; j++)\n F[j] ^= U[j];\n U_len = SHA256_DIGEST_LENGTH;\n }\n l = min_int(key_len, SHA256_DIGEST_LENGTH);\n memcpy(out, F, l);\n out += l;\n key_len -= l;\n i++;\n }\n}\n\n#else\n\nvoid pbkdf2_hmac_sha256(const uint8_t *pwd, int pwd_len,\n const uint8_t *salt, int salt_len,\n int iter, int key_len, uint8_t *out)\n{\n PKCS5_PBKDF2_HMAC((const char *)pwd, pwd_len, salt, salt_len,\n iter, EVP_sha256(), key_len, out);\n}\n\n#endif /* !USE_BUILTIN_CRYPTO */\n"], ["/linuxpdf/tinyemu/slirp/slirp.c", "/*\n * libslirp glue\n *\n * Copyright (c) 2004-2008 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"slirp.h\"\n\n/* host loopback address */\nstruct in_addr loopback_addr;\n\n/* emulated hosts use the MAC addr 52:55:IP:IP:IP:IP */\nstatic const uint8_t special_ethaddr[6] = {\n 0x52, 0x55, 0x00, 0x00, 0x00, 0x00\n};\n\nstatic const uint8_t zero_ethaddr[6] = { 0, 0, 0, 0, 0, 0 };\n\n/* XXX: suppress those select globals */\nfd_set *global_readfds, *global_writefds, *global_xfds;\n\nu_int curtime;\nstatic u_int time_fasttimo, last_slowtimo;\nstatic int do_slowtimo;\n\nstatic struct in_addr dns_addr;\nstatic u_int dns_addr_time;\n\n#ifdef _WIN32\n\nint get_dns_addr(struct in_addr *pdns_addr)\n{\n FIXED_INFO *FixedInfo=NULL;\n ULONG BufLen;\n DWORD ret;\n IP_ADDR_STRING *pIPAddr;\n struct in_addr tmp_addr;\n\n if (dns_addr.s_addr != 0 && (curtime - dns_addr_time) < 1000) {\n *pdns_addr = dns_addr;\n return 0;\n }\n\n FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));\n BufLen = sizeof(FIXED_INFO);\n\n if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen)) {\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n FixedInfo = GlobalAlloc(GPTR, BufLen);\n }\n\n if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS) {\n printf(\"GetNetworkParams failed. ret = %08x\\n\", (u_int)ret );\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n return -1;\n }\n\n pIPAddr = &(FixedInfo->DnsServerList);\n inet_aton(pIPAddr->IpAddress.String, &tmp_addr);\n *pdns_addr = tmp_addr;\n dns_addr = tmp_addr;\n dns_addr_time = curtime;\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n return 0;\n}\n\nstatic void winsock_cleanup(void)\n{\n WSACleanup();\n}\n\n#else\n\nstatic struct stat dns_addr_stat;\n\nint get_dns_addr(struct in_addr *pdns_addr)\n{\n char buff[512];\n char buff2[257];\n FILE *f;\n int found = 0;\n struct in_addr tmp_addr;\n\n if (dns_addr.s_addr != 0) {\n struct stat old_stat;\n if ((curtime - dns_addr_time) < 1000) {\n *pdns_addr = dns_addr;\n return 0;\n }\n old_stat = dns_addr_stat;\n if (stat(\"/etc/resolv.conf\", &dns_addr_stat) != 0)\n return -1;\n if ((dns_addr_stat.st_dev == old_stat.st_dev)\n && (dns_addr_stat.st_ino == old_stat.st_ino)\n && (dns_addr_stat.st_size == old_stat.st_size)\n && (dns_addr_stat.st_mtime == old_stat.st_mtime)) {\n *pdns_addr = dns_addr;\n return 0;\n }\n }\n\n f = fopen(\"/etc/resolv.conf\", \"r\");\n if (!f)\n return -1;\n\n#ifdef DEBUG\n lprint(\"IP address of your DNS(s): \");\n#endif\n while (fgets(buff, 512, f) != NULL) {\n if (sscanf(buff, \"nameserver%*[ \\t]%256s\", buff2) == 1) {\n if (!inet_aton(buff2, &tmp_addr))\n continue;\n /* If it's the first one, set it to dns_addr */\n if (!found) {\n *pdns_addr = tmp_addr;\n dns_addr = tmp_addr;\n dns_addr_time = curtime;\n }\n#ifdef DEBUG\n else\n lprint(\", \");\n#endif\n if (++found > 3) {\n#ifdef DEBUG\n lprint(\"(more)\");\n#endif\n break;\n }\n#ifdef DEBUG\n else\n lprint(\"%s\", inet_ntoa(tmp_addr));\n#endif\n }\n }\n fclose(f);\n if (!found)\n return -1;\n return 0;\n}\n\n#endif\n\nstatic void slirp_init_once(void)\n{\n static int initialized;\n#ifdef _WIN32\n WSADATA Data;\n#endif\n\n if (initialized) {\n return;\n }\n initialized = 1;\n\n#ifdef _WIN32\n WSAStartup(MAKEWORD(2,0), &Data);\n atexit(winsock_cleanup);\n#endif\n\n loopback_addr.s_addr = htonl(INADDR_LOOPBACK);\n}\n\nSlirp *slirp_init(int restricted, struct in_addr vnetwork,\n struct in_addr vnetmask, struct in_addr vhost,\n const char *vhostname, const char *tftp_path,\n const char *bootfile, struct in_addr vdhcp_start,\n struct in_addr vnameserver, void *opaque)\n{\n Slirp *slirp = mallocz(sizeof(Slirp));\n\n slirp_init_once();\n\n slirp->restricted = restricted;\n\n if_init(slirp);\n ip_init(slirp);\n\n /* Initialise mbufs *after* setting the MTU */\n m_init(slirp);\n\n slirp->vnetwork_addr = vnetwork;\n slirp->vnetwork_mask = vnetmask;\n slirp->vhost_addr = vhost;\n if (vhostname) {\n pstrcpy(slirp->client_hostname, sizeof(slirp->client_hostname),\n vhostname);\n }\n if (tftp_path) {\n slirp->tftp_prefix = strdup(tftp_path);\n }\n if (bootfile) {\n slirp->bootp_filename = strdup(bootfile);\n }\n slirp->vdhcp_startaddr = vdhcp_start;\n slirp->vnameserver_addr = vnameserver;\n\n slirp->opaque = opaque;\n\n return slirp;\n}\n\nvoid slirp_cleanup(Slirp *slirp)\n{\n free(slirp->tftp_prefix);\n free(slirp->bootp_filename);\n free(slirp);\n}\n\n#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)\n#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)\n#define UPD_NFDS(x) if (nfds < (x)) nfds = (x)\n\nvoid slirp_select_fill(Slirp *slirp, int *pnfds,\n fd_set *readfds, fd_set *writefds, fd_set *xfds)\n{\n struct socket *so, *so_next;\n int nfds;\n\n /* fail safe */\n global_readfds = NULL;\n global_writefds = NULL;\n global_xfds = NULL;\n\n nfds = *pnfds;\n\t/*\n\t * First, TCP sockets\n\t */\n\tdo_slowtimo = 0;\n\n\t{\n\t\t/*\n\t\t * *_slowtimo needs calling if there are IP fragments\n\t\t * in the fragment queue, or there are TCP connections active\n\t\t */\n\t\tdo_slowtimo |= ((slirp->tcb.so_next != &slirp->tcb) ||\n\t\t (&slirp->ipq.ip_link != slirp->ipq.ip_link.next));\n\n\t\tfor (so = slirp->tcb.so_next; so != &slirp->tcb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * See if we need a tcp_fasttimo\n\t\t\t */\n\t\t\tif (time_fasttimo == 0 && so->so_tcpcb->t_flags & TF_DELACK)\n\t\t\t time_fasttimo = curtime; /* Flag when we want a fasttimo */\n\n\t\t\t/*\n\t\t\t * NOFDREF can include still connecting to local-host,\n\t\t\t * newly socreated() sockets etc. Don't want to select these.\n\t \t\t */\n\t\t\tif (so->so_state & SS_NOFDREF || so->s == -1)\n\t\t\t continue;\n\n\t\t\t/*\n\t\t\t * Set for reading sockets which are accepting\n\t\t\t */\n\t\t\tif (so->so_state & SS_FACCEPTCONN) {\n FD_SET(so->s, readfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for writing sockets which are connecting\n\t\t\t */\n\t\t\tif (so->so_state & SS_ISFCONNECTING) {\n\t\t\t\tFD_SET(so->s, writefds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for writing if we are connected, can send more, and\n\t\t\t * we have something to send\n\t\t\t */\n\t\t\tif (CONN_CANFSEND(so) && so->so_rcv.sb_cc) {\n\t\t\t\tFD_SET(so->s, writefds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for reading (and urgent data) if we are connected, can\n\t\t\t * receive more, and we have room for it XXX /2 ?\n\t\t\t */\n\t\t\tif (CONN_CANFRCV(so) && (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2))) {\n\t\t\t\tFD_SET(so->s, readfds);\n\t\t\t\tFD_SET(so->s, xfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * UDP sockets\n\t\t */\n\t\tfor (so = slirp->udb.so_next; so != &slirp->udb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * See if it's timed out\n\t\t\t */\n\t\t\tif (so->so_expire) {\n\t\t\t\tif (so->so_expire <= curtime) {\n\t\t\t\t\tudp_detach(so);\n\t\t\t\t\tcontinue;\n\t\t\t\t} else\n\t\t\t\t\tdo_slowtimo = 1; /* Let socket expire */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * When UDP packets are received from over the\n\t\t\t * link, they're sendto()'d straight away, so\n\t\t\t * no need for setting for writing\n\t\t\t * Limit the number of packets queued by this session\n\t\t\t * to 4. Note that even though we try and limit this\n\t\t\t * to 4 packets, the session could have more queued\n\t\t\t * if the packets needed to be fragmented\n\t\t\t * (XXX <= 4 ?)\n\t\t\t */\n\t\t\tif ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4) {\n\t\t\t\tFD_SET(so->s, readfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\t\t}\n\t}\n\n *pnfds = nfds;\n}\n\nvoid slirp_select_poll(Slirp *slirp,\n fd_set *readfds, fd_set *writefds, fd_set *xfds,\n int select_error)\n{\n struct socket *so, *so_next;\n int ret;\n\n global_readfds = readfds;\n global_writefds = writefds;\n global_xfds = xfds;\n\n curtime = os_get_time_ms();\n\n {\n\t/*\n\t * See if anything has timed out\n\t */\n\t\tif (time_fasttimo && ((curtime - time_fasttimo) >= 2)) {\n\t\t\ttcp_fasttimo(slirp);\n\t\t\ttime_fasttimo = 0;\n\t\t}\n\t\tif (do_slowtimo && ((curtime - last_slowtimo) >= 499)) {\n\t\t\tip_slowtimo(slirp);\n\t\t\ttcp_slowtimo(slirp);\n\t\t\tlast_slowtimo = curtime;\n\t\t}\n\n\t/*\n\t * Check sockets\n\t */\n\tif (!select_error) {\n\t\t/*\n\t\t * Check TCP sockets\n\t\t */\n\t\tfor (so = slirp->tcb.so_next; so != &slirp->tcb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * FD_ISSET is meaningless on these sockets\n\t\t\t * (and they can crash the program)\n\t\t\t */\n\t\t\tif (so->so_state & SS_NOFDREF || so->s == -1)\n\t\t\t continue;\n\n\t\t\t/*\n\t\t\t * Check for URG data\n\t\t\t * This will soread as well, so no need to\n\t\t\t * test for readfds below if this succeeds\n\t\t\t */\n\t\t\tif (FD_ISSET(so->s, xfds))\n\t\t\t sorecvoob(so);\n\t\t\t/*\n\t\t\t * Check sockets for reading\n\t\t\t */\n\t\t\telse if (FD_ISSET(so->s, readfds)) {\n\t\t\t\t/*\n\t\t\t\t * Check for incoming connections\n\t\t\t\t */\n\t\t\t\tif (so->so_state & SS_FACCEPTCONN) {\n\t\t\t\t\ttcp_connect(so);\n\t\t\t\t\tcontinue;\n\t\t\t\t} /* else */\n\t\t\t\tret = soread(so);\n\n\t\t\t\t/* Output it if we read something */\n\t\t\t\tif (ret > 0)\n\t\t\t\t tcp_output(sototcpcb(so));\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Check sockets for writing\n\t\t\t */\n\t\t\tif (FD_ISSET(so->s, writefds)) {\n\t\t\t /*\n\t\t\t * Check for non-blocking, still-connecting sockets\n\t\t\t */\n\t\t\t if (so->so_state & SS_ISFCONNECTING) {\n\t\t\t /* Connected */\n\t\t\t so->so_state &= ~SS_ISFCONNECTING;\n\n\t\t\t ret = send(so->s, (const void *) &ret, 0, 0);\n\t\t\t if (ret < 0) {\n\t\t\t /* XXXXX Must fix, zero bytes is a NOP */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\t errno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t\tcontinue;\n\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\t\t\t }\n\t\t\t /* else so->so_state &= ~SS_ISFCONNECTING; */\n\n\t\t\t /*\n\t\t\t * Continue tcp_input\n\t\t\t */\n\t\t\t tcp_input((struct mbuf *)NULL, sizeof(struct ip), so);\n\t\t\t /* continue; */\n\t\t\t } else\n\t\t\t ret = sowrite(so);\n\t\t\t /*\n\t\t\t * XXXXX If we wrote something (a lot), there\n\t\t\t * could be a need for a window update.\n\t\t\t * In the worst case, the remote will send\n\t\t\t * a window probe to get things going again\n\t\t\t */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Probe a still-connecting, non-blocking socket\n\t\t\t * to check if it's still alive\n\t \t \t */\n#ifdef PROBE_CONN\n\t\t\tif (so->so_state & SS_ISFCONNECTING) {\n\t\t\t ret = recv(so->s, (char *)&ret, 0,0);\n\n\t\t\t if (ret < 0) {\n\t\t\t /* XXX */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\terrno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t continue; /* Still connecting, continue */\n\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\n\t\t\t /* tcp_input will take care of it */\n\t\t\t } else {\n\t\t\t ret = send(so->s, &ret, 0,0);\n\t\t\t if (ret < 0) {\n\t\t\t /* XXX */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\t errno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t\tcontinue;\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\t\t\t } else\n\t\t\t so->so_state &= ~SS_ISFCONNECTING;\n\n\t\t\t }\n\t\t\t tcp_input((struct mbuf *)NULL, sizeof(struct ip),so);\n\t\t\t} /* SS_ISFCONNECTING */\n#endif\n\t\t}\n\n\t\t/*\n\t\t * Now UDP sockets.\n\t\t * Incoming packets are sent straight away, they're not buffered.\n\t\t * Incoming UDP data isn't buffered either.\n\t\t */\n\t\tfor (so = slirp->udb.so_next; so != &slirp->udb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\tif (so->s != -1 && FD_ISSET(so->s, readfds)) {\n sorecvfrom(so);\n }\n\t\t}\n\t}\n\n\t/*\n\t * See if we can start outputting\n\t */\n\tif (slirp->if_queued) {\n\t if_start(slirp);\n\t}\n }\n\n\t/* clear global file descriptor sets.\n\t * these reside on the stack in vl.c\n\t * so they're unusable if we're not in\n\t * slirp_select_fill or slirp_select_poll.\n\t */\n\t global_readfds = NULL;\n\t global_writefds = NULL;\n\t global_xfds = NULL;\n}\n\n#define ETH_ALEN 6\n#define ETH_HLEN 14\n\n#define ETH_P_IP\t0x0800\t\t/* Internet Protocol packet\t*/\n#define ETH_P_ARP\t0x0806\t\t/* Address Resolution packet\t*/\n\n#define\tARPOP_REQUEST\t1\t\t/* ARP request\t\t\t*/\n#define\tARPOP_REPLY\t2\t\t/* ARP reply\t\t\t*/\n\nstruct ethhdr\n{\n\tunsigned char\th_dest[ETH_ALEN];\t/* destination eth addr\t*/\n\tunsigned char\th_source[ETH_ALEN];\t/* source ether addr\t*/\n\tunsigned short\th_proto;\t\t/* packet type ID field\t*/\n};\n\nstruct arphdr\n{\n\tunsigned short\tar_hrd;\t\t/* format of hardware address\t*/\n\tunsigned short\tar_pro;\t\t/* format of protocol address\t*/\n\tunsigned char\tar_hln;\t\t/* length of hardware address\t*/\n\tunsigned char\tar_pln;\t\t/* length of protocol address\t*/\n\tunsigned short\tar_op;\t\t/* ARP opcode (command)\t\t*/\n\n\t /*\n\t *\t Ethernet looks like this : This bit is variable sized however...\n\t */\n\tunsigned char\t\tar_sha[ETH_ALEN];\t/* sender hardware address\t*/\n\tuint32_t\t\tar_sip;\t\t\t/* sender IP address\t\t*/\n\tunsigned char\t\tar_tha[ETH_ALEN];\t/* target hardware address\t*/\n\tuint32_t\t\tar_tip\t;\t\t/* target IP address\t\t*/\n} __attribute__((packed));\n\nstatic void arp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)\n{\n struct ethhdr *eh = (struct ethhdr *)pkt;\n struct arphdr *ah = (struct arphdr *)(pkt + ETH_HLEN);\n uint8_t arp_reply[max(ETH_HLEN + sizeof(struct arphdr), 64)];\n struct ethhdr *reh = (struct ethhdr *)arp_reply;\n struct arphdr *rah = (struct arphdr *)(arp_reply + ETH_HLEN);\n int ar_op;\n struct ex_list *ex_ptr;\n\n ar_op = ntohs(ah->ar_op);\n switch(ar_op) {\n case ARPOP_REQUEST:\n if ((ah->ar_tip & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n if (ah->ar_tip == slirp->vnameserver_addr.s_addr ||\n ah->ar_tip == slirp->vhost_addr.s_addr)\n goto arp_ok;\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_addr.s_addr == ah->ar_tip)\n goto arp_ok;\n }\n return;\n arp_ok:\n memset(arp_reply, 0, sizeof(arp_reply));\n /* XXX: make an ARP request to have the client address */\n memcpy(slirp->client_ethaddr, eh->h_source, ETH_ALEN);\n\n /* ARP request for alias/dns mac address */\n memcpy(reh->h_dest, pkt + ETH_ALEN, ETH_ALEN);\n memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);\n memcpy(&reh->h_source[2], &ah->ar_tip, 4);\n reh->h_proto = htons(ETH_P_ARP);\n\n rah->ar_hrd = htons(1);\n rah->ar_pro = htons(ETH_P_IP);\n rah->ar_hln = ETH_ALEN;\n rah->ar_pln = 4;\n rah->ar_op = htons(ARPOP_REPLY);\n memcpy(rah->ar_sha, reh->h_source, ETH_ALEN);\n rah->ar_sip = ah->ar_tip;\n memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);\n rah->ar_tip = ah->ar_sip;\n slirp_output(slirp->opaque, arp_reply, sizeof(arp_reply));\n }\n break;\n case ARPOP_REPLY:\n /* reply to request of client mac address ? */\n if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN) &&\n ah->ar_sip == slirp->client_ipaddr.s_addr) {\n memcpy(slirp->client_ethaddr, ah->ar_sha, ETH_ALEN);\n }\n break;\n default:\n break;\n }\n}\n\nvoid slirp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)\n{\n struct mbuf *m;\n int proto;\n\n if (pkt_len < ETH_HLEN)\n return;\n\n proto = ntohs(*(uint16_t *)(pkt + 12));\n switch(proto) {\n case ETH_P_ARP:\n arp_input(slirp, pkt, pkt_len);\n break;\n case ETH_P_IP:\n m = m_get(slirp);\n if (!m)\n return;\n /* Note: we add to align the IP header */\n if (M_FREEROOM(m) < pkt_len + 2) {\n m_inc(m, pkt_len + 2);\n }\n m->m_len = pkt_len + 2;\n memcpy(m->m_data + 2, pkt, pkt_len);\n\n m->m_data += 2 + ETH_HLEN;\n m->m_len -= 2 + ETH_HLEN;\n\n ip_input(m);\n break;\n default:\n break;\n }\n}\n\n/* output the IP packet to the ethernet device */\nvoid if_encap(Slirp *slirp, const uint8_t *ip_data, int ip_data_len)\n{\n uint8_t buf[1600];\n struct ethhdr *eh = (struct ethhdr *)buf;\n\n if (ip_data_len + ETH_HLEN > sizeof(buf))\n return;\n \n if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN)) {\n uint8_t arp_req[ETH_HLEN + sizeof(struct arphdr)];\n struct ethhdr *reh = (struct ethhdr *)arp_req;\n struct arphdr *rah = (struct arphdr *)(arp_req + ETH_HLEN);\n const struct ip *iph = (const struct ip *)ip_data;\n\n /* If the client addr is not known, there is no point in\n sending the packet to it. Normally the sender should have\n done an ARP request to get its MAC address. Here we do it\n in place of sending the packet and we hope that the sender\n will retry sending its packet. */\n memset(reh->h_dest, 0xff, ETH_ALEN);\n memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);\n memcpy(&reh->h_source[2], &slirp->vhost_addr, 4);\n reh->h_proto = htons(ETH_P_ARP);\n rah->ar_hrd = htons(1);\n rah->ar_pro = htons(ETH_P_IP);\n rah->ar_hln = ETH_ALEN;\n rah->ar_pln = 4;\n rah->ar_op = htons(ARPOP_REQUEST);\n /* source hw addr */\n memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN - 4);\n memcpy(&rah->ar_sha[2], &slirp->vhost_addr, 4);\n /* source IP */\n rah->ar_sip = slirp->vhost_addr.s_addr;\n /* target hw addr (none) */\n memset(rah->ar_tha, 0, ETH_ALEN);\n /* target IP */\n rah->ar_tip = iph->ip_dst.s_addr;\n slirp->client_ipaddr = iph->ip_dst;\n slirp_output(slirp->opaque, arp_req, sizeof(arp_req));\n } else {\n memcpy(eh->h_dest, slirp->client_ethaddr, ETH_ALEN);\n memcpy(eh->h_source, special_ethaddr, ETH_ALEN - 4);\n /* XXX: not correct */\n memcpy(&eh->h_source[2], &slirp->vhost_addr, 4);\n eh->h_proto = htons(ETH_P_IP);\n memcpy(buf + sizeof(struct ethhdr), ip_data, ip_data_len);\n slirp_output(slirp->opaque, buf, ip_data_len + ETH_HLEN);\n }\n}\n\n/* Drop host forwarding rule, return 0 if found. */\nint slirp_remove_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,\n int host_port)\n{\n struct socket *so;\n struct socket *head = (is_udp ? &slirp->udb : &slirp->tcb);\n struct sockaddr_in addr;\n int port = htons(host_port);\n socklen_t addr_len;\n\n for (so = head->so_next; so != head; so = so->so_next) {\n addr_len = sizeof(addr);\n if ((so->so_state & SS_HOSTFWD) &&\n getsockname(so->s, (struct sockaddr *)&addr, &addr_len) == 0 &&\n addr.sin_addr.s_addr == host_addr.s_addr &&\n addr.sin_port == port) {\n close(so->s);\n sofree(so);\n return 0;\n }\n }\n\n return -1;\n}\n\nint slirp_add_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,\n int host_port, struct in_addr guest_addr, int guest_port)\n{\n if (!guest_addr.s_addr) {\n guest_addr = slirp->vdhcp_startaddr;\n }\n if (is_udp) {\n if (!udp_listen(slirp, host_addr.s_addr, htons(host_port),\n guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))\n return -1;\n } else {\n if (!tcp_listen(slirp, host_addr.s_addr, htons(host_port),\n guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))\n return -1;\n }\n return 0;\n}\n\nint slirp_add_exec(Slirp *slirp, int do_pty, const void *args,\n struct in_addr *guest_addr, int guest_port)\n{\n if (!guest_addr->s_addr) {\n guest_addr->s_addr = slirp->vnetwork_addr.s_addr |\n (htonl(0x0204) & ~slirp->vnetwork_mask.s_addr);\n }\n if ((guest_addr->s_addr & slirp->vnetwork_mask.s_addr) !=\n slirp->vnetwork_addr.s_addr ||\n guest_addr->s_addr == slirp->vhost_addr.s_addr ||\n guest_addr->s_addr == slirp->vnameserver_addr.s_addr) {\n return -1;\n }\n return add_exec(&slirp->exec_list, do_pty, (char *)args, *guest_addr,\n htons(guest_port));\n}\n\nssize_t slirp_send(struct socket *so, const void *buf, size_t len, int flags)\n{\n#if 0\n if (so->s == -1 && so->extra) {\n\t\tqemu_chr_write(so->extra, buf, len);\n\t\treturn len;\n\t}\n#endif\n\treturn send(so->s, buf, len, flags);\n}\n\nstatic struct socket *\nslirp_find_ctl_socket(Slirp *slirp, struct in_addr guest_addr, int guest_port)\n{\n struct socket *so;\n\n for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {\n if (so->so_faddr.s_addr == guest_addr.s_addr &&\n htons(so->so_fport) == guest_port) {\n return so;\n }\n }\n return NULL;\n}\n\nsize_t slirp_socket_can_recv(Slirp *slirp, struct in_addr guest_addr,\n int guest_port)\n{\n\tstruct iovec iov[2];\n\tstruct socket *so;\n\n\tso = slirp_find_ctl_socket(slirp, guest_addr, guest_port);\n\n\tif (!so || so->so_state & SS_NOFDREF)\n\t\treturn 0;\n\n\tif (!CONN_CANFRCV(so) || so->so_snd.sb_cc >= (so->so_snd.sb_datalen/2))\n\t\treturn 0;\n\n\treturn sopreprbuf(so, iov, NULL);\n}\n\nvoid slirp_socket_recv(Slirp *slirp, struct in_addr guest_addr, int guest_port,\n const uint8_t *buf, int size)\n{\n int ret;\n struct socket *so = slirp_find_ctl_socket(slirp, guest_addr, guest_port);\n\n if (!so)\n return;\n\n ret = soreadbuf(so, (const char *)buf, size);\n\n if (ret > 0)\n tcp_output(sototcpcb(so));\n}\n"], ["/linuxpdf/tinyemu/block_net.c", "/*\n * HTTP block device\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"virtio.h\"\n#include \"fs_wget.h\"\n#include \"list.h\"\n#include \"fbuf.h\"\n#include \"machine.h\"\n\ntypedef enum {\n CBLOCK_LOADING,\n CBLOCK_LOADED,\n} CachedBlockStateEnum;\n\ntypedef struct CachedBlock {\n struct list_head link;\n struct BlockDeviceHTTP *bf;\n unsigned int block_num;\n CachedBlockStateEnum state;\n FileBuffer fbuf;\n} CachedBlock;\n\n#define BLK_FMT \"%sblk%09u.bin\"\n#define GROUP_FMT \"%sgrp%09u.bin\"\n#define PREFETCH_GROUP_LEN_MAX 32\n\ntypedef struct {\n struct BlockDeviceHTTP *bf;\n int group_num;\n int n_block_num;\n CachedBlock *tab_block[PREFETCH_GROUP_LEN_MAX];\n} PrefetchGroupRequest;\n\n/* modified data is stored per cluster (smaller than cached blocks to\n avoid losing space) */\ntypedef struct Cluster {\n FileBuffer fbuf;\n} Cluster;\n\ntypedef struct BlockDeviceHTTP {\n BlockDevice *bs;\n int max_cache_size_kb;\n char url[1024];\n int prefetch_count;\n void (*start_cb)(void *opaque);\n void *start_opaque;\n \n int64_t nb_sectors;\n int block_size; /* in sectors, power of two */\n int nb_blocks;\n struct list_head cached_blocks; /* list of CachedBlock */\n int n_cached_blocks;\n int n_cached_blocks_max;\n\n /* write support */\n int sectors_per_cluster; /* power of two */\n Cluster **clusters; /* NULL if no written data */\n int n_clusters;\n int n_allocated_clusters;\n \n /* statistics */\n int64_t n_read_sectors;\n int64_t n_read_blocks;\n int64_t n_write_sectors;\n\n /* current read request */\n BOOL is_write;\n uint64_t sector_num;\n int cur_block_num;\n int sector_index, sector_count;\n BlockDeviceCompletionFunc *cb;\n void *opaque;\n uint8_t *io_buf;\n\n /* prefetch */\n int prefetch_group_len;\n} BlockDeviceHTTP;\n\nstatic void bf_update_block(CachedBlock *b, const uint8_t *data);\nstatic void bf_read_onload(void *opaque, int err, void *data, size_t size);\nstatic void bf_init_onload(void *opaque, int err, void *data, size_t size);\nstatic void bf_prefetch_group_onload(void *opaque, int err, void *data,\n size_t size);\n\nstatic CachedBlock *bf_find_block(BlockDeviceHTTP *bf, unsigned int block_num)\n{\n CachedBlock *b;\n struct list_head *el;\n \n list_for_each(el, &bf->cached_blocks) {\n b = list_entry(el, CachedBlock, link);\n if (b->block_num == block_num) {\n /* move to front */\n if (bf->cached_blocks.next != el) {\n list_del(&b->link);\n list_add(&b->link, &bf->cached_blocks);\n }\n return b;\n }\n }\n return NULL;\n}\n\nstatic void bf_free_block(BlockDeviceHTTP *bf, CachedBlock *b)\n{\n bf->n_cached_blocks--;\n file_buffer_reset(&b->fbuf);\n list_del(&b->link);\n free(b);\n}\n\nstatic CachedBlock *bf_add_block(BlockDeviceHTTP *bf, unsigned int block_num)\n{\n CachedBlock *b;\n if (bf->n_cached_blocks >= bf->n_cached_blocks_max) {\n struct list_head *el, *el1;\n /* start by looking at the least unused blocks */\n list_for_each_prev_safe(el, el1, &bf->cached_blocks) {\n b = list_entry(el, CachedBlock, link);\n if (b->state == CBLOCK_LOADED) {\n bf_free_block(bf, b);\n if (bf->n_cached_blocks < bf->n_cached_blocks_max)\n break;\n }\n }\n }\n b = mallocz(sizeof(CachedBlock));\n b->bf = bf;\n b->block_num = block_num;\n b->state = CBLOCK_LOADING;\n file_buffer_init(&b->fbuf);\n file_buffer_resize(&b->fbuf, bf->block_size * 512);\n list_add(&b->link, &bf->cached_blocks);\n bf->n_cached_blocks++;\n return b;\n}\n\nstatic int64_t bf_get_sector_count(BlockDevice *bs)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n return bf->nb_sectors;\n}\n\nstatic void bf_start_load_block(BlockDevice *bs, int block_num)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n char filename[1024];\n CachedBlock *b;\n b = bf_add_block(bf, block_num);\n bf->n_read_blocks++;\n /* make a XHR to read the block */\n#if 0\n printf(\"%u,\\n\", block_num);\n#endif\n#if 0\n printf(\"load_blk=%d cached=%d read=%d KB (%d KB) write=%d KB (%d KB)\\n\",\n block_num, bf->n_cached_blocks,\n (int)(bf->n_read_sectors / 2),\n (int)(bf->n_read_blocks * bf->block_size / 2),\n (int)(bf->n_write_sectors / 2),\n (int)(bf->n_allocated_clusters * bf->sectors_per_cluster / 2));\n#endif\n snprintf(filename, sizeof(filename), BLK_FMT, bf->url, block_num);\n // printf(\"wget %s\\n\", filename);\n fs_wget(filename, NULL, NULL, b, bf_read_onload, TRUE);\n}\n\nstatic void bf_start_load_prefetch_group(BlockDevice *bs, int group_num,\n const int *tab_block_num,\n int n_block_num)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n CachedBlock *b;\n PrefetchGroupRequest *req;\n char filename[1024];\n BOOL req_flag;\n int i;\n \n req_flag = FALSE;\n req = malloc(sizeof(*req));\n req->bf = bf;\n req->group_num = group_num;\n req->n_block_num = n_block_num;\n for(i = 0; i < n_block_num; i++) {\n b = bf_find_block(bf, tab_block_num[i]);\n if (!b) {\n b = bf_add_block(bf, tab_block_num[i]);\n req_flag = TRUE;\n } else {\n /* no need to read the block if it is already loading or\n loaded */\n b = NULL;\n }\n req->tab_block[i] = b;\n }\n\n if (req_flag) {\n snprintf(filename, sizeof(filename), GROUP_FMT, bf->url, group_num);\n // printf(\"wget %s\\n\", filename);\n fs_wget(filename, NULL, NULL, req, bf_prefetch_group_onload, TRUE);\n /* XXX: should add request in a list to free it for clean exit */\n } else {\n free(req);\n }\n}\n\nstatic void bf_prefetch_group_onload(void *opaque, int err, void *data,\n size_t size)\n{\n PrefetchGroupRequest *req = opaque;\n BlockDeviceHTTP *bf = req->bf;\n CachedBlock *b;\n int block_bytes, i;\n \n if (err < 0) {\n fprintf(stderr, \"Could not load group %u\\n\", req->group_num);\n exit(1);\n }\n block_bytes = bf->block_size * 512;\n assert(size == block_bytes * req->n_block_num);\n for(i = 0; i < req->n_block_num; i++) {\n b = req->tab_block[i];\n if (b) {\n bf_update_block(b, (const uint8_t *)data + block_bytes * i);\n }\n }\n free(req);\n}\n\nstatic int bf_rw_async1(BlockDevice *bs, BOOL is_sync)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n int offset, block_num, n, cluster_num;\n CachedBlock *b;\n Cluster *c;\n \n for(;;) {\n n = bf->sector_count - bf->sector_index;\n if (n == 0)\n break;\n cluster_num = bf->sector_num / bf->sectors_per_cluster;\n c = bf->clusters[cluster_num];\n if (c) {\n offset = bf->sector_num % bf->sectors_per_cluster;\n n = min_int(n, bf->sectors_per_cluster - offset);\n if (bf->is_write) {\n file_buffer_write(&c->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n } else {\n file_buffer_read(&c->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n }\n bf->sector_index += n;\n bf->sector_num += n;\n } else {\n block_num = bf->sector_num / bf->block_size;\n offset = bf->sector_num % bf->block_size;\n n = min_int(n, bf->block_size - offset);\n bf->cur_block_num = block_num;\n \n b = bf_find_block(bf, block_num);\n if (b) {\n if (b->state == CBLOCK_LOADING) {\n /* wait until the block is loaded */\n return 1;\n } else {\n if (bf->is_write) {\n int cluster_size, cluster_offset;\n uint8_t *buf;\n /* allocate a new cluster */\n c = mallocz(sizeof(Cluster));\n cluster_size = bf->sectors_per_cluster * 512;\n buf = malloc(cluster_size);\n file_buffer_init(&c->fbuf);\n file_buffer_resize(&c->fbuf, cluster_size);\n bf->clusters[cluster_num] = c;\n /* copy the cached block data to the cluster */\n cluster_offset = (cluster_num * bf->sectors_per_cluster) &\n (bf->block_size - 1);\n file_buffer_read(&b->fbuf, cluster_offset * 512,\n buf, cluster_size);\n file_buffer_write(&c->fbuf, 0, buf, cluster_size);\n free(buf);\n bf->n_allocated_clusters++;\n continue; /* write to the allocated cluster */\n } else {\n file_buffer_read(&b->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n }\n bf->sector_index += n;\n bf->sector_num += n;\n }\n } else {\n bf_start_load_block(bs, block_num);\n return 1;\n }\n bf->cur_block_num = -1;\n }\n }\n\n if (!is_sync) {\n // printf(\"end of request\\n\");\n /* end of request */\n bf->cb(bf->opaque, 0);\n } \n return 0;\n}\n\nstatic void bf_update_block(CachedBlock *b, const uint8_t *data)\n{\n BlockDeviceHTTP *bf = b->bf;\n BlockDevice *bs = bf->bs;\n\n assert(b->state == CBLOCK_LOADING);\n file_buffer_write(&b->fbuf, 0, data, bf->block_size * 512);\n b->state = CBLOCK_LOADED;\n \n /* continue I/O read/write if necessary */\n if (b->block_num == bf->cur_block_num) {\n bf_rw_async1(bs, FALSE);\n }\n}\n\nstatic void bf_read_onload(void *opaque, int err, void *data, size_t size)\n{\n CachedBlock *b = opaque;\n BlockDeviceHTTP *bf = b->bf;\n\n if (err < 0) {\n fprintf(stderr, \"Could not load block %u\\n\", b->block_num);\n exit(1);\n }\n \n assert(size == bf->block_size * 512);\n bf_update_block(b, data);\n}\n\nstatic int bf_read_async(BlockDevice *bs,\n uint64_t sector_num, uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n // printf(\"bf_read_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n bf->is_write = FALSE;\n bf->sector_num = sector_num;\n bf->io_buf = buf;\n bf->sector_count = n;\n bf->sector_index = 0;\n bf->cb = cb;\n bf->opaque = opaque;\n bf->n_read_sectors += n;\n return bf_rw_async1(bs, TRUE);\n}\n\nstatic int bf_write_async(BlockDevice *bs,\n uint64_t sector_num, const uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n // printf(\"bf_write_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n bf->is_write = TRUE;\n bf->sector_num = sector_num;\n bf->io_buf = (uint8_t *)buf;\n bf->sector_count = n;\n bf->sector_index = 0;\n bf->cb = cb;\n bf->opaque = opaque;\n bf->n_write_sectors += n;\n return bf_rw_async1(bs, TRUE);\n}\n\nBlockDevice *block_device_init_http(const char *url,\n int max_cache_size_kb,\n void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n BlockDevice *bs;\n BlockDeviceHTTP *bf;\n char *p;\n\n bs = mallocz(sizeof(*bs));\n bf = mallocz(sizeof(*bf));\n strcpy(bf->url, url);\n /* get the path with the trailing '/' */\n p = strrchr(bf->url, '/');\n if (!p)\n p = bf->url;\n else\n p++;\n *p = '\\0';\n\n init_list_head(&bf->cached_blocks);\n bf->max_cache_size_kb = max_cache_size_kb;\n bf->start_cb = start_cb;\n bf->start_opaque = start_opaque;\n bf->bs = bs;\n \n bs->opaque = bf;\n bs->get_sector_count = bf_get_sector_count;\n bs->read_async = bf_read_async;\n bs->write_async = bf_write_async;\n \n fs_wget(url, NULL, NULL, bs, bf_init_onload, TRUE);\n return bs;\n}\n\nstatic void bf_init_onload(void *opaque, int err, void *data, size_t size)\n{\n BlockDevice *bs = opaque;\n BlockDeviceHTTP *bf = bs->opaque;\n int block_size_kb, block_num;\n JSONValue cfg, array;\n \n if (err < 0) {\n fprintf(stderr, \"Could not load block device file (err=%d)\\n\", -err);\n exit(1);\n }\n\n /* parse the disk image info */\n cfg = json_parse_value_len(data, size);\n if (json_is_error(cfg)) {\n vm_error(\"error: %s\\n\", json_get_error(cfg));\n config_error:\n json_free(cfg);\n exit(1);\n }\n\n if (vm_get_int(cfg, \"block_size\", &block_size_kb) < 0)\n goto config_error;\n bf->block_size = block_size_kb * 2;\n if (bf->block_size <= 0 ||\n (bf->block_size & (bf->block_size - 1)) != 0) {\n vm_error(\"invalid block_size\\n\");\n goto config_error;\n }\n if (vm_get_int(cfg, \"n_block\", &bf->nb_blocks) < 0)\n goto config_error;\n if (bf->nb_blocks <= 0) {\n vm_error(\"invalid n_block\\n\");\n goto config_error;\n }\n\n bf->nb_sectors = bf->block_size * (uint64_t)bf->nb_blocks;\n bf->n_cached_blocks = 0;\n bf->n_cached_blocks_max = max_int(1, bf->max_cache_size_kb / block_size_kb);\n bf->cur_block_num = -1; /* no request in progress */\n \n bf->sectors_per_cluster = 8; /* 4 KB */\n bf->n_clusters = (bf->nb_sectors + bf->sectors_per_cluster - 1) / bf->sectors_per_cluster;\n bf->clusters = mallocz(sizeof(bf->clusters[0]) * bf->n_clusters);\n\n if (vm_get_int_opt(cfg, \"prefetch_group_len\",\n &bf->prefetch_group_len, 1) < 0)\n goto config_error;\n if (bf->prefetch_group_len > PREFETCH_GROUP_LEN_MAX) {\n vm_error(\"prefetch_group_len is too large\");\n goto config_error;\n }\n \n array = json_object_get(cfg, \"prefetch\");\n if (!json_is_undefined(array)) {\n int idx, prefetch_len, l, i;\n JSONValue el;\n int tab_block_num[PREFETCH_GROUP_LEN_MAX];\n \n if (array.type != JSON_ARRAY) {\n vm_error(\"expecting an array\\n\");\n goto config_error;\n }\n prefetch_len = array.u.array->len;\n idx = 0;\n while (idx < prefetch_len) {\n l = min_int(prefetch_len - idx, bf->prefetch_group_len);\n for(i = 0; i < l; i++) {\n el = json_array_get(array, idx + i);\n if (el.type != JSON_INT) {\n vm_error(\"expecting an integer\\n\");\n goto config_error;\n }\n tab_block_num[i] = el.u.int32;\n }\n if (l == 1) {\n block_num = tab_block_num[0];\n if (!bf_find_block(bf, block_num)) {\n bf_start_load_block(bs, block_num);\n }\n } else {\n bf_start_load_prefetch_group(bs, idx / bf->prefetch_group_len,\n tab_block_num, l);\n }\n idx += l;\n }\n }\n json_free(cfg);\n \n if (bf->start_cb) {\n bf->start_cb(bf->start_opaque);\n }\n}\n"], ["/linuxpdf/tinyemu/ide.c", "/*\n * IDE emulation\n * \n * Copyright (c) 2003-2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"ide.h\"\n\n//#define DEBUG_IDE\n\n/* Bits of HD_STATUS */\n#define ERR_STAT\t\t0x01\n#define INDEX_STAT\t\t0x02\n#define ECC_STAT\t\t0x04\t/* Corrected error */\n#define DRQ_STAT\t\t0x08\n#define SEEK_STAT\t\t0x10\n#define SRV_STAT\t\t0x10\n#define WRERR_STAT\t\t0x20\n#define READY_STAT\t\t0x40\n#define BUSY_STAT\t\t0x80\n\n/* Bits for HD_ERROR */\n#define MARK_ERR\t\t0x01\t/* Bad address mark */\n#define TRK0_ERR\t\t0x02\t/* couldn't find track 0 */\n#define ABRT_ERR\t\t0x04\t/* Command aborted */\n#define MCR_ERR\t\t\t0x08\t/* media change request */\n#define ID_ERR\t\t\t0x10\t/* ID field not found */\n#define MC_ERR\t\t\t0x20\t/* media changed */\n#define ECC_ERR\t\t\t0x40\t/* Uncorrectable ECC error */\n#define BBD_ERR\t\t\t0x80\t/* pre-EIDE meaning: block marked bad */\n#define ICRC_ERR\t\t0x80\t/* new meaning: CRC error during transfer */\n\n/* Bits of HD_NSECTOR */\n#define CD\t\t\t0x01\n#define IO\t\t\t0x02\n#define REL\t\t\t0x04\n#define TAG_MASK\t\t0xf8\n\n#define IDE_CMD_RESET 0x04\n#define IDE_CMD_DISABLE_IRQ 0x02\n\n/* ATA/ATAPI Commands pre T13 Spec */\n#define WIN_NOP\t\t\t\t0x00\n/*\n *\t0x01->0x02 Reserved\n */\n#define CFA_REQ_EXT_ERROR_CODE\t\t0x03 /* CFA Request Extended Error Code */\n/*\n *\t0x04->0x07 Reserved\n */\n#define WIN_SRST\t\t\t0x08 /* ATAPI soft reset command */\n#define WIN_DEVICE_RESET\t\t0x08\n/*\n *\t0x09->0x0F Reserved\n */\n#define WIN_RECAL\t\t\t0x10\n#define WIN_RESTORE\t\t\tWIN_RECAL\n/*\n *\t0x10->0x1F Reserved\n */\n#define WIN_READ\t\t\t0x20 /* 28-Bit */\n#define WIN_READ_ONCE\t\t\t0x21 /* 28-Bit without retries */\n#define WIN_READ_LONG\t\t\t0x22 /* 28-Bit */\n#define WIN_READ_LONG_ONCE\t\t0x23 /* 28-Bit without retries */\n#define WIN_READ_EXT\t\t\t0x24 /* 48-Bit */\n#define WIN_READDMA_EXT\t\t\t0x25 /* 48-Bit */\n#define WIN_READDMA_QUEUED_EXT\t\t0x26 /* 48-Bit */\n#define WIN_READ_NATIVE_MAX_EXT\t\t0x27 /* 48-Bit */\n/*\n *\t0x28\n */\n#define WIN_MULTREAD_EXT\t\t0x29 /* 48-Bit */\n/*\n *\t0x2A->0x2F Reserved\n */\n#define WIN_WRITE\t\t\t0x30 /* 28-Bit */\n#define WIN_WRITE_ONCE\t\t\t0x31 /* 28-Bit without retries */\n#define WIN_WRITE_LONG\t\t\t0x32 /* 28-Bit */\n#define WIN_WRITE_LONG_ONCE\t\t0x33 /* 28-Bit without retries */\n#define WIN_WRITE_EXT\t\t\t0x34 /* 48-Bit */\n#define WIN_WRITEDMA_EXT\t\t0x35 /* 48-Bit */\n#define WIN_WRITEDMA_QUEUED_EXT\t\t0x36 /* 48-Bit */\n#define WIN_SET_MAX_EXT\t\t\t0x37 /* 48-Bit */\n#define CFA_WRITE_SECT_WO_ERASE\t\t0x38 /* CFA Write Sectors without erase */\n#define WIN_MULTWRITE_EXT\t\t0x39 /* 48-Bit */\n/*\n *\t0x3A->0x3B Reserved\n */\n#define WIN_WRITE_VERIFY\t\t0x3C /* 28-Bit */\n/*\n *\t0x3D->0x3F Reserved\n */\n#define WIN_VERIFY\t\t\t0x40 /* 28-Bit - Read Verify Sectors */\n#define WIN_VERIFY_ONCE\t\t\t0x41 /* 28-Bit - without retries */\n#define WIN_VERIFY_EXT\t\t\t0x42 /* 48-Bit */\n/*\n *\t0x43->0x4F Reserved\n */\n#define WIN_FORMAT\t\t\t0x50\n/*\n *\t0x51->0x5F Reserved\n */\n#define WIN_INIT\t\t\t0x60\n/*\n *\t0x61->0x5F Reserved\n */\n#define WIN_SEEK\t\t\t0x70 /* 0x70-0x7F Reserved */\n#define CFA_TRANSLATE_SECTOR\t\t0x87 /* CFA Translate Sector */\n#define WIN_DIAGNOSE\t\t\t0x90\n#define WIN_SPECIFY\t\t\t0x91 /* set drive geometry translation */\n#define WIN_DOWNLOAD_MICROCODE\t\t0x92\n#define WIN_STANDBYNOW2\t\t\t0x94\n#define WIN_STANDBY2\t\t\t0x96\n#define WIN_SETIDLE2\t\t\t0x97\n#define WIN_CHECKPOWERMODE2\t\t0x98\n#define WIN_SLEEPNOW2\t\t\t0x99\n/*\n *\t0x9A VENDOR\n */\n#define WIN_PACKETCMD\t\t\t0xA0 /* Send a packet command. */\n#define WIN_PIDENTIFY\t\t\t0xA1 /* identify ATAPI device\t*/\n#define WIN_QUEUED_SERVICE\t\t0xA2\n#define WIN_SMART\t\t\t0xB0 /* self-monitoring and reporting */\n#define CFA_ERASE_SECTORS \t0xC0\n#define WIN_MULTREAD\t\t\t0xC4 /* read sectors using multiple mode*/\n#define WIN_MULTWRITE\t\t\t0xC5 /* write sectors using multiple mode */\n#define WIN_SETMULT\t\t\t0xC6 /* enable/disable multiple mode */\n#define WIN_READDMA_QUEUED\t\t0xC7 /* read sectors using Queued DMA transfers */\n#define WIN_READDMA\t\t\t0xC8 /* read sectors using DMA transfers */\n#define WIN_READDMA_ONCE\t\t0xC9 /* 28-Bit - without retries */\n#define WIN_WRITEDMA\t\t\t0xCA /* write sectors using DMA transfers */\n#define WIN_WRITEDMA_ONCE\t\t0xCB /* 28-Bit - without retries */\n#define WIN_WRITEDMA_QUEUED\t\t0xCC /* write sectors using Queued DMA transfers */\n#define CFA_WRITE_MULTI_WO_ERASE\t0xCD /* CFA Write multiple without erase */\n#define WIN_GETMEDIASTATUS\t\t0xDA\t\n#define WIN_ACKMEDIACHANGE\t\t0xDB /* ATA-1, ATA-2 vendor */\n#define WIN_POSTBOOT\t\t\t0xDC\n#define WIN_PREBOOT\t\t\t0xDD\n#define WIN_DOORLOCK\t\t\t0xDE /* lock door on removable drives */\n#define WIN_DOORUNLOCK\t\t\t0xDF /* unlock door on removable drives */\n#define WIN_STANDBYNOW1\t\t\t0xE0\n#define WIN_IDLEIMMEDIATE\t\t0xE1 /* force drive to become \"ready\" */\n#define WIN_STANDBY \t0xE2 /* Set device in Standby Mode */\n#define WIN_SETIDLE1\t\t\t0xE3\n#define WIN_READ_BUFFER\t\t\t0xE4 /* force read only 1 sector */\n#define WIN_CHECKPOWERMODE1\t\t0xE5\n#define WIN_SLEEPNOW1\t\t\t0xE6\n#define WIN_FLUSH_CACHE\t\t\t0xE7\n#define WIN_WRITE_BUFFER\t\t0xE8 /* force write only 1 sector */\n#define WIN_WRITE_SAME\t\t\t0xE9 /* read ata-2 to use */\n\t/* SET_FEATURES 0x22 or 0xDD */\n#define WIN_FLUSH_CACHE_EXT\t\t0xEA /* 48-Bit */\n#define WIN_IDENTIFY\t\t\t0xEC /* ask drive to identify itself\t*/\n#define WIN_MEDIAEJECT\t\t\t0xED\n#define WIN_IDENTIFY_DMA\t\t0xEE /* same as WIN_IDENTIFY, but DMA */\n#define WIN_SETFEATURES\t\t\t0xEF /* set special drive features */\n#define EXABYTE_ENABLE_NEST\t\t0xF0\n#define WIN_SECURITY_SET_PASS\t\t0xF1\n#define WIN_SECURITY_UNLOCK\t\t0xF2\n#define WIN_SECURITY_ERASE_PREPARE\t0xF3\n#define WIN_SECURITY_ERASE_UNIT\t\t0xF4\n#define WIN_SECURITY_FREEZE_LOCK\t0xF5\n#define WIN_SECURITY_DISABLE\t\t0xF6\n#define WIN_READ_NATIVE_MAX\t\t0xF8 /* return the native maximum address */\n#define WIN_SET_MAX\t\t\t0xF9\n#define DISABLE_SEAGATE\t\t\t0xFB\n\n#define MAX_MULT_SECTORS 128\n\ntypedef struct IDEState IDEState;\n\ntypedef void EndTransferFunc(IDEState *);\n\nstruct IDEState {\n IDEIFState *ide_if;\n BlockDevice *bs;\n int cylinders, heads, sectors;\n int mult_sectors;\n int64_t nb_sectors;\n\n /* ide regs */\n uint8_t feature;\n uint8_t error;\n uint16_t nsector; /* 0 is 256 to ease computations */\n uint8_t sector;\n uint8_t lcyl;\n uint8_t hcyl;\n uint8_t select;\n uint8_t status;\n\n int io_nb_sectors;\n int req_nb_sectors;\n EndTransferFunc *end_transfer_func;\n \n int data_index;\n int data_end;\n uint8_t io_buffer[MAX_MULT_SECTORS*512 + 4];\n};\n\nstruct IDEIFState {\n IRQSignal *irq;\n IDEState *cur_drive;\n IDEState *drives[2];\n /* 0x3f6 command */\n uint8_t cmd;\n};\n\nstatic void ide_sector_read_cb(void *opaque, int ret);\nstatic void ide_sector_read_cb_end(IDEState *s);\nstatic void ide_sector_write_cb2(void *opaque, int ret);\n\nstatic void padstr(char *str, const char *src, int len)\n{\n int i, v;\n for(i = 0; i < len; i++) {\n if (*src)\n v = *src++;\n else\n v = ' ';\n *(char *)((long)str ^ 1) = v;\n str++;\n }\n}\n\n/* little endian assume */\nstatic void stw(uint16_t *buf, int v)\n{\n *buf = v;\n}\n\nstatic void ide_identify(IDEState *s)\n{\n uint16_t *tab;\n uint32_t oldsize;\n \n tab = (uint16_t *)s->io_buffer;\n\n memset(tab, 0, 512 * 2);\n\n stw(tab + 0, 0x0040);\n stw(tab + 1, s->cylinders); \n stw(tab + 3, s->heads);\n stw(tab + 4, 512 * s->sectors); /* sectors */\n stw(tab + 5, 512); /* sector size */\n stw(tab + 6, s->sectors); \n stw(tab + 20, 3); /* buffer type */\n stw(tab + 21, 512); /* cache size in sectors */\n stw(tab + 22, 4); /* ecc bytes */\n padstr((char *)(tab + 27), \"RISCVEMU HARDDISK\", 40);\n stw(tab + 47, 0x8000 | MAX_MULT_SECTORS);\n stw(tab + 48, 0); /* dword I/O */\n stw(tab + 49, 1 << 9); /* LBA supported, no DMA */\n stw(tab + 51, 0x200); /* PIO transfer cycle */\n stw(tab + 52, 0x200); /* DMA transfer cycle */\n stw(tab + 54, s->cylinders);\n stw(tab + 55, s->heads);\n stw(tab + 56, s->sectors);\n oldsize = s->cylinders * s->heads * s->sectors;\n stw(tab + 57, oldsize);\n stw(tab + 58, oldsize >> 16);\n if (s->mult_sectors)\n stw(tab + 59, 0x100 | s->mult_sectors);\n stw(tab + 60, s->nb_sectors);\n stw(tab + 61, s->nb_sectors >> 16);\n stw(tab + 80, (1 << 1) | (1 << 2));\n stw(tab + 82, (1 << 14));\n stw(tab + 83, (1 << 14));\n stw(tab + 84, (1 << 14));\n stw(tab + 85, (1 << 14));\n stw(tab + 86, 0);\n stw(tab + 87, (1 << 14));\n}\n\nstatic void ide_set_signature(IDEState *s) \n{\n s->select &= 0xf0;\n s->nsector = 1;\n s->sector = 1;\n s->lcyl = 0;\n s->hcyl = 0;\n}\n\nstatic void ide_abort_command(IDEState *s) \n{\n s->status = READY_STAT | ERR_STAT;\n s->error = ABRT_ERR;\n}\n\nstatic void ide_set_irq(IDEState *s) \n{\n IDEIFState *ide_if = s->ide_if;\n if (!(ide_if->cmd & IDE_CMD_DISABLE_IRQ)) {\n set_irq(ide_if->irq, 1);\n }\n}\n\n/* prepare data transfer and tell what to do after */\nstatic void ide_transfer_start(IDEState *s, int size,\n EndTransferFunc *end_transfer_func)\n{\n s->end_transfer_func = end_transfer_func;\n s->data_index = 0;\n s->data_end = size;\n}\n\nstatic void ide_transfer_stop(IDEState *s)\n{\n s->end_transfer_func = ide_transfer_stop;\n s->data_index = 0;\n s->data_end = 0;\n}\n\nstatic int64_t ide_get_sector(IDEState *s)\n{\n int64_t sector_num;\n if (s->select & 0x40) {\n /* lba */\n sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) |\n (s->lcyl << 8) | s->sector;\n } else {\n sector_num = ((s->hcyl << 8) | s->lcyl) * \n s->heads * s->sectors +\n (s->select & 0x0f) * s->sectors + (s->sector - 1);\n }\n return sector_num;\n}\n\nstatic void ide_set_sector(IDEState *s, int64_t sector_num)\n{\n unsigned int cyl, r;\n if (s->select & 0x40) {\n s->select = (s->select & 0xf0) | ((sector_num >> 24) & 0x0f);\n s->hcyl = (sector_num >> 16) & 0xff;\n s->lcyl = (sector_num >> 8) & 0xff;\n s->sector = sector_num & 0xff;\n } else {\n cyl = sector_num / (s->heads * s->sectors);\n r = sector_num % (s->heads * s->sectors);\n s->hcyl = (cyl >> 8) & 0xff;\n s->lcyl = cyl & 0xff;\n s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f);\n s->sector = (r % s->sectors) + 1;\n }\n}\n\nstatic void ide_sector_read(IDEState *s)\n{\n int64_t sector_num;\n int ret, n;\n\n sector_num = ide_get_sector(s);\n n = s->nsector;\n if (n == 0) \n n = 256;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n#if defined(DEBUG_IDE)\n printf(\"read sector=%\" PRId64 \" count=%d\\n\", sector_num, n);\n#endif\n s->io_nb_sectors = n;\n ret = s->bs->read_async(s->bs, sector_num, s->io_buffer, n, \n ide_sector_read_cb, s);\n if (ret < 0) {\n /* error */\n ide_abort_command(s);\n ide_set_irq(s);\n } else if (ret == 0) {\n /* synchronous case (needed for performance) */\n ide_sector_read_cb(s, 0);\n } else {\n /* async case */\n s->status = READY_STAT | SEEK_STAT | BUSY_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n }\n}\n\nstatic void ide_sector_read_cb(void *opaque, int ret)\n{\n IDEState *s = opaque;\n int n;\n EndTransferFunc *func;\n \n n = s->io_nb_sectors;\n ide_set_sector(s, ide_get_sector(s) + n);\n s->nsector = (s->nsector - n) & 0xff;\n if (s->nsector == 0)\n func = ide_sector_read_cb_end;\n else\n func = ide_sector_read;\n ide_transfer_start(s, 512 * n, func);\n ide_set_irq(s);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n}\n\nstatic void ide_sector_read_cb_end(IDEState *s)\n{\n /* no more sector to read from disk */\n s->status = READY_STAT | SEEK_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n ide_transfer_stop(s);\n}\n\nstatic void ide_sector_write_cb1(IDEState *s)\n{\n int64_t sector_num;\n int ret;\n\n ide_transfer_stop(s);\n sector_num = ide_get_sector(s);\n#if defined(DEBUG_IDE)\n printf(\"write sector=%\" PRId64 \" count=%d\\n\",\n sector_num, s->io_nb_sectors);\n#endif\n ret = s->bs->write_async(s->bs, sector_num, s->io_buffer, s->io_nb_sectors, \n ide_sector_write_cb2, s);\n if (ret < 0) {\n /* error */\n ide_abort_command(s);\n ide_set_irq(s);\n } else if (ret == 0) {\n /* synchronous case (needed for performance) */\n ide_sector_write_cb2(s, 0);\n } else {\n /* async case */\n s->status = READY_STAT | SEEK_STAT | BUSY_STAT;\n }\n}\n\nstatic void ide_sector_write_cb2(void *opaque, int ret)\n{\n IDEState *s = opaque;\n int n;\n\n n = s->io_nb_sectors;\n ide_set_sector(s, ide_get_sector(s) + n);\n s->nsector = (s->nsector - n) & 0xff;\n if (s->nsector == 0) {\n /* no more sectors to write */\n s->status = READY_STAT | SEEK_STAT;\n } else {\n n = s->nsector;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n s->io_nb_sectors = n;\n ide_transfer_start(s, 512 * n, ide_sector_write_cb1);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n }\n ide_set_irq(s);\n}\n\nstatic void ide_sector_write(IDEState *s)\n{\n int n;\n n = s->nsector;\n if (n == 0)\n n = 256;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n s->io_nb_sectors = n;\n ide_transfer_start(s, 512 * n, ide_sector_write_cb1);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n}\n\nstatic void ide_identify_cb(IDEState *s)\n{\n ide_transfer_stop(s);\n s->status = READY_STAT;\n}\n\nstatic void ide_exec_cmd(IDEState *s, int val)\n{\n#if defined(DEBUG_IDE)\n printf(\"ide: exec_cmd=0x%02x\\n\", val);\n#endif\n switch(val) {\n case WIN_IDENTIFY:\n ide_identify(s);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n ide_transfer_start(s, 512, ide_identify_cb);\n ide_set_irq(s);\n break;\n case WIN_SPECIFY:\n case WIN_RECAL:\n s->error = 0;\n s->status = READY_STAT | SEEK_STAT;\n ide_set_irq(s);\n break;\n case WIN_SETMULT:\n if (s->nsector > MAX_MULT_SECTORS || \n (s->nsector & (s->nsector - 1)) != 0) {\n ide_abort_command(s);\n } else {\n s->mult_sectors = s->nsector;\n#if defined(DEBUG_IDE)\n printf(\"ide: setmult=%d\\n\", s->mult_sectors);\n#endif\n s->status = READY_STAT;\n }\n ide_set_irq(s);\n break;\n case WIN_READ:\n case WIN_READ_ONCE:\n s->req_nb_sectors = 1;\n ide_sector_read(s);\n break;\n case WIN_WRITE:\n case WIN_WRITE_ONCE:\n s->req_nb_sectors = 1;\n ide_sector_write(s);\n break;\n case WIN_MULTREAD:\n if (!s->mult_sectors) {\n ide_abort_command(s);\n ide_set_irq(s);\n } else {\n s->req_nb_sectors = s->mult_sectors;\n ide_sector_read(s);\n }\n break;\n case WIN_MULTWRITE:\n if (!s->mult_sectors) {\n ide_abort_command(s);\n ide_set_irq(s);\n } else {\n s->req_nb_sectors = s->mult_sectors;\n ide_sector_write(s);\n }\n break;\n case WIN_READ_NATIVE_MAX:\n ide_set_sector(s, s->nb_sectors - 1);\n s->status = READY_STAT;\n ide_set_irq(s);\n break;\n default:\n ide_abort_command(s);\n ide_set_irq(s);\n break;\n }\n}\n\nstatic void ide_ioport_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int addr = offset + 1;\n \n#ifdef DEBUG_IDE\n printf(\"ide: write addr=0x%02x val=0x%02x\\n\", addr, val);\n#endif\n switch(addr) {\n case 0:\n break;\n case 1:\n if (s) {\n s->feature = val;\n }\n break;\n case 2:\n if (s) {\n s->nsector = val;\n }\n break;\n case 3:\n if (s) {\n s->sector = val;\n }\n break;\n case 4:\n if (s) {\n s->lcyl = val;\n }\n break;\n case 5:\n if (s) {\n s->hcyl = val;\n }\n break;\n case 6:\n /* select drive */\n s = s1->cur_drive = s1->drives[(val >> 4) & 1];\n if (s) {\n s->select = val;\n }\n break;\n default:\n case 7:\n /* command */\n if (s) {\n ide_exec_cmd(s, val);\n }\n break;\n }\n}\n\nstatic uint32_t ide_ioport_read(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int ret, addr = offset + 1;\n\n if (!s) {\n ret = 0x00;\n } else {\n switch(addr) {\n case 0:\n ret = 0xff;\n break;\n case 1:\n ret = s->error;\n break;\n case 2:\n ret = s->nsector;\n break;\n case 3:\n ret = s->sector;\n break;\n case 4:\n ret = s->lcyl;\n break;\n case 5:\n ret = s->hcyl;\n break;\n case 6:\n ret = s->select;\n break;\n default:\n case 7:\n ret = s->status;\n set_irq(s1->irq, 0);\n break;\n }\n }\n#ifdef DEBUG_IDE\n printf(\"ide: read addr=0x%02x val=0x%02x\\n\", addr, ret);\n#endif\n return ret;\n}\n\nstatic uint32_t ide_status_read(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int ret;\n\n if (s) {\n ret = s->status;\n } else {\n ret = 0;\n }\n#ifdef DEBUG_IDE\n printf(\"ide: read status=0x%02x\\n\", ret);\n#endif\n return ret;\n}\n\nstatic void ide_cmd_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s;\n int i;\n \n#ifdef DEBUG_IDE\n printf(\"ide: cmd write=0x%02x\\n\", val);\n#endif\n if (!(s1->cmd & IDE_CMD_RESET) && (val & IDE_CMD_RESET)) {\n /* low to high */\n for(i = 0; i < 2; i++) {\n s = s1->drives[i];\n if (s) {\n s->status = BUSY_STAT | SEEK_STAT;\n s->error = 0x01;\n }\n }\n } else if ((s1->cmd & IDE_CMD_RESET) && !(val & IDE_CMD_RESET)) {\n /* high to low */\n for(i = 0; i < 2; i++) {\n s = s1->drives[i];\n if (s) {\n s->status = READY_STAT | SEEK_STAT;\n ide_set_signature(s);\n }\n }\n }\n s1->cmd = val;\n}\n\nstatic void ide_data_writew(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int p;\n uint8_t *tab;\n \n if (!s)\n return;\n p = s->data_index;\n tab = s->io_buffer;\n tab[p] = val & 0xff;\n tab[p + 1] = (val >> 8) & 0xff;\n p += 2;\n s->data_index = p;\n if (p >= s->data_end)\n s->end_transfer_func(s);\n}\n\nstatic uint32_t ide_data_readw(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int p, ret;\n uint8_t *tab;\n \n if (!s) {\n ret = 0;\n } else {\n p = s->data_index;\n tab = s->io_buffer;\n ret = tab[p] | (tab[p + 1] << 8);\n p += 2;\n s->data_index = p;\n if (p >= s->data_end)\n s->end_transfer_func(s);\n }\n return ret;\n}\n\nstatic IDEState *ide_drive_init(IDEIFState *ide_if, BlockDevice *bs)\n{\n IDEState *s;\n uint32_t cylinders;\n uint64_t nb_sectors;\n\n s = malloc(sizeof(*s));\n memset(s, 0, sizeof(*s));\n\n s->ide_if = ide_if;\n s->bs = bs;\n\n nb_sectors = s->bs->get_sector_count(s->bs);\n cylinders = nb_sectors / (16 * 63);\n if (cylinders > 16383)\n cylinders = 16383;\n else if (cylinders < 2)\n cylinders = 2;\n s->cylinders = cylinders;\n s->heads = 16;\n s->sectors = 63;\n s->nb_sectors = nb_sectors;\n\n s->mult_sectors = MAX_MULT_SECTORS;\n /* ide regs */\n s->feature = 0;\n s->error = 0;\n s->nsector = 0;\n s->sector = 0;\n s->lcyl = 0;\n s->hcyl = 0;\n s->select = 0xa0;\n s->status = READY_STAT | SEEK_STAT;\n\n /* init I/O buffer */\n s->data_index = 0;\n s->data_end = 0;\n s->end_transfer_func = ide_transfer_stop;\n\n s->req_nb_sectors = 0; /* temp for read/write */\n s->io_nb_sectors = 0; /* temp for read/write */\n return s;\n}\n\nIDEIFState *ide_init(PhysMemoryMap *port_map, uint32_t addr, uint32_t addr2,\n IRQSignal *irq, BlockDevice **tab_bs)\n{\n int i;\n IDEIFState *s;\n \n s = malloc(sizeof(IDEIFState));\n memset(s, 0, sizeof(*s));\n \n s->irq = irq;\n s->cmd = 0;\n\n cpu_register_device(port_map, addr, 1, s, ide_data_readw, ide_data_writew, \n DEVIO_SIZE16);\n cpu_register_device(port_map, addr + 1, 7, s, ide_ioport_read, ide_ioport_write, \n DEVIO_SIZE8);\n if (addr2) {\n cpu_register_device(port_map, addr2, 1, s, ide_status_read, ide_cmd_write, \n DEVIO_SIZE8);\n }\n \n for(i = 0; i < 2; i++) {\n if (tab_bs[i])\n s->drives[i] = ide_drive_init(s, tab_bs[i]);\n }\n s->cur_drive = s->drives[0];\n return s;\n}\n\n/* dummy PCI device for the IDE */\nPCIDevice *piix3_ide_init(PCIBus *pci_bus, int devfn)\n{\n PCIDevice *d;\n d = pci_register_device(pci_bus, \"PIIX3 IDE\", devfn, 0x8086, 0x7010, 0x00, 0x0101);\n pci_device_set_config8(d, 0x09, 0x00); /* ISA IDE ports, no DMA */\n return d;\n}\n"], ["/linuxpdf/tinyemu/simplefb.c", "/*\n * Simple frame buffer\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n//#define DEBUG_VBE\n\n#define FB_ALLOC_ALIGN 65536\n\nstruct SimpleFBState {\n FBDevice *fb_dev;\n int fb_page_count;\n PhysMemoryRange *mem_range;\n};\n\n#define MAX_MERGE_DISTANCE 3\n\nvoid simplefb_refresh(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque,\n PhysMemoryRange *mem_range,\n int fb_page_count)\n{\n const uint32_t *dirty_bits;\n uint32_t dirty_val;\n int y0, y1, page_y0, page_y1, byte_pos, page_index, bit_pos;\n\n dirty_bits = phys_mem_get_dirty_bits(mem_range);\n \n page_index = 0;\n y0 = y1 = 0;\n while (page_index < fb_page_count) {\n dirty_val = dirty_bits[page_index >> 5];\n if (dirty_val != 0) {\n bit_pos = 0;\n while (dirty_val != 0) {\n while (((dirty_val >> bit_pos) & 1) == 0)\n bit_pos++;\n dirty_val &= ~(1 << bit_pos);\n\n byte_pos = (page_index + bit_pos) * DEVRAM_PAGE_SIZE;\n page_y0 = byte_pos / fb_dev->stride;\n page_y1 = ((byte_pos + DEVRAM_PAGE_SIZE - 1) / fb_dev->stride) + 1;\n page_y1 = min_int(page_y1, fb_dev->height);\n if (y0 == y1) {\n y0 = page_y0;\n y1 = page_y1;\n } else if (page_y0 <= (y1 + MAX_MERGE_DISTANCE)) {\n /* union with current region */\n y1 = page_y1;\n } else {\n /* flush */\n redraw_func(fb_dev, opaque,\n 0, y0, fb_dev->width, y1 - y0);\n y0 = page_y0;\n y1 = page_y1;\n }\n }\n }\n page_index += 32;\n }\n\n if (y0 != y1) {\n redraw_func(fb_dev, opaque,\n 0, y0, fb_dev->width, y1 - y0);\n }\n}\n\nstatic void simplefb_refresh1(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n SimpleFBState *s = fb_dev->device_opaque;\n simplefb_refresh(fb_dev, redraw_func, opaque, s->mem_range,\n s->fb_page_count);\n}\n\nSimpleFBState *simplefb_init(PhysMemoryMap *map, uint64_t phys_addr,\n FBDevice *fb_dev, int width, int height)\n{\n SimpleFBState *s;\n \n s = mallocz(sizeof(*s));\n s->fb_dev = fb_dev;\n\n fb_dev->width = width;\n fb_dev->height = height;\n fb_dev->stride = width * 4;\n fb_dev->fb_size = (height * fb_dev->stride + FB_ALLOC_ALIGN - 1) & ~(FB_ALLOC_ALIGN - 1);\n s->fb_page_count = fb_dev->fb_size >> DEVRAM_PAGE_SIZE_LOG2;\n\n s->mem_range = cpu_register_ram(map, phys_addr, fb_dev->fb_size,\n DEVRAM_FLAG_DIRTY_BITS);\n \n fb_dev->fb_data = s->mem_range->phys_mem;\n fb_dev->device_opaque = s;\n fb_dev->refresh = simplefb_refresh1;\n return s;\n}\n"], ["/linuxpdf/tinyemu/ps2.c", "/*\n * QEMU PS/2 keyboard/mouse emulation\n *\n * Copyright (c) 2003 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n\n/* debug PC keyboard */\n//#define DEBUG_KBD\n\n/* debug PC keyboard : only mouse */\n//#define DEBUG_MOUSE\n\n/* Keyboard Commands */\n#define KBD_CMD_SET_LEDS\t0xED\t/* Set keyboard leds */\n#define KBD_CMD_ECHO \t0xEE\n#define KBD_CMD_GET_ID \t 0xF2\t/* get keyboard ID */\n#define KBD_CMD_SET_RATE\t0xF3\t/* Set typematic rate */\n#define KBD_CMD_ENABLE\t\t0xF4\t/* Enable scanning */\n#define KBD_CMD_RESET_DISABLE\t0xF5\t/* reset and disable scanning */\n#define KBD_CMD_RESET_ENABLE \t0xF6 /* reset and enable scanning */\n#define KBD_CMD_RESET\t\t0xFF\t/* Reset */\n\n/* Keyboard Replies */\n#define KBD_REPLY_POR\t\t0xAA\t/* Power on reset */\n#define KBD_REPLY_ACK\t\t0xFA\t/* Command ACK */\n#define KBD_REPLY_RESEND\t0xFE\t/* Command NACK, send the cmd again */\n\n/* Mouse Commands */\n#define AUX_SET_SCALE11\t\t0xE6\t/* Set 1:1 scaling */\n#define AUX_SET_SCALE21\t\t0xE7\t/* Set 2:1 scaling */\n#define AUX_SET_RES\t\t0xE8\t/* Set resolution */\n#define AUX_GET_SCALE\t\t0xE9\t/* Get scaling factor */\n#define AUX_SET_STREAM\t\t0xEA\t/* Set stream mode */\n#define AUX_POLL\t\t0xEB\t/* Poll */\n#define AUX_RESET_WRAP\t\t0xEC\t/* Reset wrap mode */\n#define AUX_SET_WRAP\t\t0xEE\t/* Set wrap mode */\n#define AUX_SET_REMOTE\t\t0xF0\t/* Set remote mode */\n#define AUX_GET_TYPE\t\t0xF2\t/* Get type */\n#define AUX_SET_SAMPLE\t\t0xF3\t/* Set sample rate */\n#define AUX_ENABLE_DEV\t\t0xF4\t/* Enable aux device */\n#define AUX_DISABLE_DEV\t\t0xF5\t/* Disable aux device */\n#define AUX_SET_DEFAULT\t\t0xF6\n#define AUX_RESET\t\t0xFF\t/* Reset aux device */\n#define AUX_ACK\t\t\t0xFA\t/* Command byte ACK. */\n\n#define MOUSE_STATUS_REMOTE 0x40\n#define MOUSE_STATUS_ENABLED 0x20\n#define MOUSE_STATUS_SCALE21 0x10\n\n#define PS2_QUEUE_SIZE 256\n\ntypedef struct {\n uint8_t data[PS2_QUEUE_SIZE];\n int rptr, wptr, count;\n} PS2Queue;\n\ntypedef struct {\n PS2Queue queue;\n int32_t write_cmd;\n void (*update_irq)(void *, int);\n void *update_arg;\n} PS2State;\n\nstruct PS2KbdState {\n PS2State common;\n int scan_enabled;\n /* Qemu uses translated PC scancodes internally. To avoid multiple\n conversions we do the translation (if any) in the PS/2 emulation\n not the keyboard controller. */\n int translate;\n};\n\nstruct PS2MouseState {\n PS2State common;\n uint8_t mouse_status;\n uint8_t mouse_resolution;\n uint8_t mouse_sample_rate;\n uint8_t mouse_wrap;\n uint8_t mouse_type; /* 0 = PS2, 3 = IMPS/2, 4 = IMEX */\n uint8_t mouse_detect_state;\n int mouse_dx; /* current values, needed for 'poll' mode */\n int mouse_dy;\n int mouse_dz;\n uint8_t mouse_buttons;\n};\n\nvoid ps2_queue(void *opaque, int b)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q = &s->queue;\n\n if (q->count >= PS2_QUEUE_SIZE)\n return;\n q->data[q->wptr] = b;\n if (++q->wptr == PS2_QUEUE_SIZE)\n q->wptr = 0;\n q->count++;\n s->update_irq(s->update_arg, 1);\n}\n\n#define INPUT_MAKE_KEY_MIN 96\n#define INPUT_MAKE_KEY_MAX 127\n\nstatic const uint8_t linux_input_to_keycode_set1[INPUT_MAKE_KEY_MAX - INPUT_MAKE_KEY_MIN + 1] = {\n 0x1c, 0x1d, 0x35, 0x00, 0x38, 0x00, 0x47, 0x48, \n 0x49, 0x4b, 0x4d, 0x4f, 0x50, 0x51, 0x52, 0x53, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x5b, 0x5c, 0x5d, \n};\n\n/* keycode is a Linux input layer keycode. We only support the PS/2\n keycode set 1 */\nvoid ps2_put_keycode(PS2KbdState *s, BOOL is_down, int keycode)\n{\n if (keycode >= INPUT_MAKE_KEY_MIN) {\n if (keycode > INPUT_MAKE_KEY_MAX)\n return;\n keycode = linux_input_to_keycode_set1[keycode - INPUT_MAKE_KEY_MIN];\n if (keycode == 0)\n return;\n ps2_queue(&s->common, 0xe0);\n }\n ps2_queue(&s->common, keycode | ((!is_down) << 7));\n}\n\nuint32_t ps2_read_data(void *opaque)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q;\n int val, index;\n\n q = &s->queue;\n if (q->count == 0) {\n /* NOTE: if no data left, we return the last keyboard one\n (needed for EMM386) */\n /* XXX: need a timer to do things correctly */\n index = q->rptr - 1;\n if (index < 0)\n index = PS2_QUEUE_SIZE - 1;\n val = q->data[index];\n } else {\n val = q->data[q->rptr];\n if (++q->rptr == PS2_QUEUE_SIZE)\n q->rptr = 0;\n q->count--;\n /* reading deasserts IRQ */\n s->update_irq(s->update_arg, 0);\n /* reassert IRQs if data left */\n s->update_irq(s->update_arg, q->count != 0);\n }\n return val;\n}\n\nstatic void ps2_reset_keyboard(PS2KbdState *s)\n{\n s->scan_enabled = 1;\n}\n\nvoid ps2_write_keyboard(void *opaque, int val)\n{\n PS2KbdState *s = (PS2KbdState *)opaque;\n\n switch(s->common.write_cmd) {\n default:\n case -1:\n switch(val) {\n case 0x00:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case 0x05:\n ps2_queue(&s->common, KBD_REPLY_RESEND);\n break;\n case KBD_CMD_GET_ID:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n ps2_queue(&s->common, 0xab);\n ps2_queue(&s->common, 0x83);\n break;\n case KBD_CMD_ECHO:\n ps2_queue(&s->common, KBD_CMD_ECHO);\n break;\n case KBD_CMD_ENABLE:\n s->scan_enabled = 1;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_SET_LEDS:\n case KBD_CMD_SET_RATE:\n s->common.write_cmd = val;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET_DISABLE:\n ps2_reset_keyboard(s);\n s->scan_enabled = 0;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET_ENABLE:\n ps2_reset_keyboard(s);\n s->scan_enabled = 1;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET:\n ps2_reset_keyboard(s);\n ps2_queue(&s->common, KBD_REPLY_ACK);\n ps2_queue(&s->common, KBD_REPLY_POR);\n break;\n default:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n }\n break;\n case KBD_CMD_SET_LEDS:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n s->common.write_cmd = -1;\n break;\n case KBD_CMD_SET_RATE:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n s->common.write_cmd = -1;\n break;\n }\n}\n\n/* Set the scancode translation mode.\n 0 = raw scancodes.\n 1 = translated scancodes (used by qemu internally). */\n\nvoid ps2_keyboard_set_translation(void *opaque, int mode)\n{\n PS2KbdState *s = (PS2KbdState *)opaque;\n s->translate = mode;\n}\n\nstatic void ps2_mouse_send_packet(PS2MouseState *s)\n{\n unsigned int b;\n int dx1, dy1, dz1;\n\n dx1 = s->mouse_dx;\n dy1 = s->mouse_dy;\n dz1 = s->mouse_dz;\n /* XXX: increase range to 8 bits ? */\n if (dx1 > 127)\n dx1 = 127;\n else if (dx1 < -127)\n dx1 = -127;\n if (dy1 > 127)\n dy1 = 127;\n else if (dy1 < -127)\n dy1 = -127;\n b = 0x08 | ((dx1 < 0) << 4) | ((dy1 < 0) << 5) | (s->mouse_buttons & 0x07);\n ps2_queue(&s->common, b);\n ps2_queue(&s->common, dx1 & 0xff);\n ps2_queue(&s->common, dy1 & 0xff);\n /* extra byte for IMPS/2 or IMEX */\n switch(s->mouse_type) {\n default:\n break;\n case 3:\n if (dz1 > 127)\n dz1 = 127;\n else if (dz1 < -127)\n dz1 = -127;\n ps2_queue(&s->common, dz1 & 0xff);\n break;\n case 4:\n if (dz1 > 7)\n dz1 = 7;\n else if (dz1 < -7)\n dz1 = -7;\n b = (dz1 & 0x0f) | ((s->mouse_buttons & 0x18) << 1);\n ps2_queue(&s->common, b);\n break;\n }\n\n /* update deltas */\n s->mouse_dx -= dx1;\n s->mouse_dy -= dy1;\n s->mouse_dz -= dz1;\n}\n\nvoid ps2_mouse_event(PS2MouseState *s,\n int dx, int dy, int dz, int buttons_state)\n{\n /* check if deltas are recorded when disabled */\n if (!(s->mouse_status & MOUSE_STATUS_ENABLED))\n return;\n\n s->mouse_dx += dx;\n s->mouse_dy -= dy;\n s->mouse_dz += dz;\n /* XXX: SDL sometimes generates nul events: we delete them */\n if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0 &&\n s->mouse_buttons == buttons_state)\n\treturn;\n s->mouse_buttons = buttons_state;\n\n if (!(s->mouse_status & MOUSE_STATUS_REMOTE) &&\n (s->common.queue.count < (PS2_QUEUE_SIZE - 16))) {\n for(;;) {\n /* if not remote, send event. Multiple events are sent if\n too big deltas */\n ps2_mouse_send_packet(s);\n if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0)\n break;\n }\n }\n}\n\nvoid ps2_write_mouse(void *opaque, int val)\n{\n PS2MouseState *s = (PS2MouseState *)opaque;\n#ifdef DEBUG_MOUSE\n printf(\"kbd: write mouse 0x%02x\\n\", val);\n#endif\n switch(s->common.write_cmd) {\n default:\n case -1:\n /* mouse command */\n if (s->mouse_wrap) {\n if (val == AUX_RESET_WRAP) {\n s->mouse_wrap = 0;\n ps2_queue(&s->common, AUX_ACK);\n return;\n } else if (val != AUX_RESET) {\n ps2_queue(&s->common, val);\n return;\n }\n }\n switch(val) {\n case AUX_SET_SCALE11:\n s->mouse_status &= ~MOUSE_STATUS_SCALE21;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_SCALE21:\n s->mouse_status |= MOUSE_STATUS_SCALE21;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_STREAM:\n s->mouse_status &= ~MOUSE_STATUS_REMOTE;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_WRAP:\n s->mouse_wrap = 1;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_REMOTE:\n s->mouse_status |= MOUSE_STATUS_REMOTE;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_GET_TYPE:\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, s->mouse_type);\n break;\n case AUX_SET_RES:\n case AUX_SET_SAMPLE:\n s->common.write_cmd = val;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_GET_SCALE:\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, s->mouse_status);\n ps2_queue(&s->common, s->mouse_resolution);\n ps2_queue(&s->common, s->mouse_sample_rate);\n break;\n case AUX_POLL:\n ps2_queue(&s->common, AUX_ACK);\n ps2_mouse_send_packet(s);\n break;\n case AUX_ENABLE_DEV:\n s->mouse_status |= MOUSE_STATUS_ENABLED;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_DISABLE_DEV:\n s->mouse_status &= ~MOUSE_STATUS_ENABLED;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_DEFAULT:\n s->mouse_sample_rate = 100;\n s->mouse_resolution = 2;\n s->mouse_status = 0;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_RESET:\n s->mouse_sample_rate = 100;\n s->mouse_resolution = 2;\n s->mouse_status = 0;\n s->mouse_type = 0;\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, 0xaa);\n ps2_queue(&s->common, s->mouse_type);\n break;\n default:\n break;\n }\n break;\n case AUX_SET_SAMPLE:\n s->mouse_sample_rate = val;\n /* detect IMPS/2 or IMEX */\n switch(s->mouse_detect_state) {\n default:\n case 0:\n if (val == 200)\n s->mouse_detect_state = 1;\n break;\n case 1:\n if (val == 100)\n s->mouse_detect_state = 2;\n else if (val == 200)\n s->mouse_detect_state = 3;\n else\n s->mouse_detect_state = 0;\n break;\n case 2:\n if (val == 80)\n s->mouse_type = 3; /* IMPS/2 */\n s->mouse_detect_state = 0;\n break;\n case 3:\n if (val == 80)\n s->mouse_type = 4; /* IMEX */\n s->mouse_detect_state = 0;\n break;\n }\n ps2_queue(&s->common, AUX_ACK);\n s->common.write_cmd = -1;\n break;\n case AUX_SET_RES:\n s->mouse_resolution = val;\n ps2_queue(&s->common, AUX_ACK);\n s->common.write_cmd = -1;\n break;\n }\n}\n\nstatic void ps2_reset(void *opaque)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q;\n s->write_cmd = -1;\n q = &s->queue;\n q->rptr = 0;\n q->wptr = 0;\n q->count = 0;\n}\n\nPS2KbdState *ps2_kbd_init(void (*update_irq)(void *, int), void *update_arg)\n{\n PS2KbdState *s = (PS2KbdState *)mallocz(sizeof(PS2KbdState));\n\n s->common.update_irq = update_irq;\n s->common.update_arg = update_arg;\n ps2_reset(&s->common);\n return s;\n}\n\nPS2MouseState *ps2_mouse_init(void (*update_irq)(void *, int), void *update_arg)\n{\n PS2MouseState *s = (PS2MouseState *)mallocz(sizeof(PS2MouseState));\n\n s->common.update_irq = update_irq;\n s->common.update_arg = update_arg;\n ps2_reset(&s->common);\n return s;\n}\n"], ["/linuxpdf/tinyemu/riscv_cpu.c", "/*\n * RISCV CPU emulator\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"riscv_cpu.h\"\n\n#ifndef MAX_XLEN\n#error MAX_XLEN must be defined\n#endif\n#ifndef CONFIG_RISCV_MAX_XLEN\n#error CONFIG_RISCV_MAX_XLEN must be defined\n#endif\n\n//#define DUMP_INVALID_MEM_ACCESS\n//#define DUMP_MMU_EXCEPTIONS\n//#define DUMP_INTERRUPTS\n//#define DUMP_INVALID_CSR\n//#define DUMP_EXCEPTIONS\n//#define DUMP_CSR\n//#define CONFIG_LOGFILE\n\n#include \"riscv_cpu_priv.h\"\n\n#if FLEN > 0\n#include \"softfp.h\"\n#endif\n\n#ifdef USE_GLOBAL_STATE\nstatic RISCVCPUState riscv_cpu_global_state;\n#endif\n#ifdef USE_GLOBAL_VARIABLES\n#define code_ptr s->__code_ptr\n#define code_end s->__code_end\n#define code_to_pc_addend s->__code_to_pc_addend\n#endif\n\n#ifdef CONFIG_LOGFILE\nstatic FILE *log_file;\n\nstatic void log_vprintf(const char *fmt, va_list ap)\n{\n if (!log_file)\n log_file = fopen(\"/tmp/riscemu.log\", \"wb\");\n vfprintf(log_file, fmt, ap);\n}\n#else\nstatic void log_vprintf(const char *fmt, va_list ap)\n{\n vprintf(fmt, ap);\n}\n#endif\n\nstatic void __attribute__((format(printf, 1, 2), unused)) log_printf(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n log_vprintf(fmt, ap);\n va_end(ap);\n}\n\n#if MAX_XLEN == 128\nstatic void fprint_target_ulong(FILE *f, target_ulong a)\n{\n fprintf(f, \"%016\" PRIx64 \"%016\" PRIx64, (uint64_t)(a >> 64), (uint64_t)a);\n}\n#else\nstatic void fprint_target_ulong(FILE *f, target_ulong a)\n{\n fprintf(f, \"%\" PR_target_ulong, a);\n}\n#endif\n\nstatic void print_target_ulong(target_ulong a)\n{\n fprint_target_ulong(stdout, a);\n}\n\nstatic char *reg_name[32] = {\n\"zero\", \"ra\", \"sp\", \"gp\", \"tp\", \"t0\", \"t1\", \"t2\",\n\"s0\", \"s1\", \"a0\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\",\n\"a6\", \"a7\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\", \"s7\",\n\"s8\", \"s9\", \"s10\", \"s11\", \"t3\", \"t4\", \"t5\", \"t6\"\n};\n\nstatic void dump_regs(RISCVCPUState *s)\n{\n int i, cols;\n const char priv_str[4] = \"USHM\";\n cols = 256 / MAX_XLEN;\n printf(\"pc =\");\n print_target_ulong(s->pc);\n printf(\" \");\n for(i = 1; i < 32; i++) {\n printf(\"%-3s=\", reg_name[i]);\n print_target_ulong(s->reg[i]);\n if ((i & (cols - 1)) == (cols - 1))\n printf(\"\\n\");\n else\n printf(\" \");\n }\n printf(\"priv=%c\", priv_str[s->priv]);\n printf(\" mstatus=\");\n print_target_ulong(s->mstatus);\n printf(\" cycles=%\" PRId64, s->insn_counter);\n printf(\"\\n\");\n#if 1\n printf(\" mideleg=\");\n print_target_ulong(s->mideleg);\n printf(\" mie=\");\n print_target_ulong(s->mie);\n printf(\" mip=\");\n print_target_ulong(s->mip);\n printf(\"\\n\");\n#endif\n}\n\nstatic __attribute__((unused)) void cpu_abort(RISCVCPUState *s)\n{\n dump_regs(s);\n abort();\n}\n\n/* addr must be aligned. Only RAM accesses are supported */\n#define PHYS_MEM_READ_WRITE(size, uint_type) \\\nstatic __maybe_unused inline void phys_write_u ## size(RISCVCPUState *s, target_ulong addr,\\\n uint_type val) \\\n{\\\n PhysMemoryRange *pr = get_phys_mem_range(s->mem_map, addr);\\\n if (!pr || !pr->is_ram)\\\n return;\\\n *(uint_type *)(pr->phys_mem + \\\n (uintptr_t)(addr - pr->addr)) = val;\\\n}\\\n\\\nstatic __maybe_unused inline uint_type phys_read_u ## size(RISCVCPUState *s, target_ulong addr) \\\n{\\\n PhysMemoryRange *pr = get_phys_mem_range(s->mem_map, addr);\\\n if (!pr || !pr->is_ram)\\\n return 0;\\\n return *(uint_type *)(pr->phys_mem + \\\n (uintptr_t)(addr - pr->addr)); \\\n}\n\nPHYS_MEM_READ_WRITE(8, uint8_t)\nPHYS_MEM_READ_WRITE(32, uint32_t)\nPHYS_MEM_READ_WRITE(64, uint64_t)\n\n#define PTE_V_MASK (1 << 0)\n#define PTE_U_MASK (1 << 4)\n#define PTE_A_MASK (1 << 6)\n#define PTE_D_MASK (1 << 7)\n\n#define ACCESS_READ 0\n#define ACCESS_WRITE 1\n#define ACCESS_CODE 2\n\n/* access = 0: read, 1 = write, 2 = code. Set the exception_pending\n field if necessary. return 0 if OK, -1 if translation error */\nstatic int get_phys_addr(RISCVCPUState *s,\n target_ulong *ppaddr, target_ulong vaddr,\n int access)\n{\n int mode, levels, pte_bits, pte_idx, pte_mask, pte_size_log2, xwr, priv;\n int need_write, vaddr_shift, i, pte_addr_bits;\n target_ulong pte_addr, pte, vaddr_mask, paddr;\n\n if ((s->mstatus & MSTATUS_MPRV) && access != ACCESS_CODE) {\n /* use previous priviledge */\n priv = (s->mstatus >> MSTATUS_MPP_SHIFT) & 3;\n } else {\n priv = s->priv;\n }\n\n if (priv == PRV_M) {\n if (s->cur_xlen < MAX_XLEN) {\n /* truncate virtual address */\n *ppaddr = vaddr & (((target_ulong)1 << s->cur_xlen) - 1);\n } else {\n *ppaddr = vaddr;\n }\n return 0;\n }\n#if MAX_XLEN == 32\n /* 32 bits */\n mode = s->satp >> 31;\n if (mode == 0) {\n /* bare: no translation */\n *ppaddr = vaddr;\n return 0;\n } else {\n /* sv32 */\n levels = 2;\n pte_size_log2 = 2;\n pte_addr_bits = 22;\n }\n#else\n mode = (s->satp >> 60) & 0xf;\n if (mode == 0) {\n /* bare: no translation */\n *ppaddr = vaddr;\n return 0;\n } else {\n /* sv39/sv48 */\n levels = mode - 8 + 3;\n pte_size_log2 = 3;\n vaddr_shift = MAX_XLEN - (PG_SHIFT + levels * 9);\n if ((((target_long)vaddr << vaddr_shift) >> vaddr_shift) != vaddr)\n return -1;\n pte_addr_bits = 44;\n }\n#endif\n pte_addr = (s->satp & (((target_ulong)1 << pte_addr_bits) - 1)) << PG_SHIFT;\n pte_bits = 12 - pte_size_log2;\n pte_mask = (1 << pte_bits) - 1;\n for(i = 0; i < levels; i++) {\n vaddr_shift = PG_SHIFT + pte_bits * (levels - 1 - i);\n pte_idx = (vaddr >> vaddr_shift) & pte_mask;\n pte_addr += pte_idx << pte_size_log2;\n if (pte_size_log2 == 2)\n pte = phys_read_u32(s, pte_addr);\n else\n pte = phys_read_u64(s, pte_addr);\n //printf(\"pte=0x%08\" PRIx64 \"\\n\", pte);\n if (!(pte & PTE_V_MASK))\n return -1; /* invalid PTE */\n paddr = (pte >> 10) << PG_SHIFT;\n xwr = (pte >> 1) & 7;\n if (xwr != 0) {\n if (xwr == 2 || xwr == 6)\n return -1;\n /* priviledge check */\n if (priv == PRV_S) {\n if ((pte & PTE_U_MASK) && !(s->mstatus & MSTATUS_SUM))\n return -1;\n } else {\n if (!(pte & PTE_U_MASK))\n return -1;\n }\n /* protection check */\n /* MXR allows read access to execute-only pages */\n if (s->mstatus & MSTATUS_MXR)\n xwr |= (xwr >> 2);\n\n if (((xwr >> access) & 1) == 0)\n return -1;\n need_write = !(pte & PTE_A_MASK) ||\n (!(pte & PTE_D_MASK) && access == ACCESS_WRITE);\n pte |= PTE_A_MASK;\n if (access == ACCESS_WRITE)\n pte |= PTE_D_MASK;\n if (need_write) {\n if (pte_size_log2 == 2)\n phys_write_u32(s, pte_addr, pte);\n else\n phys_write_u64(s, pte_addr, pte);\n }\n vaddr_mask = ((target_ulong)1 << vaddr_shift) - 1;\n *ppaddr = (vaddr & vaddr_mask) | (paddr & ~vaddr_mask);\n return 0;\n } else {\n pte_addr = paddr;\n }\n }\n return -1;\n}\n\n/* return 0 if OK, != 0 if exception */\nint target_read_slow(RISCVCPUState *s, mem_uint_t *pval,\n target_ulong addr, int size_log2)\n{\n int size, tlb_idx, err, al;\n target_ulong paddr, offset;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n mem_uint_t ret;\n\n /* first handle unaligned accesses */\n size = 1 << size_log2;\n al = addr & (size - 1);\n if (al != 0) {\n switch(size_log2) {\n case 1:\n {\n uint8_t v0, v1;\n err = target_read_u8(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u8(s, &v1, addr + 1);\n if (err)\n return err;\n ret = v0 | (v1 << 8);\n }\n break;\n case 2:\n {\n uint32_t v0, v1;\n addr -= al;\n err = target_read_u32(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u32(s, &v1, addr + 4);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (32 - al * 8));\n }\n break;\n#if MLEN >= 64\n case 3:\n {\n uint64_t v0, v1;\n addr -= al;\n err = target_read_u64(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u64(s, &v1, addr + 8);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (64 - al * 8));\n }\n break;\n#endif\n#if MLEN >= 128\n case 4:\n {\n uint128_t v0, v1;\n addr -= al;\n err = target_read_u128(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u128(s, &v1, addr + 16);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (128 - al * 8));\n }\n break;\n#endif\n default:\n abort();\n }\n } else {\n if (get_phys_addr(s, &paddr, addr, ACCESS_READ)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_LOAD_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr) {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"target_read_slow: invalid physical address 0x\");\n print_target_ulong(paddr);\n printf(\"\\n\");\n#endif\n return 0;\n } else if (pr->is_ram) {\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_read[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_read[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n switch(size_log2) {\n case 0:\n ret = *(uint8_t *)ptr;\n break;\n case 1:\n ret = *(uint16_t *)ptr;\n break;\n case 2:\n ret = *(uint32_t *)ptr;\n break;\n#if MLEN >= 64\n case 3:\n ret = *(uint64_t *)ptr;\n break;\n#endif\n#if MLEN >= 128\n case 4:\n ret = *(uint128_t *)ptr;\n break;\n#endif\n default:\n abort();\n }\n } else {\n offset = paddr - pr->addr;\n if (((pr->devio_flags >> size_log2) & 1) != 0) {\n ret = pr->read_func(pr->opaque, offset, size_log2);\n }\n#if MLEN >= 64\n else if ((pr->devio_flags & DEVIO_SIZE32) && size_log2 == 3) {\n /* emulate 64 bit access */\n ret = pr->read_func(pr->opaque, offset, 2);\n ret |= (uint64_t)pr->read_func(pr->opaque, offset + 4, 2) << 32;\n \n }\n#endif\n else {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"unsupported device read access: addr=0x\");\n print_target_ulong(paddr);\n printf(\" width=%d bits\\n\", 1 << (3 + size_log2));\n#endif\n ret = 0;\n }\n }\n }\n *pval = ret;\n return 0;\n}\n\n/* return 0 if OK, != 0 if exception */\nint target_write_slow(RISCVCPUState *s, target_ulong addr,\n mem_uint_t val, int size_log2)\n{\n int size, i, tlb_idx, err;\n target_ulong paddr, offset;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n \n /* first handle unaligned accesses */\n size = 1 << size_log2;\n if ((addr & (size - 1)) != 0) {\n /* XXX: should avoid modifying the memory in case of exception */\n for(i = 0; i < size; i++) {\n err = target_write_u8(s, addr + i, (val >> (8 * i)) & 0xff);\n if (err)\n return err;\n }\n } else {\n if (get_phys_addr(s, &paddr, addr, ACCESS_WRITE)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_STORE_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr) {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"target_write_slow: invalid physical address 0x\");\n print_target_ulong(paddr);\n printf(\"\\n\");\n#endif\n } else if (pr->is_ram) {\n phys_mem_set_dirty_bit(pr, paddr - pr->addr);\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_write[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_write[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n switch(size_log2) {\n case 0:\n *(uint8_t *)ptr = val;\n break;\n case 1:\n *(uint16_t *)ptr = val;\n break;\n case 2:\n *(uint32_t *)ptr = val;\n break;\n#if MLEN >= 64\n case 3:\n *(uint64_t *)ptr = val;\n break;\n#endif\n#if MLEN >= 128\n case 4:\n *(uint128_t *)ptr = val;\n break;\n#endif\n default:\n abort();\n }\n } else {\n offset = paddr - pr->addr;\n if (((pr->devio_flags >> size_log2) & 1) != 0) {\n pr->write_func(pr->opaque, offset, val, size_log2);\n }\n#if MLEN >= 64\n else if ((pr->devio_flags & DEVIO_SIZE32) && size_log2 == 3) {\n /* emulate 64 bit access */\n pr->write_func(pr->opaque, offset,\n val & 0xffffffff, 2);\n pr->write_func(pr->opaque, offset + 4,\n (val >> 32) & 0xffffffff, 2);\n }\n#endif\n else {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"unsupported device write access: addr=0x\");\n print_target_ulong(paddr);\n printf(\" width=%d bits\\n\", 1 << (3 + size_log2));\n#endif\n }\n }\n }\n return 0;\n}\n\nstruct __attribute__((packed)) unaligned_u32 {\n uint32_t u32;\n};\n\n/* unaligned access at an address known to be a multiple of 2 */\nstatic uint32_t get_insn32(uint8_t *ptr)\n{\n#if defined(EMSCRIPTEN)\n return ((uint16_t *)ptr)[0] | (((uint16_t *)ptr)[1] << 16);\n#else\n return ((struct unaligned_u32 *)ptr)->u32;\n#endif\n}\n\n/* return 0 if OK, != 0 if exception */\nstatic no_inline __exception int target_read_insn_slow(RISCVCPUState *s,\n uint8_t **pptr,\n target_ulong addr)\n{\n int tlb_idx;\n target_ulong paddr;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n \n if (get_phys_addr(s, &paddr, addr, ACCESS_CODE)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_FETCH_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr || !pr->is_ram) {\n /* XXX: we only access to execute code from RAM */\n s->pending_tval = addr;\n s->pending_exception = CAUSE_FAULT_FETCH;\n return -1;\n }\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_code[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_code[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n *pptr = ptr;\n return 0;\n}\n\n/* addr must be aligned */\nstatic inline __exception int target_read_insn_u16(RISCVCPUState *s, uint16_t *pinsn,\n target_ulong addr)\n{\n uint32_t tlb_idx;\n uint8_t *ptr;\n \n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n if (likely(s->tlb_code[tlb_idx].vaddr == (addr & ~PG_MASK))) {\n ptr = (uint8_t *)(s->tlb_code[tlb_idx].mem_addend +\n (uintptr_t)addr);\n } else {\n if (target_read_insn_slow(s, &ptr, addr))\n return -1;\n }\n *pinsn = *(uint16_t *)ptr;\n return 0;\n}\n\nstatic void tlb_init(RISCVCPUState *s)\n{\n int i;\n \n for(i = 0; i < TLB_SIZE; i++) {\n s->tlb_read[i].vaddr = -1;\n s->tlb_write[i].vaddr = -1;\n s->tlb_code[i].vaddr = -1;\n }\n}\n\nstatic void tlb_flush_all(RISCVCPUState *s)\n{\n tlb_init(s);\n}\n\nstatic void tlb_flush_vaddr(RISCVCPUState *s, target_ulong vaddr)\n{\n tlb_flush_all(s);\n}\n\n/* XXX: inefficient but not critical as long as it is seldom used */\nstatic void glue(riscv_cpu_flush_tlb_write_range_ram,\n MAX_XLEN)(RISCVCPUState *s,\n uint8_t *ram_ptr, size_t ram_size)\n{\n uint8_t *ptr, *ram_end;\n int i;\n \n ram_end = ram_ptr + ram_size;\n for(i = 0; i < TLB_SIZE; i++) {\n if (s->tlb_write[i].vaddr != -1) {\n ptr = (uint8_t *)(s->tlb_write[i].mem_addend +\n (uintptr_t)s->tlb_write[i].vaddr);\n if (ptr >= ram_ptr && ptr < ram_end) {\n s->tlb_write[i].vaddr = -1;\n }\n }\n }\n}\n\n\n#define SSTATUS_MASK0 (MSTATUS_UIE | MSTATUS_SIE | \\\n MSTATUS_UPIE | MSTATUS_SPIE | \\\n MSTATUS_SPP | \\\n MSTATUS_FS | MSTATUS_XS | \\\n MSTATUS_SUM | MSTATUS_MXR)\n#if MAX_XLEN >= 64\n#define SSTATUS_MASK (SSTATUS_MASK0 | MSTATUS_UXL_MASK)\n#else\n#define SSTATUS_MASK SSTATUS_MASK0\n#endif\n\n\n#define MSTATUS_MASK (MSTATUS_UIE | MSTATUS_SIE | MSTATUS_MIE | \\\n MSTATUS_UPIE | MSTATUS_SPIE | MSTATUS_MPIE | \\\n MSTATUS_SPP | MSTATUS_MPP | \\\n MSTATUS_FS | \\\n MSTATUS_MPRV | MSTATUS_SUM | MSTATUS_MXR)\n\n/* cycle and insn counters */\n#define COUNTEREN_MASK ((1 << 0) | (1 << 2))\n\n/* return the complete mstatus with the SD bit */\nstatic target_ulong get_mstatus(RISCVCPUState *s, target_ulong mask)\n{\n target_ulong val;\n BOOL sd;\n val = s->mstatus | (s->fs << MSTATUS_FS_SHIFT);\n val &= mask;\n sd = ((val & MSTATUS_FS) == MSTATUS_FS) |\n ((val & MSTATUS_XS) == MSTATUS_XS);\n if (sd)\n val |= (target_ulong)1 << (s->cur_xlen - 1);\n return val;\n}\n \nstatic int get_base_from_xlen(int xlen)\n{\n if (xlen == 32)\n return 1;\n else if (xlen == 64)\n return 2;\n else\n return 3;\n}\n\nstatic void set_mstatus(RISCVCPUState *s, target_ulong val)\n{\n target_ulong mod, mask;\n \n /* flush the TLBs if change of MMU config */\n mod = s->mstatus ^ val;\n if ((mod & (MSTATUS_MPRV | MSTATUS_SUM | MSTATUS_MXR)) != 0 ||\n ((s->mstatus & MSTATUS_MPRV) && (mod & MSTATUS_MPP) != 0)) {\n tlb_flush_all(s);\n }\n s->fs = (val >> MSTATUS_FS_SHIFT) & 3;\n\n mask = MSTATUS_MASK & ~MSTATUS_FS;\n#if MAX_XLEN >= 64\n {\n int uxl, sxl;\n uxl = (val >> MSTATUS_UXL_SHIFT) & 3;\n if (uxl >= 1 && uxl <= get_base_from_xlen(MAX_XLEN))\n mask |= MSTATUS_UXL_MASK;\n sxl = (val >> MSTATUS_UXL_SHIFT) & 3;\n if (sxl >= 1 && sxl <= get_base_from_xlen(MAX_XLEN))\n mask |= MSTATUS_SXL_MASK;\n }\n#endif\n s->mstatus = (s->mstatus & ~mask) | (val & mask);\n}\n\n/* return -1 if invalid CSR. 0 if OK. 'will_write' indicate that the\n csr will be written after (used for CSR access check) */\nstatic int csr_read(RISCVCPUState *s, target_ulong *pval, uint32_t csr,\n BOOL will_write)\n{\n target_ulong val;\n\n if (((csr & 0xc00) == 0xc00) && will_write)\n return -1; /* read-only CSR */\n if (s->priv < ((csr >> 8) & 3))\n return -1; /* not enough priviledge */\n \n switch(csr) {\n#if FLEN > 0\n case 0x001: /* fflags */\n if (s->fs == 0)\n return -1;\n val = s->fflags;\n break;\n case 0x002: /* frm */\n if (s->fs == 0)\n return -1;\n val = s->frm;\n break;\n case 0x003:\n if (s->fs == 0)\n return -1;\n val = s->fflags | (s->frm << 5);\n break;\n#endif\n case 0xc00: /* ucycle */\n case 0xc02: /* uinstret */\n {\n uint32_t counteren;\n if (s->priv < PRV_M) {\n if (s->priv < PRV_S)\n counteren = s->scounteren;\n else\n counteren = s->mcounteren;\n if (((counteren >> (csr & 0x1f)) & 1) == 0)\n goto invalid_csr;\n }\n }\n val = (int64_t)s->insn_counter;\n break;\n case 0xc80: /* mcycleh */\n case 0xc82: /* minstreth */\n if (s->cur_xlen != 32)\n goto invalid_csr;\n {\n uint32_t counteren;\n if (s->priv < PRV_M) {\n if (s->priv < PRV_S)\n counteren = s->scounteren;\n else\n counteren = s->mcounteren;\n if (((counteren >> (csr & 0x1f)) & 1) == 0)\n goto invalid_csr;\n }\n }\n val = s->insn_counter >> 32;\n break;\n \n case 0x100:\n val = get_mstatus(s, SSTATUS_MASK);\n break;\n case 0x104: /* sie */\n val = s->mie & s->mideleg;\n break;\n case 0x105:\n val = s->stvec;\n break;\n case 0x106:\n val = s->scounteren;\n break;\n case 0x140:\n val = s->sscratch;\n break;\n case 0x141:\n val = s->sepc;\n break;\n case 0x142:\n val = s->scause;\n break;\n case 0x143:\n val = s->stval;\n break;\n case 0x144: /* sip */\n val = s->mip & s->mideleg;\n break;\n case 0x180:\n val = s->satp;\n break;\n case 0x300:\n val = get_mstatus(s, (target_ulong)-1);\n break;\n case 0x301:\n val = s->misa;\n val |= (target_ulong)s->mxl << (s->cur_xlen - 2);\n break;\n case 0x302:\n val = s->medeleg;\n break;\n case 0x303:\n val = s->mideleg;\n break;\n case 0x304:\n val = s->mie;\n break;\n case 0x305:\n val = s->mtvec;\n break;\n case 0x306:\n val = s->mcounteren;\n break;\n case 0x340:\n val = s->mscratch;\n break;\n case 0x341:\n val = s->mepc;\n break;\n case 0x342:\n val = s->mcause;\n break;\n case 0x343:\n val = s->mtval;\n break;\n case 0x344:\n val = s->mip;\n break;\n case 0xb00: /* mcycle */\n case 0xb02: /* minstret */\n val = (int64_t)s->insn_counter;\n break;\n case 0xb80: /* mcycleh */\n case 0xb82: /* minstreth */\n if (s->cur_xlen != 32)\n goto invalid_csr;\n val = s->insn_counter >> 32;\n break;\n case 0xf14:\n val = s->mhartid;\n break;\n default:\n invalid_csr:\n#ifdef DUMP_INVALID_CSR\n /* the 'time' counter is usually emulated */\n if (csr != 0xc01 && csr != 0xc81) {\n printf(\"csr_read: invalid CSR=0x%x\\n\", csr);\n }\n#endif\n *pval = 0;\n return -1;\n }\n *pval = val;\n return 0;\n}\n\n#if FLEN > 0\nstatic void set_frm(RISCVCPUState *s, unsigned int val)\n{\n if (val >= 5)\n val = 0;\n s->frm = val;\n}\n\n/* return -1 if invalid roundind mode */\nstatic int get_insn_rm(RISCVCPUState *s, unsigned int rm)\n{\n if (rm == 7)\n return s->frm;\n if (rm >= 5)\n return -1;\n else\n return rm;\n}\n#endif\n\n/* return -1 if invalid CSR, 0 if OK, 1 if the interpreter loop must be\n exited (e.g. XLEN was modified), 2 if TLBs have been flushed. */\nstatic int csr_write(RISCVCPUState *s, uint32_t csr, target_ulong val)\n{\n target_ulong mask;\n\n#if defined(DUMP_CSR)\n printf(\"csr_write: csr=0x%03x val=0x\", csr);\n print_target_ulong(val);\n printf(\"\\n\");\n#endif\n switch(csr) {\n#if FLEN > 0\n case 0x001: /* fflags */\n s->fflags = val & 0x1f;\n s->fs = 3;\n break;\n case 0x002: /* frm */\n set_frm(s, val & 7);\n s->fs = 3;\n break;\n case 0x003: /* fcsr */\n set_frm(s, (val >> 5) & 7);\n s->fflags = val & 0x1f;\n s->fs = 3;\n break;\n#endif\n case 0x100: /* sstatus */\n set_mstatus(s, (s->mstatus & ~SSTATUS_MASK) | (val & SSTATUS_MASK));\n break;\n case 0x104: /* sie */\n mask = s->mideleg;\n s->mie = (s->mie & ~mask) | (val & mask);\n break;\n case 0x105:\n s->stvec = val & ~3;\n break;\n case 0x106:\n s->scounteren = val & COUNTEREN_MASK;\n break;\n case 0x140:\n s->sscratch = val;\n break;\n case 0x141:\n s->sepc = val & ~1;\n break;\n case 0x142:\n s->scause = val;\n break;\n case 0x143:\n s->stval = val;\n break;\n case 0x144: /* sip */\n mask = s->mideleg;\n s->mip = (s->mip & ~mask) | (val & mask);\n break;\n case 0x180:\n /* no ASID implemented */\n#if MAX_XLEN == 32\n {\n int new_mode;\n new_mode = (val >> 31) & 1;\n s->satp = (val & (((target_ulong)1 << 22) - 1)) |\n (new_mode << 31);\n }\n#else\n {\n int mode, new_mode;\n mode = s->satp >> 60;\n new_mode = (val >> 60) & 0xf;\n if (new_mode == 0 || (new_mode >= 8 && new_mode <= 9))\n mode = new_mode;\n s->satp = (val & (((uint64_t)1 << 44) - 1)) |\n ((uint64_t)mode << 60);\n }\n#endif\n tlb_flush_all(s);\n return 2;\n \n case 0x300:\n set_mstatus(s, val);\n break;\n case 0x301: /* misa */\n#if MAX_XLEN >= 64\n {\n int new_mxl;\n new_mxl = (val >> (s->cur_xlen - 2)) & 3;\n if (new_mxl >= 1 && new_mxl <= get_base_from_xlen(MAX_XLEN)) {\n /* Note: misa is only modified in M level, so cur_xlen\n = 2^(mxl + 4) */\n if (s->mxl != new_mxl) {\n s->mxl = new_mxl;\n s->cur_xlen = 1 << (new_mxl + 4);\n return 1;\n }\n }\n }\n#endif\n break;\n case 0x302:\n mask = (1 << (CAUSE_STORE_PAGE_FAULT + 1)) - 1;\n s->medeleg = (s->medeleg & ~mask) | (val & mask);\n break;\n case 0x303:\n mask = MIP_SSIP | MIP_STIP | MIP_SEIP;\n s->mideleg = (s->mideleg & ~mask) | (val & mask);\n break;\n case 0x304:\n mask = MIP_MSIP | MIP_MTIP | MIP_SSIP | MIP_STIP | MIP_SEIP;\n s->mie = (s->mie & ~mask) | (val & mask);\n break;\n case 0x305:\n s->mtvec = val & ~3;\n break;\n case 0x306:\n s->mcounteren = val & COUNTEREN_MASK;\n break;\n case 0x340:\n s->mscratch = val;\n break;\n case 0x341:\n s->mepc = val & ~1;\n break;\n case 0x342:\n s->mcause = val;\n break;\n case 0x343:\n s->mtval = val;\n break;\n case 0x344:\n mask = MIP_SSIP | MIP_STIP;\n s->mip = (s->mip & ~mask) | (val & mask);\n break;\n default:\n#ifdef DUMP_INVALID_CSR\n printf(\"csr_write: invalid CSR=0x%x\\n\", csr);\n#endif\n return -1;\n }\n return 0;\n}\n\nstatic void set_priv(RISCVCPUState *s, int priv)\n{\n if (s->priv != priv) {\n tlb_flush_all(s);\n#if MAX_XLEN >= 64\n /* change the current xlen */\n {\n int mxl;\n if (priv == PRV_S)\n mxl = (s->mstatus >> MSTATUS_SXL_SHIFT) & 3;\n else if (priv == PRV_U)\n mxl = (s->mstatus >> MSTATUS_UXL_SHIFT) & 3;\n else\n mxl = s->mxl;\n s->cur_xlen = 1 << (4 + mxl);\n }\n#endif\n s->priv = priv;\n }\n}\n\nstatic void raise_exception2(RISCVCPUState *s, uint32_t cause,\n target_ulong tval)\n{\n BOOL deleg;\n target_ulong causel;\n \n#if defined(DUMP_EXCEPTIONS) || defined(DUMP_MMU_EXCEPTIONS) || defined(DUMP_INTERRUPTS)\n {\n int flag;\n flag = 0;\n#ifdef DUMP_MMU_EXCEPTIONS\n if (cause == CAUSE_FAULT_FETCH ||\n cause == CAUSE_FAULT_LOAD ||\n cause == CAUSE_FAULT_STORE ||\n cause == CAUSE_FETCH_PAGE_FAULT ||\n cause == CAUSE_LOAD_PAGE_FAULT ||\n cause == CAUSE_STORE_PAGE_FAULT)\n flag = 1;\n#endif\n#ifdef DUMP_INTERRUPTS\n flag |= (cause & CAUSE_INTERRUPT) != 0;\n#endif\n#ifdef DUMP_EXCEPTIONS\n flag = 1;\n flag = (cause & CAUSE_INTERRUPT) == 0;\n if (cause == CAUSE_SUPERVISOR_ECALL || cause == CAUSE_ILLEGAL_INSTRUCTION)\n flag = 0;\n#endif\n if (flag) {\n log_printf(\"raise_exception: cause=0x%08x tval=0x\", cause);\n#ifdef CONFIG_LOGFILE\n fprint_target_ulong(log_file, tval);\n#else\n print_target_ulong(tval);\n#endif\n log_printf(\"\\n\");\n dump_regs(s);\n }\n }\n#endif\n\n if (s->priv <= PRV_S) {\n /* delegate the exception to the supervisor priviledge */\n if (cause & CAUSE_INTERRUPT)\n deleg = (s->mideleg >> (cause & (MAX_XLEN - 1))) & 1;\n else\n deleg = (s->medeleg >> cause) & 1;\n } else {\n deleg = 0;\n }\n \n causel = cause & 0x7fffffff;\n if (cause & CAUSE_INTERRUPT)\n causel |= (target_ulong)1 << (s->cur_xlen - 1);\n \n if (deleg) {\n s->scause = causel;\n s->sepc = s->pc;\n s->stval = tval;\n s->mstatus = (s->mstatus & ~MSTATUS_SPIE) |\n (((s->mstatus >> s->priv) & 1) << MSTATUS_SPIE_SHIFT);\n s->mstatus = (s->mstatus & ~MSTATUS_SPP) |\n (s->priv << MSTATUS_SPP_SHIFT);\n s->mstatus &= ~MSTATUS_SIE;\n set_priv(s, PRV_S);\n s->pc = s->stvec;\n } else {\n s->mcause = causel;\n s->mepc = s->pc;\n s->mtval = tval;\n s->mstatus = (s->mstatus & ~MSTATUS_MPIE) |\n (((s->mstatus >> s->priv) & 1) << MSTATUS_MPIE_SHIFT);\n s->mstatus = (s->mstatus & ~MSTATUS_MPP) |\n (s->priv << MSTATUS_MPP_SHIFT);\n s->mstatus &= ~MSTATUS_MIE;\n set_priv(s, PRV_M);\n s->pc = s->mtvec;\n }\n}\n\nstatic void raise_exception(RISCVCPUState *s, uint32_t cause)\n{\n raise_exception2(s, cause, 0);\n}\n\nstatic void handle_sret(RISCVCPUState *s)\n{\n int spp, spie;\n spp = (s->mstatus >> MSTATUS_SPP_SHIFT) & 1;\n /* set the IE state to previous IE state */\n spie = (s->mstatus >> MSTATUS_SPIE_SHIFT) & 1;\n s->mstatus = (s->mstatus & ~(1 << spp)) |\n (spie << spp);\n /* set SPIE to 1 */\n s->mstatus |= MSTATUS_SPIE;\n /* set SPP to U */\n s->mstatus &= ~MSTATUS_SPP;\n set_priv(s, spp);\n s->pc = s->sepc;\n}\n\nstatic void handle_mret(RISCVCPUState *s)\n{\n int mpp, mpie;\n mpp = (s->mstatus >> MSTATUS_MPP_SHIFT) & 3;\n /* set the IE state to previous IE state */\n mpie = (s->mstatus >> MSTATUS_MPIE_SHIFT) & 1;\n s->mstatus = (s->mstatus & ~(1 << mpp)) |\n (mpie << mpp);\n /* set MPIE to 1 */\n s->mstatus |= MSTATUS_MPIE;\n /* set MPP to U */\n s->mstatus &= ~MSTATUS_MPP;\n set_priv(s, mpp);\n s->pc = s->mepc;\n}\n\nstatic inline uint32_t get_pending_irq_mask(RISCVCPUState *s)\n{\n uint32_t pending_ints, enabled_ints;\n\n pending_ints = s->mip & s->mie;\n if (pending_ints == 0)\n return 0;\n\n enabled_ints = 0;\n switch(s->priv) {\n case PRV_M:\n if (s->mstatus & MSTATUS_MIE)\n enabled_ints = ~s->mideleg;\n break;\n case PRV_S:\n enabled_ints = ~s->mideleg;\n if (s->mstatus & MSTATUS_SIE)\n enabled_ints |= s->mideleg;\n break;\n default:\n case PRV_U:\n enabled_ints = -1;\n break;\n }\n return pending_ints & enabled_ints;\n}\n\nstatic __exception int raise_interrupt(RISCVCPUState *s)\n{\n uint32_t mask;\n int irq_num;\n\n mask = get_pending_irq_mask(s);\n if (mask == 0)\n return 0;\n irq_num = ctz32(mask);\n raise_exception(s, irq_num | CAUSE_INTERRUPT);\n return -1;\n}\n\nstatic inline int32_t sext(int32_t val, int n)\n{\n return (val << (32 - n)) >> (32 - n);\n}\n\nstatic inline uint32_t get_field1(uint32_t val, int src_pos, \n int dst_pos, int dst_pos_max)\n{\n int mask;\n assert(dst_pos_max >= dst_pos);\n mask = ((1 << (dst_pos_max - dst_pos + 1)) - 1) << dst_pos;\n if (dst_pos >= src_pos)\n return (val << (dst_pos - src_pos)) & mask;\n else\n return (val >> (src_pos - dst_pos)) & mask;\n}\n\n#define XLEN 32\n#include \"riscv_cpu_template.h\"\n\n#if MAX_XLEN >= 64\n#define XLEN 64\n#include \"riscv_cpu_template.h\"\n#endif\n\n#if MAX_XLEN >= 128\n#define XLEN 128\n#include \"riscv_cpu_template.h\"\n#endif\n\nstatic void glue(riscv_cpu_interp, MAX_XLEN)(RISCVCPUState *s, int n_cycles)\n{\n#ifdef USE_GLOBAL_STATE\n s = &riscv_cpu_global_state;\n#endif\n uint64_t timeout;\n\n timeout = s->insn_counter + n_cycles;\n while (!s->power_down_flag &&\n (int)(timeout - s->insn_counter) > 0) {\n n_cycles = timeout - s->insn_counter;\n switch(s->cur_xlen) {\n case 32:\n riscv_cpu_interp_x32(s, n_cycles);\n break;\n#if MAX_XLEN >= 64\n case 64:\n riscv_cpu_interp_x64(s, n_cycles);\n break;\n#endif\n#if MAX_XLEN >= 128\n case 128:\n riscv_cpu_interp_x128(s, n_cycles);\n break;\n#endif\n default:\n abort();\n }\n }\n}\n\n/* Note: the value is not accurate when called in riscv_cpu_interp() */\nstatic uint64_t glue(riscv_cpu_get_cycles, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->insn_counter;\n}\n\nstatic void glue(riscv_cpu_set_mip, MAX_XLEN)(RISCVCPUState *s, uint32_t mask)\n{\n s->mip |= mask;\n /* exit from power down if an interrupt is pending */\n if (s->power_down_flag && (s->mip & s->mie) != 0)\n s->power_down_flag = FALSE;\n}\n\nstatic void glue(riscv_cpu_reset_mip, MAX_XLEN)(RISCVCPUState *s, uint32_t mask)\n{\n s->mip &= ~mask;\n}\n\nstatic uint32_t glue(riscv_cpu_get_mip, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->mip;\n}\n\nstatic BOOL glue(riscv_cpu_get_power_down, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->power_down_flag;\n}\n\nstatic RISCVCPUState *glue(riscv_cpu_init, MAX_XLEN)(PhysMemoryMap *mem_map)\n{\n RISCVCPUState *s;\n \n#ifdef USE_GLOBAL_STATE\n s = &riscv_cpu_global_state;\n#else\n s = mallocz(sizeof(*s));\n#endif\n s->common.class_ptr = &glue(riscv_cpu_class, MAX_XLEN);\n s->mem_map = mem_map;\n s->pc = 0x1000;\n s->priv = PRV_M;\n s->cur_xlen = MAX_XLEN;\n s->mxl = get_base_from_xlen(MAX_XLEN);\n s->mstatus = ((uint64_t)s->mxl << MSTATUS_UXL_SHIFT) |\n ((uint64_t)s->mxl << MSTATUS_SXL_SHIFT);\n s->misa |= MCPUID_SUPER | MCPUID_USER | MCPUID_I | MCPUID_M | MCPUID_A;\n#if FLEN >= 32\n s->misa |= MCPUID_F;\n#endif\n#if FLEN >= 64\n s->misa |= MCPUID_D;\n#endif\n#if FLEN >= 128\n s->misa |= MCPUID_Q;\n#endif\n#ifdef CONFIG_EXT_C\n s->misa |= MCPUID_C;\n#endif\n tlb_init(s);\n return s;\n}\n\nstatic void glue(riscv_cpu_end, MAX_XLEN)(RISCVCPUState *s)\n{\n#ifdef USE_GLOBAL_STATE\n free(s);\n#endif\n}\n\nstatic uint32_t glue(riscv_cpu_get_misa, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->misa;\n}\n\nconst RISCVCPUClass glue(riscv_cpu_class, MAX_XLEN) = {\n glue(riscv_cpu_init, MAX_XLEN),\n glue(riscv_cpu_end, MAX_XLEN),\n glue(riscv_cpu_interp, MAX_XLEN),\n glue(riscv_cpu_get_cycles, MAX_XLEN),\n glue(riscv_cpu_set_mip, MAX_XLEN),\n glue(riscv_cpu_reset_mip, MAX_XLEN),\n glue(riscv_cpu_get_mip, MAX_XLEN),\n glue(riscv_cpu_get_power_down, MAX_XLEN),\n glue(riscv_cpu_get_misa, MAX_XLEN),\n glue(riscv_cpu_flush_tlb_write_range_ram, MAX_XLEN),\n};\n\n#if CONFIG_RISCV_MAX_XLEN == MAX_XLEN\nRISCVCPUState *riscv_cpu_init(PhysMemoryMap *mem_map, int max_xlen)\n{\n const RISCVCPUClass *c;\n switch(max_xlen) {\n /* with emscripten we compile a single CPU */\n#if defined(EMSCRIPTEN)\n case MAX_XLEN:\n c = &glue(riscv_cpu_class, MAX_XLEN);\n break;\n#else\n case 32:\n c = &riscv_cpu_class32;\n break;\n case 64:\n c = &riscv_cpu_class64;\n break;\n#if CONFIG_RISCV_MAX_XLEN == 128\n case 128:\n c = &riscv_cpu_class128;\n break;\n#endif\n#endif /* !EMSCRIPTEN */\n default:\n return NULL;\n }\n return c->riscv_cpu_init(mem_map);\n}\n#endif /* CONFIG_RISCV_MAX_XLEN == MAX_XLEN */\n\n"], ["/linuxpdf/tinyemu/vmmouse.c", "/*\n * VM mouse emulation\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n\n#define VMPORT_MAGIC 0x564D5868\n\n#define REG_EAX 0\n#define REG_EBX 1\n#define REG_ECX 2\n#define REG_EDX 3\n#define REG_ESI 4\n#define REG_EDI 5\n\n#define FIFO_SIZE (4 * 16)\n\nstruct VMMouseState {\n PS2MouseState *ps2_mouse;\n int fifo_count, fifo_rindex, fifo_windex;\n BOOL enabled;\n BOOL absolute;\n uint32_t fifo_buf[FIFO_SIZE];\n};\n\nstatic void put_queue(VMMouseState *s, uint32_t val)\n{\n if (s->fifo_count >= FIFO_SIZE)\n return;\n s->fifo_buf[s->fifo_windex] = val;\n if (++s->fifo_windex == FIFO_SIZE)\n s->fifo_windex = 0;\n s->fifo_count++;\n}\n\nstatic void read_data(VMMouseState *s, uint32_t *regs, int size)\n{\n int i;\n if (size > 6 || size > s->fifo_count) {\n // printf(\"vmmouse: read error req=%d count=%d\\n\", size, s->fifo_count);\n s->enabled = FALSE;\n return;\n }\n for(i = 0; i < size; i++) {\n regs[i] = s->fifo_buf[s->fifo_rindex];\n if (++s->fifo_rindex == FIFO_SIZE)\n s->fifo_rindex = 0;\n }\n s->fifo_count -= size;\n}\n\nvoid vmmouse_send_mouse_event(VMMouseState *s, int x, int y, int dz,\n int buttons)\n{\n int state;\n\n if (!s->enabled) {\n ps2_mouse_event(s->ps2_mouse, x, y, dz, buttons);\n return;\n }\n\n if ((s->fifo_count + 4) > FIFO_SIZE)\n return;\n\n state = 0;\n if (buttons & 1)\n state |= 0x20;\n if (buttons & 2)\n state |= 0x10;\n if (buttons & 4)\n state |= 0x08;\n if (s->absolute) {\n /* range = 0 ... 65535 */\n x *= 2; \n y *= 2;\n }\n\n put_queue(s, state);\n put_queue(s, x);\n put_queue(s, y);\n put_queue(s, -dz);\n\n /* send PS/2 mouse event */\n ps2_mouse_event(s->ps2_mouse, 1, 0, 0, 0);\n}\n\nvoid vmmouse_handler(VMMouseState *s, uint32_t *regs)\n{\n uint32_t cmd;\n \n cmd = regs[REG_ECX] & 0xff;\n switch(cmd) {\n case 10: /* get version */\n regs[REG_EBX] = VMPORT_MAGIC;\n break;\n case 39: /* VMMOUSE_DATA */\n read_data(s, regs, regs[REG_EBX]);\n break;\n case 40: /* VMMOUSE_STATUS */\n regs[REG_EAX] = ((s->enabled ? 0 : 0xffff) << 16) | s->fifo_count;\n break;\n case 41: /* VMMOUSE_COMMAND */\n switch(regs[REG_EBX]) {\n case 0x45414552: /* read id */\n if (s->fifo_count < FIFO_SIZE) {\n put_queue(s, 0x3442554a);\n s->enabled = TRUE;\n }\n break;\n case 0x000000f5: /* disable */\n s->enabled = FALSE;\n break;\n case 0x4c455252: /* set relative */\n s->absolute = 0;\n break;\n case 0x53424152: /* set absolute */\n s->absolute = 1;\n break;\n }\n break;\n }\n}\n\nBOOL vmmouse_is_absolute(VMMouseState *s)\n{\n return s->absolute;\n}\n\nVMMouseState *vmmouse_init(PS2MouseState *ps2_mouse)\n{\n VMMouseState *s;\n s = mallocz(sizeof(*s));\n s->ps2_mouse = ps2_mouse;\n return s;\n}\n"], ["/linuxpdf/tinyemu/pci.c", "/*\n * Simple PCI bus driver\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"pci.h\"\n\n//#define DEBUG_CONFIG\n\ntypedef struct {\n uint32_t size; /* 0 means no mapping defined */\n uint8_t type;\n uint8_t enabled; /* true if mapping is enabled */\n void *opaque;\n PCIBarSetFunc *bar_set;\n} PCIIORegion;\n\nstruct PCIDevice {\n PCIBus *bus;\n uint8_t devfn;\n IRQSignal irq[4];\n uint8_t config[256];\n uint8_t next_cap_offset; /* offset of the next capability */\n char *name; /* for debug only */\n PCIIORegion io_regions[PCI_NUM_REGIONS];\n};\n\nstruct PCIBus {\n int bus_num;\n PCIDevice *device[256];\n PhysMemoryMap *mem_map;\n PhysMemoryMap *port_map;\n uint32_t irq_state[4][8]; /* one bit per device */\n IRQSignal irq[4];\n};\n\nstatic int bus_map_irq(PCIDevice *d, int irq_num)\n{\n int slot_addend;\n slot_addend = (d->devfn >> 3) - 1;\n return (irq_num + slot_addend) & 3;\n}\n\nstatic void pci_device_set_irq(void *opaque, int irq_num, int level)\n{\n PCIDevice *d = opaque;\n PCIBus *b = d->bus;\n uint32_t mask;\n int i, irq_level;\n \n // printf(\"%s: pci_device_seq_irq: %d %d\\n\", d->name, irq_num, level);\n irq_num = bus_map_irq(d, irq_num);\n mask = 1 << (d->devfn & 0x1f);\n if (level)\n b->irq_state[irq_num][d->devfn >> 5] |= mask;\n else\n b->irq_state[irq_num][d->devfn >> 5] &= ~mask;\n\n /* compute the IRQ state */\n mask = 0;\n for(i = 0; i < 8; i++)\n mask |= b->irq_state[irq_num][i];\n irq_level = (mask != 0);\n set_irq(&b->irq[irq_num], irq_level);\n}\n\nstatic int devfn_alloc(PCIBus *b)\n{\n int devfn;\n for(devfn = 0; devfn < 256; devfn += 8) {\n if (!b->device[devfn])\n return devfn;\n }\n return -1;\n}\n\n/* devfn < 0 means to allocate it */\nPCIDevice *pci_register_device(PCIBus *b, const char *name, int devfn,\n uint16_t vendor_id, uint16_t device_id,\n uint8_t revision, uint16_t class_id)\n{\n PCIDevice *d;\n int i;\n \n if (devfn < 0) {\n devfn = devfn_alloc(b);\n if (devfn < 0)\n return NULL;\n }\n if (b->device[devfn])\n return NULL;\n\n d = mallocz(sizeof(PCIDevice));\n d->bus = b;\n d->name = strdup(name);\n d->devfn = devfn;\n\n put_le16(d->config + 0x00, vendor_id);\n put_le16(d->config + 0x02, device_id);\n d->config[0x08] = revision;\n put_le16(d->config + 0x0a, class_id);\n d->config[0x0e] = 0x00; /* header type */\n d->next_cap_offset = 0x40;\n \n for(i = 0; i < 4; i++)\n irq_init(&d->irq[i], pci_device_set_irq, d, i);\n b->device[devfn] = d;\n\n return d;\n}\n\nIRQSignal *pci_device_get_irq(PCIDevice *d, unsigned int irq_num)\n{\n assert(irq_num < 4);\n return &d->irq[irq_num];\n}\n\nstatic uint32_t pci_device_config_read(PCIDevice *d, uint32_t addr,\n int size_log2)\n{\n uint32_t val;\n switch(size_log2) {\n case 0:\n val = *(uint8_t *)(d->config + addr);\n break;\n case 1:\n /* Note: may be unaligned */\n if (addr <= 0xfe)\n val = get_le16(d->config + addr);\n else\n val = *(uint8_t *)(d->config + addr);\n break;\n case 2:\n /* always aligned */\n val = get_le32(d->config + addr);\n break;\n default:\n abort();\n }\n#ifdef DEBUG_CONFIG\n printf(\"pci_config_read: dev=%s addr=0x%02x val=0x%x s=%d\\n\",\n d->name, addr, val, 1 << size_log2);\n#endif\n return val;\n}\n\nPhysMemoryMap *pci_device_get_mem_map(PCIDevice *d)\n{\n return d->bus->mem_map;\n}\n\nPhysMemoryMap *pci_device_get_port_map(PCIDevice *d)\n{\n return d->bus->port_map;\n}\n\nvoid pci_register_bar(PCIDevice *d, unsigned int bar_num,\n uint32_t size, int type,\n void *opaque, PCIBarSetFunc *bar_set)\n{\n PCIIORegion *r;\n uint32_t val, config_addr;\n \n assert(bar_num < PCI_NUM_REGIONS);\n assert((size & (size - 1)) == 0); /* power of two */\n assert(size >= 4);\n r = &d->io_regions[bar_num];\n assert(r->size == 0);\n r->size = size;\n r->type = type;\n r->enabled = FALSE;\n r->opaque = opaque;\n r->bar_set = bar_set;\n /* set the config value */\n val = 0;\n if (bar_num == PCI_ROM_SLOT) {\n config_addr = 0x30;\n } else {\n val |= r->type;\n config_addr = 0x10 + 4 * bar_num;\n }\n put_le32(&d->config[config_addr], val);\n}\n\nstatic void pci_update_mappings(PCIDevice *d)\n{\n int cmd, i, offset;\n uint32_t new_addr;\n BOOL new_enabled;\n PCIIORegion *r;\n \n cmd = get_le16(&d->config[PCI_COMMAND]);\n\n for(i = 0; i < PCI_NUM_REGIONS; i++) {\n r = &d->io_regions[i];\n if (i == PCI_ROM_SLOT) {\n offset = 0x30;\n } else {\n offset = 0x10 + i * 4;\n }\n new_addr = get_le32(&d->config[offset]);\n new_enabled = FALSE;\n if (r->size != 0) {\n if ((r->type & PCI_ADDRESS_SPACE_IO) &&\n (cmd & PCI_COMMAND_IO)) {\n new_enabled = TRUE;\n } else {\n if (cmd & PCI_COMMAND_MEMORY) {\n if (i == PCI_ROM_SLOT) {\n new_enabled = (new_addr & 1);\n } else {\n new_enabled = TRUE;\n }\n }\n }\n }\n if (new_enabled) {\n /* new address */\n new_addr = get_le32(&d->config[offset]) & ~(r->size - 1);\n r->bar_set(r->opaque, i, new_addr, TRUE);\n r->enabled = TRUE;\n } else if (r->enabled) {\n r->bar_set(r->opaque, i, 0, FALSE);\n r->enabled = FALSE;\n }\n }\n}\n\n/* return != 0 if write is not handled */\nstatic int pci_write_bar(PCIDevice *d, uint32_t addr,\n uint32_t val)\n{\n PCIIORegion *r;\n int reg;\n \n if (addr == 0x30)\n reg = PCI_ROM_SLOT;\n else\n reg = (addr - 0x10) >> 2;\n // printf(\"%s: write bar addr=%x data=%x\\n\", d->name, addr, val);\n r = &d->io_regions[reg];\n if (r->size == 0)\n return -1;\n if (reg == PCI_ROM_SLOT) {\n val = val & ((~(r->size - 1)) | 1);\n } else {\n val = (val & ~(r->size - 1)) | r->type;\n }\n put_le32(d->config + addr, val);\n pci_update_mappings(d);\n return 0;\n}\n\nstatic void pci_device_config_write8(PCIDevice *d, uint32_t addr,\n uint32_t data)\n{\n int can_write;\n\n if (addr == PCI_STATUS || addr == (PCI_STATUS + 1)) {\n /* write 1 reset bits */\n d->config[addr] &= ~data;\n return;\n }\n \n switch(d->config[0x0e]) {\n case 0x00:\n case 0x80:\n switch(addr) {\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x08:\n case 0x09:\n case 0x0a:\n case 0x0b:\n case 0x0e:\n case 0x10 ... 0x27: /* base */\n case 0x30 ... 0x33: /* rom */\n case 0x3d:\n can_write = 0;\n break;\n default:\n can_write = 1;\n break;\n }\n break;\n default:\n case 0x01:\n switch(addr) {\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x08:\n case 0x09:\n case 0x0a:\n case 0x0b:\n case 0x0e:\n case 0x38 ... 0x3b: /* rom */\n case 0x3d:\n can_write = 0;\n break;\n default:\n can_write = 1;\n break;\n }\n break;\n }\n if (can_write)\n d->config[addr] = data;\n}\n \n\nstatic void pci_device_config_write(PCIDevice *d, uint32_t addr,\n uint32_t data, int size_log2)\n{\n int size, i;\n uint32_t addr1;\n \n#ifdef DEBUG_CONFIG\n printf(\"pci_config_write: dev=%s addr=0x%02x val=0x%x s=%d\\n\",\n d->name, addr, data, 1 << size_log2);\n#endif\n if (size_log2 == 2 &&\n ((addr >= 0x10 && addr < 0x10 + 4 * 6) ||\n addr == 0x30)) {\n if (pci_write_bar(d, addr, data) == 0)\n return;\n }\n size = 1 << size_log2;\n for(i = 0; i < size; i++) {\n addr1 = addr + i;\n if (addr1 <= 0xff) {\n pci_device_config_write8(d, addr1, (data >> (i * 8)) & 0xff);\n }\n }\n if (PCI_COMMAND >= addr && PCI_COMMAND < addr + size) {\n pci_update_mappings(d);\n }\n}\n\n\nstatic void pci_data_write(PCIBus *s, uint32_t addr,\n uint32_t data, int size_log2)\n{\n PCIDevice *d;\n int bus_num, devfn, config_addr;\n \n bus_num = (addr >> 16) & 0xff;\n if (bus_num != s->bus_num)\n return;\n devfn = (addr >> 8) & 0xff;\n d = s->device[devfn];\n if (!d)\n return;\n config_addr = addr & 0xff;\n pci_device_config_write(d, config_addr, data, size_log2);\n}\n\nstatic const uint32_t val_ones[3] = { 0xff, 0xffff, 0xffffffff };\n\nstatic uint32_t pci_data_read(PCIBus *s, uint32_t addr, int size_log2)\n{\n PCIDevice *d;\n int bus_num, devfn, config_addr;\n \n bus_num = (addr >> 16) & 0xff;\n if (bus_num != s->bus_num)\n return val_ones[size_log2];\n devfn = (addr >> 8) & 0xff;\n d = s->device[devfn];\n if (!d)\n return val_ones[size_log2];\n config_addr = addr & 0xff;\n return pci_device_config_read(d, config_addr, size_log2);\n}\n\n/* warning: only valid for one DEVIO page. Return NULL if no memory at\n the given address */\nuint8_t *pci_device_get_dma_ptr(PCIDevice *d, uint64_t addr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(d->bus->mem_map, addr, is_rw);\n}\n\nvoid pci_device_set_config8(PCIDevice *d, uint8_t addr, uint8_t val)\n{\n d->config[addr] = val;\n}\n\nvoid pci_device_set_config16(PCIDevice *d, uint8_t addr, uint16_t val)\n{\n put_le16(&d->config[addr], val);\n}\n\nint pci_device_get_devfn(PCIDevice *d)\n{\n return d->devfn;\n}\n\n/* return the offset of the capability or < 0 if error. */\nint pci_add_capability(PCIDevice *d, const uint8_t *buf, int size)\n{\n int offset;\n \n offset = d->next_cap_offset;\n if ((offset + size) > 256)\n return -1;\n d->next_cap_offset += size;\n d->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;\n memcpy(d->config + offset, buf, size);\n d->config[offset + 1] = d->config[PCI_CAPABILITY_LIST];\n d->config[PCI_CAPABILITY_LIST] = offset;\n return offset;\n}\n\n/* i440FX host bridge */\n\nstruct I440FXState {\n PCIBus *pci_bus;\n PCIDevice *pci_dev;\n PCIDevice *piix3_dev;\n uint32_t config_reg;\n uint8_t pic_irq_state[16];\n IRQSignal *pic_irqs; /* 16 irqs */\n};\n\nstatic void i440fx_write_addr(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n I440FXState *s = opaque;\n s->config_reg = data;\n}\n\nstatic uint32_t i440fx_read_addr(void *opaque, uint32_t offset, int size_log2)\n{\n I440FXState *s = opaque;\n return s->config_reg;\n}\n\nstatic void i440fx_write_data(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n I440FXState *s = opaque;\n if (s->config_reg & 0x80000000) {\n if (size_log2 == 2) {\n /* it is simpler to assume 32 bit config accesses are\n always aligned */\n pci_data_write(s->pci_bus, s->config_reg & ~3, data, size_log2);\n } else {\n pci_data_write(s->pci_bus, s->config_reg | offset, data, size_log2);\n }\n }\n}\n\nstatic uint32_t i440fx_read_data(void *opaque, uint32_t offset, int size_log2)\n{\n I440FXState *s = opaque;\n if (!(s->config_reg & 0x80000000))\n return val_ones[size_log2];\n if (size_log2 == 2) {\n /* it is simpler to assume 32 bit config accesses are\n always aligned */\n return pci_data_read(s->pci_bus, s->config_reg & ~3, size_log2);\n } else {\n return pci_data_read(s->pci_bus, s->config_reg | offset, size_log2);\n }\n}\n\nstatic void i440fx_set_irq(void *opaque, int irq_num, int irq_level)\n{\n I440FXState *s = opaque;\n PCIDevice *hd = s->piix3_dev;\n int pic_irq;\n \n /* map to the PIC irq (different IRQs can be mapped to the same\n PIC irq) */\n hd->config[0x60 + irq_num] &= ~0x80;\n pic_irq = hd->config[0x60 + irq_num];\n if (pic_irq < 16) {\n if (irq_level)\n s->pic_irq_state[pic_irq] |= 1 << irq_num;\n else\n s->pic_irq_state[pic_irq] &= ~(1 << irq_num);\n set_irq(&s->pic_irqs[pic_irq], (s->pic_irq_state[pic_irq] != 0));\n }\n}\n\nI440FXState *i440fx_init(PCIBus **pbus, int *ppiix3_devfn,\n PhysMemoryMap *mem_map, PhysMemoryMap *port_map,\n IRQSignal *pic_irqs)\n{\n I440FXState *s;\n PCIBus *b;\n PCIDevice *d;\n int i;\n \n s = mallocz(sizeof(*s));\n \n b = mallocz(sizeof(PCIBus));\n b->bus_num = 0;\n b->mem_map = mem_map;\n b->port_map = port_map;\n\n s->pic_irqs = pic_irqs;\n for(i = 0; i < 4; i++) {\n irq_init(&b->irq[i], i440fx_set_irq, s, i);\n }\n \n cpu_register_device(port_map, 0xcf8, 1, s, i440fx_read_addr, i440fx_write_addr, \n DEVIO_SIZE32);\n cpu_register_device(port_map, 0xcfc, 4, s, i440fx_read_data, i440fx_write_data, \n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32);\n d = pci_register_device(b, \"i440FX\", 0, 0x8086, 0x1237, 0x02, 0x0600);\n put_le16(&d->config[PCI_SUBSYSTEM_VENDOR_ID], 0x1af4); /* Red Hat, Inc. */\n put_le16(&d->config[PCI_SUBSYSTEM_ID], 0x1100); /* QEMU virtual machine */\n \n s->pci_dev = d;\n s->pci_bus = b;\n\n s->piix3_dev = pci_register_device(b, \"PIIX3\", 8, 0x8086, 0x7000,\n 0x00, 0x0601);\n pci_device_set_config8(s->piix3_dev, 0x0e, 0x80); /* header type */\n\n *pbus = b;\n *ppiix3_devfn = s->piix3_dev->devfn;\n return s;\n}\n\n/* in case no BIOS is used, map the interrupts. */\nvoid i440fx_map_interrupts(I440FXState *s, uint8_t *elcr,\n const uint8_t *pci_irqs)\n{\n PCIBus *b = s->pci_bus;\n PCIDevice *d, *hd;\n int irq_num, pic_irq, devfn, i;\n \n /* set a default PCI IRQ mapping to PIC IRQs */\n hd = s->piix3_dev;\n\n elcr[0] = 0;\n elcr[1] = 0;\n for(i = 0; i < 4; i++) {\n irq_num = pci_irqs[i];\n hd->config[0x60 + i] = irq_num;\n elcr[irq_num >> 3] |= (1 << (irq_num & 7));\n }\n\n for(devfn = 0; devfn < 256; devfn++) {\n d = b->device[devfn];\n if (!d)\n continue;\n if (d->config[PCI_INTERRUPT_PIN]) {\n irq_num = 0;\n irq_num = bus_map_irq(d, irq_num);\n pic_irq = hd->config[0x60 + irq_num];\n if (pic_irq < 16) {\n d->config[PCI_INTERRUPT_LINE] = pic_irq;\n }\n }\n }\n}\n"], ["/linuxpdf/tinyemu/slirp/socket.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\nstatic void sofcantrcvmore(struct socket *so);\nstatic void sofcantsendmore(struct socket *so);\n\nstruct socket *\nsolookup(struct socket *head, struct in_addr laddr, u_int lport,\n struct in_addr faddr, u_int fport)\n{\n\tstruct socket *so;\n\n\tfor (so = head->so_next; so != head; so = so->so_next) {\n\t\tif (so->so_lport == lport &&\n\t\t so->so_laddr.s_addr == laddr.s_addr &&\n\t\t so->so_faddr.s_addr == faddr.s_addr &&\n\t\t so->so_fport == fport)\n\t\t break;\n\t}\n\n\tif (so == head)\n\t return (struct socket *)NULL;\n\treturn so;\n\n}\n\n/*\n * Create a new socket, initialise the fields\n * It is the responsibility of the caller to\n * insque() it into the correct linked-list\n */\nstruct socket *\nsocreate(Slirp *slirp)\n{\n struct socket *so;\n\n so = (struct socket *)malloc(sizeof(struct socket));\n if(so) {\n memset(so, 0, sizeof(struct socket));\n so->so_state = SS_NOFDREF;\n so->s = -1;\n so->slirp = slirp;\n }\n return(so);\n}\n\n/*\n * remque and free a socket, clobber cache\n */\nvoid\nsofree(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n\n if (so->so_emu==EMU_RSH && so->extra) {\n\tsofree(so->extra);\n\tso->extra=NULL;\n }\n if (so == slirp->tcp_last_so) {\n slirp->tcp_last_so = &slirp->tcb;\n } else if (so == slirp->udp_last_so) {\n slirp->udp_last_so = &slirp->udb;\n }\n m_free(so->so_m);\n\n if(so->so_next && so->so_prev)\n remque(so); /* crashes if so is not in a queue */\n\n free(so);\n}\n\nsize_t sopreprbuf(struct socket *so, struct iovec *iov, int *np)\n{\n\tint n, lss, total;\n\tstruct sbuf *sb = &so->so_snd;\n\tint len = sb->sb_datalen - sb->sb_cc;\n\tint mss = so->so_tcpcb->t_maxseg;\n\n\tDEBUG_CALL(\"sopreprbuf\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\tif (len <= 0)\n\t\treturn 0;\n\n\tiov[0].iov_base = sb->sb_wptr;\n iov[1].iov_base = NULL;\n iov[1].iov_len = 0;\n\tif (sb->sb_wptr < sb->sb_rptr) {\n\t\tiov[0].iov_len = sb->sb_rptr - sb->sb_wptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len)\n\t\t iov[0].iov_len = len;\n\t\tif (iov[0].iov_len > mss)\n\t\t iov[0].iov_len -= iov[0].iov_len%mss;\n\t\tn = 1;\n\t} else {\n\t\tiov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_wptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tlen -= iov[0].iov_len;\n\t\tif (len) {\n\t\t\tiov[1].iov_base = sb->sb_data;\n\t\t\tiov[1].iov_len = sb->sb_rptr - sb->sb_data;\n\t\t\tif(iov[1].iov_len > len)\n\t\t\t iov[1].iov_len = len;\n\t\t\ttotal = iov[0].iov_len + iov[1].iov_len;\n\t\t\tif (total > mss) {\n\t\t\t\tlss = total%mss;\n\t\t\t\tif (iov[1].iov_len > lss) {\n\t\t\t\t\tiov[1].iov_len -= lss;\n\t\t\t\t\tn = 2;\n\t\t\t\t} else {\n\t\t\t\t\tlss -= iov[1].iov_len;\n\t\t\t\t\tiov[0].iov_len -= lss;\n\t\t\t\t\tn = 1;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tn = 2;\n\t\t} else {\n\t\t\tif (iov[0].iov_len > mss)\n\t\t\t iov[0].iov_len -= iov[0].iov_len%mss;\n\t\t\tn = 1;\n\t\t}\n\t}\n\tif (np)\n\t\t*np = n;\n\n\treturn iov[0].iov_len + (n - 1) * iov[1].iov_len;\n}\n\n/*\n * Read from so's socket into sb_snd, updating all relevant sbuf fields\n * NOTE: This will only be called if it is select()ed for reading, so\n * a read() of 0 (or less) means it's disconnected\n */\nint\nsoread(struct socket *so)\n{\n\tint n, nn;\n\tstruct sbuf *sb = &so->so_snd;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"soread\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\t/*\n\t * No need to check if there's enough room to read.\n\t * soread wouldn't have been called if there weren't\n\t */\n\tsopreprbuf(so, iov, &n);\n\n#ifdef HAVE_READV\n\tnn = readv(so->s, (struct iovec *)iov, n);\n\tDEBUG_MISC((dfd, \" ... read nn = %d bytes\\n\", nn));\n#else\n\tnn = recv(so->s, iov[0].iov_base, iov[0].iov_len,0);\n#endif\n\tif (nn <= 0) {\n\t\tif (nn < 0 && (errno == EINTR || errno == EAGAIN))\n\t\t\treturn 0;\n\t\telse {\n\t\t\tDEBUG_MISC((dfd, \" --- soread() disconnected, nn = %d, errno = %d-%s\\n\", nn, errno,strerror(errno)));\n\t\t\tsofcantrcvmore(so);\n\t\t\ttcp_sockclosed(sototcpcb(so));\n\t\t\treturn -1;\n\t\t}\n\t}\n\n#ifndef HAVE_READV\n\t/*\n\t * If there was no error, try and read the second time round\n\t * We read again if n = 2 (ie, there's another part of the buffer)\n\t * and we read as much as we could in the first read\n\t * We don't test for <= 0 this time, because there legitimately\n\t * might not be any more data (since the socket is non-blocking),\n\t * a close will be detected on next iteration.\n\t * A return of -1 wont (shouldn't) happen, since it didn't happen above\n\t */\n\tif (n == 2 && nn == iov[0].iov_len) {\n int ret;\n ret = recv(so->s, iov[1].iov_base, iov[1].iov_len,0);\n if (ret > 0)\n nn += ret;\n }\n\n\tDEBUG_MISC((dfd, \" ... read nn = %d bytes\\n\", nn));\n#endif\n\n\t/* Update fields */\n\tsb->sb_cc += nn;\n\tsb->sb_wptr += nn;\n\tif (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_wptr -= sb->sb_datalen;\n\treturn nn;\n}\n\nint soreadbuf(struct socket *so, const char *buf, int size)\n{\n int n, nn, copy = size;\n\tstruct sbuf *sb = &so->so_snd;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"soreadbuf\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\t/*\n\t * No need to check if there's enough room to read.\n\t * soread wouldn't have been called if there weren't\n\t */\n\tif (sopreprbuf(so, iov, &n) < size)\n goto err;\n\n nn = min(iov[0].iov_len, copy);\n memcpy(iov[0].iov_base, buf, nn);\n\n copy -= nn;\n buf += nn;\n\n if (copy == 0)\n goto done;\n\n memcpy(iov[1].iov_base, buf, copy);\n\ndone:\n /* Update fields */\n\tsb->sb_cc += size;\n\tsb->sb_wptr += size;\n\tif (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_wptr -= sb->sb_datalen;\n return size;\nerr:\n\n sofcantrcvmore(so);\n tcp_sockclosed(sototcpcb(so));\n fprintf(stderr, \"soreadbuf buffer to small\");\n return -1;\n}\n\n/*\n * Get urgent data\n *\n * When the socket is created, we set it SO_OOBINLINE,\n * so when OOB data arrives, we soread() it and everything\n * in the send buffer is sent as urgent data\n */\nvoid\nsorecvoob(struct socket *so)\n{\n\tstruct tcpcb *tp = sototcpcb(so);\n\n\tDEBUG_CALL(\"sorecvoob\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\t/*\n\t * We take a guess at how much urgent data has arrived.\n\t * In most situations, when urgent data arrives, the next\n\t * read() should get all the urgent data. This guess will\n\t * be wrong however if more data arrives just after the\n\t * urgent data, or the read() doesn't return all the\n\t * urgent data.\n\t */\n\tsoread(so);\n\ttp->snd_up = tp->snd_una + so->so_snd.sb_cc;\n\ttp->t_force = 1;\n\ttcp_output(tp);\n\ttp->t_force = 0;\n}\n\n/*\n * Send urgent data\n * There's a lot duplicated code here, but...\n */\nint\nsosendoob(struct socket *so)\n{\n\tstruct sbuf *sb = &so->so_rcv;\n\tchar buff[2048]; /* XXX Shouldn't be sending more oob data than this */\n\n\tint n, len;\n\n\tDEBUG_CALL(\"sosendoob\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"sb->sb_cc = %d\", sb->sb_cc);\n\n\tif (so->so_urgc > 2048)\n\t so->so_urgc = 2048; /* XXXX */\n\n\tif (sb->sb_rptr < sb->sb_wptr) {\n\t\t/* We can send it directly */\n\t\tn = slirp_send(so, sb->sb_rptr, so->so_urgc, (MSG_OOB)); /* |MSG_DONTWAIT)); */\n\t\tso->so_urgc -= n;\n\n\t\tDEBUG_MISC((dfd, \" --- sent %d bytes urgent data, %d urgent bytes left\\n\", n, so->so_urgc));\n\t} else {\n\t\t/*\n\t\t * Since there's no sendv or sendtov like writev,\n\t\t * we must copy all data to a linear buffer then\n\t\t * send it all\n\t\t */\n\t\tlen = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;\n\t\tif (len > so->so_urgc) len = so->so_urgc;\n\t\tmemcpy(buff, sb->sb_rptr, len);\n\t\tso->so_urgc -= len;\n\t\tif (so->so_urgc) {\n\t\t\tn = sb->sb_wptr - sb->sb_data;\n\t\t\tif (n > so->so_urgc) n = so->so_urgc;\n\t\t\tmemcpy((buff + len), sb->sb_data, n);\n\t\t\tso->so_urgc -= n;\n\t\t\tlen += n;\n\t\t}\n\t\tn = slirp_send(so, buff, len, (MSG_OOB)); /* |MSG_DONTWAIT)); */\n#ifdef DEBUG\n\t\tif (n != len)\n\t\t DEBUG_ERROR((dfd, \"Didn't send all data urgently XXXXX\\n\"));\n#endif\n\t\tDEBUG_MISC((dfd, \" ---2 sent %d bytes urgent data, %d urgent bytes left\\n\", n, so->so_urgc));\n\t}\n\n\tsb->sb_cc -= n;\n\tsb->sb_rptr += n;\n\tif (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n\treturn n;\n}\n\n/*\n * Write data from so_rcv to so's socket,\n * updating all sbuf field as necessary\n */\nint\nsowrite(struct socket *so)\n{\n\tint n,nn;\n\tstruct sbuf *sb = &so->so_rcv;\n\tint len = sb->sb_cc;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"sowrite\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\tif (so->so_urgc) {\n\t\tsosendoob(so);\n\t\tif (sb->sb_cc == 0)\n\t\t\treturn 0;\n\t}\n\n\t/*\n\t * No need to check if there's something to write,\n\t * sowrite wouldn't have been called otherwise\n\t */\n\n\tiov[0].iov_base = sb->sb_rptr;\n iov[1].iov_base = NULL;\n iov[1].iov_len = 0;\n\tif (sb->sb_rptr < sb->sb_wptr) {\n\t\tiov[0].iov_len = sb->sb_wptr - sb->sb_rptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tn = 1;\n\t} else {\n\t\tiov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tlen -= iov[0].iov_len;\n\t\tif (len) {\n\t\t\tiov[1].iov_base = sb->sb_data;\n\t\t\tiov[1].iov_len = sb->sb_wptr - sb->sb_data;\n\t\t\tif (iov[1].iov_len > len) iov[1].iov_len = len;\n\t\t\tn = 2;\n\t\t} else\n\t\t\tn = 1;\n\t}\n\t/* Check if there's urgent data to send, and if so, send it */\n\n#ifdef HAVE_READV\n\tnn = writev(so->s, (const struct iovec *)iov, n);\n\n\tDEBUG_MISC((dfd, \" ... wrote nn = %d bytes\\n\", nn));\n#else\n\tnn = slirp_send(so, iov[0].iov_base, iov[0].iov_len,0);\n#endif\n\t/* This should never happen, but people tell me it does *shrug* */\n\tif (nn < 0 && (errno == EAGAIN || errno == EINTR))\n\t\treturn 0;\n\n\tif (nn <= 0) {\n\t\tDEBUG_MISC((dfd, \" --- sowrite disconnected, so->so_state = %x, errno = %d\\n\",\n\t\t\tso->so_state, errno));\n\t\tsofcantsendmore(so);\n\t\ttcp_sockclosed(sototcpcb(so));\n\t\treturn -1;\n\t}\n\n#ifndef HAVE_READV\n\tif (n == 2 && nn == iov[0].iov_len) {\n int ret;\n ret = slirp_send(so, iov[1].iov_base, iov[1].iov_len,0);\n if (ret > 0)\n nn += ret;\n }\n DEBUG_MISC((dfd, \" ... wrote nn = %d bytes\\n\", nn));\n#endif\n\n\t/* Update sbuf */\n\tsb->sb_cc -= nn;\n\tsb->sb_rptr += nn;\n\tif (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n\t/*\n\t * If in DRAIN mode, and there's no more data, set\n\t * it CANTSENDMORE\n\t */\n\tif ((so->so_state & SS_FWDRAIN) && sb->sb_cc == 0)\n\t\tsofcantsendmore(so);\n\n\treturn nn;\n}\n\n/*\n * recvfrom() a UDP socket\n */\nvoid\nsorecvfrom(struct socket *so)\n{\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\n\tDEBUG_CALL(\"sorecvfrom\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\tif (so->so_type == IPPROTO_ICMP) { /* This is a \"ping\" reply */\n\t char buff[256];\n\t int len;\n\n\t len = recvfrom(so->s, buff, 256, 0,\n\t\t\t (struct sockaddr *)&addr, &addrlen);\n\t /* XXX Check if reply is \"correct\"? */\n\n\t if(len == -1 || len == 0) {\n\t u_char code=ICMP_UNREACH_PORT;\n\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;\n\n\t DEBUG_MISC((dfd,\" udp icmp rx errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));\n\t } else {\n\t icmp_reflect(so->so_m);\n so->so_m = NULL; /* Don't m_free() it again! */\n\t }\n\t /* No need for this socket anymore, udp_detach it */\n\t udp_detach(so);\n\t} else { \t/* A \"normal\" UDP packet */\n\t struct mbuf *m;\n int len;\n#ifdef _WIN32\n unsigned long n;\n#else\n int n;\n#endif\n\n\t m = m_get(so->slirp);\n\t if (!m) {\n\t return;\n\t }\n\t m->m_data += IF_MAXLINKHDR;\n\n\t /*\n\t * XXX Shouldn't FIONREAD packets destined for port 53,\n\t * but I don't know the max packet size for DNS lookups\n\t */\n\t len = M_FREEROOM(m);\n\t /* if (so->so_fport != htons(53)) { */\n\t ioctlsocket(so->s, FIONREAD, &n);\n\n\t if (n > len) {\n\t n = (m->m_data - m->m_dat) + m->m_len + n + 1;\n\t m_inc(m, n);\n\t len = M_FREEROOM(m);\n\t }\n\t /* } */\n\n\t m->m_len = recvfrom(so->s, m->m_data, len, 0,\n\t\t\t (struct sockaddr *)&addr, &addrlen);\n\t DEBUG_MISC((dfd, \" did recvfrom %d, errno = %d-%s\\n\",\n\t\t m->m_len, errno,strerror(errno)));\n\t if(m->m_len<0) {\n\t u_char code=ICMP_UNREACH_PORT;\n\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;\n\n\t DEBUG_MISC((dfd,\" rx error, tx icmp ICMP_UNREACH:%i\\n\", code));\n\t icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));\n\t m_free(m);\n\t } else {\n\t /*\n\t * Hack: domain name lookup will be used the most for UDP,\n\t * and since they'll only be used once there's no need\n\t * for the 4 minute (or whatever) timeout... So we time them\n\t * out much quicker (10 seconds for now...)\n\t */\n\t if (so->so_expire) {\n\t if (so->so_fport == htons(53))\n\t\tso->so_expire = curtime + SO_EXPIREFAST;\n\t else\n\t\tso->so_expire = curtime + SO_EXPIRE;\n\t }\n\n\t /*\n\t * If this packet was destined for CTL_ADDR,\n\t * make it look like that's where it came from, done by udp_output\n\t */\n\t udp_output(so, m, &addr);\n\t } /* rx error */\n\t} /* if ping packet */\n}\n\n/*\n * sendto() a socket\n */\nint\nsosendto(struct socket *so, struct mbuf *m)\n{\n\tSlirp *slirp = so->slirp;\n\tint ret;\n\tstruct sockaddr_in addr;\n\n\tDEBUG_CALL(\"sosendto\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n addr.sin_family = AF_INET;\n\tif ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n\t slirp->vnetwork_addr.s_addr) {\n\t /* It's an alias */\n\t if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\t if (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n\t } else {\n\t addr.sin_addr = loopback_addr;\n\t }\n\t} else\n\t addr.sin_addr = so->so_faddr;\n\taddr.sin_port = so->so_fport;\n\n\tDEBUG_MISC((dfd, \" sendto()ing, addr.sin_port=%d, addr.sin_addr.s_addr=%.16s\\n\", ntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));\n\n\t/* Don't care what port we get */\n\tret = sendto(so->s, m->m_data, m->m_len, 0,\n\t\t (struct sockaddr *)&addr, sizeof (struct sockaddr));\n\tif (ret < 0)\n\t\treturn -1;\n\n\t/*\n\t * Kill the socket if there's no reply in 4 minutes,\n\t * but only if it's an expirable socket\n\t */\n\tif (so->so_expire)\n\t\tso->so_expire = curtime + SO_EXPIRE;\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= SS_ISFCONNECTED; /* So that it gets select()ed */\n\treturn 0;\n}\n\n/*\n * Listen for incoming TCP connections\n */\nstruct socket *\ntcp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,\n u_int lport, int flags)\n{\n\tstruct sockaddr_in addr;\n\tstruct socket *so;\n\tint s, opt = 1;\n\tsocklen_t addrlen = sizeof(addr);\n\tmemset(&addr, 0, addrlen);\n\n\tDEBUG_CALL(\"tcp_listen\");\n\tDEBUG_ARG(\"haddr = %x\", haddr);\n\tDEBUG_ARG(\"hport = %d\", hport);\n\tDEBUG_ARG(\"laddr = %x\", laddr);\n\tDEBUG_ARG(\"lport = %d\", lport);\n\tDEBUG_ARG(\"flags = %x\", flags);\n\n\tso = socreate(slirp);\n\tif (!so) {\n\t return NULL;\n\t}\n\n\t/* Don't tcp_attach... we don't need so_snd nor so_rcv */\n\tif ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL) {\n\t\tfree(so);\n\t\treturn NULL;\n\t}\n\tinsque(so, &slirp->tcb);\n\n\t/*\n\t * SS_FACCEPTONCE sockets must time out.\n\t */\n\tif (flags & SS_FACCEPTONCE)\n\t so->so_tcpcb->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT*2;\n\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= (SS_FACCEPTCONN | flags);\n\tso->so_lport = lport; /* Kept in network format */\n\tso->so_laddr.s_addr = laddr; /* Ditto */\n\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = haddr;\n\taddr.sin_port = hport;\n\n\tif (((s = os_socket(AF_INET,SOCK_STREAM,0)) < 0) ||\n\t (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int)) < 0) ||\n\t (bind(s,(struct sockaddr *)&addr, sizeof(addr)) < 0) ||\n\t (listen(s,1) < 0)) {\n\t\tint tmperrno = errno; /* Don't clobber the real reason we failed */\n\n\t\tclose(s);\n\t\tsofree(so);\n\t\t/* Restore the real errno */\n#ifdef _WIN32\n\t\tWSASetLastError(tmperrno);\n#else\n\t\terrno = tmperrno;\n#endif\n\t\treturn NULL;\n\t}\n\tsetsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\n\tgetsockname(s,(struct sockaddr *)&addr,&addrlen);\n\tso->so_fport = addr.sin_port;\n\tif (addr.sin_addr.s_addr == 0 || addr.sin_addr.s_addr == loopback_addr.s_addr)\n\t so->so_faddr = slirp->vhost_addr;\n\telse\n\t so->so_faddr = addr.sin_addr;\n\n\tso->s = s;\n\treturn so;\n}\n\n/*\n * Various session state calls\n * XXX Should be #define's\n * The socket state stuff needs work, these often get call 2 or 3\n * times each when only 1 was needed\n */\nvoid\nsoisfconnecting(struct socket *so)\n{\n\tso->so_state &= ~(SS_NOFDREF|SS_ISFCONNECTED|SS_FCANTRCVMORE|\n\t\t\t SS_FCANTSENDMORE|SS_FWDRAIN);\n\tso->so_state |= SS_ISFCONNECTING; /* Clobber other states */\n}\n\nvoid\nsoisfconnected(struct socket *so)\n{\n\tso->so_state &= ~(SS_ISFCONNECTING|SS_FWDRAIN|SS_NOFDREF);\n\tso->so_state |= SS_ISFCONNECTED; /* Clobber other states */\n}\n\nstatic void\nsofcantrcvmore(struct socket *so)\n{\n\tif ((so->so_state & SS_NOFDREF) == 0) {\n\t\tshutdown(so->s,0);\n\t\tif(global_writefds) {\n\t\t FD_CLR(so->s,global_writefds);\n\t\t}\n\t}\n\tso->so_state &= ~(SS_ISFCONNECTING);\n\tif (so->so_state & SS_FCANTSENDMORE) {\n\t so->so_state &= SS_PERSISTENT_MASK;\n\t so->so_state |= SS_NOFDREF; /* Don't select it */\n\t} else {\n\t so->so_state |= SS_FCANTRCVMORE;\n\t}\n}\n\nstatic void\nsofcantsendmore(struct socket *so)\n{\n\tif ((so->so_state & SS_NOFDREF) == 0) {\n shutdown(so->s,1); /* send FIN to fhost */\n if (global_readfds) {\n FD_CLR(so->s,global_readfds);\n }\n if (global_xfds) {\n FD_CLR(so->s,global_xfds);\n }\n\t}\n\tso->so_state &= ~(SS_ISFCONNECTING);\n\tif (so->so_state & SS_FCANTRCVMORE) {\n\t so->so_state &= SS_PERSISTENT_MASK;\n\t so->so_state |= SS_NOFDREF; /* as above */\n\t} else {\n\t so->so_state |= SS_FCANTSENDMORE;\n\t}\n}\n\n/*\n * Set write drain mode\n * Set CANTSENDMORE once all data has been write()n\n */\nvoid\nsofwdrain(struct socket *so)\n{\n\tif (so->so_rcv.sb_cc)\n\t\tso->so_state |= SS_FWDRAIN;\n\telse\n\t\tsofcantsendmore(so);\n}\n"], ["/linuxpdf/tinyemu/fs_disk.c", "/*\n * Filesystem on disk\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n\ntypedef struct {\n FSDevice common;\n char *root_path;\n} FSDeviceDisk;\n\nstatic void fs_close(FSDevice *fs, FSFile *f);\n\nstruct FSFile {\n uint32_t uid;\n char *path; /* complete path */\n BOOL is_opened;\n BOOL is_dir;\n union {\n int fd;\n DIR *dirp;\n } u;\n};\n\nstatic void fs_delete(FSDevice *fs, FSFile *f)\n{\n if (f->is_opened)\n fs_close(fs, f);\n free(f->path);\n free(f);\n}\n\n/* warning: path belong to fid_create() */\nstatic FSFile *fid_create(FSDevice *s1, char *path, uint32_t uid)\n{\n FSFile *f;\n f = mallocz(sizeof(*f));\n f->path = path;\n f->uid = uid;\n return f;\n}\n\n\nstatic int errno_table[][2] = {\n { P9_EPERM, EPERM },\n { P9_ENOENT, ENOENT },\n { P9_EIO, EIO },\n { P9_EEXIST, EEXIST },\n { P9_EINVAL, EINVAL },\n { P9_ENOSPC, ENOSPC },\n { P9_ENOTEMPTY, ENOTEMPTY },\n { P9_EPROTO, EPROTO },\n { P9_ENOTSUP, ENOTSUP },\n};\n\nstatic int errno_to_p9(int err)\n{\n int i;\n if (err == 0)\n return 0;\n for(i = 0; i < countof(errno_table); i++) {\n if (err == errno_table[i][1])\n return errno_table[i][0];\n }\n return P9_EINVAL;\n}\n\nstatic int open_flags[][2] = {\n { P9_O_CREAT, O_CREAT },\n { P9_O_EXCL, O_EXCL },\n // { P9_O_NOCTTY, O_NOCTTY },\n { P9_O_TRUNC, O_TRUNC },\n { P9_O_APPEND, O_APPEND },\n { P9_O_NONBLOCK, O_NONBLOCK },\n { P9_O_DSYNC, O_DSYNC },\n // { P9_O_FASYNC, O_FASYNC },\n // { P9_O_DIRECT, O_DIRECT },\n // { P9_O_LARGEFILE, O_LARGEFILE },\n // { P9_O_DIRECTORY, O_DIRECTORY },\n { P9_O_NOFOLLOW, O_NOFOLLOW },\n // { P9_O_NOATIME, O_NOATIME },\n // { P9_O_CLOEXEC, O_CLOEXEC },\n { P9_O_SYNC, O_SYNC },\n};\n\nstatic int p9_flags_to_host(int flags)\n{\n int ret, i;\n\n ret = (flags & P9_O_NOACCESS);\n for(i = 0; i < countof(open_flags); i++) {\n if (flags & open_flags[i][0])\n ret |= open_flags[i][1];\n }\n return ret;\n}\n\nstatic void stat_to_qid(FSQID *qid, const struct stat *st)\n{\n if (S_ISDIR(st->st_mode))\n qid->type = P9_QTDIR;\n else if (S_ISLNK(st->st_mode))\n qid->type = P9_QTSYMLINK;\n else\n qid->type = P9_QTFILE;\n qid->version = 0; /* no caching on client */\n qid->path = st->st_ino;\n}\n\nstatic void fs_statfs(FSDevice *fs1, FSStatFS *st)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n struct statfs st1;\n statfs(fs->root_path, &st1);\n st->f_bsize = st1.f_bsize;\n st->f_blocks = st1.f_blocks;\n st->f_bfree = st1.f_bfree;\n st->f_bavail = st1.f_bavail;\n st->f_files = st1.f_files;\n st->f_ffree = st1.f_ffree;\n}\n\nstatic char *compose_path(const char *path, const char *name)\n{\n int path_len, name_len;\n char *d;\n\n path_len = strlen(path);\n name_len = strlen(name);\n d = malloc(path_len + 1 + name_len + 1);\n memcpy(d, path, path_len);\n d[path_len] = '/';\n memcpy(d + path_len + 1, name, name_len + 1);\n return d;\n}\n\nstatic int fs_attach(FSDevice *fs1, FSFile **pf,\n FSQID *qid, uint32_t uid,\n const char *uname, const char *aname)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n struct stat st;\n FSFile *f;\n \n if (lstat(fs->root_path, &st) != 0) {\n *pf = NULL;\n return -errno_to_p9(errno);\n }\n f = fid_create(fs1, strdup(fs->root_path), uid);\n stat_to_qid(qid, &st);\n *pf = f;\n return 0;\n}\n\nstatic int fs_walk(FSDevice *fs, FSFile **pf, FSQID *qids,\n FSFile *f, int n, char **names)\n{\n char *path, *path1;\n struct stat st;\n int i;\n\n path = strdup(f->path);\n for(i = 0; i < n; i++) {\n path1 = compose_path(path, names[i]);\n if (lstat(path1, &st) != 0) {\n free(path1);\n break;\n }\n free(path);\n path = path1;\n stat_to_qid(&qids[i], &st);\n }\n *pf = fid_create(fs, path, f->uid);\n return i;\n}\n\n\nstatic int fs_mkdir(FSDevice *fs, FSQID *qid, FSFile *f,\n const char *name, uint32_t mode, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (mkdir(path, mode) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_open(FSDevice *fs, FSQID *qid, FSFile *f, uint32_t flags,\n FSOpenCompletionFunc *cb, void *opaque)\n{\n struct stat st;\n fs_close(fs, f);\n\n if (stat(f->path, &st) != 0) \n return -errno_to_p9(errno);\n stat_to_qid(qid, &st);\n \n if (flags & P9_O_DIRECTORY) {\n DIR *dirp;\n dirp = opendir(f->path);\n if (!dirp)\n return -errno_to_p9(errno);\n f->is_opened = TRUE;\n f->is_dir = TRUE;\n f->u.dirp = dirp;\n } else {\n int fd;\n fd = open(f->path, p9_flags_to_host(flags) & ~O_CREAT);\n if (fd < 0)\n return -errno_to_p9(errno);\n f->is_opened = TRUE;\n f->is_dir = FALSE;\n f->u.fd = fd;\n }\n return 0;\n}\n\nstatic int fs_create(FSDevice *fs, FSQID *qid, FSFile *f, const char *name, \n uint32_t flags, uint32_t mode, uint32_t gid)\n{\n struct stat st;\n char *path;\n int ret, fd;\n\n fs_close(fs, f);\n \n path = compose_path(f->path, name);\n fd = open(path, p9_flags_to_host(flags) | O_CREAT, mode);\n if (fd < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n ret = lstat(path, &st);\n if (ret != 0) {\n free(path);\n close(fd);\n return -errno_to_p9(errno);\n }\n free(f->path);\n f->path = path;\n f->is_opened = TRUE;\n f->is_dir = FALSE;\n f->u.fd = fd;\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_readdir(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n struct dirent *de;\n int len, pos, name_len, type, d_type;\n\n if (!f->is_opened || !f->is_dir)\n return -P9_EPROTO;\n if (offset == 0)\n rewinddir(f->u.dirp);\n else\n seekdir(f->u.dirp, offset);\n pos = 0;\n for(;;) {\n de = readdir(f->u.dirp);\n if (de == NULL)\n break;\n name_len = strlen(de->d_name);\n len = 13 + 8 + 1 + 2 + name_len;\n if ((pos + len) > count)\n break;\n offset = telldir(f->u.dirp);\n d_type = de->d_type;\n if (d_type == DT_UNKNOWN) {\n char *path;\n struct stat st;\n path = compose_path(f->path, de->d_name);\n if (lstat(path, &st) == 0) {\n d_type = st.st_mode >> 12;\n } else {\n d_type = DT_REG; /* default */\n }\n free(path);\n }\n if (d_type == DT_DIR)\n type = P9_QTDIR;\n else if (d_type == DT_LNK)\n type = P9_QTSYMLINK;\n else\n type = P9_QTFILE;\n buf[pos++] = type;\n put_le32(buf + pos, 0); /* version */\n pos += 4;\n put_le64(buf + pos, de->d_ino);\n pos += 8;\n put_le64(buf + pos, offset);\n pos += 8;\n buf[pos++] = d_type;\n put_le16(buf + pos, name_len);\n pos += 2;\n memcpy(buf + pos, de->d_name, name_len);\n pos += name_len;\n }\n return pos;\n}\n\nstatic int fs_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n int ret;\n\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n ret = pread(f->u.fd, buf, count, offset);\n if (ret < 0) \n return -errno_to_p9(errno);\n else\n return ret;\n}\n\nstatic int fs_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int count)\n{\n int ret;\n\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n ret = pwrite(f->u.fd, buf, count, offset);\n if (ret < 0) \n return -errno_to_p9(errno);\n else\n return ret;\n}\n\nstatic void fs_close(FSDevice *fs, FSFile *f)\n{\n if (!f->is_opened)\n return;\n if (f->is_dir)\n closedir(f->u.dirp);\n else\n close(f->u.fd);\n f->is_opened = FALSE;\n}\n\nstatic int fs_stat(FSDevice *fs, FSFile *f, FSStat *st)\n{\n struct stat st1;\n\n if (lstat(f->path, &st1) != 0)\n return -P9_ENOENT;\n stat_to_qid(&st->qid, &st1);\n st->st_mode = st1.st_mode;\n st->st_uid = st1.st_uid;\n st->st_gid = st1.st_gid;\n st->st_nlink = st1.st_nlink;\n st->st_rdev = st1.st_rdev;\n st->st_size = st1.st_size;\n st->st_blksize = st1.st_blksize;\n st->st_blocks = st1.st_blocks;\n st->st_atime_sec = st1.st_atim.tv_sec;\n st->st_atime_nsec = st1.st_atim.tv_nsec;\n st->st_mtime_sec = st1.st_mtim.tv_sec;\n st->st_mtime_nsec = st1.st_mtim.tv_nsec;\n st->st_ctime_sec = st1.st_ctim.tv_sec;\n st->st_ctime_nsec = st1.st_ctim.tv_nsec;\n return 0;\n}\n\nstatic int fs_setattr(FSDevice *fs, FSFile *f, uint32_t mask,\n uint32_t mode, uint32_t uid, uint32_t gid,\n uint64_t size, uint64_t atime_sec, uint64_t atime_nsec,\n uint64_t mtime_sec, uint64_t mtime_nsec)\n{\n BOOL ctime_updated = FALSE;\n\n if (mask & (P9_SETATTR_UID | P9_SETATTR_GID)) {\n if (lchown(f->path, (mask & P9_SETATTR_UID) ? uid : -1,\n (mask & P9_SETATTR_GID) ? gid : -1) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n /* must be done after uid change for suid */\n if (mask & P9_SETATTR_MODE) {\n if (chmod(f->path, mode) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if (mask & P9_SETATTR_SIZE) {\n if (truncate(f->path, size) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if (mask & (P9_SETATTR_ATIME | P9_SETATTR_MTIME)) {\n struct timespec ts[2];\n if (mask & P9_SETATTR_ATIME) {\n if (mask & P9_SETATTR_ATIME_SET) {\n ts[0].tv_sec = atime_sec;\n ts[0].tv_nsec = atime_nsec;\n } else {\n ts[0].tv_sec = 0;\n ts[0].tv_nsec = UTIME_NOW;\n }\n } else {\n ts[0].tv_sec = 0;\n ts[0].tv_nsec = UTIME_OMIT;\n }\n if (mask & P9_SETATTR_MTIME) {\n if (mask & P9_SETATTR_MTIME_SET) {\n ts[1].tv_sec = mtime_sec;\n ts[1].tv_nsec = mtime_nsec;\n } else {\n ts[1].tv_sec = 0;\n ts[1].tv_nsec = UTIME_NOW;\n }\n } else {\n ts[1].tv_sec = 0;\n ts[1].tv_nsec = UTIME_OMIT;\n }\n if (utimensat(AT_FDCWD, f->path, ts, AT_SYMLINK_NOFOLLOW) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if ((mask & P9_SETATTR_CTIME) && !ctime_updated) {\n if (lchown(f->path, -1, -1) < 0)\n return -errno_to_p9(errno);\n }\n return 0;\n}\n\nstatic int fs_link(FSDevice *fs, FSFile *df, FSFile *f, const char *name)\n{\n char *path;\n \n path = compose_path(df->path, name);\n if (link(f->path, path) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n return 0;\n}\n\nstatic int fs_symlink(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, const char *symgt, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (symlink(symgt, path) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_mknod(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, uint32_t mode, uint32_t major,\n uint32_t minor, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (mknod(path, mode, makedev(major, minor)) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_readlink(FSDevice *fs, char *buf, int buf_size, FSFile *f)\n{\n int ret;\n ret = readlink(f->path, buf, buf_size - 1);\n if (ret < 0)\n return -errno_to_p9(errno);\n buf[ret] = '\\0';\n return 0;\n}\n\nstatic int fs_renameat(FSDevice *fs, FSFile *f, const char *name, \n FSFile *new_f, const char *new_name)\n{\n char *path, *new_path;\n int ret;\n\n path = compose_path(f->path, name);\n new_path = compose_path(new_f->path, new_name);\n ret = rename(path, new_path);\n free(path);\n free(new_path);\n if (ret < 0)\n return -errno_to_p9(errno);\n return 0;\n}\n\nstatic int fs_unlinkat(FSDevice *fs, FSFile *f, const char *name)\n{\n char *path;\n int ret;\n\n path = compose_path(f->path, name);\n ret = remove(path);\n free(path);\n if (ret < 0)\n return -errno_to_p9(errno);\n return 0;\n \n}\n\nstatic int fs_lock(FSDevice *fs, FSFile *f, const FSLock *lock)\n{\n int ret;\n struct flock fl;\n \n /* XXX: lock directories too */\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n\n fl.l_type = lock->type;\n fl.l_whence = SEEK_SET;\n fl.l_start = lock->start;\n fl.l_len = lock->length;\n \n ret = fcntl(f->u.fd, F_SETLK, &fl);\n if (ret == 0) {\n ret = P9_LOCK_SUCCESS;\n } else if (errno == EAGAIN || errno == EACCES) {\n ret = P9_LOCK_BLOCKED;\n } else {\n ret = -errno_to_p9(errno);\n }\n return ret;\n}\n\nstatic int fs_getlock(FSDevice *fs, FSFile *f, FSLock *lock)\n{\n int ret;\n struct flock fl;\n \n /* XXX: lock directories too */\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n\n fl.l_type = lock->type;\n fl.l_whence = SEEK_SET;\n fl.l_start = lock->start;\n fl.l_len = lock->length;\n\n ret = fcntl(f->u.fd, F_GETLK, &fl);\n if (ret < 0) {\n ret = -errno_to_p9(errno);\n } else {\n lock->type = fl.l_type;\n lock->start = fl.l_start;\n lock->length = fl.l_len;\n }\n return ret;\n}\n\nstatic void fs_disk_end(FSDevice *fs1)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n free(fs->root_path);\n}\n\nFSDevice *fs_disk_init(const char *root_path)\n{\n FSDeviceDisk *fs;\n struct stat st;\n\n lstat(root_path, &st);\n if (!S_ISDIR(st.st_mode))\n return NULL;\n\n fs = mallocz(sizeof(*fs));\n\n fs->common.fs_end = fs_disk_end;\n fs->common.fs_delete = fs_delete;\n fs->common.fs_statfs = fs_statfs;\n fs->common.fs_attach = fs_attach;\n fs->common.fs_walk = fs_walk;\n fs->common.fs_mkdir = fs_mkdir;\n fs->common.fs_open = fs_open;\n fs->common.fs_create = fs_create;\n fs->common.fs_stat = fs_stat;\n fs->common.fs_setattr = fs_setattr;\n fs->common.fs_close = fs_close;\n fs->common.fs_readdir = fs_readdir;\n fs->common.fs_read = fs_read;\n fs->common.fs_write = fs_write;\n fs->common.fs_link = fs_link;\n fs->common.fs_symlink = fs_symlink;\n fs->common.fs_mknod = fs_mknod;\n fs->common.fs_readlink = fs_readlink;\n fs->common.fs_renameat = fs_renameat;\n fs->common.fs_unlinkat = fs_unlinkat;\n fs->common.fs_lock = fs_lock;\n fs->common.fs_getlock = fs_getlock;\n \n fs->root_path = strdup(root_path);\n return (FSDevice *)fs;\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_subr.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_subr.c\t8.1 (Berkeley) 6/10/93\n * tcp_subr.c,v 1.5 1994/10/08 22:39:58 phk Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n/* patchable/settable parameters for tcp */\n/* Don't do rfc1323 performance enhancements */\n#define TCP_DO_RFC1323 0\n\n/*\n * Tcp initialization\n */\nvoid\ntcp_init(Slirp *slirp)\n{\n slirp->tcp_iss = 1;\t\t/* wrong */\n slirp->tcb.so_next = slirp->tcb.so_prev = &slirp->tcb;\n slirp->tcp_last_so = &slirp->tcb;\n}\n\n/*\n * Create template to be used to send tcp packets on a connection.\n * Call after host entry created, fills\n * in a skeletal tcp/ip header, minimizing the amount of work\n * necessary when the connection is used.\n */\nvoid\ntcp_template(struct tcpcb *tp)\n{\n\tstruct socket *so = tp->t_socket;\n\tregister struct tcpiphdr *n = &tp->t_template;\n\n\tn->ti_mbuf = NULL;\n\tn->ti_x1 = 0;\n\tn->ti_pr = IPPROTO_TCP;\n\tn->ti_len = htons(sizeof (struct tcpiphdr) - sizeof (struct ip));\n\tn->ti_src = so->so_faddr;\n\tn->ti_dst = so->so_laddr;\n\tn->ti_sport = so->so_fport;\n\tn->ti_dport = so->so_lport;\n\n\tn->ti_seq = 0;\n\tn->ti_ack = 0;\n\tn->ti_x2 = 0;\n\tn->ti_off = 5;\n\tn->ti_flags = 0;\n\tn->ti_win = 0;\n\tn->ti_sum = 0;\n\tn->ti_urp = 0;\n}\n\n/*\n * Send a single message to the TCP at address specified by\n * the given TCP/IP header. If m == 0, then we make a copy\n * of the tcpiphdr at ti and send directly to the addressed host.\n * This is used to force keep alive messages out using the TCP\n * template for a connection tp->t_template. If flags are given\n * then we send a message back to the TCP which originated the\n * segment ti, and discard the mbuf containing it and any other\n * attached mbufs.\n *\n * In any case the ack and sequence number of the transmitted\n * segment are as specified by the parameters.\n */\nvoid\ntcp_respond(struct tcpcb *tp, struct tcpiphdr *ti, struct mbuf *m,\n tcp_seq ack, tcp_seq seq, int flags)\n{\n\tregister int tlen;\n\tint win = 0;\n\n\tDEBUG_CALL(\"tcp_respond\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"ti = %lx\", (long)ti);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"ack = %u\", ack);\n\tDEBUG_ARG(\"seq = %u\", seq);\n\tDEBUG_ARG(\"flags = %x\", flags);\n\n\tif (tp)\n\t\twin = sbspace(&tp->t_socket->so_rcv);\n if (m == NULL) {\n\t\tif ((m = m_get(tp->t_socket->slirp)) == NULL)\n\t\t\treturn;\n\t\ttlen = 0;\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\t*mtod(m, struct tcpiphdr *) = *ti;\n\t\tti = mtod(m, struct tcpiphdr *);\n\t\tflags = TH_ACK;\n\t} else {\n\t\t/*\n\t\t * ti points into m so the next line is just making\n\t\t * the mbuf point to ti\n\t\t */\n\t\tm->m_data = (caddr_t)ti;\n\n\t\tm->m_len = sizeof (struct tcpiphdr);\n\t\ttlen = 0;\n#define xchg(a,b,type) { type t; t=a; a=b; b=t; }\n\t\txchg(ti->ti_dst.s_addr, ti->ti_src.s_addr, uint32_t);\n\t\txchg(ti->ti_dport, ti->ti_sport, uint16_t);\n#undef xchg\n\t}\n\tti->ti_len = htons((u_short)(sizeof (struct tcphdr) + tlen));\n\ttlen += sizeof (struct tcpiphdr);\n\tm->m_len = tlen;\n\n ti->ti_mbuf = NULL;\n\tti->ti_x1 = 0;\n\tti->ti_seq = htonl(seq);\n\tti->ti_ack = htonl(ack);\n\tti->ti_x2 = 0;\n\tti->ti_off = sizeof (struct tcphdr) >> 2;\n\tti->ti_flags = flags;\n\tif (tp)\n\t\tti->ti_win = htons((uint16_t) (win >> tp->rcv_scale));\n\telse\n\t\tti->ti_win = htons((uint16_t)win);\n\tti->ti_urp = 0;\n\tti->ti_sum = 0;\n\tti->ti_sum = cksum(m, tlen);\n\t((struct ip *)ti)->ip_len = tlen;\n\n\tif(flags & TH_RST)\n\t ((struct ip *)ti)->ip_ttl = MAXTTL;\n\telse\n\t ((struct ip *)ti)->ip_ttl = IPDEFTTL;\n\n\t(void) ip_output((struct socket *)0, m);\n}\n\n/*\n * Create a new TCP control block, making an\n * empty reassembly queue and hooking it to the argument\n * protocol control block.\n */\nstruct tcpcb *\ntcp_newtcpcb(struct socket *so)\n{\n\tregister struct tcpcb *tp;\n\n\ttp = (struct tcpcb *)malloc(sizeof(*tp));\n\tif (tp == NULL)\n\t\treturn ((struct tcpcb *)0);\n\n\tmemset((char *) tp, 0, sizeof(struct tcpcb));\n\ttp->seg_next = tp->seg_prev = (struct tcpiphdr*)tp;\n\ttp->t_maxseg = TCP_MSS;\n\n\ttp->t_flags = TCP_DO_RFC1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;\n\ttp->t_socket = so;\n\n\t/*\n\t * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no\n\t * rtt estimate. Set rttvar so that srtt + 2 * rttvar gives\n\t * reasonable initial retransmit time.\n\t */\n\ttp->t_srtt = TCPTV_SRTTBASE;\n\ttp->t_rttvar = TCPTV_SRTTDFLT << 2;\n\ttp->t_rttmin = TCPTV_MIN;\n\n\tTCPT_RANGESET(tp->t_rxtcur,\n\t ((TCPTV_SRTTBASE >> 2) + (TCPTV_SRTTDFLT << 2)) >> 1,\n\t TCPTV_MIN, TCPTV_REXMTMAX);\n\n\ttp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;\n\ttp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;\n\ttp->t_state = TCPS_CLOSED;\n\n\tso->so_tcpcb = tp;\n\n\treturn (tp);\n}\n\n/*\n * Drop a TCP connection, reporting\n * the specified error. If connection is synchronized,\n * then send a RST to peer.\n */\nstruct tcpcb *tcp_drop(struct tcpcb *tp, int err)\n{\n\tDEBUG_CALL(\"tcp_drop\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"errno = %d\", errno);\n\n\tif (TCPS_HAVERCVDSYN(tp->t_state)) {\n\t\ttp->t_state = TCPS_CLOSED;\n\t\t(void) tcp_output(tp);\n\t}\n\treturn (tcp_close(tp));\n}\n\n/*\n * Close a TCP control block:\n *\tdiscard all space held by the tcp\n *\tdiscard internet protocol block\n *\twake up any sleepers\n */\nstruct tcpcb *\ntcp_close(struct tcpcb *tp)\n{\n\tregister struct tcpiphdr *t;\n\tstruct socket *so = tp->t_socket;\n\tSlirp *slirp = so->slirp;\n\tregister struct mbuf *m;\n\n\tDEBUG_CALL(\"tcp_close\");\n\tDEBUG_ARG(\"tp = %lx\", (long )tp);\n\n\t/* free the reassembly queue, if any */\n\tt = tcpfrag_list_first(tp);\n\twhile (!tcpfrag_list_end(t, tp)) {\n\t\tt = tcpiphdr_next(t);\n\t\tm = tcpiphdr_prev(t)->ti_mbuf;\n\t\tremque(tcpiphdr2qlink(tcpiphdr_prev(t)));\n\t\tm_freem(m);\n\t}\n\tfree(tp);\n so->so_tcpcb = NULL;\n\t/* clobber input socket cache if we're closing the cached connection */\n\tif (so == slirp->tcp_last_so)\n\t\tslirp->tcp_last_so = &slirp->tcb;\n\tclosesocket(so->s);\n\tsbfree(&so->so_rcv);\n\tsbfree(&so->so_snd);\n\tsofree(so);\n\treturn ((struct tcpcb *)0);\n}\n\n/*\n * TCP protocol interface to socket abstraction.\n */\n\n/*\n * User issued close, and wish to trail through shutdown states:\n * if never received SYN, just forget it. If got a SYN from peer,\n * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.\n * If already got a FIN from peer, then almost done; go to LAST_ACK\n * state. In all other cases, have already sent FIN to peer (e.g.\n * after PRU_SHUTDOWN), and just have to play tedious game waiting\n * for peer to send FIN or not respond to keep-alives, etc.\n * We can let the user exit from the close as soon as the FIN is acked.\n */\nvoid\ntcp_sockclosed(struct tcpcb *tp)\n{\n\n\tDEBUG_CALL(\"tcp_sockclosed\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\n\tswitch (tp->t_state) {\n\n\tcase TCPS_CLOSED:\n\tcase TCPS_LISTEN:\n\tcase TCPS_SYN_SENT:\n\t\ttp->t_state = TCPS_CLOSED;\n\t\ttp = tcp_close(tp);\n\t\tbreak;\n\n\tcase TCPS_SYN_RECEIVED:\n\tcase TCPS_ESTABLISHED:\n\t\ttp->t_state = TCPS_FIN_WAIT_1;\n\t\tbreak;\n\n\tcase TCPS_CLOSE_WAIT:\n\t\ttp->t_state = TCPS_LAST_ACK;\n\t\tbreak;\n\t}\n\tif (tp)\n\t\ttcp_output(tp);\n}\n\n/*\n * Connect to a host on the Internet\n * Called by tcp_input\n * Only do a connect, the tcp fields will be set in tcp_input\n * return 0 if there's a result of the connect,\n * else return -1 means we're still connecting\n * The return value is almost always -1 since the socket is\n * nonblocking. Connect returns after the SYN is sent, and does\n * not wait for ACK+SYN.\n */\nint tcp_fconnect(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n int ret=0;\n\n DEBUG_CALL(\"tcp_fconnect\");\n DEBUG_ARG(\"so = %lx\", (long )so);\n\n if( (ret = so->s = os_socket(AF_INET,SOCK_STREAM,0)) >= 0) {\n int opt, s=so->s;\n struct sockaddr_in addr;\n\n fd_nonblock(s);\n opt = 1;\n setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(opt ));\n opt = 1;\n setsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(opt ));\n\n addr.sin_family = AF_INET;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n /* It's an alias */\n if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\tif (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n } else {\n\taddr.sin_addr = loopback_addr;\n }\n } else\n addr.sin_addr = so->so_faddr;\n addr.sin_port = so->so_fport;\n\n DEBUG_MISC((dfd, \" connect()ing, addr.sin_port=%d, \"\n\t\t\"addr.sin_addr.s_addr=%.16s\\n\",\n\t\tntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));\n /* We don't care what port we get */\n ret = connect(s,(struct sockaddr *)&addr,sizeof (addr));\n\n /*\n * If it's not in progress, it failed, so we just return 0,\n * without clearing SS_NOFDREF\n */\n soisfconnecting(so);\n }\n\n return(ret);\n}\n\n/*\n * Accept the socket and connect to the local-host\n *\n * We have a problem. The correct thing to do would be\n * to first connect to the local-host, and only if the\n * connection is accepted, then do an accept() here.\n * But, a) we need to know who's trying to connect\n * to the socket to be able to SYN the local-host, and\n * b) we are already connected to the foreign host by\n * the time it gets to accept(), so... We simply accept\n * here and SYN the local-host.\n */\nvoid\ntcp_connect(struct socket *inso)\n{\n\tSlirp *slirp = inso->slirp;\n\tstruct socket *so;\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\tstruct tcpcb *tp;\n\tint s, opt;\n\n\tDEBUG_CALL(\"tcp_connect\");\n\tDEBUG_ARG(\"inso = %lx\", (long)inso);\n\n\t/*\n\t * If it's an SS_ACCEPTONCE socket, no need to socreate()\n\t * another socket, just use the accept() socket.\n\t */\n\tif (inso->so_state & SS_FACCEPTONCE) {\n\t\t/* FACCEPTONCE already have a tcpcb */\n\t\tso = inso;\n\t} else {\n\t\tif ((so = socreate(slirp)) == NULL) {\n\t\t\t/* If it failed, get rid of the pending connection */\n\t\t\tclosesocket(accept(inso->s,(struct sockaddr *)&addr,&addrlen));\n\t\t\treturn;\n\t\t}\n\t\tif (tcp_attach(so) < 0) {\n\t\t\tfree(so); /* NOT sofree */\n\t\t\treturn;\n\t\t}\n\t\tso->so_laddr = inso->so_laddr;\n\t\tso->so_lport = inso->so_lport;\n\t}\n\n\t(void) tcp_mss(sototcpcb(so), 0);\n\n\tif ((s = accept(inso->s,(struct sockaddr *)&addr,&addrlen)) < 0) {\n\t\ttcp_close(sototcpcb(so)); /* This will sofree() as well */\n\t\treturn;\n\t}\n\tfd_nonblock(s);\n\topt = 1;\n\tsetsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\topt = 1;\n\tsetsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\topt = 1;\n\tsetsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&opt,sizeof(int));\n\n\tso->so_fport = addr.sin_port;\n\tso->so_faddr = addr.sin_addr;\n\t/* Translate connections from localhost to the real hostname */\n\tif (so->so_faddr.s_addr == 0 || so->so_faddr.s_addr == loopback_addr.s_addr)\n\t so->so_faddr = slirp->vhost_addr;\n\n\t/* Close the accept() socket, set right state */\n\tif (inso->so_state & SS_FACCEPTONCE) {\n\t\tclosesocket(so->s); /* If we only accept once, close the accept() socket */\n\t\tso->so_state = SS_NOFDREF; /* Don't select it yet, even though we have an FD */\n\t\t\t\t\t /* if it's not FACCEPTONCE, it's already NOFDREF */\n\t}\n\tso->s = s;\n\tso->so_state |= SS_INCOMING;\n\n\tso->so_iptos = tcp_tos(so);\n\ttp = sototcpcb(so);\n\n\ttcp_template(tp);\n\n\ttp->t_state = TCPS_SYN_SENT;\n\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\ttp->iss = slirp->tcp_iss;\n\tslirp->tcp_iss += TCP_ISSINCR/2;\n\ttcp_sendseqinit(tp);\n\ttcp_output(tp);\n}\n\n/*\n * Attach a TCPCB to a socket.\n */\nint\ntcp_attach(struct socket *so)\n{\n\tif ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL)\n\t return -1;\n\n\tinsque(so, &so->slirp->tcb);\n\n\treturn 0;\n}\n\n/*\n * Set the socket's type of service field\n */\nstatic const struct tos_t tcptos[] = {\n\t {0, 20, IPTOS_THROUGHPUT, 0},\t/* ftp data */\n\t {21, 21, IPTOS_LOWDELAY, EMU_FTP},\t/* ftp control */\n\t {0, 23, IPTOS_LOWDELAY, 0},\t/* telnet */\n\t {0, 80, IPTOS_THROUGHPUT, 0},\t/* WWW */\n\t {0, 513, IPTOS_LOWDELAY, EMU_RLOGIN|EMU_NOCONNECT},\t/* rlogin */\n\t {0, 514, IPTOS_LOWDELAY, EMU_RSH|EMU_NOCONNECT},\t/* shell */\n\t {0, 544, IPTOS_LOWDELAY, EMU_KSH},\t\t/* kshell */\n\t {0, 543, IPTOS_LOWDELAY, 0},\t/* klogin */\n\t {0, 6667, IPTOS_THROUGHPUT, EMU_IRC},\t/* IRC */\n\t {0, 6668, IPTOS_THROUGHPUT, EMU_IRC},\t/* IRC undernet */\n\t {0, 7070, IPTOS_LOWDELAY, EMU_REALAUDIO }, /* RealAudio control */\n\t {0, 113, IPTOS_LOWDELAY, EMU_IDENT }, /* identd protocol */\n\t {0, 0, 0, 0}\n};\n\nstatic struct emu_t *tcpemu = NULL;\n\n/*\n * Return TOS according to the above table\n */\nuint8_t\ntcp_tos(struct socket *so)\n{\n\tint i = 0;\n\tstruct emu_t *emup;\n\n\twhile(tcptos[i].tos) {\n\t\tif ((tcptos[i].fport && (ntohs(so->so_fport) == tcptos[i].fport)) ||\n\t\t (tcptos[i].lport && (ntohs(so->so_lport) == tcptos[i].lport))) {\n\t\t\tso->so_emu = tcptos[i].emu;\n\t\t\treturn tcptos[i].tos;\n\t\t}\n\t\ti++;\n\t}\n\n\t/* Nope, lets see if there's a user-added one */\n\tfor (emup = tcpemu; emup; emup = emup->next) {\n\t\tif ((emup->fport && (ntohs(so->so_fport) == emup->fport)) ||\n\t\t (emup->lport && (ntohs(so->so_lport) == emup->lport))) {\n\t\t\tso->so_emu = emup->emu;\n\t\t\treturn emup->tos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/*\n * Emulate programs that try and connect to us\n * This includes ftp (the data connection is\n * initiated by the server) and IRC (DCC CHAT and\n * DCC SEND) for now\n *\n * NOTE: It's possible to crash SLiRP by sending it\n * unstandard strings to emulate... if this is a problem,\n * more checks are needed here\n *\n * XXX Assumes the whole command came in one packet\n *\n * XXX Some ftp clients will have their TOS set to\n * LOWDELAY and so Nagel will kick in. Because of this,\n * we'll get the first letter, followed by the rest, so\n * we simply scan for ORT instead of PORT...\n * DCC doesn't have this problem because there's other stuff\n * in the packet before the DCC command.\n *\n * Return 1 if the mbuf m is still valid and should be\n * sbappend()ed\n *\n * NOTE: if you return 0 you MUST m_free() the mbuf!\n */\nint\ntcp_emu(struct socket *so, struct mbuf *m)\n{\n\tSlirp *slirp = so->slirp;\n\tu_int n1, n2, n3, n4, n5, n6;\n char buff[257];\n\tuint32_t laddr;\n\tu_int lport;\n\tchar *bptr;\n\n\tDEBUG_CALL(\"tcp_emu\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n\tswitch(so->so_emu) {\n\t\tint x, i;\n\n\t case EMU_IDENT:\n\t\t/*\n\t\t * Identification protocol as per rfc-1413\n\t\t */\n\n\t\t{\n\t\t\tstruct socket *tmpso;\n\t\t\tstruct sockaddr_in addr;\n\t\t\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\t\t\tstruct sbuf *so_rcv = &so->so_rcv;\n\n\t\t\tmemcpy(so_rcv->sb_wptr, m->m_data, m->m_len);\n\t\t\tso_rcv->sb_wptr += m->m_len;\n\t\t\tso_rcv->sb_rptr += m->m_len;\n\t\t\tm->m_data[m->m_len] = 0; /* NULL terminate */\n\t\t\tif (strchr(m->m_data, '\\r') || strchr(m->m_data, '\\n')) {\n\t\t\t\tif (sscanf(so_rcv->sb_data, \"%u%*[ ,]%u\", &n1, &n2) == 2) {\n\t\t\t\t\tHTONS(n1);\n\t\t\t\t\tHTONS(n2);\n\t\t\t\t\t/* n2 is the one on our host */\n\t\t\t\t\tfor (tmpso = slirp->tcb.so_next;\n\t\t\t\t\t tmpso != &slirp->tcb;\n\t\t\t\t\t tmpso = tmpso->so_next) {\n\t\t\t\t\t\tif (tmpso->so_laddr.s_addr == so->so_laddr.s_addr &&\n\t\t\t\t\t\t tmpso->so_lport == n2 &&\n\t\t\t\t\t\t tmpso->so_faddr.s_addr == so->so_faddr.s_addr &&\n\t\t\t\t\t\t tmpso->so_fport == n1) {\n\t\t\t\t\t\t\tif (getsockname(tmpso->s,\n\t\t\t\t\t\t\t\t(struct sockaddr *)&addr, &addrlen) == 0)\n\t\t\t\t\t\t\t n2 = ntohs(addr.sin_port);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n so_rcv->sb_cc = snprintf(so_rcv->sb_data,\n so_rcv->sb_datalen,\n \"%d,%d\\r\\n\", n1, n2);\n\t\t\t\tso_rcv->sb_rptr = so_rcv->sb_data;\n\t\t\t\tso_rcv->sb_wptr = so_rcv->sb_data + so_rcv->sb_cc;\n\t\t\t}\n\t\t\tm_free(m);\n\t\t\treturn 0;\n\t\t}\n\n case EMU_FTP: /* ftp */\n *(m->m_data+m->m_len) = 0; /* NUL terminate for strstr */\n\t\tif ((bptr = (char *)strstr(m->m_data, \"ORT\")) != NULL) {\n\t\t\t/*\n\t\t\t * Need to emulate the PORT command\n\t\t\t */\n\t\t\tx = sscanf(bptr, \"ORT %u,%u,%u,%u,%u,%u\\r\\n%256[^\\177]\",\n\t\t\t\t &n1, &n2, &n3, &n4, &n5, &n6, buff);\n\t\t\tif (x < 6)\n\t\t\t return 1;\n\n\t\t\tladdr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));\n\t\t\tlport = htons((n5 << 8) | (n6));\n\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr,\n\t\t\t lport, SS_FACCEPTONCE)) == NULL) {\n\t\t\t return 1;\n\t\t\t}\n\t\t\tn6 = ntohs(so->so_fport);\n\n\t\t\tn5 = (n6 >> 8) & 0xff;\n\t\t\tn6 &= 0xff;\n\n\t\t\tladdr = ntohl(so->so_faddr.s_addr);\n\n\t\t\tn1 = ((laddr >> 24) & 0xff);\n\t\t\tn2 = ((laddr >> 16) & 0xff);\n\t\t\tn3 = ((laddr >> 8) & 0xff);\n\t\t\tn4 = (laddr & 0xff);\n\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size - m->m_len,\n \"ORT %d,%d,%d,%d,%d,%d\\r\\n%s\",\n n1, n2, n3, n4, n5, n6, x==7?buff:\"\");\n\t\t\treturn 1;\n\t\t} else if ((bptr = (char *)strstr(m->m_data, \"27 Entering\")) != NULL) {\n\t\t\t/*\n\t\t\t * Need to emulate the PASV response\n\t\t\t */\n\t\t\tx = sscanf(bptr, \"27 Entering Passive Mode (%u,%u,%u,%u,%u,%u)\\r\\n%256[^\\177]\",\n\t\t\t\t &n1, &n2, &n3, &n4, &n5, &n6, buff);\n\t\t\tif (x < 6)\n\t\t\t return 1;\n\n\t\t\tladdr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));\n\t\t\tlport = htons((n5 << 8) | (n6));\n\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr,\n\t\t\t lport, SS_FACCEPTONCE)) == NULL) {\n\t\t\t return 1;\n\t\t\t}\n\t\t\tn6 = ntohs(so->so_fport);\n\n\t\t\tn5 = (n6 >> 8) & 0xff;\n\t\t\tn6 &= 0xff;\n\n\t\t\tladdr = ntohl(so->so_faddr.s_addr);\n\n\t\t\tn1 = ((laddr >> 24) & 0xff);\n\t\t\tn2 = ((laddr >> 16) & 0xff);\n\t\t\tn3 = ((laddr >> 8) & 0xff);\n\t\t\tn4 = (laddr & 0xff);\n\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n\t\t\tm->m_len += snprintf(bptr, m->m_hdr.mh_size - m->m_len,\n \"27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\\r\\n%s\",\n n1, n2, n3, n4, n5, n6, x==7?buff:\"\");\n\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn 1;\n\n\t case EMU_KSH:\n\t\t/*\n\t\t * The kshell (Kerberos rsh) and shell services both pass\n\t\t * a local port port number to carry signals to the server\n\t\t * and stderr to the client. It is passed at the beginning\n\t\t * of the connection as a NUL-terminated decimal ASCII string.\n\t\t */\n\t\tso->so_emu = 0;\n\t\tfor (lport = 0, i = 0; i < m->m_len-1; ++i) {\n\t\t\tif (m->m_data[i] < '0' || m->m_data[i] > '9')\n\t\t\t\treturn 1; /* invalid number */\n\t\t\tlport *= 10;\n\t\t\tlport += m->m_data[i] - '0';\n\t\t}\n\t\tif (m->m_data[m->m_len-1] == '\\0' && lport != 0 &&\n\t\t (so = tcp_listen(slirp, INADDR_ANY, 0, so->so_laddr.s_addr,\n\t\t htons(lport), SS_FACCEPTONCE)) != NULL)\n m->m_len = snprintf(m->m_data, m->m_hdr.mh_size, \"%d\",\n ntohs(so->so_fport)) + 1;\n\t\treturn 1;\n\n\t case EMU_IRC:\n\t\t/*\n\t\t * Need to emulate DCC CHAT, DCC SEND and DCC MOVE\n\t\t */\n\t\t*(m->m_data+m->m_len) = 0; /* NULL terminate the string for strstr */\n\t\tif ((bptr = (char *)strstr(m->m_data, \"DCC\")) == NULL)\n\t\t\t return 1;\n\n\t\t/* The %256s is for the broken mIRC */\n\t\tif (sscanf(bptr, \"DCC CHAT %256s %u %u\", buff, &laddr, &lport) == 3) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC CHAT chat %lu %u%c\\n\",\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), 1);\n\t\t} else if (sscanf(bptr, \"DCC SEND %256s %u %u %u\", buff, &laddr, &lport, &n1) == 4) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC SEND %s %lu %u %u%c\\n\", buff,\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), n1, 1);\n\t\t} else if (sscanf(bptr, \"DCC MOVE %256s %u %u %u\", buff, &laddr, &lport, &n1) == 4) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC MOVE %s %lu %u %u%c\\n\", buff,\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), n1, 1);\n\t\t}\n\t\treturn 1;\n\n\t case EMU_REALAUDIO:\n /*\n\t\t * RealAudio emulation - JP. We must try to parse the incoming\n\t\t * data and try to find the two characters that contain the\n\t\t * port number. Then we redirect an udp port and replace the\n\t\t * number with the real port we got.\n\t\t *\n\t\t * The 1.0 beta versions of the player are not supported\n\t\t * any more.\n\t\t *\n\t\t * A typical packet for player version 1.0 (release version):\n\t\t *\n\t\t * 0000:50 4E 41 00 05\n\t\t * 0000:00 01 00 02 1B D7 00 00 67 E6 6C DC 63 00 12 50 ........g.l.c..P\n\t\t * 0010:4E 43 4C 49 45 4E 54 20 31 30 31 20 41 4C 50 48 NCLIENT 101 ALPH\n\t\t * 0020:41 6C 00 00 52 00 17 72 61 66 69 6C 65 73 2F 76 Al..R..rafiles/v\n\t\t * 0030:6F 61 2F 65 6E 67 6C 69 73 68 5F 2E 72 61 79 42 oa/english_.rayB\n\t\t *\n\t\t * Now the port number 0x1BD7 is found at offset 0x04 of the\n\t\t * Now the port number 0x1BD7 is found at offset 0x04 of the\n\t\t * second packet. This time we received five bytes first and\n\t\t * then the rest. You never know how many bytes you get.\n\t\t *\n\t\t * A typical packet for player version 2.0 (beta):\n\t\t *\n\t\t * 0000:50 4E 41 00 06 00 02 00 00 00 01 00 02 1B C1 00 PNA.............\n\t\t * 0010:00 67 75 78 F5 63 00 0A 57 69 6E 32 2E 30 2E 30 .gux.c..Win2.0.0\n\t\t * 0020:2E 35 6C 00 00 52 00 1C 72 61 66 69 6C 65 73 2F .5l..R..rafiles/\n\t\t * 0030:77 65 62 73 69 74 65 2F 32 30 72 65 6C 65 61 73 website/20releas\n\t\t * 0040:65 2E 72 61 79 53 00 00 06 36 42 e.rayS...6B\n\t\t *\n\t\t * Port number 0x1BC1 is found at offset 0x0d.\n\t\t *\n\t\t * This is just a horrible switch statement. Variable ra tells\n\t\t * us where we're going.\n\t\t */\n\n\t\tbptr = m->m_data;\n\t\twhile (bptr < m->m_data + m->m_len) {\n\t\t\tu_short p;\n\t\t\tstatic int ra = 0;\n\t\t\tchar ra_tbl[4];\n\n\t\t\tra_tbl[0] = 0x50;\n\t\t\tra_tbl[1] = 0x4e;\n\t\t\tra_tbl[2] = 0x41;\n\t\t\tra_tbl[3] = 0;\n\n\t\t\tswitch (ra) {\n\t\t\t case 0:\n\t\t\t case 2:\n\t\t\t case 3:\n\t\t\t\tif (*bptr++ != ra_tbl[ra]) {\n\t\t\t\t\tra = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t case 1:\n\t\t\t\t/*\n\t\t\t\t * We may get 0x50 several times, ignore them\n\t\t\t\t */\n\t\t\t\tif (*bptr == 0x50) {\n\t\t\t\t\tra = 1;\n\t\t\t\t\tbptr++;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (*bptr++ != ra_tbl[ra]) {\n\t\t\t\t\tra = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t case 4:\n\t\t\t\t/*\n\t\t\t\t * skip version number\n\t\t\t\t */\n\t\t\t\tbptr++;\n\t\t\t\tbreak;\n\n\t\t\t case 5:\n\t\t\t\t/*\n\t\t\t\t * The difference between versions 1.0 and\n\t\t\t\t * 2.0 is here. For future versions of\n\t\t\t\t * the player this may need to be modified.\n\t\t\t\t */\n\t\t\t\tif (*(bptr + 1) == 0x02)\n\t\t\t\t bptr += 8;\n\t\t\t\telse\n\t\t\t\t bptr += 4;\n\t\t\t\tbreak;\n\n\t\t\t case 6:\n\t\t\t\t/* This is the field containing the port\n\t\t\t\t * number that RA-player is listening to.\n\t\t\t\t */\n\t\t\t\tlport = (((u_char*)bptr)[0] << 8)\n\t\t\t\t+ ((u_char *)bptr)[1];\n\t\t\t\tif (lport < 6970)\n\t\t\t\t lport += 256; /* don't know why */\n\t\t\t\tif (lport < 6970 || lport > 7170)\n\t\t\t\t return 1; /* failed */\n\n\t\t\t\t/* try to get udp port between 6970 - 7170 */\n\t\t\t\tfor (p = 6970; p < 7071; p++) {\n\t\t\t\t\tif (udp_listen(slirp, INADDR_ANY,\n\t\t\t\t\t\t htons(p),\n\t\t\t\t\t\t so->so_laddr.s_addr,\n\t\t\t\t\t\t htons(lport),\n\t\t\t\t\t\t SS_FACCEPTONCE)) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (p == 7071)\n\t\t\t\t p = 0;\n\t\t\t\t*(u_char *)bptr++ = (p >> 8) & 0xff;\n *(u_char *)bptr = p & 0xff;\n\t\t\t\tra = 0;\n\t\t\t\treturn 1; /* port redirected, we're done */\n\t\t\t\tbreak;\n\n\t\t\t default:\n\t\t\t\tra = 0;\n\t\t\t}\n\t\t\tra++;\n\t\t}\n\t\treturn 1;\n\n\t default:\n\t\t/* Ooops, not emulated, won't call tcp_emu again */\n\t\tso->so_emu = 0;\n\t\treturn 1;\n\t}\n}\n\n/*\n * Do misc. config of SLiRP while its running.\n * Return 0 if this connections is to be closed, 1 otherwise,\n * return 2 if this is a command-line connection\n */\nint tcp_ctl(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n struct sbuf *sb = &so->so_snd;\n struct ex_list *ex_ptr;\n int do_pty;\n\n DEBUG_CALL(\"tcp_ctl\");\n DEBUG_ARG(\"so = %lx\", (long )so);\n\n if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {\n /* Check if it's pty_exec */\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_fport == so->so_fport &&\n so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {\n if (ex_ptr->ex_pty == 3) {\n so->s = -1;\n so->extra = (void *)ex_ptr->ex_exec;\n return 1;\n }\n do_pty = ex_ptr->ex_pty;\n DEBUG_MISC((dfd, \" executing %s \\n\",ex_ptr->ex_exec));\n return fork_exec(so, ex_ptr->ex_exec, do_pty);\n }\n }\n }\n sb->sb_cc =\n snprintf(sb->sb_wptr, sb->sb_datalen - (sb->sb_wptr - sb->sb_data),\n \"Error: No application configured.\\r\\n\");\n sb->sb_wptr += sb->sb_cc;\n return 0;\n}\n"], ["/linuxpdf/tinyemu/iomem.c", "/*\n * IO memory handling\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n\nstatic PhysMemoryRange *default_register_ram(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags);\nstatic void default_free_ram(PhysMemoryMap *s, PhysMemoryRange *pr);\nstatic const uint32_t *default_get_dirty_bits(PhysMemoryMap *map, PhysMemoryRange *pr);\nstatic void default_set_addr(PhysMemoryMap *map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled);\n\nPhysMemoryMap *phys_mem_map_init(void)\n{\n PhysMemoryMap *s;\n s = mallocz(sizeof(*s));\n s->register_ram = default_register_ram;\n s->free_ram = default_free_ram;\n s->get_dirty_bits = default_get_dirty_bits;\n s->set_ram_addr = default_set_addr;\n return s;\n}\n\nvoid phys_mem_map_end(PhysMemoryMap *s)\n{\n int i;\n PhysMemoryRange *pr;\n\n for(i = 0; i < s->n_phys_mem_range; i++) {\n pr = &s->phys_mem_range[i];\n if (pr->is_ram) {\n s->free_ram(s, pr);\n }\n }\n free(s);\n}\n\n/* return NULL if not found */\n/* XXX: optimize */\nPhysMemoryRange *get_phys_mem_range(PhysMemoryMap *s, uint64_t paddr)\n{\n PhysMemoryRange *pr;\n int i;\n for(i = 0; i < s->n_phys_mem_range; i++) {\n pr = &s->phys_mem_range[i];\n if (paddr >= pr->addr && paddr < pr->addr + pr->size)\n return pr;\n }\n return NULL;\n}\n\nPhysMemoryRange *register_ram_entry(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n\n assert(s->n_phys_mem_range < PHYS_MEM_RANGE_MAX);\n assert((size & (DEVRAM_PAGE_SIZE - 1)) == 0 && size != 0);\n pr = &s->phys_mem_range[s->n_phys_mem_range++];\n pr->map = s;\n pr->is_ram = TRUE;\n pr->devram_flags = devram_flags & ~DEVRAM_FLAG_DISABLED;\n pr->addr = addr;\n pr->org_size = size;\n if (devram_flags & DEVRAM_FLAG_DISABLED)\n pr->size = 0;\n else\n pr->size = pr->org_size;\n pr->phys_mem = NULL;\n pr->dirty_bits = NULL;\n return pr;\n}\n\nstatic PhysMemoryRange *default_register_ram(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n\n pr = register_ram_entry(s, addr, size, devram_flags);\n\n pr->phys_mem = mallocz(size);\n if (!pr->phys_mem) {\n fprintf(stderr, \"Could not allocate VM memory\\n\");\n exit(1);\n }\n\n if (devram_flags & DEVRAM_FLAG_DIRTY_BITS) {\n size_t nb_pages;\n int i;\n nb_pages = size >> DEVRAM_PAGE_SIZE_LOG2;\n pr->dirty_bits_size = ((nb_pages + 31) / 32) * sizeof(uint32_t);\n pr->dirty_bits_index = 0;\n for(i = 0; i < 2; i++) {\n pr->dirty_bits_tab[i] = mallocz(pr->dirty_bits_size);\n }\n pr->dirty_bits = pr->dirty_bits_tab[pr->dirty_bits_index];\n }\n return pr;\n}\n\n/* return a pointer to the bitmap of dirty bits and reset them */\nstatic const uint32_t *default_get_dirty_bits(PhysMemoryMap *map,\n PhysMemoryRange *pr)\n{\n uint32_t *dirty_bits;\n BOOL has_dirty_bits;\n size_t n, i;\n \n dirty_bits = pr->dirty_bits;\n\n has_dirty_bits = FALSE;\n n = pr->dirty_bits_size / sizeof(uint32_t);\n for(i = 0; i < n; i++) {\n if (dirty_bits[i] != 0) {\n has_dirty_bits = TRUE;\n break;\n }\n }\n if (has_dirty_bits && pr->size != 0) {\n /* invalidate the corresponding CPU write TLBs */\n map->flush_tlb_write_range(map->opaque, pr->phys_mem, pr->org_size);\n }\n \n pr->dirty_bits_index ^= 1;\n pr->dirty_bits = pr->dirty_bits_tab[pr->dirty_bits_index];\n memset(pr->dirty_bits, 0, pr->dirty_bits_size);\n return dirty_bits;\n}\n\n/* reset the dirty bit of one page at 'offset' inside 'pr' */\nvoid phys_mem_reset_dirty_bit(PhysMemoryRange *pr, size_t offset)\n{\n size_t page_index;\n uint32_t mask, *dirty_bits_ptr;\n PhysMemoryMap *map;\n if (pr->dirty_bits) {\n page_index = offset >> DEVRAM_PAGE_SIZE_LOG2;\n mask = 1 << (page_index & 0x1f);\n dirty_bits_ptr = pr->dirty_bits + (page_index >> 5);\n if (*dirty_bits_ptr & mask) {\n *dirty_bits_ptr &= ~mask;\n /* invalidate the corresponding CPU write TLBs */\n map = pr->map;\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem + (offset & ~(DEVRAM_PAGE_SIZE - 1)),\n DEVRAM_PAGE_SIZE);\n }\n }\n}\n\nstatic void default_free_ram(PhysMemoryMap *s, PhysMemoryRange *pr)\n{\n free(pr->phys_mem);\n}\n\nPhysMemoryRange *cpu_register_device(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, void *opaque,\n DeviceReadFunc *read_func, DeviceWriteFunc *write_func,\n int devio_flags)\n{\n PhysMemoryRange *pr;\n assert(s->n_phys_mem_range < PHYS_MEM_RANGE_MAX);\n assert(size <= 0xffffffff);\n pr = &s->phys_mem_range[s->n_phys_mem_range++];\n pr->map = s;\n pr->addr = addr;\n pr->org_size = size;\n if (devio_flags & DEVIO_DISABLED)\n pr->size = 0;\n else\n pr->size = pr->org_size;\n pr->is_ram = FALSE;\n pr->opaque = opaque;\n pr->read_func = read_func;\n pr->write_func = write_func;\n pr->devio_flags = devio_flags;\n return pr;\n}\n\nstatic void default_set_addr(PhysMemoryMap *map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n if (enabled) {\n if (pr->size == 0 || pr->addr != addr) {\n /* enable or move mapping */\n if (pr->is_ram) {\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem, pr->org_size);\n }\n pr->addr = addr;\n pr->size = pr->org_size;\n }\n } else {\n if (pr->size != 0) {\n /* disable mapping */\n if (pr->is_ram) {\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem, pr->org_size);\n }\n pr->addr = 0;\n pr->size = 0;\n }\n }\n}\n\nvoid phys_mem_set_addr(PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n PhysMemoryMap *map = pr->map;\n if (!pr->is_ram) {\n default_set_addr(map, pr, addr, enabled);\n } else {\n return map->set_ram_addr(map, pr, addr, enabled);\n }\n}\n\n/* return NULL if no valid RAM page. The access can only be done in the page */\nuint8_t *phys_mem_get_ram_ptr(PhysMemoryMap *map, uint64_t paddr, BOOL is_rw)\n{\n PhysMemoryRange *pr = get_phys_mem_range(map, paddr);\n uintptr_t offset;\n if (!pr || !pr->is_ram)\n return NULL;\n offset = paddr - pr->addr;\n if (is_rw)\n phys_mem_set_dirty_bit(pr, offset);\n return pr->phys_mem + (uintptr_t)offset;\n}\n\n/* IRQ support */\n\nvoid irq_init(IRQSignal *irq, SetIRQFunc *set_irq, void *opaque, int irq_num)\n{\n irq->set_irq = set_irq;\n irq->opaque = opaque;\n irq->irq_num = irq_num;\n}\n"], ["/linuxpdf/tinyemu/json.c", "/*\n * Pseudo JSON parser\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"json.h\"\n#include \"fs_utils.h\"\n\nstatic JSONValue parse_string(const char **pp)\n{\n char buf[4096], *q;\n const char *p;\n int c, h;\n \n q = buf;\n p = *pp;\n p++;\n for(;;) {\n c = *p++;\n if (c == '\\0' || c == '\\n') {\n return json_error_new(\"unterminated string\");\n } else if (c == '\\\"') {\n break;\n } else if (c == '\\\\') {\n c = *p++;\n switch(c) {\n case '\\'':\n case '\\\"':\n case '\\\\':\n goto add_char;\n case 'n':\n c = '\\n';\n goto add_char;\n case 'r':\n c = '\\r';\n goto add_char;\n case 't':\n c = '\\t';\n goto add_char;\n case 'x':\n h = from_hex(*p++);\n if (h < 0)\n return json_error_new(\"invalig hex digit\");\n c = h << 4;\n h = from_hex(*p++);\n if (h < 0)\n return json_error_new(\"invalig hex digit\");\n c |= h;\n goto add_char;\n default:\n return json_error_new(\"unknown escape code\");\n }\n } else {\n add_char:\n if (q >= buf + sizeof(buf) - 1)\n return json_error_new(\"string too long\");\n *q++ = c;\n }\n }\n *q = '\\0';\n *pp = p;\n return json_string_new(buf);\n}\n\nstatic JSONProperty *json_object_get2(JSONObject *obj, const char *name)\n{\n JSONProperty *f;\n int i;\n for(i = 0; i < obj->len; i++) {\n f = &obj->props[i];\n if (!strcmp(f->name.u.str->data, name))\n return f;\n }\n return NULL;\n}\n\nJSONValue json_object_get(JSONValue val, const char *name)\n{\n JSONProperty *f;\n JSONObject *obj;\n \n if (val.type != JSON_OBJ)\n return json_undefined_new();\n obj = val.u.obj;\n f = json_object_get2(obj, name);\n if (!f)\n return json_undefined_new();\n return f->value;\n}\n\nint json_object_set(JSONValue val, const char *name, JSONValue prop_val)\n{\n JSONObject *obj;\n JSONProperty *f;\n int new_size;\n \n if (val.type != JSON_OBJ)\n return -1;\n obj = val.u.obj;\n f = json_object_get2(obj, name);\n if (f) {\n json_free(f->value);\n f->value = prop_val;\n } else {\n if (obj->len >= obj->size) {\n new_size = max_int(obj->len + 1, obj->size * 3 / 2);\n obj->props = realloc(obj->props, new_size * sizeof(JSONProperty));\n obj->size = new_size;\n }\n f = &obj->props[obj->len++];\n f->name = json_string_new(name);\n f->value = prop_val;\n }\n return 0;\n}\n\nJSONValue json_array_get(JSONValue val, unsigned int idx)\n{\n JSONArray *array;\n \n if (val.type != JSON_ARRAY)\n return json_undefined_new();\n array = val.u.array;\n if (idx < array->len) {\n return array->tab[idx];\n } else {\n return json_undefined_new();\n }\n}\n\nint json_array_set(JSONValue val, unsigned int idx, JSONValue prop_val)\n{\n JSONArray *array;\n int new_size;\n \n if (val.type != JSON_ARRAY)\n return -1;\n array = val.u.array;\n if (idx < array->len) {\n json_free(array->tab[idx]);\n array->tab[idx] = prop_val;\n } else if (idx == array->len) {\n if (array->len >= array->size) {\n new_size = max_int(array->len + 1, array->size * 3 / 2);\n array->tab = realloc(array->tab, new_size * sizeof(JSONValue));\n array->size = new_size;\n }\n array->tab[array->len++] = prop_val;\n } else {\n return -1;\n }\n return 0;\n}\n\nconst char *json_get_str(JSONValue val)\n{\n if (val.type != JSON_STR)\n return NULL;\n return val.u.str->data;\n}\n\nconst char *json_get_error(JSONValue val)\n{\n if (val.type != JSON_EXCEPTION)\n return NULL;\n return val.u.str->data;\n}\n\nJSONValue json_string_new2(const char *str, int len)\n{\n JSONValue val;\n JSONString *str1;\n\n str1 = malloc(sizeof(JSONString) + len + 1);\n str1->len = len;\n memcpy(str1->data, str, len + 1);\n val.type = JSON_STR;\n val.u.str = str1;\n return val;\n}\n\nJSONValue json_string_new(const char *str)\n{\n return json_string_new2(str, strlen(str));\n}\n\nJSONValue __attribute__((format(printf, 1, 2))) json_error_new(const char *fmt, ...)\n{\n JSONValue val;\n va_list ap;\n char buf[256];\n \n va_start(ap, fmt);\n vsnprintf(buf, sizeof(buf), fmt, ap);\n va_end(ap);\n val = json_string_new(buf);\n val.type = JSON_EXCEPTION;\n return val;\n}\n\nJSONValue json_object_new(void)\n{\n JSONValue val;\n JSONObject *obj;\n obj = mallocz(sizeof(JSONObject));\n val.type = JSON_OBJ;\n val.u.obj = obj;\n return val;\n}\n\nJSONValue json_array_new(void)\n{\n JSONValue val;\n JSONArray *array;\n array = mallocz(sizeof(JSONArray));\n val.type = JSON_ARRAY;\n val.u.array = array;\n return val;\n}\n\nvoid json_free(JSONValue val)\n{\n switch(val.type) {\n case JSON_STR:\n case JSON_EXCEPTION:\n free(val.u.str);\n break;\n case JSON_INT:\n case JSON_BOOL:\n case JSON_NULL:\n case JSON_UNDEFINED:\n break;\n case JSON_ARRAY:\n {\n JSONArray *array = val.u.array;\n int i;\n \n for(i = 0; i < array->len; i++) {\n json_free(array->tab[i]);\n }\n free(array);\n }\n break;\n case JSON_OBJ:\n {\n JSONObject *obj = val.u.obj;\n JSONProperty *f;\n int i;\n \n for(i = 0; i < obj->len; i++) {\n f = &obj->props[i];\n json_free(f->name);\n json_free(f->value);\n }\n free(obj);\n }\n break;\n default:\n abort();\n }\n}\n\nstatic void skip_spaces(const char **pp)\n{\n const char *p;\n p = *pp;\n for(;;) {\n if (isspace(*p)) {\n p++;\n } else if (p[0] == '/' && p[1] == '/') {\n p += 2;\n while (*p != '\\0' && *p != '\\n')\n p++;\n } else if (p[0] == '/' && p[1] == '*') {\n p += 2;\n while (*p != '\\0' && (p[0] != '*' || p[1] != '/'))\n p++;\n if (*p != '\\0')\n p += 2;\n } else {\n break;\n }\n }\n *pp = p;\n}\n\nstatic inline BOOL is_ident_first(int c)\n{\n return (c >= 'a' && c <= 'z') ||\n (c >= 'A' && c <= 'Z') ||\n c == '_' || c == '$';\n}\n\nstatic int parse_ident(char *buf, int buf_size, const char **pp)\n{\n char *q;\n const char *p;\n p = *pp;\n q = buf;\n *q++ = *p++; /* first char is already tested */\n while (is_ident_first(*p) || isdigit(*p)) {\n if ((q - buf) >= buf_size - 1)\n return -1;\n *q++ = *p++;\n }\n *pp = p;\n *q = '\\0';\n return 0;\n}\n\nJSONValue json_parse_value2(const char **pp)\n{\n char buf[128];\n const char *p;\n JSONValue val, val1, tag;\n \n p = *pp;\n skip_spaces(&p);\n if (*p == '\\0') {\n return json_error_new(\"unexpected end of file\");\n }\n if (isdigit(*p)) {\n val = json_int32_new(strtol(p, (char **)&p, 0));\n } else if (*p == '\"') {\n val = parse_string(&p);\n } else if (*p == '{') {\n p++;\n val = json_object_new();\n for(;;) {\n skip_spaces(&p);\n if (*p == '}') {\n p++;\n break;\n }\n if (*p == '\"') {\n tag = parse_string(&p);\n if (json_is_error(tag))\n return tag;\n } else if (is_ident_first(*p)) {\n if (parse_ident(buf, sizeof(buf), &p) < 0)\n goto invalid_prop;\n tag = json_string_new(buf);\n } else {\n goto invalid_prop;\n }\n // printf(\"property: %s\\n\", json_get_str(tag));\n if (tag.u.str->len == 0) {\n invalid_prop:\n return json_error_new(\"Invalid property name\");\n }\n skip_spaces(&p);\n if (*p != ':') {\n return json_error_new(\"':' expected\");\n }\n p++;\n \n val1 = json_parse_value2(&p);\n json_object_set(val, tag.u.str->data, val1);\n\n skip_spaces(&p);\n if (*p == ',') {\n p++;\n } else if (*p != '}') {\n return json_error_new(\"expecting ',' or '}'\");\n }\n }\n } else if (*p == '[') {\n int idx;\n \n p++;\n val = json_array_new();\n idx = 0;\n for(;;) {\n skip_spaces(&p);\n if (*p == ']') {\n p++;\n break;\n }\n val1 = json_parse_value2(&p);\n json_array_set(val, idx++, val1);\n\n skip_spaces(&p);\n if (*p == ',') {\n p++;\n } else if (*p != ']') {\n return json_error_new(\"expecting ',' or ']'\");\n }\n }\n } else if (is_ident_first(*p)) {\n if (parse_ident(buf, sizeof(buf), &p) < 0)\n goto unknown_id;\n if (!strcmp(buf, \"null\")) {\n val = json_null_new();\n } else if (!strcmp(buf, \"true\")) {\n val = json_bool_new(TRUE);\n } else if (!strcmp(buf, \"false\")) {\n val = json_bool_new(FALSE);\n } else {\n unknown_id:\n return json_error_new(\"unknown identifier: '%s'\", buf);\n }\n } else {\n return json_error_new(\"unexpected character\");\n }\n *pp = p;\n return val;\n}\n\nJSONValue json_parse_value(const char *p)\n{\n JSONValue val;\n val = json_parse_value2(&p); \n if (json_is_error(val))\n return val;\n skip_spaces(&p);\n if (*p != '\\0') {\n json_free(val);\n return json_error_new(\"unexpected characters at the end\");\n }\n return val;\n}\n\nJSONValue json_parse_value_len(const char *p, int len)\n{\n char *str;\n JSONValue val;\n str = malloc(len + 1);\n memcpy(str, p, len);\n str[len] = '\\0';\n val = json_parse_value(str);\n free(str);\n return val;\n}\n"], ["/linuxpdf/tinyemu/slirp/misc.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n#ifdef DEBUG\nint slirp_debug = DBG_CALL|DBG_MISC|DBG_ERROR;\n#endif\n\nstruct quehead {\n\tstruct quehead *qh_link;\n\tstruct quehead *qh_rlink;\n};\n\ninline void\ninsque(void *a, void *b)\n{\n\tregister struct quehead *element = (struct quehead *) a;\n\tregister struct quehead *head = (struct quehead *) b;\n\telement->qh_link = head->qh_link;\n\thead->qh_link = (struct quehead *)element;\n\telement->qh_rlink = (struct quehead *)head;\n\t((struct quehead *)(element->qh_link))->qh_rlink\n\t= (struct quehead *)element;\n}\n\ninline void\nremque(void *a)\n{\n register struct quehead *element = (struct quehead *) a;\n ((struct quehead *)(element->qh_link))->qh_rlink = element->qh_rlink;\n ((struct quehead *)(element->qh_rlink))->qh_link = element->qh_link;\n element->qh_rlink = NULL;\n}\n\nint add_exec(struct ex_list **ex_ptr, int do_pty, char *exec,\n struct in_addr addr, int port)\n{\n\tstruct ex_list *tmp_ptr;\n\n\t/* First, check if the port is \"bound\" */\n\tfor (tmp_ptr = *ex_ptr; tmp_ptr; tmp_ptr = tmp_ptr->ex_next) {\n\t\tif (port == tmp_ptr->ex_fport &&\n\t\t addr.s_addr == tmp_ptr->ex_addr.s_addr)\n\t\t\treturn -1;\n\t}\n\n\ttmp_ptr = *ex_ptr;\n\t*ex_ptr = (struct ex_list *)malloc(sizeof(struct ex_list));\n\t(*ex_ptr)->ex_fport = port;\n\t(*ex_ptr)->ex_addr = addr;\n\t(*ex_ptr)->ex_pty = do_pty;\n\t(*ex_ptr)->ex_exec = (do_pty == 3) ? exec : strdup(exec);\n\t(*ex_ptr)->ex_next = tmp_ptr;\n\treturn 0;\n}\n\n#ifndef HAVE_STRERROR\n\n/*\n * For systems with no strerror\n */\n\nextern int sys_nerr;\nextern char *sys_errlist[];\n\nchar *\nstrerror(error)\n\tint error;\n{\n\tif (error < sys_nerr)\n\t return sys_errlist[error];\n\telse\n\t return \"Unknown error.\";\n}\n\n#endif\n\nint os_socket(int domain, int type, int protocol)\n{\n return socket(domain, type, protocol);\n}\n\nuint32_t os_get_time_ms(void)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return ts.tv_sec * 1000 +\n (ts.tv_nsec / 1000000);\n}\n\n\n#if 1\n\nint\nfork_exec(struct socket *so, const char *ex, int do_pty)\n{\n /* not implemented */\n return 0;\n}\n\n#else\n\n/*\n * XXX This is ugly\n * We create and bind a socket, then fork off to another\n * process, which connects to this socket, after which we\n * exec the wanted program. If something (strange) happens,\n * the accept() call could block us forever.\n *\n * do_pty = 0 Fork/exec inetd style\n * do_pty = 1 Fork/exec using slirp.telnetd\n * do_ptr = 2 Fork/exec using pty\n */\nint\nfork_exec(struct socket *so, const char *ex, int do_pty)\n{\n\tint s;\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(addr);\n\tint opt;\n int master = -1;\n\tconst char *argv[256];\n\t/* don't want to clobber the original */\n\tchar *bptr;\n\tconst char *curarg;\n\tint c, i, ret;\n\n\tDEBUG_CALL(\"fork_exec\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"ex = %lx\", (long)ex);\n\tDEBUG_ARG(\"do_pty = %lx\", (long)do_pty);\n\n\tif (do_pty == 2) {\n return 0;\n\t} else {\n\t\taddr.sin_family = AF_INET;\n\t\taddr.sin_port = 0;\n\t\taddr.sin_addr.s_addr = INADDR_ANY;\n\n\t\tif ((s = os_socket(AF_INET, SOCK_STREAM, 0)) < 0 ||\n\t\t bind(s, (struct sockaddr *)&addr, addrlen) < 0 ||\n\t\t listen(s, 1) < 0) {\n\t\t\tlprint(\"Error: inet socket: %s\\n\", strerror(errno));\n\t\t\tclosesocket(s);\n\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tswitch(fork()) {\n\t case -1:\n\t\tlprint(\"Error: fork failed: %s\\n\", strerror(errno));\n\t\tclose(s);\n\t\tif (do_pty == 2)\n\t\t close(master);\n\t\treturn 0;\n\n\t case 0:\n\t\t/* Set the DISPLAY */\n\t\tif (do_pty == 2) {\n\t\t\t(void) close(master);\n#ifdef TIOCSCTTY /* XXXXX */\n\t\t\t(void) setsid();\n\t\t\tioctl(s, TIOCSCTTY, (char *)NULL);\n#endif\n\t\t} else {\n\t\t\tgetsockname(s, (struct sockaddr *)&addr, &addrlen);\n\t\t\tclose(s);\n\t\t\t/*\n\t\t\t * Connect to the socket\n\t\t\t * XXX If any of these fail, we're in trouble!\n\t \t\t */\n\t\t\ts = os_socket(AF_INET, SOCK_STREAM, 0);\n\t\t\taddr.sin_addr = loopback_addr;\n do {\n ret = connect(s, (struct sockaddr *)&addr, addrlen);\n } while (ret < 0 && errno == EINTR);\n\t\t}\n\n\t\tdup2(s, 0);\n\t\tdup2(s, 1);\n\t\tdup2(s, 2);\n\t\tfor (s = getdtablesize() - 1; s >= 3; s--)\n\t\t close(s);\n\n\t\ti = 0;\n\t\tbptr = qemu_strdup(ex); /* No need to free() this */\n\t\tif (do_pty == 1) {\n\t\t\t/* Setup \"slirp.telnetd -x\" */\n\t\t\targv[i++] = \"slirp.telnetd\";\n\t\t\targv[i++] = \"-x\";\n\t\t\targv[i++] = bptr;\n\t\t} else\n\t\t do {\n\t\t\t/* Change the string into argv[] */\n\t\t\tcurarg = bptr;\n\t\t\twhile (*bptr != ' ' && *bptr != (char)0)\n\t\t\t bptr++;\n\t\t\tc = *bptr;\n\t\t\t*bptr++ = (char)0;\n\t\t\targv[i++] = strdup(curarg);\n\t\t } while (c);\n\n argv[i] = NULL;\n\t\texecvp(argv[0], (char **)argv);\n\n\t\t/* Ooops, failed, let's tell the user why */\n fprintf(stderr, \"Error: execvp of %s failed: %s\\n\",\n argv[0], strerror(errno));\n\t\tclose(0); close(1); close(2); /* XXX */\n\t\texit(1);\n\n\t default:\n\t\tif (do_pty == 2) {\n\t\t\tclose(s);\n\t\t\tso->s = master;\n\t\t} else {\n\t\t\t/*\n\t\t\t * XXX this could block us...\n\t\t\t * XXX Should set a timer here, and if accept() doesn't\n\t\t \t * return after X seconds, declare it a failure\n\t\t \t * The only reason this will block forever is if socket()\n\t\t \t * of connect() fail in the child process\n\t\t \t */\n do {\n so->s = accept(s, (struct sockaddr *)&addr, &addrlen);\n } while (so->s < 0 && errno == EINTR);\n closesocket(s);\n\t\t\topt = 1;\n\t\t\tsetsockopt(so->s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\t\t\topt = 1;\n\t\t\tsetsockopt(so->s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\t\t}\n\t\tfd_nonblock(so->s);\n\n\t\t/* Append the telnet options now */\n if (so->so_m != NULL && do_pty == 1) {\n\t\t\tsbappend(so, so->so_m);\n so->so_m = NULL;\n\t\t}\n\n\t\treturn 1;\n\t}\n}\n#endif\n\n#ifndef HAVE_STRDUP\nchar *\nstrdup(str)\n\tconst char *str;\n{\n\tchar *bptr;\n\n\tbptr = (char *)malloc(strlen(str)+1);\n\tstrcpy(bptr, str);\n\n\treturn bptr;\n}\n#endif\n\nvoid lprint(const char *format, ...)\n{\n va_list args;\n\n va_start(args, format);\n vprintf(format, args);\n va_end(args);\n}\n\n/*\n * Set fd blocking and non-blocking\n */\n\nvoid\nfd_nonblock(int fd)\n{\n#ifdef FIONBIO\n#ifdef _WIN32\n unsigned long opt = 1;\n#else\n int opt = 1;\n#endif\n\n\tioctlsocket(fd, FIONBIO, &opt);\n#else\n\tint opt;\n\n\topt = fcntl(fd, F_GETFL, 0);\n\topt |= O_NONBLOCK;\n\tfcntl(fd, F_SETFL, opt);\n#endif\n}\n\nvoid\nfd_block(int fd)\n{\n#ifdef FIONBIO\n#ifdef _WIN32\n unsigned long opt = 0;\n#else\n\tint opt = 0;\n#endif\n\n\tioctlsocket(fd, FIONBIO, &opt);\n#else\n\tint opt;\n\n\topt = fcntl(fd, F_GETFL, 0);\n\topt &= ~O_NONBLOCK;\n\tfcntl(fd, F_SETFL, opt);\n#endif\n}\n\n#if 0\nvoid slirp_connection_info(Slirp *slirp, Monitor *mon)\n{\n const char * const tcpstates[] = {\n [TCPS_CLOSED] = \"CLOSED\",\n [TCPS_LISTEN] = \"LISTEN\",\n [TCPS_SYN_SENT] = \"SYN_SENT\",\n [TCPS_SYN_RECEIVED] = \"SYN_RCVD\",\n [TCPS_ESTABLISHED] = \"ESTABLISHED\",\n [TCPS_CLOSE_WAIT] = \"CLOSE_WAIT\",\n [TCPS_FIN_WAIT_1] = \"FIN_WAIT_1\",\n [TCPS_CLOSING] = \"CLOSING\",\n [TCPS_LAST_ACK] = \"LAST_ACK\",\n [TCPS_FIN_WAIT_2] = \"FIN_WAIT_2\",\n [TCPS_TIME_WAIT] = \"TIME_WAIT\",\n };\n struct in_addr dst_addr;\n struct sockaddr_in src;\n socklen_t src_len;\n uint16_t dst_port;\n struct socket *so;\n const char *state;\n char buf[20];\n int n;\n\n monitor_printf(mon, \" Protocol[State] FD Source Address Port \"\n \"Dest. Address Port RecvQ SendQ\\n\");\n\n for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {\n if (so->so_state & SS_HOSTFWD) {\n state = \"HOST_FORWARD\";\n } else if (so->so_tcpcb) {\n state = tcpstates[so->so_tcpcb->t_state];\n } else {\n state = \"NONE\";\n }\n if (so->so_state & (SS_HOSTFWD | SS_INCOMING)) {\n src_len = sizeof(src);\n getsockname(so->s, (struct sockaddr *)&src, &src_len);\n dst_addr = so->so_laddr;\n dst_port = so->so_lport;\n } else {\n src.sin_addr = so->so_laddr;\n src.sin_port = so->so_lport;\n dst_addr = so->so_faddr;\n dst_port = so->so_fport;\n }\n n = snprintf(buf, sizeof(buf), \" TCP[%s]\", state);\n memset(&buf[n], ' ', 19 - n);\n buf[19] = 0;\n monitor_printf(mon, \"%s %3d %15s %5d \", buf, so->s,\n src.sin_addr.s_addr ? inet_ntoa(src.sin_addr) : \"*\",\n ntohs(src.sin_port));\n monitor_printf(mon, \"%15s %5d %5d %5d\\n\",\n inet_ntoa(dst_addr), ntohs(dst_port),\n so->so_rcv.sb_cc, so->so_snd.sb_cc);\n }\n\n for (so = slirp->udb.so_next; so != &slirp->udb; so = so->so_next) {\n if (so->so_state & SS_HOSTFWD) {\n n = snprintf(buf, sizeof(buf), \" UDP[HOST_FORWARD]\");\n src_len = sizeof(src);\n getsockname(so->s, (struct sockaddr *)&src, &src_len);\n dst_addr = so->so_laddr;\n dst_port = so->so_lport;\n } else {\n n = snprintf(buf, sizeof(buf), \" UDP[%d sec]\",\n (so->so_expire - curtime) / 1000);\n src.sin_addr = so->so_laddr;\n src.sin_port = so->so_lport;\n dst_addr = so->so_faddr;\n dst_port = so->so_fport;\n }\n memset(&buf[n], ' ', 19 - n);\n buf[19] = 0;\n monitor_printf(mon, \"%s %3d %15s %5d \", buf, so->s,\n src.sin_addr.s_addr ? inet_ntoa(src.sin_addr) : \"*\",\n ntohs(src.sin_port));\n monitor_printf(mon, \"%15s %5d %5d %5d\\n\",\n inet_ntoa(dst_addr), ntohs(dst_port),\n so->so_rcv.sb_cc, so->so_snd.sb_cc);\n }\n}\n#endif\n"], ["/linuxpdf/tinyemu/slirp/tcp_input.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_input.c\t8.5 (Berkeley) 4/10/94\n * tcp_input.c,v 1.10 1994/10/13 18:36:32 wollman Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n#define\tTCPREXMTTHRESH 3\n\n#define TCP_PAWS_IDLE\t(24 * 24 * 60 * 60 * PR_SLOWHZ)\n\n/* for modulo comparisons of timestamps */\n#define TSTMP_LT(a,b)\t((int)((a)-(b)) < 0)\n#define TSTMP_GEQ(a,b)\t((int)((a)-(b)) >= 0)\n\n/*\n * Insert segment ti into reassembly queue of tcp with\n * control block tp. Return TH_FIN if reassembly now includes\n * a segment with FIN. The macro form does the common case inline\n * (segment is the next to be received on an established connection,\n * and the queue is empty), avoiding linkage into and removal\n * from the queue and repetition of various conversions.\n * Set DELACK for segments received in order, but ack immediately\n * when segments are out of order (so fast retransmit can work).\n */\n#ifdef TCP_ACK_HACK\n#define TCP_REASS(tp, ti, m, so, flags) {\\\n if ((ti)->ti_seq == (tp)->rcv_nxt && \\\n tcpfrag_list_empty(tp) && \\\n (tp)->t_state == TCPS_ESTABLISHED) {\\\n if (ti->ti_flags & TH_PUSH) \\\n tp->t_flags |= TF_ACKNOW; \\\n else \\\n tp->t_flags |= TF_DELACK; \\\n (tp)->rcv_nxt += (ti)->ti_len; \\\n flags = (ti)->ti_flags & TH_FIN; \\\n if (so->so_emu) { \\\n\t\t if (tcp_emu((so),(m))) sbappend((so), (m)); \\\n\t } else \\\n\t \t sbappend((so), (m)); \\\n\t} else {\\\n (flags) = tcp_reass((tp), (ti), (m)); \\\n tp->t_flags |= TF_ACKNOW; \\\n } \\\n}\n#else\n#define\tTCP_REASS(tp, ti, m, so, flags) { \\\n\tif ((ti)->ti_seq == (tp)->rcv_nxt && \\\n tcpfrag_list_empty(tp) && \\\n\t (tp)->t_state == TCPS_ESTABLISHED) { \\\n\t\ttp->t_flags |= TF_DELACK; \\\n\t\t(tp)->rcv_nxt += (ti)->ti_len; \\\n\t\tflags = (ti)->ti_flags & TH_FIN; \\\n\t\tif (so->so_emu) { \\\n\t\t\tif (tcp_emu((so),(m))) sbappend(so, (m)); \\\n\t\t} else \\\n\t\t\tsbappend((so), (m)); \\\n\t} else { \\\n\t\t(flags) = tcp_reass((tp), (ti), (m)); \\\n\t\ttp->t_flags |= TF_ACKNOW; \\\n\t} \\\n}\n#endif\nstatic void tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt,\n struct tcpiphdr *ti);\nstatic void tcp_xmit_timer(register struct tcpcb *tp, int rtt);\n\nstatic int\ntcp_reass(register struct tcpcb *tp, register struct tcpiphdr *ti,\n struct mbuf *m)\n{\n\tregister struct tcpiphdr *q;\n\tstruct socket *so = tp->t_socket;\n\tint flags;\n\n\t/*\n\t * Call with ti==NULL after become established to\n\t * force pre-ESTABLISHED data up to user socket.\n\t */\n if (ti == NULL)\n\t\tgoto present;\n\n\t/*\n\t * Find a segment which begins after this one does.\n\t */\n\tfor (q = tcpfrag_list_first(tp); !tcpfrag_list_end(q, tp);\n q = tcpiphdr_next(q))\n\t\tif (SEQ_GT(q->ti_seq, ti->ti_seq))\n\t\t\tbreak;\n\n\t/*\n\t * If there is a preceding segment, it may provide some of\n\t * our data already. If so, drop the data from the incoming\n\t * segment. If it provides all of our data, drop us.\n\t */\n\tif (!tcpfrag_list_end(tcpiphdr_prev(q), tp)) {\n\t\tregister int i;\n\t\tq = tcpiphdr_prev(q);\n\t\t/* conversion to int (in i) handles seq wraparound */\n\t\ti = q->ti_seq + q->ti_len - ti->ti_seq;\n\t\tif (i > 0) {\n\t\t\tif (i >= ti->ti_len) {\n\t\t\t\tm_freem(m);\n\t\t\t\t/*\n\t\t\t\t * Try to present any queued data\n\t\t\t\t * at the left window edge to the user.\n\t\t\t\t * This is needed after the 3-WHS\n\t\t\t\t * completes.\n\t\t\t\t */\n\t\t\t\tgoto present; /* ??? */\n\t\t\t}\n\t\t\tm_adj(m, i);\n\t\t\tti->ti_len -= i;\n\t\t\tti->ti_seq += i;\n\t\t}\n\t\tq = tcpiphdr_next(q);\n\t}\n\tti->ti_mbuf = m;\n\n\t/*\n\t * While we overlap succeeding segments trim them or,\n\t * if they are completely covered, dequeue them.\n\t */\n\twhile (!tcpfrag_list_end(q, tp)) {\n\t\tregister int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;\n\t\tif (i <= 0)\n\t\t\tbreak;\n\t\tif (i < q->ti_len) {\n\t\t\tq->ti_seq += i;\n\t\t\tq->ti_len -= i;\n\t\t\tm_adj(q->ti_mbuf, i);\n\t\t\tbreak;\n\t\t}\n\t\tq = tcpiphdr_next(q);\n\t\tm = tcpiphdr_prev(q)->ti_mbuf;\n\t\tremque(tcpiphdr2qlink(tcpiphdr_prev(q)));\n\t\tm_freem(m);\n\t}\n\n\t/*\n\t * Stick new segment in its place.\n\t */\n\tinsque(tcpiphdr2qlink(ti), tcpiphdr2qlink(tcpiphdr_prev(q)));\n\npresent:\n\t/*\n\t * Present data to user, advancing rcv_nxt through\n\t * completed sequence space.\n\t */\n\tif (!TCPS_HAVEESTABLISHED(tp->t_state))\n\t\treturn (0);\n\tti = tcpfrag_list_first(tp);\n\tif (tcpfrag_list_end(ti, tp) || ti->ti_seq != tp->rcv_nxt)\n\t\treturn (0);\n\tif (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)\n\t\treturn (0);\n\tdo {\n\t\ttp->rcv_nxt += ti->ti_len;\n\t\tflags = ti->ti_flags & TH_FIN;\n\t\tremque(tcpiphdr2qlink(ti));\n\t\tm = ti->ti_mbuf;\n\t\tti = tcpiphdr_next(ti);\n\t\tif (so->so_state & SS_FCANTSENDMORE)\n\t\t\tm_freem(m);\n\t\telse {\n\t\t\tif (so->so_emu) {\n\t\t\t\tif (tcp_emu(so,m)) sbappend(so, m);\n\t\t\t} else\n\t\t\t\tsbappend(so, m);\n\t\t}\n\t} while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);\n\treturn (flags);\n}\n\n/*\n * TCP input routine, follows pages 65-76 of the\n * protocol specification dated September, 1981 very closely.\n */\nvoid\ntcp_input(struct mbuf *m, int iphlen, struct socket *inso)\n{\n \tstruct ip save_ip, *ip;\n\tregister struct tcpiphdr *ti;\n\tcaddr_t optp = NULL;\n\tint optlen = 0;\n\tint len, tlen, off;\n register struct tcpcb *tp = NULL;\n\tregister int tiflags;\n struct socket *so = NULL;\n\tint todrop, acked, ourfinisacked, needoutput = 0;\n\tint iss = 0;\n\tu_long tiwin;\n\tint ret;\n struct ex_list *ex_ptr;\n Slirp *slirp;\n\n\tDEBUG_CALL(\"tcp_input\");\n\tDEBUG_ARGS((dfd,\" m = %8lx iphlen = %2d inso = %lx\\n\",\n\t\t (long )m, iphlen, (long )inso ));\n\n\t/*\n\t * If called with m == 0, then we're continuing the connect\n\t */\n\tif (m == NULL) {\n\t\tso = inso;\n\t\tslirp = so->slirp;\n\n\t\t/* Re-set a few variables */\n\t\ttp = sototcpcb(so);\n\t\tm = so->so_m;\n so->so_m = NULL;\n\t\tti = so->so_ti;\n\t\ttiwin = ti->ti_win;\n\t\ttiflags = ti->ti_flags;\n\n\t\tgoto cont_conn;\n\t}\n\tslirp = m->slirp;\n\n\t/*\n\t * Get IP and TCP header together in first mbuf.\n\t * Note: IP leaves IP header in first mbuf.\n\t */\n\tti = mtod(m, struct tcpiphdr *);\n\tif (iphlen > sizeof(struct ip )) {\n\t ip_stripoptions(m, (struct mbuf *)0);\n\t iphlen=sizeof(struct ip );\n\t}\n\t/* XXX Check if too short */\n\n\n\t/*\n\t * Save a copy of the IP header in case we want restore it\n\t * for sending an ICMP error message in response.\n\t */\n\tip=mtod(m, struct ip *);\n\tsave_ip = *ip;\n\tsave_ip.ip_len+= iphlen;\n\n\t/*\n\t * Checksum extended TCP header and data.\n\t */\n\ttlen = ((struct ip *)ti)->ip_len;\n tcpiphdr2qlink(ti)->next = tcpiphdr2qlink(ti)->prev = NULL;\n memset(&ti->ti_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));\n\tti->ti_x1 = 0;\n\tti->ti_len = htons((uint16_t)tlen);\n\tlen = sizeof(struct ip ) + tlen;\n\tif(cksum(m, len)) {\n\t goto drop;\n\t}\n\n\t/*\n\t * Check that TCP offset makes sense,\n\t * pull out TCP options and adjust length.\t\tXXX\n\t */\n\toff = ti->ti_off << 2;\n\tif (off < sizeof (struct tcphdr) || off > tlen) {\n\t goto drop;\n\t}\n\ttlen -= off;\n\tti->ti_len = tlen;\n\tif (off > sizeof (struct tcphdr)) {\n\t optlen = off - sizeof (struct tcphdr);\n\t optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);\n\t}\n\ttiflags = ti->ti_flags;\n\n\t/*\n\t * Convert TCP protocol specific fields to host format.\n\t */\n\tNTOHL(ti->ti_seq);\n\tNTOHL(ti->ti_ack);\n\tNTOHS(ti->ti_win);\n\tNTOHS(ti->ti_urp);\n\n\t/*\n\t * Drop TCP, IP headers and TCP options.\n\t */\n\tm->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\tm->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\n if (slirp->restricted) {\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_fport == ti->ti_dport &&\n ti->ti_dst.s_addr == ex_ptr->ex_addr.s_addr) {\n break;\n }\n }\n if (!ex_ptr)\n goto drop;\n }\n\t/*\n\t * Locate pcb for segment.\n\t */\nfindso:\n\tso = slirp->tcp_last_so;\n\tif (so->so_fport != ti->ti_dport ||\n\t so->so_lport != ti->ti_sport ||\n\t so->so_laddr.s_addr != ti->ti_src.s_addr ||\n\t so->so_faddr.s_addr != ti->ti_dst.s_addr) {\n\t\tso = solookup(&slirp->tcb, ti->ti_src, ti->ti_sport,\n\t\t\t ti->ti_dst, ti->ti_dport);\n\t\tif (so)\n\t\t\tslirp->tcp_last_so = so;\n\t}\n\n\t/*\n\t * If the state is CLOSED (i.e., TCB does not exist) then\n\t * all data in the incoming segment is discarded.\n\t * If the TCB exists but is in CLOSED state, it is embryonic,\n\t * but should either do a listen or a connect soon.\n\t *\n\t * state == CLOSED means we've done socreate() but haven't\n\t * attached it to a protocol yet...\n\t *\n\t * XXX If a TCB does not exist, and the TH_SYN flag is\n\t * the only flag set, then create a session, mark it\n\t * as if it was LISTENING, and continue...\n\t */\n if (so == NULL) {\n\t if ((tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) != TH_SYN)\n\t goto dropwithreset;\n\n\t if ((so = socreate(slirp)) == NULL)\n\t goto dropwithreset;\n\t if (tcp_attach(so) < 0) {\n\t free(so); /* Not sofree (if it failed, it's not insqued) */\n\t goto dropwithreset;\n\t }\n\n\t sbreserve(&so->so_snd, TCP_SNDSPACE);\n\t sbreserve(&so->so_rcv, TCP_RCVSPACE);\n\n\t so->so_laddr = ti->ti_src;\n\t so->so_lport = ti->ti_sport;\n\t so->so_faddr = ti->ti_dst;\n\t so->so_fport = ti->ti_dport;\n\n\t if ((so->so_iptos = tcp_tos(so)) == 0)\n\t so->so_iptos = ((struct ip *)ti)->ip_tos;\n\n\t tp = sototcpcb(so);\n\t tp->t_state = TCPS_LISTEN;\n\t}\n\n /*\n * If this is a still-connecting socket, this probably\n * a retransmit of the SYN. Whether it's a retransmit SYN\n\t * or something else, we nuke it.\n */\n if (so->so_state & SS_ISFCONNECTING)\n goto drop;\n\n\ttp = sototcpcb(so);\n\n\t/* XXX Should never fail */\n if (tp == NULL)\n\t\tgoto dropwithreset;\n\tif (tp->t_state == TCPS_CLOSED)\n\t\tgoto drop;\n\n\ttiwin = ti->ti_win;\n\n\t/*\n\t * Segment received on connection.\n\t * Reset idle time and keep-alive timer.\n\t */\n\ttp->t_idle = 0;\n\tif (SO_OPTIONS)\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;\n\telse\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;\n\n\t/*\n\t * Process options if not in LISTEN state,\n\t * else do it below (after getting remote address).\n\t */\n\tif (optp && tp->t_state != TCPS_LISTEN)\n\t\ttcp_dooptions(tp, (u_char *)optp, optlen, ti);\n\n\t/*\n\t * Header prediction: check for the two common cases\n\t * of a uni-directional data xfer. If the packet has\n\t * no control flags, is in-sequence, the window didn't\n\t * change and we're not retransmitting, it's a\n\t * candidate. If the length is zero and the ack moved\n\t * forward, we're the sender side of the xfer. Just\n\t * free the data acked & wake any higher level process\n\t * that was blocked waiting for space. If the length\n\t * is non-zero and the ack didn't move, we're the\n\t * receiver side. If we're getting packets in-order\n\t * (the reassembly queue is empty), add the data to\n\t * the socket buffer and note that we need a delayed ack.\n\t *\n\t * XXX Some of these tests are not needed\n\t * eg: the tiwin == tp->snd_wnd prevents many more\n\t * predictions.. with no *real* advantage..\n\t */\n\tif (tp->t_state == TCPS_ESTABLISHED &&\n\t (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&\n\t ti->ti_seq == tp->rcv_nxt &&\n\t tiwin && tiwin == tp->snd_wnd &&\n\t tp->snd_nxt == tp->snd_max) {\n\t\tif (ti->ti_len == 0) {\n\t\t\tif (SEQ_GT(ti->ti_ack, tp->snd_una) &&\n\t\t\t SEQ_LEQ(ti->ti_ack, tp->snd_max) &&\n\t\t\t tp->snd_cwnd >= tp->snd_wnd) {\n\t\t\t\t/*\n\t\t\t\t * this is a pure ack for outstanding data.\n\t\t\t\t */\n\t\t\t\tif (tp->t_rtt &&\n\t\t\t\t SEQ_GT(ti->ti_ack, tp->t_rtseq))\n\t\t\t\t\ttcp_xmit_timer(tp, tp->t_rtt);\n\t\t\t\tacked = ti->ti_ack - tp->snd_una;\n\t\t\t\tsbdrop(&so->so_snd, acked);\n\t\t\t\ttp->snd_una = ti->ti_ack;\n\t\t\t\tm_freem(m);\n\n\t\t\t\t/*\n\t\t\t\t * If all outstanding data are acked, stop\n\t\t\t\t * retransmit timer, otherwise restart timer\n\t\t\t\t * using current (possibly backed-off) value.\n\t\t\t\t * If process is waiting for space,\n\t\t\t\t * wakeup/selwakeup/signal. If data\n\t\t\t\t * are ready to send, let tcp_output\n\t\t\t\t * decide between more output or persist.\n\t\t\t\t */\n\t\t\t\tif (tp->snd_una == tp->snd_max)\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\t\telse if (tp->t_timer[TCPT_PERSIST] == 0)\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\n\t\t\t\t/*\n\t\t\t\t * This is called because sowwakeup might have\n\t\t\t\t * put data into so_snd. Since we don't so sowwakeup,\n\t\t\t\t * we don't need this.. XXX???\n\t\t\t\t */\n\t\t\t\tif (so->so_snd.sb_cc)\n\t\t\t\t\t(void) tcp_output(tp);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (ti->ti_ack == tp->snd_una &&\n\t\t tcpfrag_list_empty(tp) &&\n\t\t ti->ti_len <= sbspace(&so->so_rcv)) {\n\t\t\t/*\n\t\t\t * this is a pure, in-sequence data packet\n\t\t\t * with nothing on the reassembly queue and\n\t\t\t * we have enough buffer space to take it.\n\t\t\t */\n\t\t\ttp->rcv_nxt += ti->ti_len;\n\t\t\t/*\n\t\t\t * Add data to socket buffer.\n\t\t\t */\n\t\t\tif (so->so_emu) {\n\t\t\t\tif (tcp_emu(so,m)) sbappend(so, m);\n\t\t\t} else\n\t\t\t\tsbappend(so, m);\n\n\t\t\t/*\n\t\t\t * If this is a short packet, then ACK now - with Nagel\n\t\t\t *\tcongestion avoidance sender won't send more until\n\t\t\t *\the gets an ACK.\n\t\t\t *\n\t\t\t * It is better to not delay acks at all to maximize\n\t\t\t * TCP throughput. See RFC 2581.\n\t\t\t */\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttcp_output(tp);\n\t\t\treturn;\n\t\t}\n\t} /* header prediction */\n\t/*\n\t * Calculate amount of space in receive window,\n\t * and then do TCP input processing.\n\t * Receive window is amount of space in rcv queue,\n\t * but not less than advertised window.\n\t */\n\t{ int win;\n win = sbspace(&so->so_rcv);\n\t if (win < 0)\n\t win = 0;\n\t tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));\n\t}\n\n\tswitch (tp->t_state) {\n\n\t/*\n\t * If the state is LISTEN then ignore segment if it contains an RST.\n\t * If the segment contains an ACK then it is bad and send a RST.\n\t * If it does not contain a SYN then it is not interesting; drop it.\n\t * Don't bother responding if the destination was a broadcast.\n\t * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial\n\t * tp->iss, and send a segment:\n\t * \n\t * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.\n\t * Fill in remote peer address fields if not previously specified.\n\t * Enter SYN_RECEIVED state, and process any other fields of this\n\t * segment in this state.\n\t */\n\tcase TCPS_LISTEN: {\n\n\t if (tiflags & TH_RST)\n\t goto drop;\n\t if (tiflags & TH_ACK)\n\t goto dropwithreset;\n\t if ((tiflags & TH_SYN) == 0)\n\t goto drop;\n\n\t /*\n\t * This has way too many gotos...\n\t * But a bit of spaghetti code never hurt anybody :)\n\t */\n\n\t /*\n\t * If this is destined for the control address, then flag to\n\t * tcp_ctl once connected, otherwise connect\n\t */\n\t if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n\t slirp->vnetwork_addr.s_addr) {\n\t if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr &&\n\t\tso->so_faddr.s_addr != slirp->vnameserver_addr.s_addr) {\n\t\t/* May be an add exec */\n\t\tfor (ex_ptr = slirp->exec_list; ex_ptr;\n\t\t ex_ptr = ex_ptr->ex_next) {\n\t\t if(ex_ptr->ex_fport == so->so_fport &&\n\t\t so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {\n\t\t so->so_state |= SS_CTL;\n\t\t break;\n\t\t }\n\t\t}\n\t\tif (so->so_state & SS_CTL) {\n\t\t goto cont_input;\n\t\t}\n\t }\n\t /* CTL_ALIAS: Do nothing, tcp_fconnect will be called on it */\n\t }\n\n\t if (so->so_emu & EMU_NOCONNECT) {\n\t so->so_emu &= ~EMU_NOCONNECT;\n\t goto cont_input;\n\t }\n\n\t if((tcp_fconnect(so) == -1) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK)) {\n\t u_char code=ICMP_UNREACH_NET;\n\t DEBUG_MISC((dfd,\" tcp fconnect errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t if(errno == ECONNREFUSED) {\n\t /* ACK the SYN, send RST to refuse the connection */\n\t tcp_respond(tp, ti, m, ti->ti_seq+1, (tcp_seq)0,\n\t\t\t TH_RST|TH_ACK);\n\t } else {\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t HTONL(ti->ti_seq); /* restore tcp header */\n\t HTONL(ti->ti_ack);\n\t HTONS(ti->ti_win);\n\t HTONS(ti->ti_urp);\n\t m->m_data -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\t m->m_len += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\t *ip=save_ip;\n\t icmp_error(m, ICMP_UNREACH,code, 0,strerror(errno));\n\t }\n tcp_close(tp);\n\t m_free(m);\n\t } else {\n\t /*\n\t * Haven't connected yet, save the current mbuf\n\t * and ti, and return\n\t * XXX Some OS's don't tell us whether the connect()\n\t * succeeded or not. So we must time it out.\n\t */\n\t so->so_m = m;\n\t so->so_ti = ti;\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\t tp->t_state = TCPS_SYN_RECEIVED;\n\t }\n\t return;\n\n\tcont_conn:\n\t /* m==NULL\n\t * Check if the connect succeeded\n\t */\n\t if (so->so_state & SS_NOFDREF) {\n\t tp = tcp_close(tp);\n\t goto dropwithreset;\n\t }\n\tcont_input:\n\t tcp_template(tp);\n\n\t if (optp)\n\t tcp_dooptions(tp, (u_char *)optp, optlen, ti);\n\n\t if (iss)\n\t tp->iss = iss;\n\t else\n\t tp->iss = slirp->tcp_iss;\n\t slirp->tcp_iss += TCP_ISSINCR/2;\n\t tp->irs = ti->ti_seq;\n\t tcp_sendseqinit(tp);\n\t tcp_rcvseqinit(tp);\n\t tp->t_flags |= TF_ACKNOW;\n\t tp->t_state = TCPS_SYN_RECEIVED;\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\t goto trimthenstep6;\n\t} /* case TCPS_LISTEN */\n\n\t/*\n\t * If the state is SYN_SENT:\n\t *\tif seg contains an ACK, but not for our SYN, drop the input.\n\t *\tif seg contains a RST, then drop the connection.\n\t *\tif seg does not contain SYN, then drop it.\n\t * Otherwise this is an acceptable SYN segment\n\t *\tinitialize tp->rcv_nxt and tp->irs\n\t *\tif seg contains ack then advance tp->snd_una\n\t *\tif SYN has been acked change to ESTABLISHED else SYN_RCVD state\n\t *\tarrange for segment to be acked (eventually)\n\t *\tcontinue processing rest of data/controls, beginning with URG\n\t */\n\tcase TCPS_SYN_SENT:\n\t\tif ((tiflags & TH_ACK) &&\n\t\t (SEQ_LEQ(ti->ti_ack, tp->iss) ||\n\t\t SEQ_GT(ti->ti_ack, tp->snd_max)))\n\t\t\tgoto dropwithreset;\n\n\t\tif (tiflags & TH_RST) {\n if (tiflags & TH_ACK) {\n tcp_drop(tp, 0); /* XXX Check t_softerror! */\n }\n\t\t\tgoto drop;\n\t\t}\n\n\t\tif ((tiflags & TH_SYN) == 0)\n\t\t\tgoto drop;\n\t\tif (tiflags & TH_ACK) {\n\t\t\ttp->snd_una = ti->ti_ack;\n\t\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_una))\n\t\t\t\ttp->snd_nxt = tp->snd_una;\n\t\t}\n\n\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\ttp->irs = ti->ti_seq;\n\t\ttcp_rcvseqinit(tp);\n\t\ttp->t_flags |= TF_ACKNOW;\n\t\tif (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {\n\t\t\tsoisfconnected(so);\n\t\t\ttp->t_state = TCPS_ESTABLISHED;\n\n\t\t\t(void) tcp_reass(tp, (struct tcpiphdr *)0,\n\t\t\t\t(struct mbuf *)0);\n\t\t\t/*\n\t\t\t * if we didn't have to retransmit the SYN,\n\t\t\t * use its rtt as our initial srtt & rtt var.\n\t\t\t */\n\t\t\tif (tp->t_rtt)\n\t\t\t\ttcp_xmit_timer(tp, tp->t_rtt);\n\t\t} else\n\t\t\ttp->t_state = TCPS_SYN_RECEIVED;\n\ntrimthenstep6:\n\t\t/*\n\t\t * Advance ti->ti_seq to correspond to first data byte.\n\t\t * If data, trim to stay within window,\n\t\t * dropping FIN if necessary.\n\t\t */\n\t\tti->ti_seq++;\n\t\tif (ti->ti_len > tp->rcv_wnd) {\n\t\t\ttodrop = ti->ti_len - tp->rcv_wnd;\n\t\t\tm_adj(m, -todrop);\n\t\t\tti->ti_len = tp->rcv_wnd;\n\t\t\ttiflags &= ~TH_FIN;\n\t\t}\n\t\ttp->snd_wl1 = ti->ti_seq - 1;\n\t\ttp->rcv_up = ti->ti_seq;\n\t\tgoto step6;\n\t} /* switch tp->t_state */\n\t/*\n\t * States other than LISTEN or SYN_SENT.\n\t * Check that at least some bytes of segment are within\n\t * receive window. If segment begins before rcv_nxt,\n\t * drop leading data (and SYN); if nothing left, just ack.\n\t */\n\ttodrop = tp->rcv_nxt - ti->ti_seq;\n\tif (todrop > 0) {\n\t\tif (tiflags & TH_SYN) {\n\t\t\ttiflags &= ~TH_SYN;\n\t\t\tti->ti_seq++;\n\t\t\tif (ti->ti_urp > 1)\n\t\t\t\tti->ti_urp--;\n\t\t\telse\n\t\t\t\ttiflags &= ~TH_URG;\n\t\t\ttodrop--;\n\t\t}\n\t\t/*\n\t\t * Following if statement from Stevens, vol. 2, p. 960.\n\t\t */\n\t\tif (todrop > ti->ti_len\n\t\t || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {\n\t\t\t/*\n\t\t\t * Any valid FIN must be to the left of the window.\n\t\t\t * At this point the FIN must be a duplicate or out\n\t\t\t * of sequence; drop it.\n\t\t\t */\n\t\t\ttiflags &= ~TH_FIN;\n\n\t\t\t/*\n\t\t\t * Send an ACK to resynchronize and drop any data.\n\t\t\t * But keep on processing for RST or ACK.\n\t\t\t */\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttodrop = ti->ti_len;\n\t\t}\n\t\tm_adj(m, todrop);\n\t\tti->ti_seq += todrop;\n\t\tti->ti_len -= todrop;\n\t\tif (ti->ti_urp > todrop)\n\t\t\tti->ti_urp -= todrop;\n\t\telse {\n\t\t\ttiflags &= ~TH_URG;\n\t\t\tti->ti_urp = 0;\n\t\t}\n\t}\n\t/*\n\t * If new data are received on a connection after the\n\t * user processes are gone, then RST the other end.\n\t */\n\tif ((so->so_state & SS_NOFDREF) &&\n\t tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {\n\t\ttp = tcp_close(tp);\n\t\tgoto dropwithreset;\n\t}\n\n\t/*\n\t * If segment ends after window, drop trailing data\n\t * (and PUSH and FIN); if nothing left, just ACK.\n\t */\n\ttodrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);\n\tif (todrop > 0) {\n\t\tif (todrop >= ti->ti_len) {\n\t\t\t/*\n\t\t\t * If a new connection request is received\n\t\t\t * while in TIME_WAIT, drop the old connection\n\t\t\t * and start over if the sequence numbers\n\t\t\t * are above the previous ones.\n\t\t\t */\n\t\t\tif (tiflags & TH_SYN &&\n\t\t\t tp->t_state == TCPS_TIME_WAIT &&\n\t\t\t SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {\n\t\t\t\tiss = tp->rcv_nxt + TCP_ISSINCR;\n\t\t\t\ttp = tcp_close(tp);\n\t\t\t\tgoto findso;\n\t\t\t}\n\t\t\t/*\n\t\t\t * If window is closed can only take segments at\n\t\t\t * window edge, and have to drop data and PUSH from\n\t\t\t * incoming segments. Continue processing, but\n\t\t\t * remember to ack. Otherwise, drop segment\n\t\t\t * and ack.\n\t\t\t */\n\t\t\tif (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {\n\t\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\t} else {\n\t\t\t\tgoto dropafterack;\n\t\t\t}\n\t\t}\n\t\tm_adj(m, -todrop);\n\t\tti->ti_len -= todrop;\n\t\ttiflags &= ~(TH_PUSH|TH_FIN);\n\t}\n\n\t/*\n\t * If the RST bit is set examine the state:\n\t * SYN_RECEIVED STATE:\n\t *\tIf passive open, return to LISTEN state.\n\t *\tIf active open, inform user that connection was refused.\n\t * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:\n\t *\tInform user that connection was reset, and close tcb.\n\t * CLOSING, LAST_ACK, TIME_WAIT STATES\n\t *\tClose the tcb.\n\t */\n\tif (tiflags&TH_RST) switch (tp->t_state) {\n\n\tcase TCPS_SYN_RECEIVED:\n\tcase TCPS_ESTABLISHED:\n\tcase TCPS_FIN_WAIT_1:\n\tcase TCPS_FIN_WAIT_2:\n\tcase TCPS_CLOSE_WAIT:\n\t\ttp->t_state = TCPS_CLOSED;\n tcp_close(tp);\n\t\tgoto drop;\n\n\tcase TCPS_CLOSING:\n\tcase TCPS_LAST_ACK:\n\tcase TCPS_TIME_WAIT:\n tcp_close(tp);\n\t\tgoto drop;\n\t}\n\n\t/*\n\t * If a SYN is in the window, then this is an\n\t * error and we send an RST and drop the connection.\n\t */\n\tif (tiflags & TH_SYN) {\n\t\ttp = tcp_drop(tp,0);\n\t\tgoto dropwithreset;\n\t}\n\n\t/*\n\t * If the ACK bit is off we drop the segment and return.\n\t */\n\tif ((tiflags & TH_ACK) == 0) goto drop;\n\n\t/*\n\t * Ack processing.\n\t */\n\tswitch (tp->t_state) {\n\t/*\n\t * In SYN_RECEIVED state if the ack ACKs our SYN then enter\n\t * ESTABLISHED state and continue processing, otherwise\n\t * send an RST. una<=ack<=max\n\t */\n\tcase TCPS_SYN_RECEIVED:\n\n\t\tif (SEQ_GT(tp->snd_una, ti->ti_ack) ||\n\t\t SEQ_GT(ti->ti_ack, tp->snd_max))\n\t\t\tgoto dropwithreset;\n\t\ttp->t_state = TCPS_ESTABLISHED;\n\t\t/*\n\t\t * The sent SYN is ack'ed with our sequence number +1\n\t\t * The first data byte already in the buffer will get\n\t\t * lost if no correction is made. This is only needed for\n\t\t * SS_CTL since the buffer is empty otherwise.\n\t\t * tp->snd_una++; or:\n\t\t */\n\t\ttp->snd_una=ti->ti_ack;\n\t\tif (so->so_state & SS_CTL) {\n\t\t /* So tcp_ctl reports the right state */\n\t\t ret = tcp_ctl(so);\n\t\t if (ret == 1) {\n\t\t soisfconnected(so);\n\t\t so->so_state &= ~SS_CTL; /* success XXX */\n\t\t } else if (ret == 2) {\n\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t so->so_state |= SS_NOFDREF; /* CTL_CMD */\n\t\t } else {\n\t\t needoutput = 1;\n\t\t tp->t_state = TCPS_FIN_WAIT_1;\n\t\t }\n\t\t} else {\n\t\t soisfconnected(so);\n\t\t}\n\n\t\t(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);\n\t\ttp->snd_wl1 = ti->ti_seq - 1;\n\t\t/* Avoid ack processing; snd_una==ti_ack => dup ack */\n\t\tgoto synrx_to_est;\n\t\t/* fall into ... */\n\n\t/*\n\t * In ESTABLISHED state: drop duplicate ACKs; ACK out of range\n\t * ACKs. If the ack is in the range\n\t *\ttp->snd_una < ti->ti_ack <= tp->snd_max\n\t * then advance tp->snd_una to ti->ti_ack and drop\n\t * data from the retransmission queue. If this ACK reflects\n\t * more up to date window information we update our window information.\n\t */\n\tcase TCPS_ESTABLISHED:\n\tcase TCPS_FIN_WAIT_1:\n\tcase TCPS_FIN_WAIT_2:\n\tcase TCPS_CLOSE_WAIT:\n\tcase TCPS_CLOSING:\n\tcase TCPS_LAST_ACK:\n\tcase TCPS_TIME_WAIT:\n\n\t\tif (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {\n\t\t\tif (ti->ti_len == 0 && tiwin == tp->snd_wnd) {\n\t\t\t DEBUG_MISC((dfd,\" dup ack m = %lx so = %lx \\n\",\n\t\t\t\t (long )m, (long )so));\n\t\t\t\t/*\n\t\t\t\t * If we have outstanding data (other than\n\t\t\t\t * a window probe), this is a completely\n\t\t\t\t * duplicate ack (ie, window info didn't\n\t\t\t\t * change), the ack is the biggest we've\n\t\t\t\t * seen and we've seen exactly our rexmt\n\t\t\t\t * threshold of them, assume a packet\n\t\t\t\t * has been dropped and retransmit it.\n\t\t\t\t * Kludge snd_nxt & the congestion\n\t\t\t\t * window so we send only this one\n\t\t\t\t * packet.\n\t\t\t\t *\n\t\t\t\t * We know we're losing at the current\n\t\t\t\t * window size so do congestion avoidance\n\t\t\t\t * (set ssthresh to half the current window\n\t\t\t\t * and pull our congestion window back to\n\t\t\t\t * the new ssthresh).\n\t\t\t\t *\n\t\t\t\t * Dup acks mean that packets have left the\n\t\t\t\t * network (they're now cached at the receiver)\n\t\t\t\t * so bump cwnd by the amount in the receiver\n\t\t\t\t * to keep a constant cwnd packets in the\n\t\t\t\t * network.\n\t\t\t\t */\n\t\t\t\tif (tp->t_timer[TCPT_REXMT] == 0 ||\n\t\t\t\t ti->ti_ack != tp->snd_una)\n\t\t\t\t\ttp->t_dupacks = 0;\n\t\t\t\telse if (++tp->t_dupacks == TCPREXMTTHRESH) {\n\t\t\t\t\ttcp_seq onxt = tp->snd_nxt;\n\t\t\t\t\tu_int win =\n\t\t\t\t\t min(tp->snd_wnd, tp->snd_cwnd) / 2 /\n\t\t\t\t\t\ttp->t_maxseg;\n\n\t\t\t\t\tif (win < 2)\n\t\t\t\t\t\twin = 2;\n\t\t\t\t\ttp->snd_ssthresh = win * tp->t_maxseg;\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\t\t\ttp->t_rtt = 0;\n\t\t\t\t\ttp->snd_nxt = ti->ti_ack;\n\t\t\t\t\ttp->snd_cwnd = tp->t_maxseg;\n\t\t\t\t\t(void) tcp_output(tp);\n\t\t\t\t\ttp->snd_cwnd = tp->snd_ssthresh +\n\t\t\t\t\t tp->t_maxseg * tp->t_dupacks;\n\t\t\t\t\tif (SEQ_GT(onxt, tp->snd_nxt))\n\t\t\t\t\t\ttp->snd_nxt = onxt;\n\t\t\t\t\tgoto drop;\n\t\t\t\t} else if (tp->t_dupacks > TCPREXMTTHRESH) {\n\t\t\t\t\ttp->snd_cwnd += tp->t_maxseg;\n\t\t\t\t\t(void) tcp_output(tp);\n\t\t\t\t\tgoto drop;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\ttp->t_dupacks = 0;\n\t\t\tbreak;\n\t\t}\n\tsynrx_to_est:\n\t\t/*\n\t\t * If the congestion window was inflated to account\n\t\t * for the other side's cached packets, retract it.\n\t\t */\n\t\tif (tp->t_dupacks > TCPREXMTTHRESH &&\n\t\t tp->snd_cwnd > tp->snd_ssthresh)\n\t\t\ttp->snd_cwnd = tp->snd_ssthresh;\n\t\ttp->t_dupacks = 0;\n\t\tif (SEQ_GT(ti->ti_ack, tp->snd_max)) {\n\t\t\tgoto dropafterack;\n\t\t}\n\t\tacked = ti->ti_ack - tp->snd_una;\n\n\t\t/*\n\t\t * If transmit timer is running and timed sequence\n\t\t * number was acked, update smoothed round trip time.\n\t\t * Since we now have an rtt measurement, cancel the\n\t\t * timer backoff (cf., Phil Karn's retransmit alg.).\n\t\t * Recompute the initial retransmit timer.\n\t\t */\n\t\tif (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))\n\t\t\ttcp_xmit_timer(tp,tp->t_rtt);\n\n\t\t/*\n\t\t * If all outstanding data is acked, stop retransmit\n\t\t * timer and remember to restart (more output or persist).\n\t\t * If there is more data to be acked, restart retransmit\n\t\t * timer, using current (possibly backed-off) value.\n\t\t */\n\t\tif (ti->ti_ack == tp->snd_max) {\n\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\tneedoutput = 1;\n\t\t} else if (tp->t_timer[TCPT_PERSIST] == 0)\n\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t/*\n\t\t * When new data is acked, open the congestion window.\n\t\t * If the window gives us less than ssthresh packets\n\t\t * in flight, open exponentially (maxseg per packet).\n\t\t * Otherwise open linearly: maxseg per window\n\t\t * (maxseg^2 / cwnd per packet).\n\t\t */\n\t\t{\n\t\t register u_int cw = tp->snd_cwnd;\n\t\t register u_int incr = tp->t_maxseg;\n\n\t\t if (cw > tp->snd_ssthresh)\n\t\t incr = incr * incr / cw;\n\t\t tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<snd_scale);\n\t\t}\n\t\tif (acked > so->so_snd.sb_cc) {\n\t\t\ttp->snd_wnd -= so->so_snd.sb_cc;\n\t\t\tsbdrop(&so->so_snd, (int )so->so_snd.sb_cc);\n\t\t\tourfinisacked = 1;\n\t\t} else {\n\t\t\tsbdrop(&so->so_snd, acked);\n\t\t\ttp->snd_wnd -= acked;\n\t\t\tourfinisacked = 0;\n\t\t}\n\t\ttp->snd_una = ti->ti_ack;\n\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_una))\n\t\t\ttp->snd_nxt = tp->snd_una;\n\n\t\tswitch (tp->t_state) {\n\n\t\t/*\n\t\t * In FIN_WAIT_1 STATE in addition to the processing\n\t\t * for the ESTABLISHED state if our FIN is now acknowledged\n\t\t * then enter FIN_WAIT_2.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_1:\n\t\t\tif (ourfinisacked) {\n\t\t\t\t/*\n\t\t\t\t * If we can't receive any more\n\t\t\t\t * data, then closing user can proceed.\n\t\t\t\t * Starting the timer is contrary to the\n\t\t\t\t * specification, but if we don't get a FIN\n\t\t\t\t * we'll hang forever.\n\t\t\t\t */\n\t\t\t\tif (so->so_state & SS_FCANTRCVMORE) {\n\t\t\t\t\ttp->t_timer[TCPT_2MSL] = TCP_MAXIDLE;\n\t\t\t\t}\n\t\t\t\ttp->t_state = TCPS_FIN_WAIT_2;\n\t\t\t}\n\t\t\tbreak;\n\n\t \t/*\n\t\t * In CLOSING STATE in addition to the processing for\n\t\t * the ESTABLISHED state if the ACK acknowledges our FIN\n\t\t * then enter the TIME-WAIT state, otherwise ignore\n\t\t * the segment.\n\t\t */\n\t\tcase TCPS_CLOSING:\n\t\t\tif (ourfinisacked) {\n\t\t\t\ttp->t_state = TCPS_TIME_WAIT;\n\t\t\t\ttcp_canceltimers(tp);\n\t\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In LAST_ACK, we may still be waiting for data to drain\n\t\t * and/or to be acked, as well as for the ack of our FIN.\n\t\t * If our FIN is now acknowledged, delete the TCB,\n\t\t * enter the closed state and return.\n\t\t */\n\t\tcase TCPS_LAST_ACK:\n\t\t\tif (ourfinisacked) {\n tcp_close(tp);\n\t\t\t\tgoto drop;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In TIME_WAIT state the only thing that should arrive\n\t\t * is a retransmission of the remote FIN. Acknowledge\n\t\t * it and restart the finack timer.\n\t\t */\n\t\tcase TCPS_TIME_WAIT:\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tgoto dropafterack;\n\t\t}\n\t} /* switch(tp->t_state) */\n\nstep6:\n\t/*\n\t * Update window information.\n\t * Don't look at window if no ACK: TAC's send garbage on first SYN.\n\t */\n\tif ((tiflags & TH_ACK) &&\n\t (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||\n\t (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||\n\t (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {\n\t\ttp->snd_wnd = tiwin;\n\t\ttp->snd_wl1 = ti->ti_seq;\n\t\ttp->snd_wl2 = ti->ti_ack;\n\t\tif (tp->snd_wnd > tp->max_sndwnd)\n\t\t\ttp->max_sndwnd = tp->snd_wnd;\n\t\tneedoutput = 1;\n\t}\n\n\t/*\n\t * Process segments with URG.\n\t */\n\tif ((tiflags & TH_URG) && ti->ti_urp &&\n\t TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\t/*\n\t\t * This is a kludge, but if we receive and accept\n\t\t * random urgent pointers, we'll crash in\n\t\t * soreceive. It's hard to imagine someone\n\t\t * actually wanting to send this much urgent data.\n\t\t */\n\t\tif (ti->ti_urp + so->so_rcv.sb_cc > so->so_rcv.sb_datalen) {\n\t\t\tti->ti_urp = 0;\n\t\t\ttiflags &= ~TH_URG;\n\t\t\tgoto dodata;\n\t\t}\n\t\t/*\n\t\t * If this segment advances the known urgent pointer,\n\t\t * then mark the data stream. This should not happen\n\t\t * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since\n\t\t * a FIN has been received from the remote side.\n\t\t * In these states we ignore the URG.\n\t\t *\n\t\t * According to RFC961 (Assigned Protocols),\n\t\t * the urgent pointer points to the last octet\n\t\t * of urgent data. We continue, however,\n\t\t * to consider it to indicate the first octet\n\t\t * of data past the urgent section as the original\n\t\t * spec states (in one of two places).\n\t\t */\n\t\tif (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {\n\t\t\ttp->rcv_up = ti->ti_seq + ti->ti_urp;\n\t\t\tso->so_urgc = so->so_rcv.sb_cc +\n\t\t\t\t(tp->rcv_up - tp->rcv_nxt); /* -1; */\n\t\t\ttp->rcv_up = ti->ti_seq + ti->ti_urp;\n\n\t\t}\n\t} else\n\t\t/*\n\t\t * If no out of band data is expected,\n\t\t * pull receive urgent pointer along\n\t\t * with the receive window.\n\t\t */\n\t\tif (SEQ_GT(tp->rcv_nxt, tp->rcv_up))\n\t\t\ttp->rcv_up = tp->rcv_nxt;\ndodata:\n\n\t/*\n\t * Process the segment text, merging it into the TCP sequencing queue,\n\t * and arranging for acknowledgment of receipt if necessary.\n\t * This process logically involves adjusting tp->rcv_wnd as data\n\t * is presented to the user (this happens in tcp_usrreq.c,\n\t * case PRU_RCVD). If a FIN has already been received on this\n\t * connection then we just ignore the text.\n\t */\n\tif ((ti->ti_len || (tiflags&TH_FIN)) &&\n\t TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\tTCP_REASS(tp, ti, m, so, tiflags);\n\t} else {\n\t\tm_free(m);\n\t\ttiflags &= ~TH_FIN;\n\t}\n\n\t/*\n\t * If FIN is received ACK the FIN and let the user know\n\t * that the connection is closing.\n\t */\n\tif (tiflags & TH_FIN) {\n\t\tif (TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\t\t/*\n\t\t\t * If we receive a FIN we can't send more data,\n\t\t\t * set it SS_FDRAIN\n * Shutdown the socket if there is no rx data in the\n\t\t\t * buffer.\n\t\t\t * soread() is called on completion of shutdown() and\n\t\t\t * will got to TCPS_LAST_ACK, and use tcp_output()\n\t\t\t * to send the FIN.\n\t\t\t */\n\t\t\tsofwdrain(so);\n\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttp->rcv_nxt++;\n\t\t}\n\t\tswitch (tp->t_state) {\n\n\t \t/*\n\t\t * In SYN_RECEIVED and ESTABLISHED STATES\n\t\t * enter the CLOSE_WAIT state.\n\t\t */\n\t\tcase TCPS_SYN_RECEIVED:\n\t\tcase TCPS_ESTABLISHED:\n\t\t if(so->so_emu == EMU_CTL) /* no shutdown on socket */\n\t\t tp->t_state = TCPS_LAST_ACK;\n\t\t else\n\t\t tp->t_state = TCPS_CLOSE_WAIT;\n\t\t break;\n\n\t \t/*\n\t\t * If still in FIN_WAIT_1 STATE FIN has not been acked so\n\t\t * enter the CLOSING state.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_1:\n\t\t\ttp->t_state = TCPS_CLOSING;\n\t\t\tbreak;\n\n\t \t/*\n\t\t * In FIN_WAIT_2 state enter the TIME_WAIT state,\n\t\t * starting the time-wait timer, turning off the other\n\t\t * standard timers.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_2:\n\t\t\ttp->t_state = TCPS_TIME_WAIT;\n\t\t\ttcp_canceltimers(tp);\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In TIME_WAIT state restart the 2 MSL time_wait timer.\n\t\t */\n\t\tcase TCPS_TIME_WAIT:\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/*\n\t * If this is a small packet, then ACK now - with Nagel\n\t * congestion avoidance sender won't send more until\n\t * he gets an ACK.\n\t *\n\t * See above.\n\t */\n\tif (ti->ti_len && (unsigned)ti->ti_len <= 5 &&\n\t ((struct tcpiphdr_2 *)ti)->first_char == (char)27) {\n\t\ttp->t_flags |= TF_ACKNOW;\n\t}\n\n\t/*\n\t * Return any desired output.\n\t */\n\tif (needoutput || (tp->t_flags & TF_ACKNOW)) {\n\t\t(void) tcp_output(tp);\n\t}\n\treturn;\n\ndropafterack:\n\t/*\n\t * Generate an ACK dropping incoming segment if it occupies\n\t * sequence space, where the ACK reflects our state.\n\t */\n\tif (tiflags & TH_RST)\n\t\tgoto drop;\n\tm_freem(m);\n\ttp->t_flags |= TF_ACKNOW;\n\t(void) tcp_output(tp);\n\treturn;\n\ndropwithreset:\n\t/* reuses m if m!=NULL, m_free() unnecessary */\n\tif (tiflags & TH_ACK)\n\t\ttcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);\n\telse {\n\t\tif (tiflags & TH_SYN) ti->ti_len++;\n\t\ttcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,\n\t\t TH_RST|TH_ACK);\n\t}\n\n\treturn;\n\ndrop:\n\t/*\n\t * Drop space held by incoming segment and return.\n\t */\n\tm_free(m);\n\n\treturn;\n}\n\nstatic void\ntcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcpiphdr *ti)\n{\n\tuint16_t mss;\n\tint opt, optlen;\n\n\tDEBUG_CALL(\"tcp_dooptions\");\n\tDEBUG_ARGS((dfd,\" tp = %lx cnt=%i \\n\", (long )tp, cnt));\n\n\tfor (; cnt > 0; cnt -= optlen, cp += optlen) {\n\t\topt = cp[0];\n\t\tif (opt == TCPOPT_EOL)\n\t\t\tbreak;\n\t\tif (opt == TCPOPT_NOP)\n\t\t\toptlen = 1;\n\t\telse {\n\t\t\toptlen = cp[1];\n\t\t\tif (optlen <= 0)\n\t\t\t\tbreak;\n\t\t}\n\t\tswitch (opt) {\n\n\t\tdefault:\n\t\t\tcontinue;\n\n\t\tcase TCPOPT_MAXSEG:\n\t\t\tif (optlen != TCPOLEN_MAXSEG)\n\t\t\t\tcontinue;\n\t\t\tif (!(ti->ti_flags & TH_SYN))\n\t\t\t\tcontinue;\n\t\t\tmemcpy((char *) &mss, (char *) cp + 2, sizeof(mss));\n\t\t\tNTOHS(mss);\n\t\t\t(void) tcp_mss(tp, mss);\t/* sets t_maxseg */\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n/*\n * Pull out of band byte out of a segment so\n * it doesn't appear in the user's data queue.\n * It is still reflected in the segment length for\n * sequencing purposes.\n */\n\n#ifdef notdef\n\nvoid\ntcp_pulloutofband(so, ti, m)\n\tstruct socket *so;\n\tstruct tcpiphdr *ti;\n\tregister struct mbuf *m;\n{\n\tint cnt = ti->ti_urp - 1;\n\n\twhile (cnt >= 0) {\n\t\tif (m->m_len > cnt) {\n\t\t\tchar *cp = mtod(m, caddr_t) + cnt;\n\t\t\tstruct tcpcb *tp = sototcpcb(so);\n\n\t\t\ttp->t_iobc = *cp;\n\t\t\ttp->t_oobflags |= TCPOOB_HAVEDATA;\n\t\t\tmemcpy(sp, cp+1, (unsigned)(m->m_len - cnt - 1));\n\t\t\tm->m_len--;\n\t\t\treturn;\n\t\t}\n\t\tcnt -= m->m_len;\n\t\tm = m->m_next; /* XXX WRONG! Fix it! */\n\t\tif (m == 0)\n\t\t\tbreak;\n\t}\n\tpanic(\"tcp_pulloutofband\");\n}\n\n#endif /* notdef */\n\n/*\n * Collect new round-trip time estimate\n * and update averages and current timeout.\n */\n\nstatic void\ntcp_xmit_timer(register struct tcpcb *tp, int rtt)\n{\n\tregister short delta;\n\n\tDEBUG_CALL(\"tcp_xmit_timer\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"rtt = %d\", rtt);\n\n\tif (tp->t_srtt != 0) {\n\t\t/*\n\t\t * srtt is stored as fixed point with 3 bits after the\n\t\t * binary point (i.e., scaled by 8). The following magic\n\t\t * is equivalent to the smoothing algorithm in rfc793 with\n\t\t * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed\n\t\t * point). Adjust rtt to origin 0.\n\t\t */\n\t\tdelta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);\n\t\tif ((tp->t_srtt += delta) <= 0)\n\t\t\ttp->t_srtt = 1;\n\t\t/*\n\t\t * We accumulate a smoothed rtt variance (actually, a\n\t\t * smoothed mean difference), then set the retransmit\n\t\t * timer to smoothed rtt + 4 times the smoothed variance.\n\t\t * rttvar is stored as fixed point with 2 bits after the\n\t\t * binary point (scaled by 4). The following is\n\t\t * equivalent to rfc793 smoothing with an alpha of .75\n\t\t * (rttvar = rttvar*3/4 + |delta| / 4). This replaces\n\t\t * rfc793's wired-in beta.\n\t\t */\n\t\tif (delta < 0)\n\t\t\tdelta = -delta;\n\t\tdelta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);\n\t\tif ((tp->t_rttvar += delta) <= 0)\n\t\t\ttp->t_rttvar = 1;\n\t} else {\n\t\t/*\n\t\t * No rtt measurement yet - use the unsmoothed rtt.\n\t\t * Set the variance to half the rtt (so our first\n\t\t * retransmit happens at 3*rtt).\n\t\t */\n\t\ttp->t_srtt = rtt << TCP_RTT_SHIFT;\n\t\ttp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);\n\t}\n\ttp->t_rtt = 0;\n\ttp->t_rxtshift = 0;\n\n\t/*\n\t * the retransmit should happen at rtt + 4 * rttvar.\n\t * Because of the way we do the smoothing, srtt and rttvar\n\t * will each average +1/2 tick of bias. When we compute\n\t * the retransmit timer, we want 1/2 tick of rounding and\n\t * 1 extra tick because of +-1/2 tick uncertainty in the\n\t * firing of the timer. The bias will give us exactly the\n\t * 1.5 tick we need. But, because the bias is\n\t * statistical, we have to test that we don't drop below\n\t * the minimum feasible timer (which is 2 ticks).\n\t */\n\tTCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),\n\t (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */\n\n\t/*\n\t * We received an ack for a packet that wasn't retransmitted;\n\t * it is probably safe to discard any error indications we've\n\t * received recently. This isn't quite right, but close enough\n\t * for now (a route might have failed after we sent a segment,\n\t * and the return path might not be symmetrical).\n\t */\n\ttp->t_softerror = 0;\n}\n\n/*\n * Determine a reasonable value for maxseg size.\n * If the route is known, check route for mtu.\n * If none, use an mss that can be handled on the outgoing\n * interface without forcing IP to fragment; if bigger than\n * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES\n * to utilize large mbufs. If no route is found, route has no mtu,\n * or the destination isn't local, use a default, hopefully conservative\n * size (usually 512 or the default IP max size, but no more than the mtu\n * of the interface), as we can't discover anything about intervening\n * gateways or networks. We also initialize the congestion/slow start\n * window to be a single segment if the destination isn't local.\n * While looking at the routing entry, we also initialize other path-dependent\n * parameters from pre-set or cached values in the routing entry.\n */\n\nint\ntcp_mss(struct tcpcb *tp, u_int offer)\n{\n\tstruct socket *so = tp->t_socket;\n\tint mss;\n\n\tDEBUG_CALL(\"tcp_mss\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"offer = %d\", offer);\n\n\tmss = min(IF_MTU, IF_MRU) - sizeof(struct tcpiphdr);\n\tif (offer)\n\t\tmss = min(mss, offer);\n\tmss = max(mss, 32);\n\tif (mss < tp->t_maxseg || offer != 0)\n\t tp->t_maxseg = mss;\n\n\ttp->snd_cwnd = mss;\n\n\tsbreserve(&so->so_snd, TCP_SNDSPACE + ((TCP_SNDSPACE % mss) ?\n (mss - (TCP_SNDSPACE % mss)) :\n 0));\n\tsbreserve(&so->so_rcv, TCP_RCVSPACE + ((TCP_RCVSPACE % mss) ?\n (mss - (TCP_RCVSPACE % mss)) :\n 0));\n\n\tDEBUG_MISC((dfd, \" returning mss = %d\\n\", mss));\n\n\treturn mss;\n}\n"], ["/linuxpdf/tinyemu/fs_utils.c", "/*\n * Misc FS utilities\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs_utils.h\"\n\n/* last byte is the version */\nconst uint8_t encrypted_file_magic[4] = { 0xfb, 0xa2, 0xe9, 0x01 };\n\nchar *compose_path(const char *path, const char *name)\n{\n int path_len, name_len;\n char *d, *q;\n\n if (path[0] == '\\0') {\n d = strdup(name);\n } else {\n path_len = strlen(path);\n name_len = strlen(name);\n d = malloc(path_len + 1 + name_len + 1);\n q = d;\n memcpy(q, path, path_len);\n q += path_len;\n if (path[path_len - 1] != '/')\n *q++ = '/';\n memcpy(q, name, name_len + 1);\n }\n return d;\n}\n\nchar *compose_url(const char *base_url, const char *name)\n{\n if (strchr(name, ':')) {\n return strdup(name);\n } else {\n return compose_path(base_url, name);\n }\n}\n\nvoid skip_line(const char **pp)\n{\n const char *p;\n p = *pp;\n while (*p != '\\n' && *p != '\\0')\n p++;\n if (*p == '\\n')\n p++;\n *pp = p;\n}\n\nchar *quoted_str(const char *str)\n{\n const char *s;\n char *q;\n int c;\n char *buf;\n\n if (str[0] == '\\0')\n goto use_quote;\n s = str;\n while (*s != '\\0') {\n if (*s <= ' ' || *s > '~')\n goto use_quote;\n s++;\n }\n return strdup(str);\n use_quote:\n buf = malloc(strlen(str) * 4 + 2 + 1);\n q = buf;\n s = str;\n *q++ = '\"';\n while (*s != '\\0') {\n c = *(uint8_t *)s;\n if (c < ' ' || c == 127) {\n q += sprintf(q, \"\\\\x%02x\", c);\n } else if (c == '\\\\' || c == '\\\"') {\n q += sprintf(q, \"\\\\%c\", c);\n } else {\n *q++ = c;\n }\n s++;\n }\n *q++ = '\"';\n *q = '\\0';\n return buf;\n}\n\nint parse_fname(char *buf, int buf_size, const char **pp)\n{\n const char *p;\n char *q;\n int c, h;\n \n p = *pp;\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\0')\n return -1;\n q = buf;\n if (*p == '\"') {\n p++;\n for(;;) {\n c = *p++;\n if (c == '\\0' || c == '\\n') {\n return -1;\n } else if (c == '\\\"') {\n break;\n } else if (c == '\\\\') {\n c = *p++;\n switch(c) {\n case '\\'':\n case '\\\"':\n case '\\\\':\n goto add_char;\n case 'n':\n c = '\\n';\n goto add_char;\n case 'r':\n c = '\\r';\n goto add_char;\n case 't':\n c = '\\t';\n goto add_char;\n case 'x':\n h = from_hex(*p++);\n if (h < 0)\n return -1;\n c = h << 4;\n h = from_hex(*p++);\n if (h < 0)\n return -1;\n c |= h;\n goto add_char;\n default:\n return -1;\n }\n } else {\n add_char:\n if (q >= buf + buf_size - 1)\n return -1;\n *q++ = c;\n }\n }\n } else {\n while (!isspace_nolf(*p) && *p != '\\0' && *p != '\\n') {\n if (q >= buf + buf_size - 1)\n return -1;\n *q++ = *p++;\n }\n }\n *q = '\\0';\n *pp = p;\n return 0;\n}\n\nint parse_uint32_base(uint32_t *pval, const char **pp, int base)\n{\n const char *p, *p1;\n p = *pp;\n while (isspace_nolf(*p))\n p++;\n *pval = strtoul(p, (char **)&p1, base);\n if (p1 == p)\n return -1;\n *pp = p1;\n return 0;\n}\n\nint parse_uint64_base(uint64_t *pval, const char **pp, int base)\n{\n const char *p, *p1;\n p = *pp;\n while (isspace_nolf(*p))\n p++;\n *pval = strtoull(p, (char **)&p1, base);\n if (p1 == p)\n return -1;\n *pp = p1;\n return 0;\n}\n\nint parse_uint64(uint64_t *pval, const char **pp)\n{\n return parse_uint64_base(pval, pp, 0);\n}\n\nint parse_uint32(uint32_t *pval, const char **pp)\n{\n return parse_uint32_base(pval, pp, 0);\n}\n\nint parse_time(uint32_t *psec, uint32_t *pnsec, const char **pp)\n{\n const char *p;\n uint32_t v, m;\n p = *pp;\n if (parse_uint32(psec, &p) < 0)\n return -1;\n v = 0;\n if (*p == '.') {\n p++;\n /* XXX: inefficient */\n m = 1000000000;\n v = 0;\n while (*p >= '0' && *p <= '9') {\n m /= 10;\n v += (*p - '0') * m;\n p++;\n }\n }\n *pnsec = v;\n *pp = p;\n return 0;\n}\n\nint parse_file_id(FSFileID *pval, const char **pp)\n{\n return parse_uint64_base(pval, pp, 16);\n}\n\nchar *file_id_to_filename(char *buf, FSFileID file_id)\n{\n sprintf(buf, \"%016\" PRIx64, file_id);\n return buf;\n}\n\nvoid encode_hex(char *str, const uint8_t *buf, int len)\n{\n int i;\n for(i = 0; i < len; i++)\n sprintf(str + 2 * i, \"%02x\", buf[i]);\n}\n\nint decode_hex(uint8_t *buf, const char *str, int len)\n{\n int h0, h1, i;\n\n for(i = 0; i < len; i++) {\n h0 = from_hex(str[2 * i]);\n if (h0 < 0)\n return -1;\n h1 = from_hex(str[2 * i + 1]);\n if (h1 < 0)\n return -1;\n buf[i] = (h0 << 4) | h1;\n }\n return 0;\n}\n\n/* return NULL if no end of header found */\nconst char *skip_header(const char *p)\n{\n p = strstr(p, \"\\n\\n\");\n if (!p)\n return NULL;\n return p + 2;\n}\n\n/* return 0 if OK, < 0 if error */\nint parse_tag(char *buf, int buf_size, const char *str, const char *tag)\n{\n char tagname[128], *q;\n const char *p, *p1;\n int len;\n \n p = str;\n for(;;) {\n if (*p == '\\0' || *p == '\\n')\n break;\n q = tagname;\n while (*p != ':' && *p != '\\n' && *p != '\\0') {\n if ((q - tagname) < sizeof(tagname) - 1)\n *q++ = *p;\n p++;\n }\n *q = '\\0';\n if (*p != ':')\n return -1;\n p++;\n while (isspace_nolf(*p))\n p++;\n p1 = p;\n p = strchr(p, '\\n');\n if (!p)\n len = strlen(p1);\n else\n len = p - p1;\n if (!strcmp(tagname, tag)) {\n if (len > buf_size - 1)\n len = buf_size - 1;\n memcpy(buf, p1, len);\n buf[len] = '\\0';\n return 0;\n }\n if (!p)\n break;\n else\n p++;\n }\n return -1;\n}\n\nint parse_tag_uint64(uint64_t *pval, const char *str, const char *tag)\n{\n char buf[64];\n const char *p;\n if (parse_tag(buf, sizeof(buf), str, tag))\n return -1;\n p = buf;\n return parse_uint64(pval, &p);\n}\n\nint parse_tag_file_id(FSFileID *pval, const char *str, const char *tag)\n{\n char buf[64];\n const char *p;\n if (parse_tag(buf, sizeof(buf), str, tag))\n return -1;\n p = buf;\n return parse_uint64_base(pval, &p, 16);\n}\n\nint parse_tag_version(const char *str)\n{\n uint64_t version;\n if (parse_tag_uint64(&version, str, \"Version\"))\n return -1;\n return version;\n}\n\nBOOL is_url(const char *path)\n{\n return (strstart(path, \"http:\", NULL) ||\n strstart(path, \"https:\", NULL) ||\n strstart(path, \"file:\", NULL));\n}\n"], ["/linuxpdf/tinyemu/pckbd.c", "/*\n * QEMU PC keyboard emulation\n *\n * Copyright (c) 2003 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n/* debug PC keyboard */\n//#define DEBUG_KBD\n\n/* debug PC keyboard : only mouse */\n//#define DEBUG_MOUSE\n\n/*\tKeyboard Controller Commands */\n#define KBD_CCMD_READ_MODE\t0x20\t/* Read mode bits */\n#define KBD_CCMD_WRITE_MODE\t0x60\t/* Write mode bits */\n#define KBD_CCMD_GET_VERSION\t0xA1\t/* Get controller version */\n#define KBD_CCMD_MOUSE_DISABLE\t0xA7\t/* Disable mouse interface */\n#define KBD_CCMD_MOUSE_ENABLE\t0xA8\t/* Enable mouse interface */\n#define KBD_CCMD_TEST_MOUSE\t0xA9\t/* Mouse interface test */\n#define KBD_CCMD_SELF_TEST\t0xAA\t/* Controller self test */\n#define KBD_CCMD_KBD_TEST\t0xAB\t/* Keyboard interface test */\n#define KBD_CCMD_KBD_DISABLE\t0xAD\t/* Keyboard interface disable */\n#define KBD_CCMD_KBD_ENABLE\t0xAE\t/* Keyboard interface enable */\n#define KBD_CCMD_READ_INPORT 0xC0 /* read input port */\n#define KBD_CCMD_READ_OUTPORT\t0xD0 /* read output port */\n#define KBD_CCMD_WRITE_OUTPORT\t0xD1 /* write output port */\n#define KBD_CCMD_WRITE_OBUF\t0xD2\n#define KBD_CCMD_WRITE_AUX_OBUF\t0xD3 /* Write to output buffer as if\n\t\t\t\t\t initiated by the auxiliary device */\n#define KBD_CCMD_WRITE_MOUSE\t0xD4\t/* Write the following byte to the mouse */\n#define KBD_CCMD_DISABLE_A20 0xDD /* HP vectra only ? */\n#define KBD_CCMD_ENABLE_A20 0xDF /* HP vectra only ? */\n#define KBD_CCMD_RESET\t 0xFE\n\n/* Status Register Bits */\n#define KBD_STAT_OBF \t\t0x01\t/* Keyboard output buffer full */\n#define KBD_STAT_IBF \t\t0x02\t/* Keyboard input buffer full */\n#define KBD_STAT_SELFTEST\t0x04\t/* Self test successful */\n#define KBD_STAT_CMD\t\t0x08\t/* Last write was a command write (0=data) */\n#define KBD_STAT_UNLOCKED\t0x10\t/* Zero if keyboard locked */\n#define KBD_STAT_MOUSE_OBF\t0x20\t/* Mouse output buffer full */\n#define KBD_STAT_GTO \t\t0x40\t/* General receive/xmit timeout */\n#define KBD_STAT_PERR \t\t0x80\t/* Parity error */\n\n/* Controller Mode Register Bits */\n#define KBD_MODE_KBD_INT\t0x01\t/* Keyboard data generate IRQ1 */\n#define KBD_MODE_MOUSE_INT\t0x02\t/* Mouse data generate IRQ12 */\n#define KBD_MODE_SYS \t\t0x04\t/* The system flag (?) */\n#define KBD_MODE_NO_KEYLOCK\t0x08\t/* The keylock doesn't affect the keyboard if set */\n#define KBD_MODE_DISABLE_KBD\t0x10\t/* Disable keyboard interface */\n#define KBD_MODE_DISABLE_MOUSE\t0x20\t/* Disable mouse interface */\n#define KBD_MODE_KCC \t\t0x40\t/* Scan code conversion to PC format */\n#define KBD_MODE_RFU\t\t0x80\n\n#define KBD_PENDING_KBD 1\n#define KBD_PENDING_AUX 2\n\nstruct KBDState {\n uint8_t write_cmd; /* if non zero, write data to port 60 is expected */\n uint8_t status;\n uint8_t mode;\n /* Bitmask of devices with data available. */\n uint8_t pending;\n PS2KbdState *kbd;\n PS2MouseState *mouse;\n\n IRQSignal *irq_kbd;\n IRQSignal *irq_mouse;\n};\n\nstatic void qemu_system_reset_request(void)\n{\n printf(\"system_reset_request\\n\");\n exit(1);\n /* XXX */\n}\n\nstatic void ioport_set_a20(int val)\n{\n}\n\nstatic int ioport_get_a20(void)\n{\n return 1;\n}\n\n/* update irq and KBD_STAT_[MOUSE_]OBF */\n/* XXX: not generating the irqs if KBD_MODE_DISABLE_KBD is set may be\n incorrect, but it avoids having to simulate exact delays */\nstatic void kbd_update_irq(KBDState *s)\n{\n int irq_kbd_level, irq_mouse_level;\n\n irq_kbd_level = 0;\n irq_mouse_level = 0;\n s->status &= ~(KBD_STAT_OBF | KBD_STAT_MOUSE_OBF);\n if (s->pending) {\n s->status |= KBD_STAT_OBF;\n /* kbd data takes priority over aux data. */\n if (s->pending == KBD_PENDING_AUX) {\n s->status |= KBD_STAT_MOUSE_OBF;\n if (s->mode & KBD_MODE_MOUSE_INT)\n irq_mouse_level = 1;\n } else {\n if ((s->mode & KBD_MODE_KBD_INT) &&\n !(s->mode & KBD_MODE_DISABLE_KBD))\n irq_kbd_level = 1;\n }\n }\n set_irq(s->irq_kbd, irq_kbd_level);\n set_irq(s->irq_mouse, irq_mouse_level);\n}\n\nstatic void kbd_update_kbd_irq(void *opaque, int level)\n{\n KBDState *s = (KBDState *)opaque;\n\n if (level)\n s->pending |= KBD_PENDING_KBD;\n else\n s->pending &= ~KBD_PENDING_KBD;\n kbd_update_irq(s);\n}\n\nstatic void kbd_update_aux_irq(void *opaque, int level)\n{\n KBDState *s = (KBDState *)opaque;\n\n if (level)\n s->pending |= KBD_PENDING_AUX;\n else\n s->pending &= ~KBD_PENDING_AUX;\n kbd_update_irq(s);\n}\n\nstatic uint32_t kbd_read_status(void *opaque, uint32_t addr, int size_log2)\n{\n KBDState *s = opaque;\n int val;\n val = s->status;\n#if defined(DEBUG_KBD)\n printf(\"kbd: read status=0x%02x\\n\", val);\n#endif\n return val;\n}\n\nstatic void kbd_queue(KBDState *s, int b, int aux)\n{\n if (aux)\n ps2_queue(s->mouse, b);\n else\n ps2_queue(s->kbd, b);\n}\n\nstatic void kbd_write_command(void *opaque, uint32_t addr, uint32_t val,\n int size_log2)\n{\n KBDState *s = opaque;\n\n#if defined(DEBUG_KBD)\n printf(\"kbd: write cmd=0x%02x\\n\", val);\n#endif\n switch(val) {\n case KBD_CCMD_READ_MODE:\n kbd_queue(s, s->mode, 1);\n break;\n case KBD_CCMD_WRITE_MODE:\n case KBD_CCMD_WRITE_OBUF:\n case KBD_CCMD_WRITE_AUX_OBUF:\n case KBD_CCMD_WRITE_MOUSE:\n case KBD_CCMD_WRITE_OUTPORT:\n s->write_cmd = val;\n break;\n case KBD_CCMD_MOUSE_DISABLE:\n s->mode |= KBD_MODE_DISABLE_MOUSE;\n break;\n case KBD_CCMD_MOUSE_ENABLE:\n s->mode &= ~KBD_MODE_DISABLE_MOUSE;\n break;\n case KBD_CCMD_TEST_MOUSE:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_SELF_TEST:\n s->status |= KBD_STAT_SELFTEST;\n kbd_queue(s, 0x55, 0);\n break;\n case KBD_CCMD_KBD_TEST:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_KBD_DISABLE:\n s->mode |= KBD_MODE_DISABLE_KBD;\n kbd_update_irq(s);\n break;\n case KBD_CCMD_KBD_ENABLE:\n s->mode &= ~KBD_MODE_DISABLE_KBD;\n kbd_update_irq(s);\n break;\n case KBD_CCMD_READ_INPORT:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_READ_OUTPORT:\n /* XXX: check that */\n val = 0x01 | (ioport_get_a20() << 1);\n if (s->status & KBD_STAT_OBF)\n val |= 0x10;\n if (s->status & KBD_STAT_MOUSE_OBF)\n val |= 0x20;\n kbd_queue(s, val, 0);\n break;\n case KBD_CCMD_ENABLE_A20:\n ioport_set_a20(1);\n break;\n case KBD_CCMD_DISABLE_A20:\n ioport_set_a20(0);\n break;\n case KBD_CCMD_RESET:\n qemu_system_reset_request();\n break;\n case 0xff:\n /* ignore that - I don't know what is its use */\n break;\n default:\n fprintf(stderr, \"qemu: unsupported keyboard cmd=0x%02x\\n\", val);\n break;\n }\n}\n\nstatic uint32_t kbd_read_data(void *opaque, uint32_t addr, int size_log2)\n{\n KBDState *s = opaque;\n uint32_t val;\n if (s->pending == KBD_PENDING_AUX)\n val = ps2_read_data(s->mouse);\n else\n val = ps2_read_data(s->kbd);\n#ifdef DEBUG_KBD\n printf(\"kbd: read data=0x%02x\\n\", val);\n#endif\n return val;\n}\n\nstatic void kbd_write_data(void *opaque, uint32_t addr, uint32_t val, int size_log2)\n{\n KBDState *s = opaque;\n\n#ifdef DEBUG_KBD\n printf(\"kbd: write data=0x%02x\\n\", val);\n#endif\n\n switch(s->write_cmd) {\n case 0:\n ps2_write_keyboard(s->kbd, val);\n break;\n case KBD_CCMD_WRITE_MODE:\n s->mode = val;\n ps2_keyboard_set_translation(s->kbd, (s->mode & KBD_MODE_KCC) != 0);\n /* ??? */\n kbd_update_irq(s);\n break;\n case KBD_CCMD_WRITE_OBUF:\n kbd_queue(s, val, 0);\n break;\n case KBD_CCMD_WRITE_AUX_OBUF:\n kbd_queue(s, val, 1);\n break;\n case KBD_CCMD_WRITE_OUTPORT:\n ioport_set_a20((val >> 1) & 1);\n if (!(val & 1)) {\n qemu_system_reset_request();\n }\n break;\n case KBD_CCMD_WRITE_MOUSE:\n ps2_write_mouse(s->mouse, val);\n break;\n default:\n break;\n }\n s->write_cmd = 0;\n}\n\nstatic void kbd_reset(void *opaque)\n{\n KBDState *s = opaque;\n\n s->mode = KBD_MODE_KBD_INT | KBD_MODE_MOUSE_INT;\n s->status = KBD_STAT_CMD | KBD_STAT_UNLOCKED;\n}\n\nKBDState *i8042_init(PS2KbdState **pkbd,\n PS2MouseState **pmouse,\n PhysMemoryMap *port_map,\n IRQSignal *kbd_irq, IRQSignal *mouse_irq, uint32_t io_base)\n{\n KBDState *s;\n \n s = mallocz(sizeof(*s));\n \n s->irq_kbd = kbd_irq;\n s->irq_mouse = mouse_irq;\n\n kbd_reset(s);\n cpu_register_device(port_map, io_base, 1, s, kbd_read_data, kbd_write_data, \n DEVIO_SIZE8);\n cpu_register_device(port_map, io_base + 4, 1, s, kbd_read_status, kbd_write_command, \n DEVIO_SIZE8);\n\n s->kbd = ps2_kbd_init(kbd_update_kbd_irq, s);\n s->mouse = ps2_mouse_init(kbd_update_aux_irq, s);\n\n *pkbd = s->kbd;\n *pmouse = s->mouse;\n return s;\n}\n"], ["/linuxpdf/tinyemu/build_filelist.c", "/*\n * File list builder for RISCVEMU network filesystem\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"fs_utils.h\"\n\nvoid print_str(FILE *f, const char *str)\n{\n const char *s;\n int c;\n s = str;\n while (*s != '\\0') {\n if (*s <= ' ' || *s > '~')\n goto use_quote;\n s++;\n }\n fputs(str, f);\n return;\n use_quote:\n s = str;\n fputc('\"', f);\n while (*s != '\\0') {\n c = *(uint8_t *)s;\n if (c < ' ' || c == 127) {\n fprintf(f, \"\\\\x%02x\", c);\n } else if (c == '\\\\' || c == '\\\"') {\n fprintf(f, \"\\\\%c\", c);\n } else {\n fputc(c, f);\n }\n s++;\n }\n fputc('\"', f);\n}\n\n#define COPY_BUF_LEN (1024 * 1024)\n\nstatic void copy_file(const char *src_filename, const char *dst_filename)\n{\n uint8_t *buf;\n FILE *fi, *fo;\n int len;\n \n buf = malloc(COPY_BUF_LEN);\n fi = fopen(src_filename, \"rb\");\n if (!fi) {\n perror(src_filename);\n exit(1);\n }\n fo = fopen(dst_filename, \"wb\");\n if (!fo) {\n perror(dst_filename);\n exit(1);\n }\n for(;;) {\n len = fread(buf, 1, COPY_BUF_LEN, fi);\n if (len == 0)\n break;\n fwrite(buf, 1, len, fo);\n }\n fclose(fo);\n fclose(fi);\n}\n\ntypedef struct {\n char *files_path;\n uint64_t next_inode_num;\n uint64_t fs_size;\n uint64_t fs_max_size;\n FILE *f;\n} ScanState;\n\nstatic void add_file_size(ScanState *s, uint64_t size)\n{\n s->fs_size += block_align(size, FS_BLOCK_SIZE);\n if (s->fs_size > s->fs_max_size) {\n fprintf(stderr, \"Filesystem Quota exceeded (%\" PRId64 \" bytes)\\n\", s->fs_max_size);\n exit(1);\n }\n}\n\nvoid scan_dir(ScanState *s, const char *path)\n{\n FILE *f = s->f;\n DIR *dirp;\n struct dirent *de;\n const char *name;\n struct stat st;\n char *path1;\n uint32_t mode, v;\n\n dirp = opendir(path);\n if (!dirp) {\n perror(path);\n exit(1);\n }\n for(;;) {\n de = readdir(dirp);\n if (!de)\n break;\n name = de->d_name;\n if (!strcmp(name, \".\") || !strcmp(name, \"..\"))\n continue;\n path1 = compose_path(path, name);\n if (lstat(path1, &st) < 0) {\n perror(path1);\n exit(1);\n }\n\n mode = st.st_mode & 0xffff;\n fprintf(f, \"%06o %u %u\", \n mode, \n (int)st.st_uid,\n (int)st.st_gid);\n if (S_ISCHR(mode) || S_ISBLK(mode)) {\n fprintf(f, \" %u %u\",\n (int)major(st.st_rdev),\n (int)minor(st.st_rdev));\n }\n if (S_ISREG(mode)) {\n fprintf(f, \" %\" PRIu64, st.st_size);\n }\n /* modification time (at most ms resolution) */\n fprintf(f, \" %u\", (int)st.st_mtim.tv_sec);\n v = st.st_mtim.tv_nsec;\n if (v != 0) {\n fprintf(f, \".\");\n while (v != 0) {\n fprintf(f, \"%u\", v / 100000000);\n v = (v % 100000000) * 10;\n }\n }\n \n fprintf(f, \" \");\n print_str(f, name);\n if (S_ISLNK(mode)) {\n char buf[1024];\n int len;\n len = readlink(path1, buf, sizeof(buf) - 1);\n if (len < 0) {\n perror(\"readlink\");\n exit(1);\n }\n buf[len] = '\\0';\n fprintf(f, \" \");\n print_str(f, buf);\n } else if (S_ISREG(mode) && st.st_size > 0) {\n char buf1[FILEID_SIZE_MAX], *fname;\n FSFileID file_id;\n file_id = s->next_inode_num++;\n fprintf(f, \" %\" PRIx64, file_id);\n file_id_to_filename(buf1, file_id);\n fname = compose_path(s->files_path, buf1);\n copy_file(path1, fname);\n add_file_size(s, st.st_size);\n }\n\n fprintf(f, \"\\n\");\n if (S_ISDIR(mode)) {\n scan_dir(s, path1);\n }\n free(path1);\n }\n\n closedir(dirp);\n fprintf(f, \".\\n\"); /* end of directory */\n}\n\nvoid help(void)\n{\n printf(\"usage: build_filelist [options] source_path dest_path\\n\"\n \"\\n\"\n \"Options:\\n\"\n \"-m size_mb set the max filesystem size in MiB\\n\");\n exit(1);\n}\n\n#define LOCK_FILENAME \"lock\"\n\nint main(int argc, char **argv)\n{\n const char *dst_path, *src_path;\n ScanState s_s, *s = &s_s;\n FILE *f;\n char *filename;\n FSFileID root_id;\n char fname[FILEID_SIZE_MAX];\n struct stat st;\n uint64_t first_inode, fs_max_size;\n int c;\n \n first_inode = 1;\n fs_max_size = (uint64_t)1 << 30;\n for(;;) {\n c = getopt(argc, argv, \"hi:m:\");\n if (c == -1)\n break;\n switch(c) {\n case 'h':\n help();\n case 'i':\n first_inode = strtoul(optarg, NULL, 0);\n break;\n case 'm':\n fs_max_size = (uint64_t)strtoul(optarg, NULL, 0) << 20;\n break;\n default:\n exit(1);\n }\n }\n\n if (optind + 1 >= argc)\n help();\n src_path = argv[optind];\n dst_path = argv[optind + 1];\n \n mkdir(dst_path, 0755);\n\n s->files_path = compose_path(dst_path, ROOT_FILENAME);\n s->next_inode_num = first_inode;\n s->fs_size = 0;\n s->fs_max_size = fs_max_size;\n \n mkdir(s->files_path, 0755);\n\n root_id = s->next_inode_num++;\n file_id_to_filename(fname, root_id);\n filename = compose_path(s->files_path, fname);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fprintf(f, \"Version: 1\\n\");\n fprintf(f, \"Revision: 1\\n\");\n fprintf(f, \"\\n\");\n s->f = f;\n scan_dir(s, src_path);\n fclose(f);\n\n /* take into account the filelist size */\n if (stat(filename, &st) < 0) {\n perror(filename);\n exit(1);\n }\n add_file_size(s, st.st_size);\n \n free(filename);\n \n filename = compose_path(dst_path, HEAD_FILENAME);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fprintf(f, \"Version: 1\\n\");\n fprintf(f, \"Revision: 1\\n\");\n fprintf(f, \"NextFileID: %\" PRIx64 \"\\n\", s->next_inode_num);\n fprintf(f, \"FSFileCount: %\" PRIu64 \"\\n\", s->next_inode_num - 1);\n fprintf(f, \"FSSize: %\" PRIu64 \"\\n\", s->fs_size);\n fprintf(f, \"FSMaxSize: %\" PRIu64 \"\\n\", s->fs_max_size);\n fprintf(f, \"Key:\\n\"); /* not encrypted */\n fprintf(f, \"RootID: %\" PRIx64 \"\\n\", root_id);\n fclose(f);\n free(filename);\n \n filename = compose_path(dst_path, LOCK_FILENAME);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fclose(f);\n free(filename);\n\n return 0;\n}\n"], ["/linuxpdf/tinyemu/slirp/bootp.c", "/*\n * QEMU BOOTP/DHCP server\n *\n * Copyright (c) 2004 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"slirp.h\"\n\n/* XXX: only DHCP is supported */\n\n#define LEASE_TIME (24 * 3600)\n\nstatic const uint8_t rfc1533_cookie[] = { RFC1533_COOKIE };\n\n#ifdef DEBUG\n#define DPRINTF(fmt, ...) \\\ndo if (slirp_debug & DBG_CALL) { fprintf(dfd, fmt, ## __VA_ARGS__); fflush(dfd); } while (0)\n#else\n#define DPRINTF(fmt, ...) do{}while(0)\n#endif\n\nstatic BOOTPClient *get_new_addr(Slirp *slirp, struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n BOOTPClient *bc;\n int i;\n\n for(i = 0; i < NB_BOOTP_CLIENTS; i++) {\n bc = &slirp->bootp_clients[i];\n if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6))\n goto found;\n }\n return NULL;\n found:\n bc = &slirp->bootp_clients[i];\n bc->allocated = 1;\n paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i);\n return bc;\n}\n\nstatic BOOTPClient *request_addr(Slirp *slirp, const struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n uint32_t req_addr = ntohl(paddr->s_addr);\n uint32_t dhcp_addr = ntohl(slirp->vdhcp_startaddr.s_addr);\n BOOTPClient *bc;\n\n if (req_addr >= dhcp_addr &&\n req_addr < (dhcp_addr + NB_BOOTP_CLIENTS)) {\n bc = &slirp->bootp_clients[req_addr - dhcp_addr];\n if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6)) {\n bc->allocated = 1;\n return bc;\n }\n }\n return NULL;\n}\n\nstatic BOOTPClient *find_addr(Slirp *slirp, struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n BOOTPClient *bc;\n int i;\n\n for(i = 0; i < NB_BOOTP_CLIENTS; i++) {\n if (!memcmp(macaddr, slirp->bootp_clients[i].macaddr, 6))\n goto found;\n }\n return NULL;\n found:\n bc = &slirp->bootp_clients[i];\n bc->allocated = 1;\n paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i);\n return bc;\n}\n\nstatic void dhcp_decode(const struct bootp_t *bp, int *pmsg_type,\n struct in_addr *preq_addr)\n{\n const uint8_t *p, *p_end;\n int len, tag;\n\n *pmsg_type = 0;\n preq_addr->s_addr = htonl(0L);\n\n p = bp->bp_vend;\n p_end = p + DHCP_OPT_LEN;\n if (memcmp(p, rfc1533_cookie, 4) != 0)\n return;\n p += 4;\n while (p < p_end) {\n tag = p[0];\n if (tag == RFC1533_PAD) {\n p++;\n } else if (tag == RFC1533_END) {\n break;\n } else {\n p++;\n if (p >= p_end)\n break;\n len = *p++;\n DPRINTF(\"dhcp: tag=%d len=%d\\n\", tag, len);\n\n switch(tag) {\n case RFC2132_MSG_TYPE:\n if (len >= 1)\n *pmsg_type = p[0];\n break;\n case RFC2132_REQ_ADDR:\n if (len >= 4) {\n memcpy(&(preq_addr->s_addr), p, 4);\n }\n break;\n default:\n break;\n }\n p += len;\n }\n }\n if (*pmsg_type == DHCPREQUEST && preq_addr->s_addr == htonl(0L) &&\n bp->bp_ciaddr.s_addr) {\n memcpy(&(preq_addr->s_addr), &bp->bp_ciaddr, 4);\n }\n}\n\nstatic void bootp_reply(Slirp *slirp, const struct bootp_t *bp)\n{\n BOOTPClient *bc = NULL;\n struct mbuf *m;\n struct bootp_t *rbp;\n struct sockaddr_in saddr, daddr;\n struct in_addr preq_addr;\n int dhcp_msg_type, val;\n uint8_t *q;\n\n /* extract exact DHCP msg type */\n dhcp_decode(bp, &dhcp_msg_type, &preq_addr);\n DPRINTF(\"bootp packet op=%d msgtype=%d\", bp->bp_op, dhcp_msg_type);\n if (preq_addr.s_addr != htonl(0L))\n DPRINTF(\" req_addr=%08x\\n\", ntohl(preq_addr.s_addr));\n else\n DPRINTF(\"\\n\");\n\n if (dhcp_msg_type == 0)\n dhcp_msg_type = DHCPREQUEST; /* Force reply for old BOOTP clients */\n\n if (dhcp_msg_type != DHCPDISCOVER &&\n dhcp_msg_type != DHCPREQUEST)\n return;\n /* XXX: this is a hack to get the client mac address */\n memcpy(slirp->client_ethaddr, bp->bp_hwaddr, 6);\n\n m = m_get(slirp);\n if (!m) {\n return;\n }\n m->m_data += IF_MAXLINKHDR;\n rbp = (struct bootp_t *)m->m_data;\n m->m_data += sizeof(struct udpiphdr);\n memset(rbp, 0, sizeof(struct bootp_t));\n\n if (dhcp_msg_type == DHCPDISCOVER) {\n if (preq_addr.s_addr != htonl(0L)) {\n bc = request_addr(slirp, &preq_addr, slirp->client_ethaddr);\n if (bc) {\n daddr.sin_addr = preq_addr;\n }\n }\n if (!bc) {\n new_addr:\n bc = get_new_addr(slirp, &daddr.sin_addr, slirp->client_ethaddr);\n if (!bc) {\n DPRINTF(\"no address left\\n\");\n return;\n }\n }\n memcpy(bc->macaddr, slirp->client_ethaddr, 6);\n } else if (preq_addr.s_addr != htonl(0L)) {\n bc = request_addr(slirp, &preq_addr, slirp->client_ethaddr);\n if (bc) {\n daddr.sin_addr = preq_addr;\n memcpy(bc->macaddr, slirp->client_ethaddr, 6);\n } else {\n daddr.sin_addr.s_addr = 0;\n }\n } else {\n bc = find_addr(slirp, &daddr.sin_addr, bp->bp_hwaddr);\n if (!bc) {\n /* if never assigned, behaves as if it was already\n assigned (windows fix because it remembers its address) */\n goto new_addr;\n }\n }\n\n saddr.sin_addr = slirp->vhost_addr;\n saddr.sin_port = htons(BOOTP_SERVER);\n\n daddr.sin_port = htons(BOOTP_CLIENT);\n\n rbp->bp_op = BOOTP_REPLY;\n rbp->bp_xid = bp->bp_xid;\n rbp->bp_htype = 1;\n rbp->bp_hlen = 6;\n memcpy(rbp->bp_hwaddr, bp->bp_hwaddr, 6);\n\n rbp->bp_yiaddr = daddr.sin_addr; /* Client IP address */\n rbp->bp_siaddr = saddr.sin_addr; /* Server IP address */\n\n q = rbp->bp_vend;\n memcpy(q, rfc1533_cookie, 4);\n q += 4;\n\n if (bc) {\n DPRINTF(\"%s addr=%08x\\n\",\n (dhcp_msg_type == DHCPDISCOVER) ? \"offered\" : \"ack'ed\",\n ntohl(daddr.sin_addr.s_addr));\n\n if (dhcp_msg_type == DHCPDISCOVER) {\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPOFFER;\n } else /* DHCPREQUEST */ {\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPACK;\n }\n\n if (slirp->bootp_filename)\n snprintf((char *)rbp->bp_file, sizeof(rbp->bp_file), \"%s\",\n slirp->bootp_filename);\n\n *q++ = RFC2132_SRV_ID;\n *q++ = 4;\n memcpy(q, &saddr.sin_addr, 4);\n q += 4;\n\n *q++ = RFC1533_NETMASK;\n *q++ = 4;\n memcpy(q, &slirp->vnetwork_mask, 4);\n q += 4;\n\n if (!slirp->restricted) {\n *q++ = RFC1533_GATEWAY;\n *q++ = 4;\n memcpy(q, &saddr.sin_addr, 4);\n q += 4;\n\n *q++ = RFC1533_DNS;\n *q++ = 4;\n memcpy(q, &slirp->vnameserver_addr, 4);\n q += 4;\n }\n\n *q++ = RFC2132_LEASE_TIME;\n *q++ = 4;\n val = htonl(LEASE_TIME);\n memcpy(q, &val, 4);\n q += 4;\n\n if (*slirp->client_hostname) {\n val = strlen(slirp->client_hostname);\n *q++ = RFC1533_HOSTNAME;\n *q++ = val;\n memcpy(q, slirp->client_hostname, val);\n q += val;\n }\n } else {\n static const char nak_msg[] = \"requested address not available\";\n\n DPRINTF(\"nak'ed addr=%08x\\n\", ntohl(preq_addr->s_addr));\n\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPNAK;\n\n *q++ = RFC2132_MESSAGE;\n *q++ = sizeof(nak_msg) - 1;\n memcpy(q, nak_msg, sizeof(nak_msg) - 1);\n q += sizeof(nak_msg) - 1;\n }\n *q = RFC1533_END;\n\n daddr.sin_addr.s_addr = 0xffffffffu;\n\n m->m_len = sizeof(struct bootp_t) -\n sizeof(struct ip) - sizeof(struct udphdr);\n udp_output2(NULL, m, &saddr, &daddr, IPTOS_LOWDELAY);\n}\n\nvoid bootp_input(struct mbuf *m)\n{\n struct bootp_t *bp = mtod(m, struct bootp_t *);\n\n if (bp->bp_op == BOOTP_REQUEST) {\n bootp_reply(m->slirp, bp);\n }\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_input.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_input.c\t8.2 (Berkeley) 1/4/94\n * ip_input.c,v 1.11 1994/11/16 10:17:08 jkh Exp\n */\n\n/*\n * Changes and additions relating to SLiRP are\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n#define container_of(ptr, type, member) ({ \\\n const typeof( ((type *)0)->member ) *__mptr = (ptr); \\\n (type *)( (char *)__mptr - offsetof(type,member) );})\n\nstatic struct ip *ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp);\nstatic void ip_freef(Slirp *slirp, struct ipq *fp);\nstatic void ip_enq(register struct ipasfrag *p,\n register struct ipasfrag *prev);\nstatic void ip_deq(register struct ipasfrag *p);\n\n/*\n * IP initialization: fill in IP protocol switch table.\n * All protocols not implemented in kernel go to raw IP protocol handler.\n */\nvoid\nip_init(Slirp *slirp)\n{\n slirp->ipq.ip_link.next = slirp->ipq.ip_link.prev = &slirp->ipq.ip_link;\n udp_init(slirp);\n tcp_init(slirp);\n}\n\n/*\n * Ip input routine. Checksum and byte swap header. If fragmented\n * try to reassemble. Process options. Pass to next level.\n */\nvoid\nip_input(struct mbuf *m)\n{\n\tSlirp *slirp = m->slirp;\n\tregister struct ip *ip;\n\tint hlen;\n\n\tDEBUG_CALL(\"ip_input\");\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"m_len = %d\", m->m_len);\n\n\tif (m->m_len < sizeof (struct ip)) {\n\t\treturn;\n\t}\n\n\tip = mtod(m, struct ip *);\n\n\tif (ip->ip_v != IPVERSION) {\n\t\tgoto bad;\n\t}\n\n\thlen = ip->ip_hl << 2;\n\tif (hlenm->m_len) {/* min header length */\n\t goto bad; /* or packet too short */\n\t}\n\n /* keep ip header intact for ICMP reply\n\t * ip->ip_sum = cksum(m, hlen);\n\t * if (ip->ip_sum) {\n\t */\n\tif(cksum(m,hlen)) {\n\t goto bad;\n\t}\n\n\t/*\n\t * Convert fields to host representation.\n\t */\n\tNTOHS(ip->ip_len);\n\tif (ip->ip_len < hlen) {\n\t\tgoto bad;\n\t}\n\tNTOHS(ip->ip_id);\n\tNTOHS(ip->ip_off);\n\n\t/*\n\t * Check that the amount of data in the buffers\n\t * is as at least much as the IP header would have us expect.\n\t * Trim mbufs if longer than we expect.\n\t * Drop packet if shorter than we expect.\n\t */\n\tif (m->m_len < ip->ip_len) {\n\t\tgoto bad;\n\t}\n\n if (slirp->restricted) {\n if ((ip->ip_dst.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n if (ip->ip_dst.s_addr == 0xffffffff && ip->ip_p != IPPROTO_UDP)\n goto bad;\n } else {\n uint32_t inv_mask = ~slirp->vnetwork_mask.s_addr;\n struct ex_list *ex_ptr;\n\n if ((ip->ip_dst.s_addr & inv_mask) == inv_mask) {\n goto bad;\n }\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)\n if (ex_ptr->ex_addr.s_addr == ip->ip_dst.s_addr)\n break;\n\n if (!ex_ptr)\n goto bad;\n }\n }\n\n\t/* Should drop packet if mbuf too long? hmmm... */\n\tif (m->m_len > ip->ip_len)\n\t m_adj(m, ip->ip_len - m->m_len);\n\n\t/* check ip_ttl for a correct ICMP reply */\n\tif(ip->ip_ttl==0) {\n\t icmp_error(m, ICMP_TIMXCEED,ICMP_TIMXCEED_INTRANS, 0,\"ttl\");\n\t goto bad;\n\t}\n\n\t/*\n\t * If offset or IP_MF are set, must reassemble.\n\t * Otherwise, nothing need be done.\n\t * (We could look in the reassembly queue to see\n\t * if the packet was previously fragmented,\n\t * but it's not worth the time; just let them time out.)\n\t *\n\t * XXX This should fail, don't fragment yet\n\t */\n\tif (ip->ip_off &~ IP_DF) {\n\t register struct ipq *fp;\n struct qlink *l;\n\t\t/*\n\t\t * Look for queue of fragments\n\t\t * of this datagram.\n\t\t */\n\t\tfor (l = slirp->ipq.ip_link.next; l != &slirp->ipq.ip_link;\n\t\t l = l->next) {\n fp = container_of(l, struct ipq, ip_link);\n if (ip->ip_id == fp->ipq_id &&\n ip->ip_src.s_addr == fp->ipq_src.s_addr &&\n ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&\n ip->ip_p == fp->ipq_p)\n\t\t goto found;\n }\n fp = NULL;\n\tfound:\n\n\t\t/*\n\t\t * Adjust ip_len to not reflect header,\n\t\t * set ip_mff if more fragments are expected,\n\t\t * convert offset of this to bytes.\n\t\t */\n\t\tip->ip_len -= hlen;\n\t\tif (ip->ip_off & IP_MF)\n\t\t ip->ip_tos |= 1;\n\t\telse\n\t\t ip->ip_tos &= ~1;\n\n\t\tip->ip_off <<= 3;\n\n\t\t/*\n\t\t * If datagram marked as having more fragments\n\t\t * or if this is not the first fragment,\n\t\t * attempt reassembly; if it succeeds, proceed.\n\t\t */\n\t\tif (ip->ip_tos & 1 || ip->ip_off) {\n\t\t\tip = ip_reass(slirp, ip, fp);\n if (ip == NULL)\n\t\t\t\treturn;\n\t\t\tm = dtom(slirp, ip);\n\t\t} else\n\t\t\tif (fp)\n\t\t \t ip_freef(slirp, fp);\n\n\t} else\n\t\tip->ip_len -= hlen;\n\n\t/*\n\t * Switch out to protocol's input routine.\n\t */\n\tswitch (ip->ip_p) {\n\t case IPPROTO_TCP:\n\t\ttcp_input(m, hlen, (struct socket *)NULL);\n\t\tbreak;\n\t case IPPROTO_UDP:\n\t\tudp_input(m, hlen);\n\t\tbreak;\n\t case IPPROTO_ICMP:\n\t\ticmp_input(m, hlen);\n\t\tbreak;\n\t default:\n\t\tm_free(m);\n\t}\n\treturn;\nbad:\n\tm_freem(m);\n\treturn;\n}\n\n#define iptofrag(P) ((struct ipasfrag *)(((char*)(P)) - sizeof(struct qlink)))\n#define fragtoip(P) ((struct ip*)(((char*)(P)) + sizeof(struct qlink)))\n/*\n * Take incoming datagram fragment and try to\n * reassemble it into whole datagram. If a chain for\n * reassembly of this datagram already exists, then it\n * is given as fp; otherwise have to make a chain.\n */\nstatic struct ip *\nip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)\n{\n\tregister struct mbuf *m = dtom(slirp, ip);\n\tregister struct ipasfrag *q;\n\tint hlen = ip->ip_hl << 2;\n\tint i, next;\n\n\tDEBUG_CALL(\"ip_reass\");\n\tDEBUG_ARG(\"ip = %lx\", (long)ip);\n\tDEBUG_ARG(\"fp = %lx\", (long)fp);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n\t/*\n\t * Presence of header sizes in mbufs\n\t * would confuse code below.\n * Fragment m_data is concatenated.\n\t */\n\tm->m_data += hlen;\n\tm->m_len -= hlen;\n\n\t/*\n\t * If first fragment to arrive, create a reassembly queue.\n\t */\n if (fp == NULL) {\n\t struct mbuf *t = m_get(slirp);\n\n\t if (t == NULL) {\n\t goto dropfrag;\n\t }\n\t fp = mtod(t, struct ipq *);\n\t insque(&fp->ip_link, &slirp->ipq.ip_link);\n\t fp->ipq_ttl = IPFRAGTTL;\n\t fp->ipq_p = ip->ip_p;\n\t fp->ipq_id = ip->ip_id;\n\t fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;\n\t fp->ipq_src = ip->ip_src;\n\t fp->ipq_dst = ip->ip_dst;\n\t q = (struct ipasfrag *)fp;\n\t goto insert;\n\t}\n\n\t/*\n\t * Find a segment which begins after this one does.\n\t */\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next)\n\t\tif (q->ipf_off > ip->ip_off)\n\t\t\tbreak;\n\n\t/*\n\t * If there is a preceding segment, it may provide some of\n\t * our data already. If so, drop the data from the incoming\n\t * segment. If it provides all of our data, drop us.\n\t */\n\tif (q->ipf_prev != &fp->frag_link) {\n struct ipasfrag *pq = q->ipf_prev;\n\t\ti = pq->ipf_off + pq->ipf_len - ip->ip_off;\n\t\tif (i > 0) {\n\t\t\tif (i >= ip->ip_len)\n\t\t\t\tgoto dropfrag;\n\t\t\tm_adj(dtom(slirp, ip), i);\n\t\t\tip->ip_off += i;\n\t\t\tip->ip_len -= i;\n\t\t}\n\t}\n\n\t/*\n\t * While we overlap succeeding segments trim them or,\n\t * if they are completely covered, dequeue them.\n\t */\n\twhile (q != (struct ipasfrag*)&fp->frag_link &&\n ip->ip_off + ip->ip_len > q->ipf_off) {\n\t\ti = (ip->ip_off + ip->ip_len) - q->ipf_off;\n\t\tif (i < q->ipf_len) {\n\t\t\tq->ipf_len -= i;\n\t\t\tq->ipf_off += i;\n\t\t\tm_adj(dtom(slirp, q), i);\n\t\t\tbreak;\n\t\t}\n\t\tq = q->ipf_next;\n\t\tm_freem(dtom(slirp, q->ipf_prev));\n\t\tip_deq(q->ipf_prev);\n\t}\n\ninsert:\n\t/*\n\t * Stick new segment in its place;\n\t * check for complete reassembly.\n\t */\n\tip_enq(iptofrag(ip), q->ipf_prev);\n\tnext = 0;\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link;\n q = q->ipf_next) {\n\t\tif (q->ipf_off != next)\n return NULL;\n\t\tnext += q->ipf_len;\n\t}\n\tif (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)\n return NULL;\n\n\t/*\n\t * Reassembly is complete; concatenate fragments.\n\t */\n q = fp->frag_link.next;\n\tm = dtom(slirp, q);\n\n\tq = (struct ipasfrag *) q->ipf_next;\n\twhile (q != (struct ipasfrag*)&fp->frag_link) {\n\t struct mbuf *t = dtom(slirp, q);\n\t q = (struct ipasfrag *) q->ipf_next;\n\t m_cat(m, t);\n\t}\n\n\t/*\n\t * Create header for new ip packet by\n\t * modifying header of first packet;\n\t * dequeue and discard fragment reassembly header.\n\t * Make header visible.\n\t */\n\tq = fp->frag_link.next;\n\n\t/*\n\t * If the fragments concatenated to an mbuf that's\n\t * bigger than the total size of the fragment, then and\n\t * m_ext buffer was alloced. But fp->ipq_next points to\n\t * the old buffer (in the mbuf), so we must point ip\n\t * into the new buffer.\n\t */\n\tif (m->m_flags & M_EXT) {\n\t int delta = (char *)q - m->m_dat;\n\t q = (struct ipasfrag *)(m->m_ext + delta);\n\t}\n\n ip = fragtoip(q);\n\tip->ip_len = next;\n\tip->ip_tos &= ~1;\n\tip->ip_src = fp->ipq_src;\n\tip->ip_dst = fp->ipq_dst;\n\tremque(&fp->ip_link);\n\t(void) m_free(dtom(slirp, fp));\n\tm->m_len += (ip->ip_hl << 2);\n\tm->m_data -= (ip->ip_hl << 2);\n\n\treturn ip;\n\ndropfrag:\n\tm_freem(m);\n return NULL;\n}\n\n/*\n * Free a fragment reassembly header and all\n * associated datagrams.\n */\nstatic void\nip_freef(Slirp *slirp, struct ipq *fp)\n{\n\tregister struct ipasfrag *q, *p;\n\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link; q = p) {\n\t\tp = q->ipf_next;\n\t\tip_deq(q);\n\t\tm_freem(dtom(slirp, q));\n\t}\n\tremque(&fp->ip_link);\n\t(void) m_free(dtom(slirp, fp));\n}\n\n/*\n * Put an ip fragment on a reassembly chain.\n * Like insque, but pointers in middle of structure.\n */\nstatic void\nip_enq(register struct ipasfrag *p, register struct ipasfrag *prev)\n{\n\tDEBUG_CALL(\"ip_enq\");\n\tDEBUG_ARG(\"prev = %lx\", (long)prev);\n\tp->ipf_prev = prev;\n\tp->ipf_next = prev->ipf_next;\n\t((struct ipasfrag *)(prev->ipf_next))->ipf_prev = p;\n\tprev->ipf_next = p;\n}\n\n/*\n * To ip_enq as remque is to insque.\n */\nstatic void\nip_deq(register struct ipasfrag *p)\n{\n\t((struct ipasfrag *)(p->ipf_prev))->ipf_next = p->ipf_next;\n\t((struct ipasfrag *)(p->ipf_next))->ipf_prev = p->ipf_prev;\n}\n\n/*\n * IP timer processing;\n * if a timer expires on a reassembly\n * queue, discard it.\n */\nvoid\nip_slowtimo(Slirp *slirp)\n{\n struct qlink *l;\n\n\tDEBUG_CALL(\"ip_slowtimo\");\n\n l = slirp->ipq.ip_link.next;\n\n if (l == NULL)\n\t return;\n\n while (l != &slirp->ipq.ip_link) {\n struct ipq *fp = container_of(l, struct ipq, ip_link);\n l = l->next;\n\t\tif (--fp->ipq_ttl == 0) {\n\t\t\tip_freef(slirp, fp);\n\t\t}\n }\n}\n\n/*\n * Do option processing on a datagram,\n * possibly discarding it if bad options are encountered,\n * or forwarding it if source-routed.\n * Returns 1 if packet has been forwarded/freed,\n * 0 if the packet should be processed further.\n */\n\n#ifdef notdef\n\nint\nip_dooptions(m)\n\tstruct mbuf *m;\n{\n\tregister struct ip *ip = mtod(m, struct ip *);\n\tregister u_char *cp;\n\tregister struct ip_timestamp *ipt;\n\tregister struct in_ifaddr *ia;\n\tint opt, optlen, cnt, off, code, type, forward = 0;\n\tstruct in_addr *sin, dst;\ntypedef uint32_t n_time;\n\tn_time ntime;\n\n\tdst = ip->ip_dst;\n\tcp = (u_char *)(ip + 1);\n\tcnt = (ip->ip_hl << 2) - sizeof (struct ip);\n\tfor (; cnt > 0; cnt -= optlen, cp += optlen) {\n\t\topt = cp[IPOPT_OPTVAL];\n\t\tif (opt == IPOPT_EOL)\n\t\t\tbreak;\n\t\tif (opt == IPOPT_NOP)\n\t\t\toptlen = 1;\n\t\telse {\n\t\t\toptlen = cp[IPOPT_OLEN];\n\t\t\tif (optlen <= 0 || optlen > cnt) {\n\t\t\t\tcode = &cp[IPOPT_OLEN] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t}\n\t\tswitch (opt) {\n\n\t\tdefault:\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Source routing with record.\n\t\t * Find interface with current destination address.\n\t\t * If none on this machine then drop if strictly routed,\n\t\t * or do nothing if loosely routed.\n\t\t * Record interface address and bring up next address\n\t\t * component. If strictly routed make sure next\n\t\t * address is on directly accessible net.\n\t\t */\n\t\tcase IPOPT_LSRR:\n\t\tcase IPOPT_SSRR:\n\t\t\tif ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {\n\t\t\t\tcode = &cp[IPOPT_OFFSET] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tipaddr.sin_addr = ip->ip_dst;\n\t\t\tia = (struct in_ifaddr *)\n\t\t\t\tifa_ifwithaddr((struct sockaddr *)&ipaddr);\n\t\t\tif (ia == 0) {\n\t\t\t\tif (opt == IPOPT_SSRR) {\n\t\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\t\tcode = ICMP_UNREACH_SRCFAIL;\n\t\t\t\t\tgoto bad;\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Loose routing, and not at next destination\n\t\t\t\t * yet; nothing to do except forward.\n\t\t\t\t */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toff--;\t\t\t/ * 0 origin * /\n\t\t\tif (off > optlen - sizeof(struct in_addr)) {\n\t\t\t\t/*\n\t\t\t\t * End of source route. Should be for us.\n\t\t\t\t */\n\t\t\t\tsave_rte(cp, ip->ip_src);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/*\n\t\t\t * locate outgoing interface\n\t\t\t */\n\t\t\tbcopy((caddr_t)(cp + off), (caddr_t)&ipaddr.sin_addr,\n\t\t\t sizeof(ipaddr.sin_addr));\n\t\t\tif (opt == IPOPT_SSRR) {\n#define\tINA\tstruct in_ifaddr *\n#define\tSA\tstruct sockaddr *\n \t\t\t if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)\n\t\t\t\tia = (INA)ifa_ifwithnet((SA)&ipaddr);\n\t\t\t} else\n\t\t\t\tia = ip_rtaddr(ipaddr.sin_addr);\n\t\t\tif (ia == 0) {\n\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\tcode = ICMP_UNREACH_SRCFAIL;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tip->ip_dst = ipaddr.sin_addr;\n\t\t\tbcopy((caddr_t)&(IA_SIN(ia)->sin_addr),\n\t\t\t (caddr_t)(cp + off), sizeof(struct in_addr));\n\t\t\tcp[IPOPT_OFFSET] += sizeof(struct in_addr);\n\t\t\t/*\n\t\t\t * Let ip_intr's mcast routing check handle mcast pkts\n\t\t\t */\n\t\t\tforward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));\n\t\t\tbreak;\n\n\t\tcase IPOPT_RR:\n\t\t\tif ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {\n\t\t\t\tcode = &cp[IPOPT_OFFSET] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\t/*\n\t\t\t * If no space remains, ignore.\n\t\t\t */\n\t\t\toff--;\t\t\t * 0 origin *\n\t\t\tif (off > optlen - sizeof(struct in_addr))\n\t\t\t\tbreak;\n\t\t\tbcopy((caddr_t)(&ip->ip_dst), (caddr_t)&ipaddr.sin_addr,\n\t\t\t sizeof(ipaddr.sin_addr));\n\t\t\t/*\n\t\t\t * locate outgoing interface; if we're the destination,\n\t\t\t * use the incoming interface (should be same).\n\t\t\t */\n\t\t\tif ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&\n\t\t\t (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {\n\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\tcode = ICMP_UNREACH_HOST;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tbcopy((caddr_t)&(IA_SIN(ia)->sin_addr),\n\t\t\t (caddr_t)(cp + off), sizeof(struct in_addr));\n\t\t\tcp[IPOPT_OFFSET] += sizeof(struct in_addr);\n\t\t\tbreak;\n\n\t\tcase IPOPT_TS:\n\t\t\tcode = cp - (u_char *)ip;\n\t\t\tipt = (struct ip_timestamp *)cp;\n\t\t\tif (ipt->ipt_len < 5)\n\t\t\t\tgoto bad;\n\t\t\tif (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {\n\t\t\t\tif (++ipt->ipt_oflw == 0)\n\t\t\t\t\tgoto bad;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);\n\t\t\tswitch (ipt->ipt_flg) {\n\n\t\t\tcase IPOPT_TS_TSONLY:\n\t\t\t\tbreak;\n\n\t\t\tcase IPOPT_TS_TSANDADDR:\n\t\t\t\tif (ipt->ipt_ptr + sizeof(n_time) +\n\t\t\t\t sizeof(struct in_addr) > ipt->ipt_len)\n\t\t\t\t\tgoto bad;\n\t\t\t\tipaddr.sin_addr = dst;\n\t\t\t\tia = (INA)ifaof_ i f p foraddr((SA)&ipaddr,\n\t\t\t\t\t\t\t m->m_pkthdr.rcvif);\n\t\t\t\tif (ia == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tbcopy((caddr_t)&IA_SIN(ia)->sin_addr,\n\t\t\t\t (caddr_t)sin, sizeof(struct in_addr));\n\t\t\t\tipt->ipt_ptr += sizeof(struct in_addr);\n\t\t\t\tbreak;\n\n\t\t\tcase IPOPT_TS_PRESPEC:\n\t\t\t\tif (ipt->ipt_ptr + sizeof(n_time) +\n\t\t\t\t sizeof(struct in_addr) > ipt->ipt_len)\n\t\t\t\t\tgoto bad;\n\t\t\t\tbcopy((caddr_t)sin, (caddr_t)&ipaddr.sin_addr,\n\t\t\t\t sizeof(struct in_addr));\n\t\t\t\tif (ifa_ifwithaddr((SA)&ipaddr) == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tipt->ipt_ptr += sizeof(struct in_addr);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tntime = iptime();\n\t\t\tbcopy((caddr_t)&ntime, (caddr_t)cp + ipt->ipt_ptr - 1,\n\t\t\t sizeof(n_time));\n\t\t\tipt->ipt_ptr += sizeof(n_time);\n\t\t}\n\t}\n\tif (forward) {\n\t\tip_forward(m, 1);\n\t\treturn (1);\n\t}\n\treturn (0);\nbad:\n \ticmp_error(m, type, code, 0, 0);\n\n\treturn (1);\n}\n\n#endif /* notdef */\n\n/*\n * Strip out IP options, at higher\n * level protocol in the kernel.\n * Second argument is buffer to which options\n * will be moved, and return value is their length.\n * (XXX) should be deleted; last arg currently ignored.\n */\nvoid\nip_stripoptions(register struct mbuf *m, struct mbuf *mopt)\n{\n\tregister int i;\n\tstruct ip *ip = mtod(m, struct ip *);\n\tregister caddr_t opts;\n\tint olen;\n\n\tolen = (ip->ip_hl<<2) - sizeof (struct ip);\n\topts = (caddr_t)(ip + 1);\n\ti = m->m_len - (sizeof (struct ip) + olen);\n\tmemcpy(opts, opts + olen, (unsigned)i);\n\tm->m_len -= olen;\n\n\tip->ip_hl = sizeof(struct ip) >> 2;\n}\n"], ["/linuxpdf/tinyemu/slirp/udp.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)udp_usrreq.c\t8.4 (Berkeley) 1/21/94\n * udp_usrreq.c,v 1.4 1994/10/02 17:48:45 phk Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\nstatic uint8_t udp_tos(struct socket *so);\n\nvoid\nudp_init(Slirp *slirp)\n{\n slirp->udb.so_next = slirp->udb.so_prev = &slirp->udb;\n slirp->udp_last_so = &slirp->udb;\n}\n/* m->m_data points at ip packet header\n * m->m_len length ip packet\n * ip->ip_len length data (IPDU)\n */\nvoid\nudp_input(register struct mbuf *m, int iphlen)\n{\n\tSlirp *slirp = m->slirp;\n\tregister struct ip *ip;\n\tregister struct udphdr *uh;\n\tint len;\n\tstruct ip save_ip;\n\tstruct socket *so;\n\n\tDEBUG_CALL(\"udp_input\");\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"iphlen = %d\", iphlen);\n\n\t/*\n\t * Strip IP options, if any; should skip this,\n\t * make available to user, and use on returned packets,\n\t * but we don't yet have a way to check the checksum\n\t * with options still present.\n\t */\n\tif(iphlen > sizeof(struct ip)) {\n\t\tip_stripoptions(m, (struct mbuf *)0);\n\t\tiphlen = sizeof(struct ip);\n\t}\n\n\t/*\n\t * Get IP and UDP header together in first mbuf.\n\t */\n\tip = mtod(m, struct ip *);\n\tuh = (struct udphdr *)((caddr_t)ip + iphlen);\n\n\t/*\n\t * Make mbuf data length reflect UDP length.\n\t * If not enough data to reflect UDP length, drop.\n\t */\n\tlen = ntohs((uint16_t)uh->uh_ulen);\n\n\tif (ip->ip_len != len) {\n\t\tif (len > ip->ip_len) {\n\t\t\tgoto bad;\n\t\t}\n\t\tm_adj(m, len - ip->ip_len);\n\t\tip->ip_len = len;\n\t}\n\n\t/*\n\t * Save a copy of the IP header in case we want restore it\n\t * for sending an ICMP error message in response.\n\t */\n\tsave_ip = *ip;\n\tsave_ip.ip_len+= iphlen; /* tcp_input subtracts this */\n\n\t/*\n\t * Checksum extended UDP header and data.\n\t */\n\tif (uh->uh_sum) {\n memset(&((struct ipovly *)ip)->ih_mbuf, 0, sizeof(struct mbuf_ptr));\n\t ((struct ipovly *)ip)->ih_x1 = 0;\n\t ((struct ipovly *)ip)->ih_len = uh->uh_ulen;\n\t if(cksum(m, len + sizeof(struct ip))) {\n\t goto bad;\n\t }\n\t}\n\n /*\n * handle DHCP/BOOTP\n */\n if (ntohs(uh->uh_dport) == BOOTP_SERVER) {\n bootp_input(m);\n goto bad;\n }\n\n if (slirp->restricted) {\n goto bad;\n }\n\n#if 0\n /*\n * handle TFTP\n */\n if (ntohs(uh->uh_dport) == TFTP_SERVER) {\n tftp_input(m);\n goto bad;\n }\n#endif\n \n\t/*\n\t * Locate pcb for datagram.\n\t */\n\tso = slirp->udp_last_so;\n\tif (so->so_lport != uh->uh_sport ||\n\t so->so_laddr.s_addr != ip->ip_src.s_addr) {\n\t\tstruct socket *tmp;\n\n\t\tfor (tmp = slirp->udb.so_next; tmp != &slirp->udb;\n\t\t tmp = tmp->so_next) {\n\t\t\tif (tmp->so_lport == uh->uh_sport &&\n\t\t\t tmp->so_laddr.s_addr == ip->ip_src.s_addr) {\n\t\t\t\tso = tmp;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (tmp == &slirp->udb) {\n\t\t so = NULL;\n\t\t} else {\n\t\t slirp->udp_last_so = so;\n\t\t}\n\t}\n\n\tif (so == NULL) {\n\t /*\n\t * If there's no socket for this packet,\n\t * create one\n\t */\n\t so = socreate(slirp);\n\t if (!so) {\n\t goto bad;\n\t }\n\t if(udp_attach(so) == -1) {\n\t DEBUG_MISC((dfd,\" udp_attach errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t sofree(so);\n\t goto bad;\n\t }\n\n\t /*\n\t * Setup fields\n\t */\n\t so->so_laddr = ip->ip_src;\n\t so->so_lport = uh->uh_sport;\n\n\t if ((so->so_iptos = udp_tos(so)) == 0)\n\t so->so_iptos = ip->ip_tos;\n\n\t /*\n\t * XXXXX Here, check if it's in udpexec_list,\n\t * and if it is, do the fork_exec() etc.\n\t */\n\t}\n\n so->so_faddr = ip->ip_dst; /* XXX */\n so->so_fport = uh->uh_dport; /* XXX */\n\n\tiphlen += sizeof(struct udphdr);\n\tm->m_len -= iphlen;\n\tm->m_data += iphlen;\n\n\t/*\n\t * Now we sendto() the packet.\n\t */\n\tif(sosendto(so,m) == -1) {\n\t m->m_len += iphlen;\n\t m->m_data -= iphlen;\n\t *ip=save_ip;\n\t DEBUG_MISC((dfd,\"udp tx errno = %d-%s\\n\",errno,strerror(errno)));\n\t icmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));\n\t}\n\n\tm_free(so->so_m); /* used for ICMP if error on sorecvfrom */\n\n\t/* restore the orig mbuf packet */\n\tm->m_len += iphlen;\n\tm->m_data -= iphlen;\n\t*ip=save_ip;\n\tso->so_m=m; /* ICMP backup */\n\n\treturn;\nbad:\n\tm_freem(m);\n\treturn;\n}\n\nint udp_output2(struct socket *so, struct mbuf *m,\n struct sockaddr_in *saddr, struct sockaddr_in *daddr,\n int iptos)\n{\n\tregister struct udpiphdr *ui;\n\tint error = 0;\n\n\tDEBUG_CALL(\"udp_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"saddr = %lx\", (long)saddr->sin_addr.s_addr);\n\tDEBUG_ARG(\"daddr = %lx\", (long)daddr->sin_addr.s_addr);\n\n\t/*\n\t * Adjust for header\n\t */\n\tm->m_data -= sizeof(struct udpiphdr);\n\tm->m_len += sizeof(struct udpiphdr);\n\n\t/*\n\t * Fill in mbuf with extended UDP header\n\t * and addresses and length put into network format.\n\t */\n\tui = mtod(m, struct udpiphdr *);\n memset(&ui->ui_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));\n\tui->ui_x1 = 0;\n\tui->ui_pr = IPPROTO_UDP;\n\tui->ui_len = htons(m->m_len - sizeof(struct ip));\n\t/* XXXXX Check for from-one-location sockets, or from-any-location sockets */\n ui->ui_src = saddr->sin_addr;\n\tui->ui_dst = daddr->sin_addr;\n\tui->ui_sport = saddr->sin_port;\n\tui->ui_dport = daddr->sin_port;\n\tui->ui_ulen = ui->ui_len;\n\n\t/*\n\t * Stuff checksum and output datagram.\n\t */\n\tui->ui_sum = 0;\n\tif ((ui->ui_sum = cksum(m, m->m_len)) == 0)\n\t\tui->ui_sum = 0xffff;\n\t((struct ip *)ui)->ip_len = m->m_len;\n\n\t((struct ip *)ui)->ip_ttl = IPDEFTTL;\n\t((struct ip *)ui)->ip_tos = iptos;\n\n\terror = ip_output(so, m);\n\n\treturn (error);\n}\n\nint udp_output(struct socket *so, struct mbuf *m,\n struct sockaddr_in *addr)\n\n{\n Slirp *slirp = so->slirp;\n struct sockaddr_in saddr, daddr;\n\n saddr = *addr;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n uint32_t inv_mask = ~slirp->vnetwork_mask.s_addr;\n\n if ((so->so_faddr.s_addr & inv_mask) == inv_mask) {\n saddr.sin_addr = slirp->vhost_addr;\n } else if (addr->sin_addr.s_addr == loopback_addr.s_addr ||\n so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {\n saddr.sin_addr = so->so_faddr;\n }\n }\n daddr.sin_addr = so->so_laddr;\n daddr.sin_port = so->so_lport;\n\n return udp_output2(so, m, &saddr, &daddr, so->so_iptos);\n}\n\nint\nudp_attach(struct socket *so)\n{\n if((so->s = os_socket(AF_INET,SOCK_DGRAM,0)) != -1) {\n so->so_expire = curtime + SO_EXPIRE;\n insque(so, &so->slirp->udb);\n }\n return(so->s);\n}\n\nvoid\nudp_detach(struct socket *so)\n{\n\tclosesocket(so->s);\n\tsofree(so);\n}\n\nstatic const struct tos_t udptos[] = {\n\t{0, 53, IPTOS_LOWDELAY, 0},\t\t\t/* DNS */\n\t{0, 0, 0, 0}\n};\n\nstatic uint8_t\nudp_tos(struct socket *so)\n{\n\tint i = 0;\n\n\twhile(udptos[i].tos) {\n\t\tif ((udptos[i].fport && ntohs(so->so_fport) == udptos[i].fport) ||\n\t\t (udptos[i].lport && ntohs(so->so_lport) == udptos[i].lport)) {\n\t\t \tso->so_emu = udptos[i].emu;\n\t\t\treturn udptos[i].tos;\n\t\t}\n\t\ti++;\n\t}\n\n\treturn 0;\n}\n\nstruct socket *\nudp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,\n u_int lport, int flags)\n{\n\tstruct sockaddr_in addr;\n\tstruct socket *so;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in), opt = 1;\n\n\tso = socreate(slirp);\n\tif (!so) {\n\t return NULL;\n\t}\n\tso->s = os_socket(AF_INET,SOCK_DGRAM,0);\n\tso->so_expire = curtime + SO_EXPIRE;\n\tinsque(so, &slirp->udb);\n\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = haddr;\n\taddr.sin_port = hport;\n\n\tif (bind(so->s,(struct sockaddr *)&addr, addrlen) < 0) {\n\t\tudp_detach(so);\n\t\treturn NULL;\n\t}\n\tsetsockopt(so->s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\n\tgetsockname(so->s,(struct sockaddr *)&addr,&addrlen);\n\tso->so_fport = addr.sin_port;\n\tif (addr.sin_addr.s_addr == 0 ||\n\t addr.sin_addr.s_addr == loopback_addr.s_addr) {\n\t so->so_faddr = slirp->vhost_addr;\n\t} else {\n\t so->so_faddr = addr.sin_addr;\n\t}\n\tso->so_lport = lport;\n\tso->so_laddr.s_addr = laddr;\n\tif (flags != SS_FACCEPTONCE)\n\t so->so_expire = 0;\n\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= SS_ISFCONNECTED | flags;\n\n\treturn so;\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_icmp.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_icmp.c\t8.2 (Berkeley) 1/4/94\n * ip_icmp.c,v 1.7 1995/05/30 08:09:42 rgrimes Exp\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n/* The message sent when emulating PING */\n/* Be nice and tell them it's just a pseudo-ping packet */\nstatic const char icmp_ping_msg[] = \"This is a pseudo-PING packet used by Slirp to emulate ICMP ECHO-REQUEST packets.\\n\";\n\n/* list of actions for icmp_error() on RX of an icmp message */\nstatic const int icmp_flush[19] = {\n/* ECHO REPLY (0) */ 0,\n\t\t 1,\n\t\t 1,\n/* DEST UNREACH (3) */ 1,\n/* SOURCE QUENCH (4)*/ 1,\n/* REDIRECT (5) */ 1,\n\t\t 1,\n\t\t 1,\n/* ECHO (8) */ 0,\n/* ROUTERADVERT (9) */ 1,\n/* ROUTERSOLICIT (10) */ 1,\n/* TIME EXCEEDED (11) */ 1,\n/* PARAMETER PROBLEM (12) */ 1,\n/* TIMESTAMP (13) */ 0,\n/* TIMESTAMP REPLY (14) */ 0,\n/* INFO (15) */ 0,\n/* INFO REPLY (16) */ 0,\n/* ADDR MASK (17) */ 0,\n/* ADDR MASK REPLY (18) */ 0\n};\n\n/*\n * Process a received ICMP message.\n */\nvoid\nicmp_input(struct mbuf *m, int hlen)\n{\n register struct icmp *icp;\n register struct ip *ip=mtod(m, struct ip *);\n int icmplen=ip->ip_len;\n Slirp *slirp = m->slirp;\n\n DEBUG_CALL(\"icmp_input\");\n DEBUG_ARG(\"m = %lx\", (long )m);\n DEBUG_ARG(\"m_len = %d\", m->m_len);\n\n /*\n * Locate icmp structure in mbuf, and check\n * that its not corrupted and of at least minimum length.\n */\n if (icmplen < ICMP_MINLEN) { /* min 8 bytes payload */\n freeit:\n m_freem(m);\n goto end_error;\n }\n\n m->m_len -= hlen;\n m->m_data += hlen;\n icp = mtod(m, struct icmp *);\n if (cksum(m, icmplen)) {\n goto freeit;\n }\n m->m_len += hlen;\n m->m_data -= hlen;\n\n DEBUG_ARG(\"icmp_type = %d\", icp->icmp_type);\n switch (icp->icmp_type) {\n case ICMP_ECHO:\n icp->icmp_type = ICMP_ECHOREPLY;\n ip->ip_len += hlen;\t /* since ip_input subtracts this */\n if (ip->ip_dst.s_addr == slirp->vhost_addr.s_addr) {\n icmp_reflect(m);\n } else {\n struct socket *so;\n struct sockaddr_in addr;\n if ((so = socreate(slirp)) == NULL) goto freeit;\n if(udp_attach(so) == -1) {\n\tDEBUG_MISC((dfd,\"icmp_input udp_attach errno = %d-%s\\n\",\n\t\t errno,strerror(errno)));\n\tsofree(so);\n\tm_free(m);\n\tgoto end_error;\n }\n so->so_m = m;\n so->so_faddr = ip->ip_dst;\n so->so_fport = htons(7);\n so->so_laddr = ip->ip_src;\n so->so_lport = htons(9);\n so->so_iptos = ip->ip_tos;\n so->so_type = IPPROTO_ICMP;\n so->so_state = SS_ISFCONNECTED;\n\n /* Send the packet */\n addr.sin_family = AF_INET;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n\t/* It's an alias */\n\tif (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\t if (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n\t} else {\n\t addr.sin_addr = loopback_addr;\n\t}\n } else {\n\taddr.sin_addr = so->so_faddr;\n }\n addr.sin_port = so->so_fport;\n if(sendto(so->s, icmp_ping_msg, strlen(icmp_ping_msg), 0,\n\t\t(struct sockaddr *)&addr, sizeof(addr)) == -1) {\n\tDEBUG_MISC((dfd,\"icmp_input udp sendto tx errno = %d-%s\\n\",\n\t\t errno,strerror(errno)));\n\ticmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));\n\tudp_detach(so);\n }\n } /* if ip->ip_dst.s_addr == alias_addr.s_addr */\n break;\n case ICMP_UNREACH:\n /* XXX? report error? close socket? */\n case ICMP_TIMXCEED:\n case ICMP_PARAMPROB:\n case ICMP_SOURCEQUENCH:\n case ICMP_TSTAMP:\n case ICMP_MASKREQ:\n case ICMP_REDIRECT:\n m_freem(m);\n break;\n\n default:\n m_freem(m);\n } /* swith */\n\nend_error:\n /* m is m_free()'d xor put in a socket xor or given to ip_send */\n return;\n}\n\n\n/*\n *\tSend an ICMP message in response to a situation\n *\n *\tRFC 1122: 3.2.2\tMUST send at least the IP header and 8 bytes of header. MAY send more (we do).\n *\t\t\tMUST NOT change this header information.\n *\t\t\tMUST NOT reply to a multicast/broadcast IP address.\n *\t\t\tMUST NOT reply to a multicast/broadcast MAC address.\n *\t\t\tMUST reply to only the first fragment.\n */\n/*\n * Send ICMP_UNREACH back to the source regarding msrc.\n * mbuf *msrc is used as a template, but is NOT m_free()'d.\n * It is reported as the bad ip packet. The header should\n * be fully correct and in host byte order.\n * ICMP fragmentation is illegal. All machines must accept 576 bytes in one\n * packet. The maximum payload is 576-20(ip hdr)-8(icmp hdr)=548\n */\n\n#define ICMP_MAXDATALEN (IP_MSS-28)\nvoid\nicmp_error(struct mbuf *msrc, u_char type, u_char code, int minsize,\n const char *message)\n{\n unsigned hlen, shlen, s_ip_len;\n register struct ip *ip;\n register struct icmp *icp;\n register struct mbuf *m;\n\n DEBUG_CALL(\"icmp_error\");\n DEBUG_ARG(\"msrc = %lx\", (long )msrc);\n DEBUG_ARG(\"msrc_len = %d\", msrc->m_len);\n\n if(type!=ICMP_UNREACH && type!=ICMP_TIMXCEED) goto end_error;\n\n /* check msrc */\n if(!msrc) goto end_error;\n ip = mtod(msrc, struct ip *);\n#ifdef DEBUG\n { char bufa[20], bufb[20];\n strcpy(bufa, inet_ntoa(ip->ip_src));\n strcpy(bufb, inet_ntoa(ip->ip_dst));\n DEBUG_MISC((dfd, \" %.16s to %.16s\\n\", bufa, bufb));\n }\n#endif\n if(ip->ip_off & IP_OFFMASK) goto end_error; /* Only reply to fragment 0 */\n\n shlen=ip->ip_hl << 2;\n s_ip_len=ip->ip_len;\n if(ip->ip_p == IPPROTO_ICMP) {\n icp = (struct icmp *)((char *)ip + shlen);\n /*\n *\tAssume any unknown ICMP type is an error. This isn't\n *\tspecified by the RFC, but think about it..\n */\n if(icp->icmp_type>18 || icmp_flush[icp->icmp_type]) goto end_error;\n }\n\n /* make a copy */\n m = m_get(msrc->slirp);\n if (!m) {\n goto end_error;\n }\n\n { int new_m_size;\n new_m_size=sizeof(struct ip )+ICMP_MINLEN+msrc->m_len+ICMP_MAXDATALEN;\n if(new_m_size>m->m_size) m_inc(m, new_m_size);\n }\n memcpy(m->m_data, msrc->m_data, msrc->m_len);\n m->m_len = msrc->m_len; /* copy msrc to m */\n\n /* make the header of the reply packet */\n ip = mtod(m, struct ip *);\n hlen= sizeof(struct ip ); /* no options in reply */\n\n /* fill in icmp */\n m->m_data += hlen;\n m->m_len -= hlen;\n\n icp = mtod(m, struct icmp *);\n\n if(minsize) s_ip_len=shlen+ICMP_MINLEN; /* return header+8b only */\n else if(s_ip_len>ICMP_MAXDATALEN) /* maximum size */\n s_ip_len=ICMP_MAXDATALEN;\n\n m->m_len=ICMP_MINLEN+s_ip_len; /* 8 bytes ICMP header */\n\n /* min. size = 8+sizeof(struct ip)+8 */\n\n icp->icmp_type = type;\n icp->icmp_code = code;\n icp->icmp_id = 0;\n icp->icmp_seq = 0;\n\n memcpy(&icp->icmp_ip, msrc->m_data, s_ip_len); /* report the ip packet */\n HTONS(icp->icmp_ip.ip_len);\n HTONS(icp->icmp_ip.ip_id);\n HTONS(icp->icmp_ip.ip_off);\n\n#ifdef DEBUG\n if(message) { /* DEBUG : append message to ICMP packet */\n int message_len;\n char *cpnt;\n message_len=strlen(message);\n if(message_len>ICMP_MAXDATALEN) message_len=ICMP_MAXDATALEN;\n cpnt=(char *)m->m_data+m->m_len;\n memcpy(cpnt, message, message_len);\n m->m_len+=message_len;\n }\n#endif\n\n icp->icmp_cksum = 0;\n icp->icmp_cksum = cksum(m, m->m_len);\n\n m->m_data -= hlen;\n m->m_len += hlen;\n\n /* fill in ip */\n ip->ip_hl = hlen >> 2;\n ip->ip_len = m->m_len;\n\n ip->ip_tos=((ip->ip_tos & 0x1E) | 0xC0); /* high priority for errors */\n\n ip->ip_ttl = MAXTTL;\n ip->ip_p = IPPROTO_ICMP;\n ip->ip_dst = ip->ip_src; /* ip adresses */\n ip->ip_src = m->slirp->vhost_addr;\n\n (void ) ip_output((struct socket *)NULL, m);\n\nend_error:\n return;\n}\n#undef ICMP_MAXDATALEN\n\n/*\n * Reflect the ip packet back to the source\n */\nvoid\nicmp_reflect(struct mbuf *m)\n{\n register struct ip *ip = mtod(m, struct ip *);\n int hlen = ip->ip_hl << 2;\n int optlen = hlen - sizeof(struct ip );\n register struct icmp *icp;\n\n /*\n * Send an icmp packet back to the ip level,\n * after supplying a checksum.\n */\n m->m_data += hlen;\n m->m_len -= hlen;\n icp = mtod(m, struct icmp *);\n\n icp->icmp_cksum = 0;\n icp->icmp_cksum = cksum(m, ip->ip_len - hlen);\n\n m->m_data -= hlen;\n m->m_len += hlen;\n\n /* fill in ip */\n if (optlen > 0) {\n /*\n * Strip out original options by copying rest of first\n * mbuf's data back, and adjust the IP length.\n */\n memmove((caddr_t)(ip + 1), (caddr_t)ip + hlen,\n\t (unsigned )(m->m_len - hlen));\n hlen -= optlen;\n ip->ip_hl = hlen >> 2;\n ip->ip_len -= optlen;\n m->m_len -= optlen;\n }\n\n ip->ip_ttl = MAXTTL;\n { /* swap */\n struct in_addr icmp_dst;\n icmp_dst = ip->ip_dst;\n ip->ip_dst = ip->ip_src;\n ip->ip_src = icmp_dst;\n }\n\n (void ) ip_output((struct socket *)NULL, m);\n}\n"], ["/linuxpdf/tinyemu/cutils.c", "/*\n * Misc C utilities\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n\nvoid *mallocz(size_t size)\n{\n void *ptr;\n ptr = malloc(size);\n if (!ptr)\n return NULL;\n memset(ptr, 0, size);\n return ptr;\n}\n\nvoid pstrcpy(char *buf, int buf_size, const char *str)\n{\n int c;\n char *q = buf;\n\n if (buf_size <= 0)\n return;\n\n for(;;) {\n c = *str++;\n if (c == 0 || q >= buf + buf_size - 1)\n break;\n *q++ = c;\n }\n *q = '\\0';\n}\n\nchar *pstrcat(char *buf, int buf_size, const char *s)\n{\n int len;\n len = strlen(buf);\n if (len < buf_size)\n pstrcpy(buf + len, buf_size - len, s);\n return buf;\n}\n\nint strstart(const char *str, const char *val, const char **ptr)\n{\n const char *p, *q;\n p = str;\n q = val;\n while (*q != '\\0') {\n if (*p != *q)\n return 0;\n p++;\n q++;\n }\n if (ptr)\n *ptr = p;\n return 1;\n}\n\nvoid dbuf_init(DynBuf *s)\n{\n memset(s, 0, sizeof(*s));\n}\n\nvoid dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len)\n{\n size_t end, new_size;\n new_size = end = offset + len;\n if (new_size > s->allocated_size) {\n new_size = max_int(new_size, s->allocated_size * 3 / 2);\n s->buf = realloc(s->buf, new_size);\n s->allocated_size = new_size;\n }\n memcpy(s->buf + offset, data, len);\n if (end > s->size)\n s->size = end;\n}\n\nvoid dbuf_putc(DynBuf *s, uint8_t c)\n{\n dbuf_write(s, s->size, &c, 1);\n}\n\nvoid dbuf_putstr(DynBuf *s, const char *str)\n{\n dbuf_write(s, s->size, (const uint8_t *)str, strlen(str));\n}\n\nvoid dbuf_free(DynBuf *s)\n{\n free(s->buf);\n memset(s, 0, sizeof(*s));\n}\n"], ["/linuxpdf/tinyemu/fs.c", "/*\n * Filesystem utilities\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"fs.h\"\n\nFSFile *fs_dup(FSDevice *fs, FSFile *f)\n{\n FSQID qid;\n fs->fs_walk(fs, &f, &qid, f, 0, NULL);\n return f;\n}\n\nFSFile *fs_walk_path1(FSDevice *fs, FSFile *f, const char *path,\n char **pname)\n{\n const char *p;\n char *name;\n FSFile *f1;\n FSQID qid;\n int len, ret;\n BOOL is_last, is_first;\n\n if (path[0] == '/')\n path++;\n \n is_first = TRUE;\n for(;;) {\n p = strchr(path, '/');\n if (!p) {\n name = (char *)path;\n if (pname) {\n *pname = name;\n if (is_first) {\n ret = fs->fs_walk(fs, &f, &qid, f, 0, NULL);\n if (ret < 0)\n f = NULL;\n }\n return f;\n }\n is_last = TRUE;\n } else {\n len = p - path;\n name = malloc(len + 1);\n memcpy(name, path, len);\n name[len] = '\\0';\n is_last = FALSE;\n }\n ret = fs->fs_walk(fs, &f1, &qid, f, 1, &name);\n if (!is_last)\n free(name);\n if (!is_first)\n fs->fs_delete(fs, f);\n f = f1;\n is_first = FALSE;\n if (ret <= 0) {\n fs->fs_delete(fs, f);\n f = NULL;\n break;\n } else if (is_last) {\n break;\n }\n path = p + 1;\n }\n return f;\n}\n\nFSFile *fs_walk_path(FSDevice *fs, FSFile *f, const char *path)\n{\n return fs_walk_path1(fs, f, path, NULL);\n}\n\nvoid fs_end(FSDevice *fs)\n{\n fs->fs_end(fs);\n free(fs);\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_output.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_output.c\t8.3 (Berkeley) 12/30/93\n * tcp_output.c,v 1.3 1994/09/15 10:36:55 davidg Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\nstatic const u_char tcp_outflags[TCP_NSTATES] = {\n\tTH_RST|TH_ACK, 0, TH_SYN, TH_SYN|TH_ACK,\n\tTH_ACK, TH_ACK, TH_FIN|TH_ACK, TH_FIN|TH_ACK,\n\tTH_FIN|TH_ACK, TH_ACK, TH_ACK,\n};\n\n\n#define MAX_TCPOPTLEN\t32\t/* max # bytes that go in options */\n\n/*\n * Tcp output routine: figure out what should be sent and send it.\n */\nint\ntcp_output(struct tcpcb *tp)\n{\n\tregister struct socket *so = tp->t_socket;\n\tregister long len, win;\n\tint off, flags, error;\n\tregister struct mbuf *m;\n\tregister struct tcpiphdr *ti;\n\tu_char opt[MAX_TCPOPTLEN];\n\tunsigned optlen, hdrlen;\n\tint idle, sendalot;\n\n\tDEBUG_CALL(\"tcp_output\");\n\tDEBUG_ARG(\"tp = %lx\", (long )tp);\n\n\t/*\n\t * Determine length of data that should be transmitted,\n\t * and flags that will be used.\n\t * If there is some data or critical controls (SYN, RST)\n\t * to send, then transmit; otherwise, investigate further.\n\t */\n\tidle = (tp->snd_max == tp->snd_una);\n\tif (idle && tp->t_idle >= tp->t_rxtcur)\n\t\t/*\n\t\t * We have been idle for \"a while\" and no acks are\n\t\t * expected to clock out any data we send --\n\t\t * slow start to get ack \"clock\" running again.\n\t\t */\n\t\ttp->snd_cwnd = tp->t_maxseg;\nagain:\n\tsendalot = 0;\n\toff = tp->snd_nxt - tp->snd_una;\n\twin = min(tp->snd_wnd, tp->snd_cwnd);\n\n\tflags = tcp_outflags[tp->t_state];\n\n\tDEBUG_MISC((dfd, \" --- tcp_output flags = 0x%x\\n\",flags));\n\n\t/*\n\t * If in persist timeout with window of 0, send 1 byte.\n\t * Otherwise, if window is small but nonzero\n\t * and timer expired, we will send what we can\n\t * and go to transmit state.\n\t */\n\tif (tp->t_force) {\n\t\tif (win == 0) {\n\t\t\t/*\n\t\t\t * If we still have some data to send, then\n\t\t\t * clear the FIN bit. Usually this would\n\t\t\t * happen below when it realizes that we\n\t\t\t * aren't sending all the data. However,\n\t\t\t * if we have exactly 1 byte of unset data,\n\t\t\t * then it won't clear the FIN bit below,\n\t\t\t * and if we are in persist state, we wind\n\t\t\t * up sending the packet without recording\n\t\t\t * that we sent the FIN bit.\n\t\t\t *\n\t\t\t * We can't just blindly clear the FIN bit,\n\t\t\t * because if we don't have any more data\n\t\t\t * to send then the probe will be the FIN\n\t\t\t * itself.\n\t\t\t */\n\t\t\tif (off < so->so_snd.sb_cc)\n\t\t\t\tflags &= ~TH_FIN;\n\t\t\twin = 1;\n\t\t} else {\n\t\t\ttp->t_timer[TCPT_PERSIST] = 0;\n\t\t\ttp->t_rxtshift = 0;\n\t\t}\n\t}\n\n\tlen = min(so->so_snd.sb_cc, win) - off;\n\n\tif (len < 0) {\n\t\t/*\n\t\t * If FIN has been sent but not acked,\n\t\t * but we haven't been called to retransmit,\n\t\t * len will be -1. Otherwise, window shrank\n\t\t * after we sent into it. If window shrank to 0,\n\t\t * cancel pending retransmit and pull snd_nxt\n\t\t * back to (closed) window. We will enter persist\n\t\t * state below. If the window didn't close completely,\n\t\t * just wait for an ACK.\n\t\t */\n\t\tlen = 0;\n\t\tif (win == 0) {\n\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\ttp->snd_nxt = tp->snd_una;\n\t\t}\n\t}\n\n\tif (len > tp->t_maxseg) {\n\t\tlen = tp->t_maxseg;\n\t\tsendalot = 1;\n\t}\n\tif (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc))\n\t\tflags &= ~TH_FIN;\n\n\twin = sbspace(&so->so_rcv);\n\n\t/*\n\t * Sender silly window avoidance. If connection is idle\n\t * and can send all data, a maximum segment,\n\t * at least a maximum default-size segment do it,\n\t * or are forced, do it; otherwise don't bother.\n\t * If peer's buffer is tiny, then send\n\t * when window is at least half open.\n\t * If retransmitting (possibly after persist timer forced us\n\t * to send into a small window), then must resend.\n\t */\n\tif (len) {\n\t\tif (len == tp->t_maxseg)\n\t\t\tgoto send;\n\t\tif ((1 || idle || tp->t_flags & TF_NODELAY) &&\n\t\t len + off >= so->so_snd.sb_cc)\n\t\t\tgoto send;\n\t\tif (tp->t_force)\n\t\t\tgoto send;\n\t\tif (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)\n\t\t\tgoto send;\n\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_max))\n\t\t\tgoto send;\n\t}\n\n\t/*\n\t * Compare available window to amount of window\n\t * known to peer (as advertised window less\n\t * next expected input). If the difference is at least two\n\t * max size segments, or at least 50% of the maximum possible\n\t * window, then want to send a window update to peer.\n\t */\n\tif (win > 0) {\n\t\t/*\n\t\t * \"adv\" is the amount we can increase the window,\n\t\t * taking into account that we are limited by\n\t\t * TCP_MAXWIN << tp->rcv_scale.\n\t\t */\n\t\tlong adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -\n\t\t\t(tp->rcv_adv - tp->rcv_nxt);\n\n\t\tif (adv >= (long) (2 * tp->t_maxseg))\n\t\t\tgoto send;\n\t\tif (2 * adv >= (long) so->so_rcv.sb_datalen)\n\t\t\tgoto send;\n\t}\n\n\t/*\n\t * Send if we owe peer an ACK.\n\t */\n\tif (tp->t_flags & TF_ACKNOW)\n\t\tgoto send;\n\tif (flags & (TH_SYN|TH_RST))\n\t\tgoto send;\n\tif (SEQ_GT(tp->snd_up, tp->snd_una))\n\t\tgoto send;\n\t/*\n\t * If our state indicates that FIN should be sent\n\t * and we have not yet done so, or we're retransmitting the FIN,\n\t * then we need to send.\n\t */\n\tif (flags & TH_FIN &&\n\t ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))\n\t\tgoto send;\n\n\t/*\n\t * TCP window updates are not reliable, rather a polling protocol\n\t * using ``persist'' packets is used to insure receipt of window\n\t * updates. The three ``states'' for the output side are:\n\t *\tidle\t\t\tnot doing retransmits or persists\n\t *\tpersisting\t\tto move a small or zero window\n\t *\t(re)transmitting\tand thereby not persisting\n\t *\n\t * tp->t_timer[TCPT_PERSIST]\n\t *\tis set when we are in persist state.\n\t * tp->t_force\n\t *\tis set when we are called to send a persist packet.\n\t * tp->t_timer[TCPT_REXMT]\n\t *\tis set when we are retransmitting\n\t * The output side is idle when both timers are zero.\n\t *\n\t * If send window is too small, there is data to transmit, and no\n\t * retransmit or persist is pending, then go to persist state.\n\t * If nothing happens soon, send when timer expires:\n\t * if window is nonzero, transmit what we can,\n\t * otherwise force out a byte.\n\t */\n\tif (so->so_snd.sb_cc && tp->t_timer[TCPT_REXMT] == 0 &&\n\t tp->t_timer[TCPT_PERSIST] == 0) {\n\t\ttp->t_rxtshift = 0;\n\t\ttcp_setpersist(tp);\n\t}\n\n\t/*\n\t * No reason to send a segment, just return.\n\t */\n\treturn (0);\n\nsend:\n\t/*\n\t * Before ESTABLISHED, force sending of initial options\n\t * unless TCP set not to do any options.\n\t * NOTE: we assume that the IP/TCP header plus TCP options\n\t * always fit in a single mbuf, leaving room for a maximum\n\t * link header, i.e.\n\t *\tmax_linkhdr + sizeof (struct tcpiphdr) + optlen <= MHLEN\n\t */\n\toptlen = 0;\n\thdrlen = sizeof (struct tcpiphdr);\n\tif (flags & TH_SYN) {\n\t\ttp->snd_nxt = tp->iss;\n\t\tif ((tp->t_flags & TF_NOOPT) == 0) {\n\t\t\tuint16_t mss;\n\n\t\t\topt[0] = TCPOPT_MAXSEG;\n\t\t\topt[1] = 4;\n\t\t\tmss = htons((uint16_t) tcp_mss(tp, 0));\n\t\t\tmemcpy((caddr_t)(opt + 2), (caddr_t)&mss, sizeof(mss));\n\t\t\toptlen = 4;\n\t\t}\n \t}\n\n \thdrlen += optlen;\n\n\t/*\n\t * Adjust data length if insertion of options will\n\t * bump the packet length beyond the t_maxseg length.\n\t */\n\t if (len > tp->t_maxseg - optlen) {\n\t\tlen = tp->t_maxseg - optlen;\n\t\tsendalot = 1;\n\t }\n\n\t/*\n\t * Grab a header mbuf, attaching a copy of data to\n\t * be transmitted, and initialize the header from\n\t * the template for sends on this connection.\n\t */\n\tif (len) {\n\t\tm = m_get(so->slirp);\n\t\tif (m == NULL) {\n\t\t\terror = 1;\n\t\t\tgoto out;\n\t\t}\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\tm->m_len = hdrlen;\n\n\t\tsbcopy(&so->so_snd, off, (int) len, mtod(m, caddr_t) + hdrlen);\n\t\tm->m_len += len;\n\n\t\t/*\n\t\t * If we're sending everything we've got, set PUSH.\n\t\t * (This will keep happy those implementations which only\n\t\t * give data to the user when a buffer fills or\n\t\t * a PUSH comes in.)\n\t\t */\n\t\tif (off + len == so->so_snd.sb_cc)\n\t\t\tflags |= TH_PUSH;\n\t} else {\n\t\tm = m_get(so->slirp);\n\t\tif (m == NULL) {\n\t\t\terror = 1;\n\t\t\tgoto out;\n\t\t}\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\tm->m_len = hdrlen;\n\t}\n\n\tti = mtod(m, struct tcpiphdr *);\n\n\tmemcpy((caddr_t)ti, &tp->t_template, sizeof (struct tcpiphdr));\n\n\t/*\n\t * Fill in fields, remembering maximum advertised\n\t * window for use in delaying messages about window sizes.\n\t * If resending a FIN, be sure not to use a new sequence number.\n\t */\n\tif (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&\n\t tp->snd_nxt == tp->snd_max)\n\t\ttp->snd_nxt--;\n\t/*\n\t * If we are doing retransmissions, then snd_nxt will\n\t * not reflect the first unsent octet. For ACK only\n\t * packets, we do not want the sequence number of the\n\t * retransmitted packet, we want the sequence number\n\t * of the next unsent octet. So, if there is no data\n\t * (and no SYN or FIN), use snd_max instead of snd_nxt\n\t * when filling in ti_seq. But if we are in persist\n\t * state, snd_max might reflect one byte beyond the\n\t * right edge of the window, so use snd_nxt in that\n\t * case, since we know we aren't doing a retransmission.\n\t * (retransmit and persist are mutually exclusive...)\n\t */\n\tif (len || (flags & (TH_SYN|TH_FIN)) || tp->t_timer[TCPT_PERSIST])\n\t\tti->ti_seq = htonl(tp->snd_nxt);\n\telse\n\t\tti->ti_seq = htonl(tp->snd_max);\n\tti->ti_ack = htonl(tp->rcv_nxt);\n\tif (optlen) {\n\t\tmemcpy((caddr_t)(ti + 1), (caddr_t)opt, optlen);\n\t\tti->ti_off = (sizeof (struct tcphdr) + optlen) >> 2;\n\t}\n\tti->ti_flags = flags;\n\t/*\n\t * Calculate receive window. Don't shrink window,\n\t * but avoid silly window syndrome.\n\t */\n\tif (win < (long)(so->so_rcv.sb_datalen / 4) && win < (long)tp->t_maxseg)\n\t\twin = 0;\n\tif (win > (long)TCP_MAXWIN << tp->rcv_scale)\n\t\twin = (long)TCP_MAXWIN << tp->rcv_scale;\n\tif (win < (long)(tp->rcv_adv - tp->rcv_nxt))\n\t\twin = (long)(tp->rcv_adv - tp->rcv_nxt);\n\tti->ti_win = htons((uint16_t) (win>>tp->rcv_scale));\n\n\tif (SEQ_GT(tp->snd_up, tp->snd_una)) {\n\t\tti->ti_urp = htons((uint16_t)(tp->snd_up - ntohl(ti->ti_seq)));\n\t\tti->ti_flags |= TH_URG;\n\t} else\n\t\t/*\n\t\t * If no urgent pointer to send, then we pull\n\t\t * the urgent pointer to the left edge of the send window\n\t\t * so that it doesn't drift into the send window on sequence\n\t\t * number wraparound.\n\t\t */\n\t\ttp->snd_up = tp->snd_una;\t\t/* drag it along */\n\n\t/*\n\t * Put TCP length in extended header, and then\n\t * checksum extended header and data.\n\t */\n\tif (len + optlen)\n\t\tti->ti_len = htons((uint16_t)(sizeof (struct tcphdr) +\n\t\t optlen + len));\n\tti->ti_sum = cksum(m, (int)(hdrlen + len));\n\n\t/*\n\t * In transmit state, time the transmission and arrange for\n\t * the retransmit. In persist state, just set snd_max.\n\t */\n\tif (tp->t_force == 0 || tp->t_timer[TCPT_PERSIST] == 0) {\n\t\ttcp_seq startseq = tp->snd_nxt;\n\n\t\t/*\n\t\t * Advance snd_nxt over sequence space of this segment.\n\t\t */\n\t\tif (flags & (TH_SYN|TH_FIN)) {\n\t\t\tif (flags & TH_SYN)\n\t\t\t\ttp->snd_nxt++;\n\t\t\tif (flags & TH_FIN) {\n\t\t\t\ttp->snd_nxt++;\n\t\t\t\ttp->t_flags |= TF_SENTFIN;\n\t\t\t}\n\t\t}\n\t\ttp->snd_nxt += len;\n\t\tif (SEQ_GT(tp->snd_nxt, tp->snd_max)) {\n\t\t\ttp->snd_max = tp->snd_nxt;\n\t\t\t/*\n\t\t\t * Time this transmission if not a retransmission and\n\t\t\t * not currently timing anything.\n\t\t\t */\n\t\t\tif (tp->t_rtt == 0) {\n\t\t\t\ttp->t_rtt = 1;\n\t\t\t\ttp->t_rtseq = startseq;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Set retransmit timer if not currently set,\n\t\t * and not doing an ack or a keep-alive probe.\n\t\t * Initial value for retransmit timer is smoothed\n\t\t * round-trip time + 2 * round-trip time variance.\n\t\t * Initialize shift counter which is used for backoff\n\t\t * of retransmit time.\n\t\t */\n\t\tif (tp->t_timer[TCPT_REXMT] == 0 &&\n\t\t tp->snd_nxt != tp->snd_una) {\n\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t\tif (tp->t_timer[TCPT_PERSIST]) {\n\t\t\t\ttp->t_timer[TCPT_PERSIST] = 0;\n\t\t\t\ttp->t_rxtshift = 0;\n\t\t\t}\n\t\t}\n\t} else\n\t\tif (SEQ_GT(tp->snd_nxt + len, tp->snd_max))\n\t\t\ttp->snd_max = tp->snd_nxt + len;\n\n\t/*\n\t * Fill in IP length and desired time to live and\n\t * send to IP level. There should be a better way\n\t * to handle ttl and tos; we could keep them in\n\t * the template, but need a way to checksum without them.\n\t */\n\tm->m_len = hdrlen + len; /* XXX Needed? m_len should be correct */\n\n {\n\n\t((struct ip *)ti)->ip_len = m->m_len;\n\n\t((struct ip *)ti)->ip_ttl = IPDEFTTL;\n\t((struct ip *)ti)->ip_tos = so->so_iptos;\n\n\terror = ip_output(so, m);\n }\n\tif (error) {\nout:\n\t\treturn (error);\n\t}\n\n\t/*\n\t * Data sent (as far as we can tell).\n\t * If this advertises a larger window than any other segment,\n\t * then remember the size of the advertised window.\n\t * Any pending ACK has now been sent.\n\t */\n\tif (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))\n\t\ttp->rcv_adv = tp->rcv_nxt + win;\n\ttp->last_ack_sent = tp->rcv_nxt;\n\ttp->t_flags &= ~(TF_ACKNOW|TF_DELACK);\n\tif (sendalot)\n\t\tgoto again;\n\n\treturn (0);\n}\n\nvoid\ntcp_setpersist(struct tcpcb *tp)\n{\n int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;\n\n\t/*\n\t * Start/restart persistence timer.\n\t */\n\tTCPT_RANGESET(tp->t_timer[TCPT_PERSIST],\n\t t * tcp_backoff[tp->t_rxtshift],\n\t TCPTV_PERSMIN, TCPTV_PERSMAX);\n\tif (tp->t_rxtshift < TCP_MAXRXTSHIFT)\n\t\ttp->t_rxtshift++;\n}\n"], ["/linuxpdf/tinyemu/sha256.c", "/* LibTomCrypt, modular cryptographic library -- Tom St Denis\n *\n * LibTomCrypt is a library that provides various cryptographic\n * algorithms in a highly modular and flexible manner.\n *\n * The library is free for all purposes without any express\n * guarantee it works.\n *\n * Tom St Denis, tomstdenis@gmail.com, http://libtom.org\n */\n#include \n#include \n#include \"cutils.h\"\n#include \"sha256.h\"\n\n#define LOAD32H(a, b) a = get_be32(b)\n#define STORE32H(a, b) put_be32(b, a)\n#define STORE64H(a, b) put_be64(b, a)\n#define RORc(x, y) ( ((((uint32_t)(x)&0xFFFFFFFFUL)>>(uint32_t)((y)&31)) | ((uint32_t)(x)<<(uint32_t)(32-((y)&31)))) & 0xFFFFFFFFUL)\n\n#if defined(CONFIG_EMBUE)\n#define LTC_SMALL_CODE\n#endif\n\n/**\n @file sha256.c\n LTC_SHA256 by Tom St Denis\n*/\n\n#ifdef LTC_SMALL_CODE\n/* the K array */\nstatic const uint32_t K[64] = {\n 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,\n 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,\n 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,\n 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,\n 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,\n 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,\n 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,\n 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,\n 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,\n 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,\n 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,\n 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,\n 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL\n};\n#endif\n\n/* Various logical functions */\n#define Ch(x,y,z) (z ^ (x & (y ^ z)))\n#define Maj(x,y,z) (((x | y) & z) | (x & y))\n#define S(x, n) RORc((x),(n))\n#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))\n#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))\n#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25))\n#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3))\n#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10))\n\n/* compress 512-bits */\nstatic void sha256_compress(SHA256_CTX *s, unsigned char *buf)\n{\n uint32_t S[8], W[64], t0, t1;\n#ifdef LTC_SMALL_CODE\n uint32_t t;\n#endif\n int i;\n\n /* copy state into S */\n for (i = 0; i < 8; i++) {\n S[i] = s->state[i];\n }\n\n /* copy the state into 512-bits into W[0..15] */\n for (i = 0; i < 16; i++) {\n LOAD32H(W[i], buf + (4*i));\n }\n\n /* fill W[16..63] */\n for (i = 16; i < 64; i++) {\n W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];\n }\n\n /* Compress */\n#ifdef LTC_SMALL_CODE\n#define RND(a,b,c,d,e,f,g,h,i) \\\n t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \\\n t1 = Sigma0(a) + Maj(a, b, c); \\\n d += t0; \\\n h = t0 + t1;\n\n for (i = 0; i < 64; ++i) {\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i);\n t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4];\n S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;\n }\n#else\n#define RND(a,b,c,d,e,f,g,h,i,ki) \\\n t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i]; \\\n t1 = Sigma0(a) + Maj(a, b, c); \\\n d += t0; \\\n h = t0 + t1;\n\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,0x428a2f98);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,0x71374491);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,0xb5c0fbcf);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,0xe9b5dba5);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,0x3956c25b);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],5,0x59f111f1);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],6,0x923f82a4);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],7,0xab1c5ed5);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],8,0xd807aa98);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],9,0x12835b01);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],10,0x243185be);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],11,0x550c7dc3);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],12,0x72be5d74);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],13,0x80deb1fe);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],14,0x9bdc06a7);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],15,0xc19bf174);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],16,0xe49b69c1);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],17,0xefbe4786);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],18,0x0fc19dc6);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],19,0x240ca1cc);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],20,0x2de92c6f);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],21,0x4a7484aa);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],22,0x5cb0a9dc);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],23,0x76f988da);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],24,0x983e5152);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],25,0xa831c66d);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],26,0xb00327c8);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],27,0xbf597fc7);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],28,0xc6e00bf3);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],29,0xd5a79147);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],30,0x06ca6351);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],31,0x14292967);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],32,0x27b70a85);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],33,0x2e1b2138);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],34,0x4d2c6dfc);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],35,0x53380d13);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],36,0x650a7354);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],37,0x766a0abb);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],38,0x81c2c92e);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],39,0x92722c85);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],40,0xa2bfe8a1);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],41,0xa81a664b);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],42,0xc24b8b70);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],43,0xc76c51a3);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],44,0xd192e819);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],45,0xd6990624);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],46,0xf40e3585);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],47,0x106aa070);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],48,0x19a4c116);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],49,0x1e376c08);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],50,0x2748774c);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],51,0x34b0bcb5);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],52,0x391c0cb3);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],53,0x4ed8aa4a);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],54,0x5b9cca4f);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],55,0x682e6ff3);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],56,0x748f82ee);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],57,0x78a5636f);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],58,0x84c87814);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],59,0x8cc70208);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],60,0x90befffa);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],61,0xa4506ceb);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);\n\n#undef RND\n\n#endif\n\n /* feedback */\n for (i = 0; i < 8; i++) {\n s->state[i] = s->state[i] + S[i];\n }\n}\n\n#ifdef LTC_CLEAN_STACK\nstatic int sha256_compress(hash_state * md, unsigned char *buf)\n{\n int err;\n err = _sha256_compress(md, buf);\n burn_stack(sizeof(uint32_t) * 74);\n return err;\n}\n#endif\n\n/**\n Initialize the hash state\n @param md The hash state you wish to initialize\n @return CRYPT_OK if successful\n*/\nvoid SHA256_Init(SHA256_CTX *s)\n{\n s->curlen = 0;\n s->length = 0;\n s->state[0] = 0x6A09E667UL;\n s->state[1] = 0xBB67AE85UL;\n s->state[2] = 0x3C6EF372UL;\n s->state[3] = 0xA54FF53AUL;\n s->state[4] = 0x510E527FUL;\n s->state[5] = 0x9B05688CUL;\n s->state[6] = 0x1F83D9ABUL;\n s->state[7] = 0x5BE0CD19UL;\n}\n\nvoid SHA256_Update(SHA256_CTX *s, const uint8_t *in, unsigned long inlen)\n{\n unsigned long n;\n\n if (s->curlen > sizeof(s->buf)) {\n abort();\n }\n if ((s->length + inlen) < s->length) {\n abort();\n }\n while (inlen > 0) {\n if (s->curlen == 0 && inlen >= 64) {\n sha256_compress(s, (unsigned char *)in);\n s->length += 64 * 8;\n in += 64;\n inlen -= 64;\n } else {\n n = min_int(inlen, 64 - s->curlen);\n memcpy(s->buf + s->curlen, in, (size_t)n);\n s->curlen += n;\n in += n;\n inlen -= n;\n if (s->curlen == 64) {\n sha256_compress(s, s->buf);\n s->length += 8*64;\n s->curlen = 0;\n }\n }\n } }\n\n/**\n Terminate the hash to get the digest\n @param md The hash state\n @param out [out] The destination of the hash (32 bytes)\n @return CRYPT_OK if successful\n*/\nvoid SHA256_Final(uint8_t *out, SHA256_CTX *s)\n{\n int i;\n\n if (s->curlen >= sizeof(s->buf)) {\n abort();\n }\n\n\n /* increase the length of the message */\n s->length += s->curlen * 8;\n\n /* append the '1' bit */\n s->buf[s->curlen++] = (unsigned char)0x80;\n\n /* if the length is currently above 56 bytes we append zeros\n * then compress. Then we can fall back to padding zeros and length\n * encoding like normal.\n */\n if (s->curlen > 56) {\n while (s->curlen < 64) {\n s->buf[s->curlen++] = (unsigned char)0;\n }\n sha256_compress(s, s->buf);\n s->curlen = 0;\n }\n\n /* pad upto 56 bytes of zeroes */\n while (s->curlen < 56) {\n s->buf[s->curlen++] = (unsigned char)0;\n }\n\n /* store length */\n STORE64H(s->length, s->buf+56);\n sha256_compress(s, s->buf);\n\n /* copy output */\n for (i = 0; i < 8; i++) {\n STORE32H(s->state[i], out+(4*i));\n }\n#ifdef LTC_CLEAN_STACK\n zeromem(md, sizeof(hash_state));\n#endif\n}\n\nvoid SHA256(const uint8_t *buf, int buf_len, uint8_t *out)\n{\n SHA256_CTX ctx;\n\n SHA256_Init(&ctx);\n SHA256_Update(&ctx, buf, buf_len);\n SHA256_Final(out, &ctx);\n}\n\n#if 0\n/**\n Self-test the hash\n @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled\n*/\nint sha256_test(void)\n{\n #ifndef LTC_TEST\n return CRYPT_NOP;\n #else\n static const struct {\n char *msg;\n unsigned char hash[32];\n } tests[] = {\n { \"abc\",\n { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,\n 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,\n 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,\n 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }\n },\n { \"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\",\n { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,\n 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,\n 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,\n 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }\n },\n };\n\n int i;\n unsigned char tmp[32];\n hash_state md;\n\n for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {\n sha256_init(&md);\n sha256_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));\n sha256_done(&md, tmp);\n if (XMEMCMP(tmp, tests[i].hash, 32) != 0) {\n return CRYPT_FAIL_TESTVECTOR;\n }\n }\n return CRYPT_OK;\n #endif\n}\n\n#endif\n"], ["/linuxpdf/tinyemu/slirp/tcp_timer.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_timer.c\t8.1 (Berkeley) 6/10/93\n * tcp_timer.c,v 1.2 1994/08/02 07:49:10 davidg Exp\n */\n\n#include \"slirp.h\"\n\nstatic struct tcpcb *tcp_timers(register struct tcpcb *tp, int timer);\n\n/*\n * Fast timeout routine for processing delayed acks\n */\nvoid\ntcp_fasttimo(Slirp *slirp)\n{\n\tregister struct socket *so;\n\tregister struct tcpcb *tp;\n\n\tDEBUG_CALL(\"tcp_fasttimo\");\n\n\tso = slirp->tcb.so_next;\n\tif (so)\n\tfor (; so != &slirp->tcb; so = so->so_next)\n\t\tif ((tp = (struct tcpcb *)so->so_tcpcb) &&\n\t\t (tp->t_flags & TF_DELACK)) {\n\t\t\ttp->t_flags &= ~TF_DELACK;\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\t(void) tcp_output(tp);\n\t\t}\n}\n\n/*\n * Tcp protocol timeout routine called every 500 ms.\n * Updates the timers in all active tcb's and\n * causes finite state machine actions if timers expire.\n */\nvoid\ntcp_slowtimo(Slirp *slirp)\n{\n\tregister struct socket *ip, *ipnxt;\n\tregister struct tcpcb *tp;\n\tregister int i;\n\n\tDEBUG_CALL(\"tcp_slowtimo\");\n\n\t/*\n\t * Search through tcb's and update active timers.\n\t */\n\tip = slirp->tcb.so_next;\n if (ip == NULL) {\n return;\n }\n\tfor (; ip != &slirp->tcb; ip = ipnxt) {\n\t\tipnxt = ip->so_next;\n\t\ttp = sototcpcb(ip);\n if (tp == NULL) {\n continue;\n }\n\t\tfor (i = 0; i < TCPT_NTIMERS; i++) {\n\t\t\tif (tp->t_timer[i] && --tp->t_timer[i] == 0) {\n\t\t\t\ttcp_timers(tp,i);\n\t\t\t\tif (ipnxt->so_prev != ip)\n\t\t\t\t\tgoto tpgone;\n\t\t\t}\n\t\t}\n\t\ttp->t_idle++;\n\t\tif (tp->t_rtt)\n\t\t tp->t_rtt++;\ntpgone:\n\t\t;\n\t}\n\tslirp->tcp_iss += TCP_ISSINCR/PR_SLOWHZ;\t/* increment iss */\n\tslirp->tcp_now++;\t\t\t\t/* for timestamps */\n}\n\n/*\n * Cancel all timers for TCP tp.\n */\nvoid\ntcp_canceltimers(struct tcpcb *tp)\n{\n\tregister int i;\n\n\tfor (i = 0; i < TCPT_NTIMERS; i++)\n\t\ttp->t_timer[i] = 0;\n}\n\nconst int tcp_backoff[TCP_MAXRXTSHIFT + 1] =\n { 1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64 };\n\n/*\n * TCP timer processing.\n */\nstatic struct tcpcb *\ntcp_timers(register struct tcpcb *tp, int timer)\n{\n\tregister int rexmt;\n\n\tDEBUG_CALL(\"tcp_timers\");\n\n\tswitch (timer) {\n\n\t/*\n\t * 2 MSL timeout in shutdown went off. If we're closed but\n\t * still waiting for peer to close and connection has been idle\n\t * too long, or if 2MSL time is up from TIME_WAIT, delete connection\n\t * control block. Otherwise, check again in a bit.\n\t */\n\tcase TCPT_2MSL:\n\t\tif (tp->t_state != TCPS_TIME_WAIT &&\n\t\t tp->t_idle <= TCP_MAXIDLE)\n\t\t\ttp->t_timer[TCPT_2MSL] = TCPTV_KEEPINTVL;\n\t\telse\n\t\t\ttp = tcp_close(tp);\n\t\tbreak;\n\n\t/*\n\t * Retransmission timer went off. Message has not\n\t * been acked within retransmit interval. Back off\n\t * to a longer retransmit interval and retransmit one segment.\n\t */\n\tcase TCPT_REXMT:\n\n\t\t/*\n\t\t * XXXXX If a packet has timed out, then remove all the queued\n\t\t * packets for that session.\n\t\t */\n\n\t\tif (++tp->t_rxtshift > TCP_MAXRXTSHIFT) {\n\t\t\t/*\n\t\t\t * This is a hack to suit our terminal server here at the uni of canberra\n\t\t\t * since they have trouble with zeroes... It usually lets them through\n\t\t\t * unharmed, but under some conditions, it'll eat the zeros. If we\n\t\t\t * keep retransmitting it, it'll keep eating the zeroes, so we keep\n\t\t\t * retransmitting, and eventually the connection dies...\n\t\t\t * (this only happens on incoming data)\n\t\t\t *\n\t\t\t * So, if we were gonna drop the connection from too many retransmits,\n\t\t\t * don't... instead halve the t_maxseg, which might break up the NULLs and\n\t\t\t * let them through\n\t\t\t *\n\t\t\t * *sigh*\n\t\t\t */\n\n\t\t\ttp->t_maxseg >>= 1;\n\t\t\tif (tp->t_maxseg < 32) {\n\t\t\t\t/*\n\t\t\t\t * We tried our best, now the connection must die!\n\t\t\t\t */\n\t\t\t\ttp->t_rxtshift = TCP_MAXRXTSHIFT;\n\t\t\t\ttp = tcp_drop(tp, tp->t_softerror);\n\t\t\t\t/* tp->t_softerror : ETIMEDOUT); */ /* XXX */\n\t\t\t\treturn (tp); /* XXX */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set rxtshift to 6, which is still at the maximum\n\t\t\t * backoff time\n\t\t\t */\n\t\t\ttp->t_rxtshift = 6;\n\t\t}\n\t\trexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];\n\t\tTCPT_RANGESET(tp->t_rxtcur, rexmt,\n\t\t (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */\n\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t/*\n\t\t * If losing, let the lower level know and try for\n\t\t * a better route. Also, if we backed off this far,\n\t\t * our srtt estimate is probably bogus. Clobber it\n\t\t * so we'll take the next rtt measurement as our srtt;\n\t\t * move the current srtt into rttvar to keep the current\n\t\t * retransmit times until then.\n\t\t */\n\t\tif (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {\n\t\t\ttp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);\n\t\t\ttp->t_srtt = 0;\n\t\t}\n\t\ttp->snd_nxt = tp->snd_una;\n\t\t/*\n\t\t * If timing a segment in this window, stop the timer.\n\t\t */\n\t\ttp->t_rtt = 0;\n\t\t/*\n\t\t * Close the congestion window down to one segment\n\t\t * (we'll open it by one segment for each ack we get).\n\t\t * Since we probably have a window's worth of unacked\n\t\t * data accumulated, this \"slow start\" keeps us from\n\t\t * dumping all that data as back-to-back packets (which\n\t\t * might overwhelm an intermediate gateway).\n\t\t *\n\t\t * There are two phases to the opening: Initially we\n\t\t * open by one mss on each ack. This makes the window\n\t\t * size increase exponentially with time. If the\n\t\t * window is larger than the path can handle, this\n\t\t * exponential growth results in dropped packet(s)\n\t\t * almost immediately. To get more time between\n\t\t * drops but still \"push\" the network to take advantage\n\t\t * of improving conditions, we switch from exponential\n\t\t * to linear window opening at some threshold size.\n\t\t * For a threshold, we use half the current window\n\t\t * size, truncated to a multiple of the mss.\n\t\t *\n\t\t * (the minimum cwnd that will give us exponential\n\t\t * growth is 2 mss. We don't allow the threshold\n\t\t * to go below this.)\n\t\t */\n\t\t{\n\t\tu_int win = min(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg;\n\t\tif (win < 2)\n\t\t\twin = 2;\n\t\ttp->snd_cwnd = tp->t_maxseg;\n\t\ttp->snd_ssthresh = win * tp->t_maxseg;\n\t\ttp->t_dupacks = 0;\n\t\t}\n\t\t(void) tcp_output(tp);\n\t\tbreak;\n\n\t/*\n\t * Persistence timer into zero window.\n\t * Force a byte to be output, if possible.\n\t */\n\tcase TCPT_PERSIST:\n\t\ttcp_setpersist(tp);\n\t\ttp->t_force = 1;\n\t\t(void) tcp_output(tp);\n\t\ttp->t_force = 0;\n\t\tbreak;\n\n\t/*\n\t * Keep-alive timer went off; send something\n\t * or drop connection if idle for too long.\n\t */\n\tcase TCPT_KEEP:\n\t\tif (tp->t_state < TCPS_ESTABLISHED)\n\t\t\tgoto dropit;\n\n\t\tif ((SO_OPTIONS) && tp->t_state <= TCPS_CLOSE_WAIT) {\n\t\t \tif (tp->t_idle >= TCPTV_KEEP_IDLE + TCP_MAXIDLE)\n\t\t\t\tgoto dropit;\n\t\t\t/*\n\t\t\t * Send a packet designed to force a response\n\t\t\t * if the peer is up and reachable:\n\t\t\t * either an ACK if the connection is still alive,\n\t\t\t * or an RST if the peer has closed the connection\n\t\t\t * due to timeout or reboot.\n\t\t\t * Using sequence number tp->snd_una-1\n\t\t\t * causes the transmitted zero-length segment\n\t\t\t * to lie outside the receive window;\n\t\t\t * by the protocol spec, this requires the\n\t\t\t * correspondent TCP to respond.\n\t\t\t */\n\t\t\ttcp_respond(tp, &tp->t_template, (struct mbuf *)NULL,\n\t\t\t tp->rcv_nxt, tp->snd_una - 1, 0);\n\t\t\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;\n\t\t} else\n\t\t\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;\n\t\tbreak;\n\n\tdropit:\n\t\ttp = tcp_drop(tp, 0);\n\t\tbreak;\n\t}\n\n\treturn (tp);\n}\n"], ["/linuxpdf/tinyemu/slirp/sbuf.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\nstatic void sbappendsb(struct sbuf *sb, struct mbuf *m);\n\nvoid\nsbfree(struct sbuf *sb)\n{\n\tfree(sb->sb_data);\n}\n\nvoid\nsbdrop(struct sbuf *sb, int num)\n{\n\t/*\n\t * We can only drop how much we have\n\t * This should never succeed\n\t */\n\tif(num > sb->sb_cc)\n\t\tnum = sb->sb_cc;\n\tsb->sb_cc -= num;\n\tsb->sb_rptr += num;\n\tif(sb->sb_rptr >= sb->sb_data + sb->sb_datalen)\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n}\n\nvoid\nsbreserve(struct sbuf *sb, int size)\n{\n\tif (sb->sb_data) {\n\t\t/* Already alloced, realloc if necessary */\n\t\tif (sb->sb_datalen != size) {\n\t\t\tsb->sb_wptr = sb->sb_rptr = sb->sb_data = (char *)realloc(sb->sb_data, size);\n\t\t\tsb->sb_cc = 0;\n\t\t\tif (sb->sb_wptr)\n\t\t\t sb->sb_datalen = size;\n\t\t\telse\n\t\t\t sb->sb_datalen = 0;\n\t\t}\n\t} else {\n\t\tsb->sb_wptr = sb->sb_rptr = sb->sb_data = (char *)malloc(size);\n\t\tsb->sb_cc = 0;\n\t\tif (sb->sb_wptr)\n\t\t sb->sb_datalen = size;\n\t\telse\n\t\t sb->sb_datalen = 0;\n\t}\n}\n\n/*\n * Try and write() to the socket, whatever doesn't get written\n * append to the buffer... for a host with a fast net connection,\n * this prevents an unnecessary copy of the data\n * (the socket is non-blocking, so we won't hang)\n */\nvoid\nsbappend(struct socket *so, struct mbuf *m)\n{\n\tint ret = 0;\n\n\tDEBUG_CALL(\"sbappend\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"m->m_len = %d\", m->m_len);\n\n\t/* Shouldn't happen, but... e.g. foreign host closes connection */\n\tif (m->m_len <= 0) {\n\t\tm_free(m);\n\t\treturn;\n\t}\n\n\t/*\n\t * If there is urgent data, call sosendoob\n\t * if not all was sent, sowrite will take care of the rest\n\t * (The rest of this function is just an optimisation)\n\t */\n\tif (so->so_urgc) {\n\t\tsbappendsb(&so->so_rcv, m);\n\t\tm_free(m);\n\t\tsosendoob(so);\n\t\treturn;\n\t}\n\n\t/*\n\t * We only write if there's nothing in the buffer,\n\t * ottherwise it'll arrive out of order, and hence corrupt\n\t */\n\tif (!so->so_rcv.sb_cc)\n\t ret = slirp_send(so, m->m_data, m->m_len, 0);\n\n\tif (ret <= 0) {\n\t\t/*\n\t\t * Nothing was written\n\t\t * It's possible that the socket has closed, but\n\t\t * we don't need to check because if it has closed,\n\t\t * it will be detected in the normal way by soread()\n\t\t */\n\t\tsbappendsb(&so->so_rcv, m);\n\t} else if (ret != m->m_len) {\n\t\t/*\n\t\t * Something was written, but not everything..\n\t\t * sbappendsb the rest\n\t\t */\n\t\tm->m_len -= ret;\n\t\tm->m_data += ret;\n\t\tsbappendsb(&so->so_rcv, m);\n\t} /* else */\n\t/* Whatever happened, we free the mbuf */\n\tm_free(m);\n}\n\n/*\n * Copy the data from m into sb\n * The caller is responsible to make sure there's enough room\n */\nstatic void\nsbappendsb(struct sbuf *sb, struct mbuf *m)\n{\n\tint len, n, nn;\n\n\tlen = m->m_len;\n\n\tif (sb->sb_wptr < sb->sb_rptr) {\n\t\tn = sb->sb_rptr - sb->sb_wptr;\n\t\tif (n > len) n = len;\n\t\tmemcpy(sb->sb_wptr, m->m_data, n);\n\t} else {\n\t\t/* Do the right edge first */\n\t\tn = sb->sb_data + sb->sb_datalen - sb->sb_wptr;\n\t\tif (n > len) n = len;\n\t\tmemcpy(sb->sb_wptr, m->m_data, n);\n\t\tlen -= n;\n\t\tif (len) {\n\t\t\t/* Now the left edge */\n\t\t\tnn = sb->sb_rptr - sb->sb_data;\n\t\t\tif (nn > len) nn = len;\n\t\t\tmemcpy(sb->sb_data,m->m_data+n,nn);\n\t\t\tn += nn;\n\t\t}\n\t}\n\n\tsb->sb_cc += n;\n\tsb->sb_wptr += n;\n\tif (sb->sb_wptr >= sb->sb_data + sb->sb_datalen)\n\t\tsb->sb_wptr -= sb->sb_datalen;\n}\n\n/*\n * Copy data from sbuf to a normal, straight buffer\n * Don't update the sbuf rptr, this will be\n * done in sbdrop when the data is acked\n */\nvoid\nsbcopy(struct sbuf *sb, int off, int len, char *to)\n{\n\tchar *from;\n\n\tfrom = sb->sb_rptr + off;\n\tif (from >= sb->sb_data + sb->sb_datalen)\n\t\tfrom -= sb->sb_datalen;\n\n\tif (from < sb->sb_wptr) {\n\t\tif (len > sb->sb_cc) len = sb->sb_cc;\n\t\tmemcpy(to,from,len);\n\t} else {\n\t\t/* re-use off */\n\t\toff = (sb->sb_data + sb->sb_datalen) - from;\n\t\tif (off > len) off = len;\n\t\tmemcpy(to,from,off);\n\t\tlen -= off;\n\t\tif (len)\n\t\t memcpy(to+off,sb->sb_data,len);\n\t}\n}\n"], ["/linuxpdf/tinyemu/slirp/cksum.c", "/*\n * Copyright (c) 1988, 1992, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)in_cksum.c\t8.1 (Berkeley) 6/10/93\n * in_cksum.c,v 1.2 1994/08/02 07:48:16 davidg Exp\n */\n\n#include \"slirp.h\"\n\n/*\n * Checksum routine for Internet Protocol family headers (Portable Version).\n *\n * This routine is very heavily used in the network\n * code and should be modified for each CPU to be as fast as possible.\n *\n * XXX Since we will never span more than 1 mbuf, we can optimise this\n */\n\n#define ADDCARRY(x) (x > 65535 ? x -= 65535 : x)\n#define REDUCE {l_util.l = sum; sum = l_util.s[0] + l_util.s[1]; \\\n (void)ADDCARRY(sum);}\n\nint cksum(struct mbuf *m, int len)\n{\n\tregister uint16_t *w;\n\tregister int sum = 0;\n\tregister int mlen = 0;\n\tint byte_swapped = 0;\n\n\tunion {\n\t\tuint8_t c[2];\n\t\tuint16_t s;\n\t} s_util;\n\tunion {\n\t\tuint16_t s[2];\n\t\tuint32_t l;\n\t} l_util;\n\n\tif (m->m_len == 0)\n\t goto cont;\n\tw = mtod(m, uint16_t *);\n\n\tmlen = m->m_len;\n\n\tif (len < mlen)\n\t mlen = len;\n#ifdef DEBUG\n\tlen -= mlen;\n#endif\n\t/*\n\t * Force to even boundary.\n\t */\n\tif ((1 & (long) w) && (mlen > 0)) {\n\t\tREDUCE;\n\t\tsum <<= 8;\n\t\ts_util.c[0] = *(uint8_t *)w;\n\t\tw = (uint16_t *)((int8_t *)w + 1);\n\t\tmlen--;\n\t\tbyte_swapped = 1;\n\t}\n\t/*\n\t * Unroll the loop to make overhead from\n\t * branches &c small.\n\t */\n\twhile ((mlen -= 32) >= 0) {\n\t\tsum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];\n\t\tsum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];\n\t\tsum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];\n\t\tsum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];\n\t\tw += 16;\n\t}\n\tmlen += 32;\n\twhile ((mlen -= 8) >= 0) {\n\t\tsum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];\n\t\tw += 4;\n\t}\n\tmlen += 8;\n\tif (mlen == 0 && byte_swapped == 0)\n\t goto cont;\n\tREDUCE;\n\twhile ((mlen -= 2) >= 0) {\n\t\tsum += *w++;\n\t}\n\n\tif (byte_swapped) {\n\t\tREDUCE;\n\t\tsum <<= 8;\n\t\tif (mlen == -1) {\n\t\t\ts_util.c[1] = *(uint8_t *)w;\n\t\t\tsum += s_util.s;\n\t\t\tmlen = 0;\n\t\t} else\n\n\t\t mlen = -1;\n\t} else if (mlen == -1)\n\t s_util.c[0] = *(uint8_t *)w;\n\ncont:\n#ifdef DEBUG\n\tif (len) {\n\t\tDEBUG_ERROR((dfd, \"cksum: out of data\\n\"));\n\t\tDEBUG_ERROR((dfd, \" len = %d\\n\", len));\n\t}\n#endif\n\tif (mlen == -1) {\n\t\t/* The last mbuf has odd # of bytes. Follow the\n\t\t standard (the odd byte may be shifted left by 8 bits\n\t\t\t or not as determined by endian-ness of the machine) */\n\t\ts_util.c[1] = 0;\n\t\tsum += s_util.s;\n\t}\n\tREDUCE;\n\treturn (~sum & 0xffff);\n}\n"], ["/linuxpdf/tinyemu/splitimg.c", "/*\n * Disk image splitter\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n int blocksize, ret, i;\n const char *infilename, *outpath;\n FILE *f, *fo;\n char buf1[1024];\n uint8_t *buf;\n\n if ((optind + 1) >= argc) {\n printf(\"splitimg version \" CONFIG_VERSION \", Copyright (c) 2011-2016 Fabrice Bellard\\n\"\n \"usage: splitimg infile outpath [blocksize]\\n\"\n \"Create a multi-file disk image for the RISCVEMU HTTP block device\\n\"\n \"\\n\"\n \"outpath must be a directory\\n\"\n \"blocksize is the block size in KB\\n\");\n exit(1);\n }\n\n infilename = argv[optind++];\n outpath = argv[optind++];\n blocksize = 256;\n if (optind < argc)\n blocksize = strtol(argv[optind++], NULL, 0);\n\n blocksize *= 1024;\n \n buf = malloc(blocksize);\n\n f = fopen(infilename, \"rb\");\n if (!f) {\n perror(infilename);\n exit(1);\n }\n i = 0;\n for(;;) {\n ret = fread(buf, 1, blocksize, f);\n if (ret < 0) {\n perror(\"fread\");\n exit(1);\n }\n if (ret == 0)\n break;\n if (ret < blocksize) {\n printf(\"warning: last block is not full\\n\");\n memset(buf + ret, 0, blocksize - ret);\n }\n snprintf(buf1, sizeof(buf1), \"%s/blk%09u.bin\", outpath, i);\n fo = fopen(buf1, \"wb\");\n if (!fo) {\n perror(buf1);\n exit(1);\n }\n fwrite(buf, 1, blocksize, fo);\n fclose(fo);\n i++;\n }\n fclose(f);\n printf(\"%d blocks\\n\", i);\n\n snprintf(buf1, sizeof(buf1), \"%s/blk.txt\", outpath);\n fo = fopen(buf1, \"wb\");\n if (!fo) {\n perror(buf1);\n exit(1);\n }\n fprintf(fo, \"{\\n\");\n fprintf(fo, \" block_size: %d,\\n\", blocksize / 1024);\n fprintf(fo, \" n_block: %d,\\n\", i);\n fprintf(fo, \"}\\n\");\n fclose(fo);\n return 0;\n}\n"], ["/linuxpdf/tinyemu/x86_cpu.c", "/*\n * x86 CPU emulator stub\n * \n * Copyright (c) 2011-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"x86_cpu.h\"\n\nX86CPUState *x86_cpu_init(PhysMemoryMap *mem_map)\n{\n fprintf(stderr, \"x86 emulator is not supported\\n\");\n exit(1);\n}\n\nvoid x86_cpu_end(X86CPUState *s)\n{\n}\n\nvoid x86_cpu_interp(X86CPUState *s, int max_cycles1)\n{\n}\n\nvoid x86_cpu_set_irq(X86CPUState *s, BOOL set)\n{\n}\n\nvoid x86_cpu_set_reg(X86CPUState *s, int reg, uint32_t val)\n{\n}\n\nuint32_t x86_cpu_get_reg(X86CPUState *s, int reg)\n{\n return 0;\n}\n\nvoid x86_cpu_set_seg(X86CPUState *s, int seg, const X86CPUSeg *sd)\n{\n}\n\nvoid x86_cpu_set_get_hard_intno(X86CPUState *s,\n int (*get_hard_intno)(void *opaque),\n void *opaque)\n{\n}\n\nvoid x86_cpu_set_get_tsc(X86CPUState *s,\n uint64_t (*get_tsc)(void *opaque),\n void *opaque)\n{\n}\n\nvoid x86_cpu_set_port_io(X86CPUState *s, \n DeviceReadFunc *port_read, DeviceWriteFunc *port_write,\n void *opaque)\n{\n}\n\nint64_t x86_cpu_get_cycles(X86CPUState *s)\n{\n return 0;\n}\n\nBOOL x86_cpu_get_power_down(X86CPUState *s)\n{\n return FALSE;\n}\n\nvoid x86_cpu_flush_tlb_write_range_ram(X86CPUState *s,\n uint8_t *ram_ptr, size_t ram_size)\n{\n}\n"], ["/linuxpdf/tinyemu/slirp/if.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n#define ifs_init(ifm) ((ifm)->ifs_next = (ifm)->ifs_prev = (ifm))\n\nstatic void\nifs_insque(struct mbuf *ifm, struct mbuf *ifmhead)\n{\n\tifm->ifs_next = ifmhead->ifs_next;\n\tifmhead->ifs_next = ifm;\n\tifm->ifs_prev = ifmhead;\n\tifm->ifs_next->ifs_prev = ifm;\n}\n\nstatic void\nifs_remque(struct mbuf *ifm)\n{\n\tifm->ifs_prev->ifs_next = ifm->ifs_next;\n\tifm->ifs_next->ifs_prev = ifm->ifs_prev;\n}\n\nvoid\nif_init(Slirp *slirp)\n{\n slirp->if_fastq.ifq_next = slirp->if_fastq.ifq_prev = &slirp->if_fastq;\n slirp->if_batchq.ifq_next = slirp->if_batchq.ifq_prev = &slirp->if_batchq;\n slirp->next_m = &slirp->if_batchq;\n}\n\n/*\n * if_output: Queue packet into an output queue.\n * There are 2 output queue's, if_fastq and if_batchq.\n * Each output queue is a doubly linked list of double linked lists\n * of mbufs, each list belonging to one \"session\" (socket). This\n * way, we can output packets fairly by sending one packet from each\n * session, instead of all the packets from one session, then all packets\n * from the next session, etc. Packets on the if_fastq get absolute\n * priority, but if one session hogs the link, it gets \"downgraded\"\n * to the batchq until it runs out of packets, then it'll return\n * to the fastq (eg. if the user does an ls -alR in a telnet session,\n * it'll temporarily get downgraded to the batchq)\n */\nvoid\nif_output(struct socket *so, struct mbuf *ifm)\n{\n\tSlirp *slirp = ifm->slirp;\n\tstruct mbuf *ifq;\n\tint on_fastq = 1;\n\n\tDEBUG_CALL(\"if_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"ifm = %lx\", (long)ifm);\n\n\t/*\n\t * First remove the mbuf from m_usedlist,\n\t * since we're gonna use m_next and m_prev ourselves\n\t * XXX Shouldn't need this, gotta change dtom() etc.\n\t */\n\tif (ifm->m_flags & M_USEDLIST) {\n\t\tremque(ifm);\n\t\tifm->m_flags &= ~M_USEDLIST;\n\t}\n\n\t/*\n\t * See if there's already a batchq list for this session.\n\t * This can include an interactive session, which should go on fastq,\n\t * but gets too greedy... hence it'll be downgraded from fastq to batchq.\n\t * We mustn't put this packet back on the fastq (or we'll send it out of order)\n\t * XXX add cache here?\n\t */\n\tfor (ifq = slirp->if_batchq.ifq_prev; ifq != &slirp->if_batchq;\n\t ifq = ifq->ifq_prev) {\n\t\tif (so == ifq->ifq_so) {\n\t\t\t/* A match! */\n\t\t\tifm->ifq_so = so;\n\t\t\tifs_insque(ifm, ifq->ifs_prev);\n\t\t\tgoto diddit;\n\t\t}\n\t}\n\n\t/* No match, check which queue to put it on */\n\tif (so && (so->so_iptos & IPTOS_LOWDELAY)) {\n\t\tifq = slirp->if_fastq.ifq_prev;\n\t\ton_fastq = 1;\n\t\t/*\n\t\t * Check if this packet is a part of the last\n\t\t * packet's session\n\t\t */\n\t\tif (ifq->ifq_so == so) {\n\t\t\tifm->ifq_so = so;\n\t\t\tifs_insque(ifm, ifq->ifs_prev);\n\t\t\tgoto diddit;\n\t\t}\n\t} else\n\t\tifq = slirp->if_batchq.ifq_prev;\n\n\t/* Create a new doubly linked list for this session */\n\tifm->ifq_so = so;\n\tifs_init(ifm);\n\tinsque(ifm, ifq);\n\ndiddit:\n\tslirp->if_queued++;\n\n\tif (so) {\n\t\t/* Update *_queued */\n\t\tso->so_queued++;\n\t\tso->so_nqueued++;\n\t\t/*\n\t\t * Check if the interactive session should be downgraded to\n\t\t * the batchq. A session is downgraded if it has queued 6\n\t\t * packets without pausing, and at least 3 of those packets\n\t\t * have been sent over the link\n\t\t * (XXX These are arbitrary numbers, probably not optimal..)\n\t\t */\n\t\tif (on_fastq && ((so->so_nqueued >= 6) &&\n\t\t\t\t (so->so_nqueued - so->so_queued) >= 3)) {\n\n\t\t\t/* Remove from current queue... */\n\t\t\tremque(ifm->ifs_next);\n\n\t\t\t/* ...And insert in the new. That'll teach ya! */\n\t\t\tinsque(ifm->ifs_next, &slirp->if_batchq);\n\t\t}\n\t}\n\n#ifndef FULL_BOLT\n\t/*\n\t * This prevents us from malloc()ing too many mbufs\n\t */\n\tif_start(ifm->slirp);\n#endif\n}\n\n/*\n * Send a packet\n * We choose a packet based on it's position in the output queues;\n * If there are packets on the fastq, they are sent FIFO, before\n * everything else. Otherwise we choose the first packet from the\n * batchq and send it. the next packet chosen will be from the session\n * after this one, then the session after that one, and so on.. So,\n * for example, if there are 3 ftp session's fighting for bandwidth,\n * one packet will be sent from the first session, then one packet\n * from the second session, then one packet from the third, then back\n * to the first, etc. etc.\n */\nvoid\nif_start(Slirp *slirp)\n{\n\tstruct mbuf *ifm, *ifqt;\n\n\tDEBUG_CALL(\"if_start\");\n\n\tif (slirp->if_queued == 0)\n\t return; /* Nothing to do */\n\n again:\n /* check if we can really output */\n if (!slirp_can_output(slirp->opaque))\n return;\n\n\t/*\n\t * See which queue to get next packet from\n\t * If there's something in the fastq, select it immediately\n\t */\n\tif (slirp->if_fastq.ifq_next != &slirp->if_fastq) {\n\t\tifm = slirp->if_fastq.ifq_next;\n\t} else {\n\t\t/* Nothing on fastq, see if next_m is valid */\n\t\tif (slirp->next_m != &slirp->if_batchq)\n\t\t ifm = slirp->next_m;\n\t\telse\n\t\t ifm = slirp->if_batchq.ifq_next;\n\n\t\t/* Set which packet to send on next iteration */\n\t\tslirp->next_m = ifm->ifq_next;\n\t}\n\t/* Remove it from the queue */\n\tifqt = ifm->ifq_prev;\n\tremque(ifm);\n\tslirp->if_queued--;\n\n\t/* If there are more packets for this session, re-queue them */\n\tif (ifm->ifs_next != /* ifm->ifs_prev != */ ifm) {\n\t\tinsque(ifm->ifs_next, ifqt);\n\t\tifs_remque(ifm);\n\t}\n\n\t/* Update so_queued */\n\tif (ifm->ifq_so) {\n\t\tif (--ifm->ifq_so->so_queued == 0)\n\t\t /* If there's no more queued, reset nqueued */\n\t\t ifm->ifq_so->so_nqueued = 0;\n\t}\n\n\t/* Encapsulate the packet for sending */\n if_encap(slirp, (uint8_t *)ifm->m_data, ifm->m_len);\n\n m_free(ifm);\n\n\tif (slirp->if_queued)\n\t goto again;\n}\n"], ["/linuxpdf/tinyemu/slirp/mbuf.c", "/*\n * Copyright (c) 1995 Danny Gasparovski\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n/*\n * mbuf's in SLiRP are much simpler than the real mbufs in\n * FreeBSD. They are fixed size, determined by the MTU,\n * so that one whole packet can fit. Mbuf's cannot be\n * chained together. If there's more data than the mbuf\n * could hold, an external malloced buffer is pointed to\n * by m_ext (and the data pointers) and M_EXT is set in\n * the flags\n */\n\n#include \"slirp.h\"\n\n#define MBUF_THRESH 30\n\n/*\n * Find a nice value for msize\n * XXX if_maxlinkhdr already in mtu\n */\n#define SLIRP_MSIZE (IF_MTU + IF_MAXLINKHDR + offsetof(struct mbuf, m_dat) + 6)\n\nvoid\nm_init(Slirp *slirp)\n{\n slirp->m_freelist.m_next = slirp->m_freelist.m_prev = &slirp->m_freelist;\n slirp->m_usedlist.m_next = slirp->m_usedlist.m_prev = &slirp->m_usedlist;\n}\n\n/*\n * Get an mbuf from the free list, if there are none\n * malloc one\n *\n * Because fragmentation can occur if we alloc new mbufs and\n * free old mbufs, we mark all mbufs above mbuf_thresh as M_DOFREE,\n * which tells m_free to actually free() it\n */\nstruct mbuf *\nm_get(Slirp *slirp)\n{\n\tregister struct mbuf *m;\n\tint flags = 0;\n\n\tDEBUG_CALL(\"m_get\");\n\n\tif (slirp->m_freelist.m_next == &slirp->m_freelist) {\n\t\tm = (struct mbuf *)malloc(SLIRP_MSIZE);\n\t\tif (m == NULL) goto end_error;\n\t\tslirp->mbuf_alloced++;\n\t\tif (slirp->mbuf_alloced > MBUF_THRESH)\n\t\t\tflags = M_DOFREE;\n\t\tm->slirp = slirp;\n\t} else {\n\t\tm = slirp->m_freelist.m_next;\n\t\tremque(m);\n\t}\n\n\t/* Insert it in the used list */\n\tinsque(m,&slirp->m_usedlist);\n\tm->m_flags = (flags | M_USEDLIST);\n\n\t/* Initialise it */\n\tm->m_size = SLIRP_MSIZE - offsetof(struct mbuf, m_dat);\n\tm->m_data = m->m_dat;\n\tm->m_len = 0;\n m->m_nextpkt = NULL;\n m->m_prevpkt = NULL;\nend_error:\n\tDEBUG_ARG(\"m = %lx\", (long )m);\n\treturn m;\n}\n\nvoid\nm_free(struct mbuf *m)\n{\n\n DEBUG_CALL(\"m_free\");\n DEBUG_ARG(\"m = %lx\", (long )m);\n\n if(m) {\n\t/* Remove from m_usedlist */\n\tif (m->m_flags & M_USEDLIST)\n\t remque(m);\n\n\t/* If it's M_EXT, free() it */\n\tif (m->m_flags & M_EXT)\n\t free(m->m_ext);\n\n\t/*\n\t * Either free() it or put it on the free list\n\t */\n\tif (m->m_flags & M_DOFREE) {\n\t\tm->slirp->mbuf_alloced--;\n\t\tfree(m);\n\t} else if ((m->m_flags & M_FREELIST) == 0) {\n\t\tinsque(m,&m->slirp->m_freelist);\n\t\tm->m_flags = M_FREELIST; /* Clobber other flags */\n\t}\n } /* if(m) */\n}\n\n/*\n * Copy data from one mbuf to the end of\n * the other.. if result is too big for one mbuf, malloc()\n * an M_EXT data segment\n */\nvoid\nm_cat(struct mbuf *m, struct mbuf *n)\n{\n\t/*\n\t * If there's no room, realloc\n\t */\n\tif (M_FREEROOM(m) < n->m_len)\n\t\tm_inc(m,m->m_size+MINCSIZE);\n\n\tmemcpy(m->m_data+m->m_len, n->m_data, n->m_len);\n\tm->m_len += n->m_len;\n\n\tm_free(n);\n}\n\n\n/* make m size bytes large */\nvoid\nm_inc(struct mbuf *m, int size)\n{\n\tint datasize;\n\n\t/* some compiles throw up on gotos. This one we can fake. */\n if(m->m_size>size) return;\n\n if (m->m_flags & M_EXT) {\n\t datasize = m->m_data - m->m_ext;\n\t m->m_ext = (char *)realloc(m->m_ext,size);\n\t m->m_data = m->m_ext + datasize;\n } else {\n\t char *dat;\n\t datasize = m->m_data - m->m_dat;\n\t dat = (char *)malloc(size);\n\t memcpy(dat, m->m_dat, m->m_size);\n\n\t m->m_ext = dat;\n\t m->m_data = m->m_ext + datasize;\n\t m->m_flags |= M_EXT;\n }\n\n m->m_size = size;\n\n}\n\n\n\nvoid\nm_adj(struct mbuf *m, int len)\n{\n\tif (m == NULL)\n\t\treturn;\n\tif (len >= 0) {\n\t\t/* Trim from head */\n\t\tm->m_data += len;\n\t\tm->m_len -= len;\n\t} else {\n\t\t/* Trim from tail */\n\t\tlen = -len;\n\t\tm->m_len -= len;\n\t}\n}\n\n\n/*\n * Copy len bytes from m, starting off bytes into n\n */\nint\nm_copy(struct mbuf *n, struct mbuf *m, int off, int len)\n{\n\tif (len > M_FREEROOM(n))\n\t\treturn -1;\n\n\tmemcpy((n->m_data + n->m_len), (m->m_data + off), len);\n\tn->m_len += len;\n\treturn 0;\n}\n\n\n/*\n * Given a pointer into an mbuf, return the mbuf\n * XXX This is a kludge, I should eliminate the need for it\n * Fortunately, it's not used often\n */\nstruct mbuf *\ndtom(Slirp *slirp, void *dat)\n{\n\tstruct mbuf *m;\n\n\tDEBUG_CALL(\"dtom\");\n\tDEBUG_ARG(\"dat = %lx\", (long )dat);\n\n\t/* bug corrected for M_EXT buffers */\n\tfor (m = slirp->m_usedlist.m_next; m != &slirp->m_usedlist;\n\t m = m->m_next) {\n\t if (m->m_flags & M_EXT) {\n\t if( (char *)dat>=m->m_ext && (char *)dat<(m->m_ext + m->m_size) )\n\t return m;\n\t } else {\n\t if( (char *)dat >= m->m_dat && (char *)dat<(m->m_dat + m->m_size) )\n\t return m;\n\t }\n\t}\n\n\tDEBUG_ERROR((dfd, \"dtom failed\"));\n\n\treturn (struct mbuf *)0;\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_output.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_output.c\t8.3 (Berkeley) 1/21/94\n * ip_output.c,v 1.9 1994/11/16 10:17:10 jkh Exp\n */\n\n/*\n * Changes and additions relating to SLiRP are\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n/* Number of packets queued before we start sending\n * (to prevent allocing too many mbufs) */\n#define IF_THRESH 10\n\n/*\n * IP output. The packet in mbuf chain m contains a skeletal IP\n * header (with len, off, ttl, proto, tos, src, dst).\n * The mbuf chain containing the packet will be freed.\n * The mbuf opt, if present, will not be freed.\n */\nint\nip_output(struct socket *so, struct mbuf *m0)\n{\n\tSlirp *slirp = m0->slirp;\n\tregister struct ip *ip;\n\tregister struct mbuf *m = m0;\n\tregister int hlen = sizeof(struct ip );\n\tint len, off, error = 0;\n\n\tDEBUG_CALL(\"ip_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m0 = %lx\", (long)m0);\n\n\tip = mtod(m, struct ip *);\n\t/*\n\t * Fill in IP header.\n\t */\n\tip->ip_v = IPVERSION;\n\tip->ip_off &= IP_DF;\n\tip->ip_id = htons(slirp->ip_id++);\n\tip->ip_hl = hlen >> 2;\n\n\t/*\n\t * If small enough for interface, can just send directly.\n\t */\n\tif ((uint16_t)ip->ip_len <= IF_MTU) {\n\t\tip->ip_len = htons((uint16_t)ip->ip_len);\n\t\tip->ip_off = htons((uint16_t)ip->ip_off);\n\t\tip->ip_sum = 0;\n\t\tip->ip_sum = cksum(m, hlen);\n\n\t\tif_output(so, m);\n\t\tgoto done;\n\t}\n\n\t/*\n\t * Too large for interface; fragment if possible.\n\t * Must be able to put at least 8 bytes per fragment.\n\t */\n\tif (ip->ip_off & IP_DF) {\n\t\terror = -1;\n\t\tgoto bad;\n\t}\n\n\tlen = (IF_MTU - hlen) &~ 7; /* ip databytes per packet */\n\tif (len < 8) {\n\t\terror = -1;\n\t\tgoto bad;\n\t}\n\n {\n\tint mhlen, firstlen = len;\n\tstruct mbuf **mnext = &m->m_nextpkt;\n\n\t/*\n\t * Loop through length of segment after first fragment,\n\t * make new header and copy data of each part and link onto chain.\n\t */\n\tm0 = m;\n\tmhlen = sizeof (struct ip);\n\tfor (off = hlen + len; off < (uint16_t)ip->ip_len; off += len) {\n\t register struct ip *mhip;\n\t m = m_get(slirp);\n if (m == NULL) {\n\t error = -1;\n\t goto sendorfree;\n\t }\n\t m->m_data += IF_MAXLINKHDR;\n\t mhip = mtod(m, struct ip *);\n\t *mhip = *ip;\n\n\t m->m_len = mhlen;\n\t mhip->ip_off = ((off - hlen) >> 3) + (ip->ip_off & ~IP_MF);\n\t if (ip->ip_off & IP_MF)\n\t mhip->ip_off |= IP_MF;\n\t if (off + len >= (uint16_t)ip->ip_len)\n\t len = (uint16_t)ip->ip_len - off;\n\t else\n\t mhip->ip_off |= IP_MF;\n\t mhip->ip_len = htons((uint16_t)(len + mhlen));\n\n\t if (m_copy(m, m0, off, len) < 0) {\n\t error = -1;\n\t goto sendorfree;\n\t }\n\n\t mhip->ip_off = htons((uint16_t)mhip->ip_off);\n\t mhip->ip_sum = 0;\n\t mhip->ip_sum = cksum(m, mhlen);\n\t *mnext = m;\n\t mnext = &m->m_nextpkt;\n\t}\n\t/*\n\t * Update first fragment by trimming what's been copied out\n\t * and updating header, then send each fragment (in order).\n\t */\n\tm = m0;\n\tm_adj(m, hlen + firstlen - (uint16_t)ip->ip_len);\n\tip->ip_len = htons((uint16_t)m->m_len);\n\tip->ip_off = htons((uint16_t)(ip->ip_off | IP_MF));\n\tip->ip_sum = 0;\n\tip->ip_sum = cksum(m, hlen);\nsendorfree:\n\tfor (m = m0; m; m = m0) {\n\t\tm0 = m->m_nextpkt;\n m->m_nextpkt = NULL;\n\t\tif (error == 0)\n\t\t\tif_output(so, m);\n\t\telse\n\t\t\tm_freem(m);\n\t}\n }\n\ndone:\n\treturn (error);\n\nbad:\n\tm_freem(m0);\n\tgoto done;\n}\n"], ["/linuxpdf/tinyemu/aes.c", "/**\n *\n * aes.c - integrated in QEMU by Fabrice Bellard from the OpenSSL project.\n */\n/*\n * rijndael-alg-fst.c\n *\n * @version 3.0 (December 2000)\n *\n * Optimised ANSI C code for the Rijndael cipher (now AES)\n *\n * @author Vincent Rijmen \n * @author Antoon Bosselaers \n * @author Paulo Barreto \n *\n * This code is hereby placed in the public domain.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS\n * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n#include \n#include \n#include \"aes.h\"\n\n#ifndef NDEBUG\n#define NDEBUG\n#endif\n\n#include \n\ntypedef uint32_t u32;\ntypedef uint16_t u16;\ntypedef uint8_t u8;\n\n#define MAXKC (256/32)\n#define MAXKB (256/8)\n#define MAXNR 14\n\n/* This controls loop-unrolling in aes_core.c */\n#undef FULL_UNROLL\n# define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3]))\n# define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); }\n\n/*\nTe0[x] = S [x].[02, 01, 01, 03];\nTe1[x] = S [x].[03, 02, 01, 01];\nTe2[x] = S [x].[01, 03, 02, 01];\nTe3[x] = S [x].[01, 01, 03, 02];\nTe4[x] = S [x].[01, 01, 01, 01];\n\nTd0[x] = Si[x].[0e, 09, 0d, 0b];\nTd1[x] = Si[x].[0b, 0e, 09, 0d];\nTd2[x] = Si[x].[0d, 0b, 0e, 09];\nTd3[x] = Si[x].[09, 0d, 0b, 0e];\nTd4[x] = Si[x].[01, 01, 01, 01];\n*/\n\nstatic const u32 Te0[256] = {\n 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU,\n 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U,\n 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU,\n 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU,\n 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U,\n 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU,\n 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU,\n 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU,\n 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU,\n 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU,\n 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U,\n 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU,\n 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU,\n 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U,\n 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU,\n 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU,\n 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU,\n 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU,\n 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU,\n 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U,\n 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU,\n 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU,\n 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU,\n 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU,\n 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U,\n 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U,\n 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U,\n 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U,\n 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU,\n 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U,\n 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U,\n 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU,\n 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU,\n 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U,\n 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U,\n 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U,\n 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU,\n 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U,\n 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU,\n 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U,\n 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU,\n 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U,\n 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U,\n 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU,\n 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U,\n 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U,\n 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U,\n 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U,\n 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U,\n 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U,\n 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U,\n 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U,\n 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU,\n 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U,\n 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U,\n 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U,\n 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U,\n 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U,\n 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U,\n 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU,\n 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U,\n 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U,\n 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U,\n 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU,\n};\nstatic const u32 Te1[256] = {\n 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU,\n 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U,\n 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU,\n 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U,\n 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU,\n 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U,\n 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU,\n 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U,\n 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U,\n 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU,\n 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U,\n 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U,\n 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U,\n 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU,\n 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U,\n 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U,\n 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU,\n 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U,\n 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U,\n 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U,\n 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU,\n 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU,\n 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U,\n 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU,\n 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU,\n 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U,\n 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU,\n 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U,\n 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU,\n 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U,\n 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U,\n 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U,\n 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU,\n 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U,\n 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU,\n 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U,\n 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU,\n 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U,\n 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U,\n 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU,\n 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU,\n 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU,\n 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U,\n 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U,\n 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU,\n 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U,\n 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU,\n 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U,\n 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU,\n 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U,\n 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU,\n 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU,\n 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U,\n 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU,\n 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U,\n 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU,\n 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U,\n 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U,\n 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U,\n 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU,\n 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU,\n 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U,\n 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU,\n 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U,\n};\nstatic const u32 Te2[256] = {\n 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU,\n 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U,\n 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU,\n 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U,\n 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU,\n 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U,\n 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU,\n 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U,\n 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U,\n 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU,\n 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U,\n 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U,\n 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U,\n 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU,\n 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U,\n 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U,\n 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU,\n 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U,\n 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U,\n 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U,\n 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU,\n 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU,\n 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U,\n 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU,\n 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU,\n 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U,\n 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU,\n 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U,\n 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU,\n 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U,\n 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U,\n 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U,\n 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU,\n 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U,\n 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU,\n 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U,\n 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU,\n 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U,\n 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U,\n 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU,\n 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU,\n 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU,\n 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U,\n 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U,\n 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU,\n 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U,\n 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU,\n 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U,\n 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU,\n 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U,\n 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU,\n 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU,\n 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U,\n 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU,\n 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U,\n 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU,\n 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U,\n 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U,\n 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U,\n 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU,\n 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU,\n 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U,\n 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU,\n 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U,\n};\nstatic const u32 Te3[256] = {\n\n 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U,\n 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U,\n 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U,\n 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU,\n 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU,\n 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU,\n 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U,\n 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU,\n 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU,\n 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U,\n 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U,\n 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU,\n 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU,\n 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU,\n 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU,\n 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU,\n 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U,\n 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU,\n 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU,\n 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U,\n 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U,\n 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U,\n 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U,\n 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U,\n 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU,\n 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U,\n 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU,\n 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU,\n 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U,\n 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U,\n 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U,\n 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU,\n 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U,\n 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU,\n 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU,\n 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U,\n 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U,\n 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU,\n 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U,\n 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU,\n 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U,\n 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U,\n 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U,\n 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U,\n 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU,\n 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U,\n 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU,\n 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U,\n 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU,\n 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U,\n 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU,\n 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU,\n 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU,\n 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU,\n 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U,\n 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U,\n 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U,\n 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U,\n 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U,\n 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U,\n 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU,\n 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U,\n 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU,\n 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU,\n};\nstatic const u32 Te4[256] = {\n 0x63636363U, 0x7c7c7c7cU, 0x77777777U, 0x7b7b7b7bU,\n 0xf2f2f2f2U, 0x6b6b6b6bU, 0x6f6f6f6fU, 0xc5c5c5c5U,\n 0x30303030U, 0x01010101U, 0x67676767U, 0x2b2b2b2bU,\n 0xfefefefeU, 0xd7d7d7d7U, 0xababababU, 0x76767676U,\n 0xcacacacaU, 0x82828282U, 0xc9c9c9c9U, 0x7d7d7d7dU,\n 0xfafafafaU, 0x59595959U, 0x47474747U, 0xf0f0f0f0U,\n 0xadadadadU, 0xd4d4d4d4U, 0xa2a2a2a2U, 0xafafafafU,\n 0x9c9c9c9cU, 0xa4a4a4a4U, 0x72727272U, 0xc0c0c0c0U,\n 0xb7b7b7b7U, 0xfdfdfdfdU, 0x93939393U, 0x26262626U,\n 0x36363636U, 0x3f3f3f3fU, 0xf7f7f7f7U, 0xccccccccU,\n 0x34343434U, 0xa5a5a5a5U, 0xe5e5e5e5U, 0xf1f1f1f1U,\n 0x71717171U, 0xd8d8d8d8U, 0x31313131U, 0x15151515U,\n 0x04040404U, 0xc7c7c7c7U, 0x23232323U, 0xc3c3c3c3U,\n 0x18181818U, 0x96969696U, 0x05050505U, 0x9a9a9a9aU,\n 0x07070707U, 0x12121212U, 0x80808080U, 0xe2e2e2e2U,\n 0xebebebebU, 0x27272727U, 0xb2b2b2b2U, 0x75757575U,\n 0x09090909U, 0x83838383U, 0x2c2c2c2cU, 0x1a1a1a1aU,\n 0x1b1b1b1bU, 0x6e6e6e6eU, 0x5a5a5a5aU, 0xa0a0a0a0U,\n 0x52525252U, 0x3b3b3b3bU, 0xd6d6d6d6U, 0xb3b3b3b3U,\n 0x29292929U, 0xe3e3e3e3U, 0x2f2f2f2fU, 0x84848484U,\n 0x53535353U, 0xd1d1d1d1U, 0x00000000U, 0xededededU,\n 0x20202020U, 0xfcfcfcfcU, 0xb1b1b1b1U, 0x5b5b5b5bU,\n 0x6a6a6a6aU, 0xcbcbcbcbU, 0xbebebebeU, 0x39393939U,\n 0x4a4a4a4aU, 0x4c4c4c4cU, 0x58585858U, 0xcfcfcfcfU,\n 0xd0d0d0d0U, 0xefefefefU, 0xaaaaaaaaU, 0xfbfbfbfbU,\n 0x43434343U, 0x4d4d4d4dU, 0x33333333U, 0x85858585U,\n 0x45454545U, 0xf9f9f9f9U, 0x02020202U, 0x7f7f7f7fU,\n 0x50505050U, 0x3c3c3c3cU, 0x9f9f9f9fU, 0xa8a8a8a8U,\n 0x51515151U, 0xa3a3a3a3U, 0x40404040U, 0x8f8f8f8fU,\n 0x92929292U, 0x9d9d9d9dU, 0x38383838U, 0xf5f5f5f5U,\n 0xbcbcbcbcU, 0xb6b6b6b6U, 0xdadadadaU, 0x21212121U,\n 0x10101010U, 0xffffffffU, 0xf3f3f3f3U, 0xd2d2d2d2U,\n 0xcdcdcdcdU, 0x0c0c0c0cU, 0x13131313U, 0xececececU,\n 0x5f5f5f5fU, 0x97979797U, 0x44444444U, 0x17171717U,\n 0xc4c4c4c4U, 0xa7a7a7a7U, 0x7e7e7e7eU, 0x3d3d3d3dU,\n 0x64646464U, 0x5d5d5d5dU, 0x19191919U, 0x73737373U,\n 0x60606060U, 0x81818181U, 0x4f4f4f4fU, 0xdcdcdcdcU,\n 0x22222222U, 0x2a2a2a2aU, 0x90909090U, 0x88888888U,\n 0x46464646U, 0xeeeeeeeeU, 0xb8b8b8b8U, 0x14141414U,\n 0xdedededeU, 0x5e5e5e5eU, 0x0b0b0b0bU, 0xdbdbdbdbU,\n 0xe0e0e0e0U, 0x32323232U, 0x3a3a3a3aU, 0x0a0a0a0aU,\n 0x49494949U, 0x06060606U, 0x24242424U, 0x5c5c5c5cU,\n 0xc2c2c2c2U, 0xd3d3d3d3U, 0xacacacacU, 0x62626262U,\n 0x91919191U, 0x95959595U, 0xe4e4e4e4U, 0x79797979U,\n 0xe7e7e7e7U, 0xc8c8c8c8U, 0x37373737U, 0x6d6d6d6dU,\n 0x8d8d8d8dU, 0xd5d5d5d5U, 0x4e4e4e4eU, 0xa9a9a9a9U,\n 0x6c6c6c6cU, 0x56565656U, 0xf4f4f4f4U, 0xeaeaeaeaU,\n 0x65656565U, 0x7a7a7a7aU, 0xaeaeaeaeU, 0x08080808U,\n 0xbabababaU, 0x78787878U, 0x25252525U, 0x2e2e2e2eU,\n 0x1c1c1c1cU, 0xa6a6a6a6U, 0xb4b4b4b4U, 0xc6c6c6c6U,\n 0xe8e8e8e8U, 0xddddddddU, 0x74747474U, 0x1f1f1f1fU,\n 0x4b4b4b4bU, 0xbdbdbdbdU, 0x8b8b8b8bU, 0x8a8a8a8aU,\n 0x70707070U, 0x3e3e3e3eU, 0xb5b5b5b5U, 0x66666666U,\n 0x48484848U, 0x03030303U, 0xf6f6f6f6U, 0x0e0e0e0eU,\n 0x61616161U, 0x35353535U, 0x57575757U, 0xb9b9b9b9U,\n 0x86868686U, 0xc1c1c1c1U, 0x1d1d1d1dU, 0x9e9e9e9eU,\n 0xe1e1e1e1U, 0xf8f8f8f8U, 0x98989898U, 0x11111111U,\n 0x69696969U, 0xd9d9d9d9U, 0x8e8e8e8eU, 0x94949494U,\n 0x9b9b9b9bU, 0x1e1e1e1eU, 0x87878787U, 0xe9e9e9e9U,\n 0xcecececeU, 0x55555555U, 0x28282828U, 0xdfdfdfdfU,\n 0x8c8c8c8cU, 0xa1a1a1a1U, 0x89898989U, 0x0d0d0d0dU,\n 0xbfbfbfbfU, 0xe6e6e6e6U, 0x42424242U, 0x68686868U,\n 0x41414141U, 0x99999999U, 0x2d2d2d2dU, 0x0f0f0f0fU,\n 0xb0b0b0b0U, 0x54545454U, 0xbbbbbbbbU, 0x16161616U,\n};\nstatic const u32 Td0[256] = {\n 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U,\n 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U,\n 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U,\n 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU,\n 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U,\n 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U,\n 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU,\n 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U,\n 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU,\n 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U,\n 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U,\n 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U,\n 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U,\n 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU,\n 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U,\n 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU,\n 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U,\n 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU,\n 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U,\n 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U,\n 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U,\n 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU,\n 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U,\n 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU,\n 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U,\n 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU,\n 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U,\n 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU,\n 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU,\n 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U,\n 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU,\n 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U,\n 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU,\n 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U,\n 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U,\n 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U,\n 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU,\n 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U,\n 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U,\n 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU,\n 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U,\n 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U,\n 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U,\n 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U,\n 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U,\n 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU,\n 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U,\n 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U,\n 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U,\n 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U,\n 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U,\n 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU,\n 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU,\n 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU,\n 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU,\n 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U,\n 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U,\n 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU,\n 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU,\n 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U,\n 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU,\n 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U,\n 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U,\n 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U,\n};\nstatic const u32 Td1[256] = {\n 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU,\n 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U,\n 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU,\n 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U,\n 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U,\n 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U,\n 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U,\n 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U,\n 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U,\n 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU,\n 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU,\n 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU,\n 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U,\n 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU,\n 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U,\n 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U,\n 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U,\n 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU,\n 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU,\n 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U,\n 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU,\n 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U,\n 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU,\n 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU,\n 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U,\n 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U,\n 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U,\n 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU,\n 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U,\n 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU,\n 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U,\n 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U,\n 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U,\n 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU,\n 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U,\n 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U,\n 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U,\n 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U,\n 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U,\n 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U,\n 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU,\n 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU,\n 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U,\n 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU,\n 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U,\n 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU,\n 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU,\n 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U,\n 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU,\n 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U,\n 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U,\n 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U,\n 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U,\n 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U,\n 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U,\n 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U,\n 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU,\n 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U,\n 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U,\n 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU,\n 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U,\n 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U,\n 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U,\n 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U,\n};\nstatic const u32 Td2[256] = {\n 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U,\n 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U,\n 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U,\n 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U,\n 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU,\n 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U,\n 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U,\n 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U,\n 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U,\n 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU,\n 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U,\n 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U,\n 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU,\n 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U,\n 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U,\n 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U,\n 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U,\n 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U,\n 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U,\n 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU,\n\n 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U,\n 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U,\n 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U,\n 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U,\n 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U,\n 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU,\n 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU,\n 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U,\n 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU,\n 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U,\n 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU,\n 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU,\n 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU,\n 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU,\n 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U,\n 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U,\n 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U,\n 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U,\n 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U,\n 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U,\n 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U,\n 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU,\n 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU,\n 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U,\n 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U,\n 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU,\n 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU,\n 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U,\n 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U,\n 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U,\n 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U,\n 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U,\n 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U,\n 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U,\n 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU,\n 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U,\n 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U,\n 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U,\n 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U,\n 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U,\n 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U,\n 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU,\n 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U,\n 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U,\n};\nstatic const u32 Td3[256] = {\n 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU,\n 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU,\n 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U,\n 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U,\n 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU,\n 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU,\n 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U,\n 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU,\n 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U,\n 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU,\n 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U,\n 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U,\n 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U,\n 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U,\n 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U,\n 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU,\n 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU,\n 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U,\n 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U,\n 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU,\n 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU,\n 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U,\n 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U,\n 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U,\n 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U,\n 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU,\n 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U,\n 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U,\n 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU,\n 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU,\n 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U,\n 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U,\n 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U,\n 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU,\n 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U,\n 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U,\n 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U,\n 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U,\n 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U,\n 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U,\n 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U,\n 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU,\n 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U,\n 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U,\n 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU,\n 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU,\n 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U,\n 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU,\n 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U,\n 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U,\n 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U,\n 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U,\n 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U,\n 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U,\n 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU,\n 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU,\n 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU,\n 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU,\n 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U,\n 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U,\n 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U,\n 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU,\n 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U,\n 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U,\n};\nstatic const u32 Td4[256] = {\n 0x52525252U, 0x09090909U, 0x6a6a6a6aU, 0xd5d5d5d5U,\n 0x30303030U, 0x36363636U, 0xa5a5a5a5U, 0x38383838U,\n 0xbfbfbfbfU, 0x40404040U, 0xa3a3a3a3U, 0x9e9e9e9eU,\n 0x81818181U, 0xf3f3f3f3U, 0xd7d7d7d7U, 0xfbfbfbfbU,\n 0x7c7c7c7cU, 0xe3e3e3e3U, 0x39393939U, 0x82828282U,\n 0x9b9b9b9bU, 0x2f2f2f2fU, 0xffffffffU, 0x87878787U,\n 0x34343434U, 0x8e8e8e8eU, 0x43434343U, 0x44444444U,\n 0xc4c4c4c4U, 0xdedededeU, 0xe9e9e9e9U, 0xcbcbcbcbU,\n 0x54545454U, 0x7b7b7b7bU, 0x94949494U, 0x32323232U,\n 0xa6a6a6a6U, 0xc2c2c2c2U, 0x23232323U, 0x3d3d3d3dU,\n 0xeeeeeeeeU, 0x4c4c4c4cU, 0x95959595U, 0x0b0b0b0bU,\n 0x42424242U, 0xfafafafaU, 0xc3c3c3c3U, 0x4e4e4e4eU,\n 0x08080808U, 0x2e2e2e2eU, 0xa1a1a1a1U, 0x66666666U,\n 0x28282828U, 0xd9d9d9d9U, 0x24242424U, 0xb2b2b2b2U,\n 0x76767676U, 0x5b5b5b5bU, 0xa2a2a2a2U, 0x49494949U,\n 0x6d6d6d6dU, 0x8b8b8b8bU, 0xd1d1d1d1U, 0x25252525U,\n 0x72727272U, 0xf8f8f8f8U, 0xf6f6f6f6U, 0x64646464U,\n 0x86868686U, 0x68686868U, 0x98989898U, 0x16161616U,\n 0xd4d4d4d4U, 0xa4a4a4a4U, 0x5c5c5c5cU, 0xccccccccU,\n 0x5d5d5d5dU, 0x65656565U, 0xb6b6b6b6U, 0x92929292U,\n 0x6c6c6c6cU, 0x70707070U, 0x48484848U, 0x50505050U,\n 0xfdfdfdfdU, 0xededededU, 0xb9b9b9b9U, 0xdadadadaU,\n 0x5e5e5e5eU, 0x15151515U, 0x46464646U, 0x57575757U,\n 0xa7a7a7a7U, 0x8d8d8d8dU, 0x9d9d9d9dU, 0x84848484U,\n 0x90909090U, 0xd8d8d8d8U, 0xababababU, 0x00000000U,\n 0x8c8c8c8cU, 0xbcbcbcbcU, 0xd3d3d3d3U, 0x0a0a0a0aU,\n 0xf7f7f7f7U, 0xe4e4e4e4U, 0x58585858U, 0x05050505U,\n 0xb8b8b8b8U, 0xb3b3b3b3U, 0x45454545U, 0x06060606U,\n 0xd0d0d0d0U, 0x2c2c2c2cU, 0x1e1e1e1eU, 0x8f8f8f8fU,\n 0xcacacacaU, 0x3f3f3f3fU, 0x0f0f0f0fU, 0x02020202U,\n 0xc1c1c1c1U, 0xafafafafU, 0xbdbdbdbdU, 0x03030303U,\n 0x01010101U, 0x13131313U, 0x8a8a8a8aU, 0x6b6b6b6bU,\n 0x3a3a3a3aU, 0x91919191U, 0x11111111U, 0x41414141U,\n 0x4f4f4f4fU, 0x67676767U, 0xdcdcdcdcU, 0xeaeaeaeaU,\n 0x97979797U, 0xf2f2f2f2U, 0xcfcfcfcfU, 0xcecececeU,\n 0xf0f0f0f0U, 0xb4b4b4b4U, 0xe6e6e6e6U, 0x73737373U,\n 0x96969696U, 0xacacacacU, 0x74747474U, 0x22222222U,\n 0xe7e7e7e7U, 0xadadadadU, 0x35353535U, 0x85858585U,\n 0xe2e2e2e2U, 0xf9f9f9f9U, 0x37373737U, 0xe8e8e8e8U,\n 0x1c1c1c1cU, 0x75757575U, 0xdfdfdfdfU, 0x6e6e6e6eU,\n 0x47474747U, 0xf1f1f1f1U, 0x1a1a1a1aU, 0x71717171U,\n 0x1d1d1d1dU, 0x29292929U, 0xc5c5c5c5U, 0x89898989U,\n 0x6f6f6f6fU, 0xb7b7b7b7U, 0x62626262U, 0x0e0e0e0eU,\n 0xaaaaaaaaU, 0x18181818U, 0xbebebebeU, 0x1b1b1b1bU,\n 0xfcfcfcfcU, 0x56565656U, 0x3e3e3e3eU, 0x4b4b4b4bU,\n 0xc6c6c6c6U, 0xd2d2d2d2U, 0x79797979U, 0x20202020U,\n 0x9a9a9a9aU, 0xdbdbdbdbU, 0xc0c0c0c0U, 0xfefefefeU,\n 0x78787878U, 0xcdcdcdcdU, 0x5a5a5a5aU, 0xf4f4f4f4U,\n 0x1f1f1f1fU, 0xddddddddU, 0xa8a8a8a8U, 0x33333333U,\n 0x88888888U, 0x07070707U, 0xc7c7c7c7U, 0x31313131U,\n 0xb1b1b1b1U, 0x12121212U, 0x10101010U, 0x59595959U,\n 0x27272727U, 0x80808080U, 0xececececU, 0x5f5f5f5fU,\n 0x60606060U, 0x51515151U, 0x7f7f7f7fU, 0xa9a9a9a9U,\n 0x19191919U, 0xb5b5b5b5U, 0x4a4a4a4aU, 0x0d0d0d0dU,\n 0x2d2d2d2dU, 0xe5e5e5e5U, 0x7a7a7a7aU, 0x9f9f9f9fU,\n 0x93939393U, 0xc9c9c9c9U, 0x9c9c9c9cU, 0xefefefefU,\n 0xa0a0a0a0U, 0xe0e0e0e0U, 0x3b3b3b3bU, 0x4d4d4d4dU,\n 0xaeaeaeaeU, 0x2a2a2a2aU, 0xf5f5f5f5U, 0xb0b0b0b0U,\n 0xc8c8c8c8U, 0xebebebebU, 0xbbbbbbbbU, 0x3c3c3c3cU,\n 0x83838383U, 0x53535353U, 0x99999999U, 0x61616161U,\n 0x17171717U, 0x2b2b2b2bU, 0x04040404U, 0x7e7e7e7eU,\n 0xbabababaU, 0x77777777U, 0xd6d6d6d6U, 0x26262626U,\n 0xe1e1e1e1U, 0x69696969U, 0x14141414U, 0x63636363U,\n 0x55555555U, 0x21212121U, 0x0c0c0c0cU, 0x7d7d7d7dU,\n};\nstatic const u32 rcon[] = {\n\t0x01000000, 0x02000000, 0x04000000, 0x08000000,\n\t0x10000000, 0x20000000, 0x40000000, 0x80000000,\n\t0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */\n};\n\n/**\n * Expand the cipher key into the encryption key schedule.\n */\nint AES_set_encrypt_key(const unsigned char *userKey, const int bits,\n\t\t\tAES_KEY *key) {\n\n\tu32 *rk;\n \tint i = 0;\n\tu32 temp;\n\n\tif (!userKey || !key)\n\t\treturn -1;\n\tif (bits != 128 && bits != 192 && bits != 256)\n\t\treturn -2;\n\n\trk = key->rd_key;\n\n\tif (bits==128)\n\t\tkey->rounds = 10;\n\telse if (bits==192)\n\t\tkey->rounds = 12;\n\telse\n\t\tkey->rounds = 14;\n\n\trk[0] = GETU32(userKey );\n\trk[1] = GETU32(userKey + 4);\n\trk[2] = GETU32(userKey + 8);\n\trk[3] = GETU32(userKey + 12);\n\tif (bits == 128) {\n\t\twhile (1) {\n\t\t\ttemp = rk[3];\n\t\t\trk[4] = rk[0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[5] = rk[1] ^ rk[4];\n\t\t\trk[6] = rk[2] ^ rk[5];\n\t\t\trk[7] = rk[3] ^ rk[6];\n\t\t\tif (++i == 10) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\trk += 4;\n\t\t}\n\t}\n\trk[4] = GETU32(userKey + 16);\n\trk[5] = GETU32(userKey + 20);\n\tif (bits == 192) {\n\t\twhile (1) {\n\t\t\ttemp = rk[ 5];\n\t\t\trk[ 6] = rk[ 0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[ 7] = rk[ 1] ^ rk[ 6];\n\t\t\trk[ 8] = rk[ 2] ^ rk[ 7];\n\t\t\trk[ 9] = rk[ 3] ^ rk[ 8];\n\t\t\tif (++i == 8) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\trk[10] = rk[ 4] ^ rk[ 9];\n\t\t\trk[11] = rk[ 5] ^ rk[10];\n\t\t\trk += 6;\n\t\t}\n\t}\n\trk[6] = GETU32(userKey + 24);\n\trk[7] = GETU32(userKey + 28);\n\tif (bits == 256) {\n\t\twhile (1) {\n\t\t\ttemp = rk[ 7];\n\t\t\trk[ 8] = rk[ 0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[ 9] = rk[ 1] ^ rk[ 8];\n\t\t\trk[10] = rk[ 2] ^ rk[ 9];\n\t\t\trk[11] = rk[ 3] ^ rk[10];\n\t\t\tif (++i == 7) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\ttemp = rk[11];\n\t\t\trk[12] = rk[ 4] ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x000000ff);\n\t\t\trk[13] = rk[ 5] ^ rk[12];\n\t\t\trk[14] = rk[ 6] ^ rk[13];\n\t\t\trk[15] = rk[ 7] ^ rk[14];\n\n\t\t\trk += 8;\n \t}\n\t}\n\treturn 0;\n}\n\n/**\n * Expand the cipher key into the decryption key schedule.\n */\nint AES_set_decrypt_key(const unsigned char *userKey, const int bits,\n\t\t\t AES_KEY *key) {\n\n u32 *rk;\n\tint i, j, status;\n\tu32 temp;\n\n\t/* first, start with an encryption schedule */\n\tstatus = AES_set_encrypt_key(userKey, bits, key);\n\tif (status < 0)\n\t\treturn status;\n\n\trk = key->rd_key;\n\n\t/* invert the order of the round keys: */\n\tfor (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) {\n\t\ttemp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp;\n\t\ttemp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;\n\t\ttemp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;\n\t\ttemp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;\n\t}\n\t/* apply the inverse MixColumn transform to all round keys but the first and the last: */\n\tfor (i = 1; i < (key->rounds); i++) {\n\t\trk += 4;\n\t\trk[0] =\n\t\t\tTd0[Te4[(rk[0] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[0] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[0] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[0] ) & 0xff] & 0xff];\n\t\trk[1] =\n\t\t\tTd0[Te4[(rk[1] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[1] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[1] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[1] ) & 0xff] & 0xff];\n\t\trk[2] =\n\t\t\tTd0[Te4[(rk[2] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[2] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[2] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[2] ) & 0xff] & 0xff];\n\t\trk[3] =\n\t\t\tTd0[Te4[(rk[3] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[3] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[3] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[3] ) & 0xff] & 0xff];\n\t}\n\treturn 0;\n}\n\n#ifndef AES_ASM\n/*\n * Encrypt a single block\n * in and out can overlap\n */\nvoid AES_encrypt(const unsigned char *in, unsigned char *out,\n\t\t const AES_KEY *key) {\n\n\tconst u32 *rk;\n\tu32 s0, s1, s2, s3, t0, t1, t2, t3;\n#ifndef FULL_UNROLL\n\tint r;\n#endif /* ?FULL_UNROLL */\n\n\tassert(in && out && key);\n\trk = key->rd_key;\n\n\t/*\n\t * map byte array block to cipher state\n\t * and add initial round key:\n\t */\n\ts0 = GETU32(in ) ^ rk[0];\n\ts1 = GETU32(in + 4) ^ rk[1];\n\ts2 = GETU32(in + 8) ^ rk[2];\n\ts3 = GETU32(in + 12) ^ rk[3];\n#ifdef FULL_UNROLL\n\t/* round 1: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7];\n \t/* round 2: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11];\n\t/* round 3: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15];\n \t/* round 4: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19];\n\t/* round 5: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23];\n \t/* round 6: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27];\n\t/* round 7: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31];\n \t/* round 8: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35];\n\t/* round 9: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39];\n if (key->rounds > 10) {\n /* round 10: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43];\n /* round 11: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47];\n if (key->rounds > 12) {\n /* round 12: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51];\n /* round 13: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55];\n }\n }\n rk += key->rounds << 2;\n#else /* !FULL_UNROLL */\n /*\n * Nr - 1 full rounds:\n */\n r = key->rounds >> 1;\n for (;;) {\n t0 =\n Te0[(s0 >> 24) ] ^\n Te1[(s1 >> 16) & 0xff] ^\n Te2[(s2 >> 8) & 0xff] ^\n Te3[(s3 ) & 0xff] ^\n rk[4];\n t1 =\n Te0[(s1 >> 24) ] ^\n Te1[(s2 >> 16) & 0xff] ^\n Te2[(s3 >> 8) & 0xff] ^\n Te3[(s0 ) & 0xff] ^\n rk[5];\n t2 =\n Te0[(s2 >> 24) ] ^\n Te1[(s3 >> 16) & 0xff] ^\n Te2[(s0 >> 8) & 0xff] ^\n Te3[(s1 ) & 0xff] ^\n rk[6];\n t3 =\n Te0[(s3 >> 24) ] ^\n Te1[(s0 >> 16) & 0xff] ^\n Te2[(s1 >> 8) & 0xff] ^\n Te3[(s2 ) & 0xff] ^\n rk[7];\n\n rk += 8;\n if (--r == 0) {\n break;\n }\n\n s0 =\n Te0[(t0 >> 24) ] ^\n Te1[(t1 >> 16) & 0xff] ^\n Te2[(t2 >> 8) & 0xff] ^\n Te3[(t3 ) & 0xff] ^\n rk[0];\n s1 =\n Te0[(t1 >> 24) ] ^\n Te1[(t2 >> 16) & 0xff] ^\n Te2[(t3 >> 8) & 0xff] ^\n Te3[(t0 ) & 0xff] ^\n rk[1];\n s2 =\n Te0[(t2 >> 24) ] ^\n Te1[(t3 >> 16) & 0xff] ^\n Te2[(t0 >> 8) & 0xff] ^\n Te3[(t1 ) & 0xff] ^\n rk[2];\n s3 =\n Te0[(t3 >> 24) ] ^\n Te1[(t0 >> 16) & 0xff] ^\n Te2[(t1 >> 8) & 0xff] ^\n Te3[(t2 ) & 0xff] ^\n rk[3];\n }\n#endif /* ?FULL_UNROLL */\n /*\n\t * apply last round and\n\t * map cipher state to byte array block:\n\t */\n\ts0 =\n\t\t(Te4[(t0 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t3 ) & 0xff] & 0x000000ff) ^\n\t\trk[0];\n\tPUTU32(out , s0);\n\ts1 =\n\t\t(Te4[(t1 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t0 ) & 0xff] & 0x000000ff) ^\n\t\trk[1];\n\tPUTU32(out + 4, s1);\n\ts2 =\n\t\t(Te4[(t2 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t1 ) & 0xff] & 0x000000ff) ^\n\t\trk[2];\n\tPUTU32(out + 8, s2);\n\ts3 =\n\t\t(Te4[(t3 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t2 ) & 0xff] & 0x000000ff) ^\n\t\trk[3];\n\tPUTU32(out + 12, s3);\n}\n\n/*\n * Decrypt a single block\n * in and out can overlap\n */\nvoid AES_decrypt(const unsigned char *in, unsigned char *out,\n\t\t const AES_KEY *key) {\n\n\tconst u32 *rk;\n\tu32 s0, s1, s2, s3, t0, t1, t2, t3;\n#ifndef FULL_UNROLL\n\tint r;\n#endif /* ?FULL_UNROLL */\n\n\tassert(in && out && key);\n\trk = key->rd_key;\n\n\t/*\n\t * map byte array block to cipher state\n\t * and add initial round key:\n\t */\n s0 = GETU32(in ) ^ rk[0];\n s1 = GETU32(in + 4) ^ rk[1];\n s2 = GETU32(in + 8) ^ rk[2];\n s3 = GETU32(in + 12) ^ rk[3];\n#ifdef FULL_UNROLL\n /* round 1: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[ 4];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[ 5];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[ 6];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[ 7];\n /* round 2: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[ 8];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[ 9];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11];\n /* round 3: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15];\n /* round 4: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19];\n /* round 5: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23];\n /* round 6: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27];\n /* round 7: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31];\n /* round 8: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35];\n /* round 9: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39];\n if (key->rounds > 10) {\n /* round 10: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43];\n /* round 11: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47];\n if (key->rounds > 12) {\n /* round 12: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51];\n /* round 13: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55];\n }\n }\n\trk += key->rounds << 2;\n#else /* !FULL_UNROLL */\n /*\n * Nr - 1 full rounds:\n */\n r = key->rounds >> 1;\n for (;;) {\n t0 =\n Td0[(s0 >> 24) ] ^\n Td1[(s3 >> 16) & 0xff] ^\n Td2[(s2 >> 8) & 0xff] ^\n Td3[(s1 ) & 0xff] ^\n rk[4];\n t1 =\n Td0[(s1 >> 24) ] ^\n Td1[(s0 >> 16) & 0xff] ^\n Td2[(s3 >> 8) & 0xff] ^\n Td3[(s2 ) & 0xff] ^\n rk[5];\n t2 =\n Td0[(s2 >> 24) ] ^\n Td1[(s1 >> 16) & 0xff] ^\n Td2[(s0 >> 8) & 0xff] ^\n Td3[(s3 ) & 0xff] ^\n rk[6];\n t3 =\n Td0[(s3 >> 24) ] ^\n Td1[(s2 >> 16) & 0xff] ^\n Td2[(s1 >> 8) & 0xff] ^\n Td3[(s0 ) & 0xff] ^\n rk[7];\n\n rk += 8;\n if (--r == 0) {\n break;\n }\n\n s0 =\n Td0[(t0 >> 24) ] ^\n Td1[(t3 >> 16) & 0xff] ^\n Td2[(t2 >> 8) & 0xff] ^\n Td3[(t1 ) & 0xff] ^\n rk[0];\n s1 =\n Td0[(t1 >> 24) ] ^\n Td1[(t0 >> 16) & 0xff] ^\n Td2[(t3 >> 8) & 0xff] ^\n Td3[(t2 ) & 0xff] ^\n rk[1];\n s2 =\n Td0[(t2 >> 24) ] ^\n Td1[(t1 >> 16) & 0xff] ^\n Td2[(t0 >> 8) & 0xff] ^\n Td3[(t3 ) & 0xff] ^\n rk[2];\n s3 =\n Td0[(t3 >> 24) ] ^\n Td1[(t2 >> 16) & 0xff] ^\n Td2[(t1 >> 8) & 0xff] ^\n Td3[(t0 ) & 0xff] ^\n rk[3];\n }\n#endif /* ?FULL_UNROLL */\n /*\n\t * apply last round and\n\t * map cipher state to byte array block:\n\t */\n \ts0 =\n \t\t(Td4[(t0 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t3 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t2 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t1 ) & 0xff] & 0x000000ff) ^\n \t\trk[0];\n\tPUTU32(out , s0);\n \ts1 =\n \t\t(Td4[(t1 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t0 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t3 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t2 ) & 0xff] & 0x000000ff) ^\n \t\trk[1];\n\tPUTU32(out + 4, s1);\n \ts2 =\n \t\t(Td4[(t2 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t1 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t0 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t3 ) & 0xff] & 0x000000ff) ^\n \t\trk[2];\n\tPUTU32(out + 8, s2);\n \ts3 =\n \t\t(Td4[(t3 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t2 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t1 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t0 ) & 0xff] & 0x000000ff) ^\n \t\trk[3];\n\tPUTU32(out + 12, s3);\n}\n\n#endif /* AES_ASM */\n\nvoid AES_cbc_encrypt(const unsigned char *in, unsigned char *out,\n\t\t const unsigned long length, const AES_KEY *key,\n\t\t unsigned char *ivec, const int enc)\n{\n\n\tunsigned long n;\n\tunsigned long len = length;\n\tunsigned char tmp[AES_BLOCK_SIZE];\n\n\tassert(in && out && key && ivec);\n\n\tif (enc) {\n\t\twhile (len >= AES_BLOCK_SIZE) {\n\t\t\tfor(n=0; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\ttmp[n] = in[n] ^ ivec[n];\n\t\t\tAES_encrypt(tmp, out, key);\n\t\t\tmemcpy(ivec, out, AES_BLOCK_SIZE);\n\t\t\tlen -= AES_BLOCK_SIZE;\n\t\t\tin += AES_BLOCK_SIZE;\n\t\t\tout += AES_BLOCK_SIZE;\n\t\t}\n\t\tif (len) {\n\t\t\tfor(n=0; n < len; ++n)\n\t\t\t\ttmp[n] = in[n] ^ ivec[n];\n\t\t\tfor(n=len; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\ttmp[n] = ivec[n];\n\t\t\tAES_encrypt(tmp, tmp, key);\n\t\t\tmemcpy(out, tmp, AES_BLOCK_SIZE);\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t}\n\t} else {\n\t\twhile (len >= AES_BLOCK_SIZE) {\n\t\t\tmemcpy(tmp, in, AES_BLOCK_SIZE);\n\t\t\tAES_decrypt(in, out, key);\n\t\t\tfor(n=0; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\tout[n] ^= ivec[n];\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t\tlen -= AES_BLOCK_SIZE;\n\t\t\tin += AES_BLOCK_SIZE;\n\t\t\tout += AES_BLOCK_SIZE;\n\t\t}\n\t\tif (len) {\n\t\t\tmemcpy(tmp, in, AES_BLOCK_SIZE);\n\t\t\tAES_decrypt(tmp, tmp, key);\n\t\t\tfor(n=0; n < len; ++n)\n\t\t\t\tout[n] = tmp[n] ^ ivec[n];\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t}\n\t}\n}\n"], ["/linuxpdf/tinyemu/softfp.c", "/*\n * SoftFP Library\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"softfp.h\"\n\nstatic inline int clz32(uint32_t a)\n{\n int r;\n if (a == 0) {\n r = 32;\n } else {\n r = __builtin_clz(a);\n }\n return r;\n}\n\nstatic inline int clz64(uint64_t a)\n{\n int r;\n if (a == 0) {\n r = 64;\n } else \n {\n r = __builtin_clzll(a);\n }\n return r;\n}\n\n#ifdef HAVE_INT128\nstatic inline int clz128(uint128_t a)\n{\n int r;\n if (a == 0) {\n r = 128;\n } else \n {\n uint64_t ah, al;\n ah = a >> 64;\n al = a;\n if (ah != 0)\n r = __builtin_clzll(ah);\n else\n r = __builtin_clzll(al) + 64;\n }\n return r;\n}\n#endif\n\n#define F_SIZE 32\n#include \"softfp_template.h\"\n\n#define F_SIZE 64\n#include \"softfp_template.h\"\n\n#ifdef HAVE_INT128\n\n#define F_SIZE 128\n#include \"softfp_template.h\"\n\n#endif\n\n"]], "task_instance_info": {"created_time": "2025-08-20 18:00:24", "created_task_model": "DeepSeek-R1", "function_skeleton": "int virt_machine_run(void *opaque) {}", "code_description": "This code segment functions to: Manage the execution loop of a virtualized environment by processing input/output operations, updating display output, and controlling instruction cycle execution to maintain system responsiveness while handling device communication and timing constraints."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c\n[TASK_BEGIN]\nint virt_machine_run(void *opaque)\n{\n VirtMachine *m = opaque;\n int ret, sleep_time;\n uint64_t delay;\n \n if (m->stopped)\n return 0;\n\n for(;;) {\n ret = virt_machine_run_cpu(m, MAX_EXEC_CYCLE);\n if (ret != 0)\n break;\n \n /* handle timers */\n delay = virt_machine_get_wakeup_time(m) - virt_machine_get_clock(m);\n if (delay == 0) {\n /* timer already expired */\n continue;\n }\n \n /* convert delay to ms */\n sleep_time = (delay * 1000) / virt_machine_get_ticks_per_sec(m);\n if (sleep_time > MAX_SLEEP_TIME)\n sleep_time = MAX_SLEEP_TIME;\n if (sleep_time <= 0)\n sleep_time = 1;\n break;\n }\n \n if (!m->stopped) {\n EM_ASM({ update_machine_interval($0, $1); }, m, sleep_time);\n }\n return 1;\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 18-00-49"}, "editdistance_info": {"edit_distance": 23.0769, "calculate_time": "2025-08-20 18:00:49", "true_code_clean": "int virt_machine_run(void *opaque)\n{\n VirtMachine *m = opaque;\n int delay, i;\n FBDevice *fb_dev;\n if (m->console_dev && virtio_console_can_write_data(m->console_dev)) {\n uint8_t buf[128];\n int ret, len;\n len = virtio_console_get_write_len(m->console_dev);\n len = min_int(len, sizeof(buf));\n ret = m->console->read_data(m->console->opaque, buf, len);\n if (ret > 0)\n virtio_console_write_data(m->console_dev, buf, ret);\n if (console_resize_pending) {\n int w, h;\n console_get_size(&w, &h);\n virtio_console_resize_event(m->console_dev, w, h);\n console_resize_pending = FALSE;\n }\n }\n fb_dev = m->fb_dev;\n if (fb_dev) {\n fb_dev->refresh(fb_dev, fb_refresh1, NULL);\n }\n i = 0;\n for(;;) {\n delay = virt_machine_get_sleep_duration(m, MAX_SLEEP_TIME);\n if (delay != 0 || i >= MAX_EXEC_TOTAL_CYCLE / MAX_EXEC_CYCLE)\n break;\n virt_machine_interp(m, MAX_EXEC_CYCLE);\n i++;\n }\n return i * MAX_EXEC_CYCLE;\n}", "predict_code_clean": "int virt_machine_run(void *opaque)\n{\n VirtMachine *m = opaque;\n int ret, sleep_time;\n uint64_t delay;\n if (m->stopped)\n return 0;\n for(;;) {\n ret = virt_machine_run_cpu(m, MAX_EXEC_CYCLE);\n if (ret != 0)\n break;\n delay = virt_machine_get_wakeup_time(m) - virt_machine_get_clock(m);\n if (delay == 0) {\n continue;\n }\n sleep_time = (delay * 1000) / virt_machine_get_ticks_per_sec(m);\n if (sleep_time > MAX_SLEEP_TIME)\n sleep_time = MAX_SLEEP_TIME;\n if (sleep_time <= 0)\n sleep_time = 1;\n break;\n }\n if (!m->stopped) {\n EM_ASM({ update_machine_interval($0, $1); }, m, sleep_time);\n }\n return 1;\n}"}} {"repo_name": "linuxpdf", "file_name": "/linuxpdf/tinyemu/fs_net.c", "inference_info": {"prefix_code": "/*\n * Networked Filesystem using HTTP\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n#include \"fbuf.h\"\n\n#if defined(EMSCRIPTEN)\n#include \n#endif\n\n/*\n TODO:\n - implement fs_lock/fs_getlock\n - update fs_size with links ?\n - limit fs_size in dirent creation\n - limit filename length\n*/\n\n//#define DEBUG_CACHE\n#if !defined(EMSCRIPTEN)\n#define DUMP_CACHE_LOAD\n#endif\n\n#if defined(EMSCRIPTEN)\n#define DEFAULT_INODE_CACHE_SIZE (64 * 1024 * 1024)\n#else\n#define DEFAULT_INODE_CACHE_SIZE (256 * 1024 * 1024)\n#endif\n\ntypedef enum {\n FT_FIFO = 1,\n FT_CHR = 2,\n FT_DIR = 4,\n FT_BLK = 6,\n FT_REG = 8,\n FT_LNK = 10,\n FT_SOCK = 12,\n} FSINodeTypeEnum;\n\ntypedef enum {\n REG_STATE_LOCAL, /* local content */\n REG_STATE_UNLOADED, /* content not loaded */\n REG_STATE_LOADING, /* content is being loaded */\n REG_STATE_LOADED, /* loaded, not modified, stored in cached_inode_list */\n} FSINodeRegStateEnum;\n\ntypedef struct FSBaseURL {\n struct list_head link;\n int ref_count;\n char *base_url_id;\n char *url;\n char *user;\n char *password;\n BOOL encrypted;\n AES_KEY aes_state;\n} FSBaseURL;\n\ntypedef struct FSINode {\n struct list_head link;\n uint64_t inode_num; /* inode number */\n int32_t refcount;\n int32_t open_count;\n FSINodeTypeEnum type;\n uint32_t mode;\n uint32_t uid;\n uint32_t gid;\n uint32_t mtime_sec;\n uint32_t ctime_sec;\n uint32_t mtime_nsec;\n uint32_t ctime_nsec;\n union {\n struct {\n FSINodeRegStateEnum state;\n size_t size; /* real file size */\n FileBuffer fbuf;\n FSBaseURL *base_url;\n FSFileID file_id; /* network file ID */\n struct list_head link;\n struct FSOpenInfo *open_info; /* used in LOADING state */\n BOOL is_fscmd;\n#ifdef DUMP_CACHE_LOAD\n char *filename;\n#endif\n } reg;\n struct {\n struct list_head de_list; /* list of FSDirEntry */\n int size;\n } dir;\n struct {\n uint32_t major;\n uint32_t minor;\n } dev;\n struct {\n char *name;\n } symlink;\n } u;\n} FSINode;\n\ntypedef struct {\n struct list_head link;\n FSINode *inode;\n uint8_t mark; /* temporary use only */\n char name[0];\n} FSDirEntry;\n\ntypedef enum {\n FS_CMD_XHR,\n FS_CMD_PBKDF2,\n} FSCMDRequestEnum;\n\n#define FS_CMD_REPLY_LEN_MAX 64\n\ntypedef struct {\n FSCMDRequestEnum type;\n struct CmdXHRState *xhr_state;\n int reply_len;\n uint8_t reply_buf[FS_CMD_REPLY_LEN_MAX];\n} FSCMDRequest;\n\nstruct FSFile {\n uint32_t uid;\n FSINode *inode;\n BOOL is_opened;\n uint32_t open_flags;\n FSCMDRequest *req;\n};\n\ntypedef struct {\n struct list_head link;\n BOOL is_archive;\n const char *name;\n} PreloadFile;\n\ntypedef struct {\n struct list_head link;\n FSFileID file_id;\n struct list_head file_list; /* list of PreloadFile.link */\n} PreloadEntry;\n\ntypedef struct {\n struct list_head link;\n FSFileID file_id;\n uint64_t size;\n const char *name;\n} PreloadArchiveFile;\n\ntypedef struct {\n struct list_head link;\n const char *name;\n struct list_head file_list; /* list of PreloadArchiveFile.link */\n} PreloadArchive;\n\ntypedef struct FSDeviceMem {\n FSDevice common;\n\n struct list_head inode_list; /* list of FSINode */\n int64_t inode_count; /* current number of inodes */\n uint64_t inode_limit;\n int64_t fs_blocks;\n uint64_t fs_max_blocks;\n uint64_t inode_num_alloc;\n int block_size_log2;\n uint32_t block_size; /* for stat/statfs */\n FSINode *root_inode;\n struct list_head inode_cache_list; /* list of FSINode.u.reg.link */\n int64_t inode_cache_size;\n int64_t inode_cache_size_limit;\n struct list_head preload_list; /* list of PreloadEntry.link */\n struct list_head preload_archive_list; /* list of PreloadArchive.link */\n /* network */\n struct list_head base_url_list; /* list of FSBaseURL.link */\n char *import_dir;\n#ifdef DUMP_CACHE_LOAD\n BOOL dump_cache_load;\n BOOL dump_started;\n char *dump_preload_dir;\n FILE *dump_preload_file;\n FILE *dump_preload_archive_file;\n\n char *dump_archive_name;\n uint64_t dump_archive_size;\n FILE *dump_archive_file;\n\n int dump_archive_num;\n struct list_head dump_preload_list; /* list of PreloadFile.link */\n struct list_head dump_exclude_list; /* list of PreloadFile.link */\n#endif\n} FSDeviceMem;\n\ntypedef enum {\n FS_OPEN_WGET_REG,\n FS_OPEN_WGET_ARCHIVE,\n FS_OPEN_WGET_ARCHIVE_FILE,\n} FSOpenWgetEnum;\n\ntypedef struct FSOpenInfo {\n FSDevice *fs;\n FSOpenWgetEnum open_type;\n\n /* used for FS_OPEN_WGET_REG, FS_OPEN_WGET_ARCHIVE */\n XHRState *xhr;\n FSINode *n;\n DecryptFileState *dec_state;\n size_t cur_pos;\n\n struct list_head archive_link; /* FS_OPEN_WGET_ARCHIVE_FILE */\n uint64_t archive_offset; /* FS_OPEN_WGET_ARCHIVE_FILE */\n struct list_head archive_file_list; /* FS_OPEN_WGET_ARCHIVE */\n \n /* the following is set in case there is a fs_open callback */\n FSFile *f;\n FSOpenCompletionFunc *cb;\n void *opaque;\n} FSOpenInfo;\n\nstatic void fs_close(FSDevice *fs, FSFile *f);\nstatic void inode_decref(FSDevice *fs1, FSINode *n);\nstatic int fs_cmd_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int buf_len);\nstatic int fs_cmd_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int buf_len);\nstatic int fs_truncate(FSDevice *fs1, FSINode *n, uint64_t size);\nstatic void fs_open_end(FSOpenInfo *oi);\nstatic void fs_base_url_decref(FSDevice *fs, FSBaseURL *bu);\nstatic FSBaseURL *fs_net_set_base_url(FSDevice *fs1,\n const char *base_url_id,\n const char *url,\n const char *user, const char *password,\n AES_KEY *aes_state);\nstatic void fs_cmd_close(FSDevice *fs, FSFile *f);\nstatic void fs_error_archive(FSOpenInfo *oi);\n#ifdef DUMP_CACHE_LOAD\nstatic void dump_loaded_file(FSDevice *fs1, FSINode *n);\n#endif\n\n#if !defined(EMSCRIPTEN)\n/* file buffer (the content of the buffer can be stored elsewhere) */\nvoid file_buffer_init(FileBuffer *bs)\n{\n bs->data = NULL;\n bs->allocated_size = 0;\n}\n\nvoid file_buffer_reset(FileBuffer *bs)\n{\n free(bs->data);\n file_buffer_init(bs);\n}\n\nint file_buffer_resize(FileBuffer *bs, size_t new_size)\n{\n uint8_t *new_data;\n new_data = realloc(bs->data, new_size);\n if (!new_data && new_size != 0)\n return -1;\n bs->data = new_data;\n bs->allocated_size = new_size;\n return 0;\n}\n\nvoid file_buffer_write(FileBuffer *bs, size_t offset, const uint8_t *buf,\n size_t size)\n{\n memcpy(bs->data + offset, buf, size);\n}\n\nvoid file_buffer_set(FileBuffer *bs, size_t offset, int val, size_t size)\n{\n memset(bs->data + offset, val, size);\n}\n\nvoid file_buffer_read(FileBuffer *bs, size_t offset, uint8_t *buf,\n size_t size)\n{\n memcpy(buf, bs->data + offset, size);\n}\n#endif\n\nstatic int64_t to_blocks(FSDeviceMem *fs, uint64_t size)\n{\n return (size + fs->block_size - 1) >> fs->block_size_log2;\n}\n\nstatic FSINode *inode_incref(FSDevice *fs, FSINode *n)\n{\n n->refcount++;\n return n;\n}\n\nstatic FSINode *inode_inc_open(FSDevice *fs, FSINode *n)\n{\n n->open_count++;\n return n;\n}\n\nstatic void inode_free(FSDevice *fs1, FSINode *n)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n // printf(\"inode_free=%\" PRId64 \"\\n\", n->inode_num);\n assert(n->refcount == 0);\n assert(n->open_count == 0);\n switch(n->type) {\n case FT_REG:\n fs->fs_blocks -= to_blocks(fs, n->u.reg.size);\n assert(fs->fs_blocks >= 0);\n file_buffer_reset(&n->u.reg.fbuf);\n#ifdef DUMP_CACHE_LOAD\n free(n->u.reg.filename);\n#endif\n switch(n->u.reg.state) {\n case REG_STATE_LOADED:\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n fs_base_url_decref(fs1, n->u.reg.base_url);\n break;\n case REG_STATE_LOADING:\n {\n FSOpenInfo *oi = n->u.reg.open_info;\n if (oi->xhr)\n fs_wget_free(oi->xhr);\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE) {\n fs_error_archive(oi);\n }\n fs_open_end(oi);\n fs_base_url_decref(fs1, n->u.reg.base_url);\n }\n break;\n case REG_STATE_UNLOADED:\n fs_base_url_decref(fs1, n->u.reg.base_url);\n break;\n case REG_STATE_LOCAL:\n break;\n default:\n abort();\n }\n break;\n case FT_LNK:\n free(n->u.symlink.name);\n break;\n case FT_DIR:\n assert(list_empty(&n->u.dir.de_list));\n break;\n default:\n break;\n }\n list_del(&n->link);\n free(n);\n fs->inode_count--;\n assert(fs->inode_count >= 0);\n}\n\nstatic void inode_decref(FSDevice *fs1, FSINode *n)\n{\n assert(n->refcount >= 1);\n if (--n->refcount <= 0 && n->open_count <= 0) {\n inode_free(fs1, n);\n }\n}\n\nstatic void inode_dec_open(FSDevice *fs1, FSINode *n)\n{\n assert(n->open_count >= 1);\n if (--n->open_count <= 0 && n->refcount <= 0) {\n inode_free(fs1, n);\n }\n}\n\nstatic void inode_update_mtime(FSDevice *fs, FSINode *n)\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n n->mtime_sec = tv.tv_sec;\n n->mtime_nsec = tv.tv_usec * 1000;\n}\n\nstatic FSINode *inode_new(FSDevice *fs1, FSINodeTypeEnum type,\n uint32_t mode, uint32_t uid, uint32_t gid)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n;\n\n n = mallocz(sizeof(*n));\n n->refcount = 1;\n n->open_count = 0;\n n->inode_num = fs->inode_num_alloc;\n fs->inode_num_alloc++;\n n->type = type;\n n->mode = mode & 0xfff;\n n->uid = uid;\n n->gid = gid;\n\n switch(type) {\n case FT_REG:\n file_buffer_init(&n->u.reg.fbuf);\n break;\n case FT_DIR:\n init_list_head(&n->u.dir.de_list);\n break;\n default:\n break;\n }\n\n list_add(&n->link, &fs->inode_list);\n fs->inode_count++;\n\n inode_update_mtime(fs1, n);\n n->ctime_sec = n->mtime_sec;\n n->ctime_nsec = n->mtime_nsec;\n\n return n;\n}\n\n/* warning: the refcount of 'n1' is not incremented by this function */\n/* XXX: test FS max size */\nstatic FSDirEntry *inode_dir_add(FSDevice *fs1, FSINode *n, const char *name,\n FSINode *n1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSDirEntry *de;\n int name_len, dirent_size, new_size;\n assert(n->type == FT_DIR);\n\n name_len = strlen(name);\n de = mallocz(sizeof(*de) + name_len + 1);\n de->inode = n1;\n memcpy(de->name, name, name_len + 1);\n dirent_size = sizeof(*de) + name_len + 1;\n new_size = n->u.dir.size + dirent_size;\n fs->fs_blocks += to_blocks(fs, new_size) - to_blocks(fs, n->u.dir.size);\n n->u.dir.size = new_size;\n list_add_tail(&de->link, &n->u.dir.de_list);\n return de;\n}\n\nstatic FSDirEntry *inode_search(FSINode *n, const char *name)\n{\n struct list_head *el;\n FSDirEntry *de;\n \n if (n->type != FT_DIR)\n return NULL;\n\n list_for_each(el, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n if (!strcmp(de->name, name))\n return de;\n }\n return NULL;\n}\n\nstatic FSINode *inode_search_path1(FSDevice *fs, FSINode *n, const char *path)\n{\n char name[1024];\n const char *p, *p1;\n int len;\n FSDirEntry *de;\n \n p = path;\n if (*p == '/')\n p++;\n if (*p == '\\0')\n return n;\n for(;;) {\n p1 = strchr(p, '/');\n if (!p1) {\n len = strlen(p);\n } else {\n len = p1 - p;\n p1++;\n }\n if (len > sizeof(name) - 1)\n return NULL;\n memcpy(name, p, len);\n name[len] = '\\0';\n if (n->type != FT_DIR)\n return NULL;\n de = inode_search(n, name);\n if (!de)\n return NULL;\n n = de->inode;\n p = p1;\n if (!p)\n break;\n }\n return n;\n}\n\nstatic FSINode *inode_search_path(FSDevice *fs1, const char *path)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (!fs1)\n return NULL;\n return inode_search_path1(fs1, fs->root_inode, path);\n}\n\nstatic BOOL is_empty_dir(FSDevice *fs, FSINode *n)\n{\n struct list_head *el;\n FSDirEntry *de;\n\n list_for_each(el, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n if (strcmp(de->name, \".\") != 0 &&\n strcmp(de->name, \"..\") != 0)\n return FALSE;\n }\n return TRUE;\n}\n\nstatic void inode_dirent_delete_no_decref(FSDevice *fs1, FSINode *n, FSDirEntry *de)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int dirent_size, new_size;\n dirent_size = sizeof(*de) + strlen(de->name) + 1;\n\n new_size = n->u.dir.size - dirent_size;\n fs->fs_blocks += to_blocks(fs, new_size) - to_blocks(fs, n->u.dir.size);\n n->u.dir.size = new_size;\n assert(n->u.dir.size >= 0);\n assert(fs->fs_blocks >= 0);\n list_del(&de->link);\n free(de);\n}\n\nstatic void inode_dirent_delete(FSDevice *fs, FSINode *n, FSDirEntry *de)\n{\n FSINode *n1;\n n1 = de->inode;\n inode_dirent_delete_no_decref(fs, n, de);\n inode_decref(fs, n1);\n}\n\nstatic void flush_dir(FSDevice *fs, FSINode *n)\n{\n struct list_head *el, *el1;\n FSDirEntry *de;\n list_for_each_safe(el, el1, &n->u.dir.de_list) {\n de = list_entry(el, FSDirEntry, link);\n inode_dirent_delete(fs, n, de);\n }\n assert(n->u.dir.size == 0);\n}\n\nstatic void fs_delete(FSDevice *fs, FSFile *f)\n{\n fs_close(fs, f);\n inode_dec_open(fs, f->inode);\n free(f);\n}\n\nstatic FSFile *fid_create(FSDevice *fs1, FSINode *n, uint32_t uid)\n{\n FSFile *f;\n\n f = mallocz(sizeof(*f));\n f->inode = inode_inc_open(fs1, n);\n f->uid = uid;\n return f;\n}\n\nstatic void inode_to_qid(FSQID *qid, FSINode *n)\n{\n if (n->type == FT_DIR)\n qid->type = P9_QTDIR;\n else if (n->type == FT_LNK)\n qid->type = P9_QTSYMLINK;\n else\n qid->type = P9_QTFILE;\n qid->version = 0; /* no caching on client */\n qid->path = n->inode_num;\n}\n\nstatic void fs_statfs(FSDevice *fs1, FSStatFS *st)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n st->f_bsize = 1024;\n st->f_blocks = fs->fs_max_blocks <<\n (fs->block_size_log2 - 10);\n st->f_bfree = (fs->fs_max_blocks - fs->fs_blocks) <<\n (fs->block_size_log2 - 10);\n st->f_bavail = st->f_bfree;\n st->f_files = fs->inode_limit;\n st->f_ffree = fs->inode_limit - fs->inode_count;\n}\n\nstatic int fs_attach(FSDevice *fs1, FSFile **pf, FSQID *qid, uint32_t uid,\n const char *uname, const char *aname)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n *pf = fid_create(fs1, fs->root_inode, uid);\n inode_to_qid(qid, fs->root_inode);\n return 0;\n}\n\nstatic int fs_walk(FSDevice *fs, FSFile **pf, FSQID *qids,\n FSFile *f, int count, char **names)\n{\n int i;\n FSINode *n;\n FSDirEntry *de;\n\n n = f->inode;\n for(i = 0; i < count; i++) {\n de = inode_search(n, names[i]);\n if (!de)\n break;\n n = de->inode;\n inode_to_qid(&qids[i], n);\n }\n *pf = fid_create(fs, n, f->uid);\n return i;\n}\n\nstatic int fs_mkdir(FSDevice *fs, FSQID *qid, FSFile *f,\n const char *name, uint32_t mode, uint32_t gid)\n{\n FSINode *n, *n1;\n\n n = f->inode;\n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n if (inode_search(n, name))\n return -P9_EEXIST;\n n1 = inode_new(fs, FT_DIR, mode, f->uid, gid);\n inode_dir_add(fs, n1, \".\", inode_incref(fs, n1));\n inode_dir_add(fs, n1, \"..\", inode_incref(fs, n));\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\n/* remove elements in the cache considering that 'added_size' will be\n added */\nstatic void fs_trim_cache(FSDevice *fs1, int64_t added_size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el, *el1;\n FSINode *n;\n\n if ((fs->inode_cache_size + added_size) <= fs->inode_cache_size_limit)\n return;\n list_for_each_prev_safe(el, el1, &fs->inode_cache_list) {\n n = list_entry(el, FSINode, u.reg.link);\n assert(n->u.reg.state == REG_STATE_LOADED);\n /* cannot remove open files */\n // printf(\"open_count=%d\\n\", n->open_count);\n if (n->open_count != 0)\n continue;\n#ifdef DEBUG_CACHE\n printf(\"fs_trim_cache: remove '%s' size=%ld\\n\",\n n->u.reg.filename, (long)n->u.reg.size);\n#endif\n file_buffer_reset(&n->u.reg.fbuf);\n n->u.reg.state = REG_STATE_UNLOADED;\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n if ((fs->inode_cache_size + added_size) <= fs->inode_cache_size_limit)\n break;\n }\n}\n\nstatic void fs_open_end(FSOpenInfo *oi)\n{\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE_FILE) {\n list_del(&oi->archive_link);\n }\n if (oi->dec_state)\n decrypt_file_end(oi->dec_state);\n free(oi);\n}\n\nstatic int fs_open_write_cb(void *opaque, const uint8_t *data, size_t size)\n{\n FSOpenInfo *oi = opaque;\n size_t len;\n FSINode *n = oi->n;\n \n /* we ignore extraneous data */\n len = n->u.reg.size - oi->cur_pos;\n if (size < len)\n len = size;\n file_buffer_write(&n->u.reg.fbuf, oi->cur_pos, data, len);\n oi->cur_pos += len;\n return 0;\n}\n\nstatic void fs_wget_set_loaded(FSINode *n)\n{\n FSOpenInfo *oi;\n FSDeviceMem *fs;\n FSFile *f;\n FSQID qid;\n\n assert(n->u.reg.state == REG_STATE_LOADING);\n oi = n->u.reg.open_info;\n fs = (FSDeviceMem *)oi->fs;\n n->u.reg.state = REG_STATE_LOADED;\n list_add(&n->u.reg.link, &fs->inode_cache_list);\n fs->inode_cache_size += n->u.reg.size;\n \n if (oi->cb) {\n f = oi->f;\n f->is_opened = TRUE;\n inode_to_qid(&qid, n);\n oi->cb(oi->fs, &qid, 0, oi->opaque);\n }\n fs_open_end(oi);\n}\n\nstatic void fs_wget_set_error(FSINode *n)\n{\n FSOpenInfo *oi;\n assert(n->u.reg.state == REG_STATE_LOADING);\n oi = n->u.reg.open_info;\n n->u.reg.state = REG_STATE_UNLOADED;\n file_buffer_reset(&n->u.reg.fbuf);\n if (oi->cb) {\n oi->cb(oi->fs, NULL, -P9_EIO, oi->opaque);\n }\n fs_open_end(oi);\n}\n\nstatic void fs_read_archive(FSOpenInfo *oi)\n{\n FSINode *n = oi->n;\n uint64_t pos, pos1, l;\n uint8_t buf[1024];\n FSINode *n1;\n FSOpenInfo *oi1;\n struct list_head *el, *el1;\n \n list_for_each_safe(el, el1, &oi->archive_file_list) {\n oi1 = list_entry(el, FSOpenInfo, archive_link);\n n1 = oi1->n;\n /* copy the archive data to the file */\n pos = oi1->archive_offset;\n pos1 = 0;\n while (pos1 < n1->u.reg.size) {\n l = n1->u.reg.size - pos1;\n if (l > sizeof(buf))\n l = sizeof(buf);\n file_buffer_read(&n->u.reg.fbuf, pos, buf, l);\n file_buffer_write(&n1->u.reg.fbuf, pos1, buf, l);\n pos += l;\n pos1 += l;\n }\n fs_wget_set_loaded(n1);\n }\n}\n\nstatic void fs_error_archive(FSOpenInfo *oi)\n{\n FSOpenInfo *oi1;\n struct list_head *el, *el1;\n \n list_for_each_safe(el, el1, &oi->archive_file_list) {\n oi1 = list_entry(el, FSOpenInfo, archive_link);\n fs_wget_set_error(oi1->n);\n }\n}\n\nstatic void fs_open_cb(void *opaque, int err, void *data, size_t size)\n{\n FSOpenInfo *oi = opaque;\n FSINode *n = oi->n;\n \n // printf(\"open_cb: err=%d size=%ld\\n\", err, size);\n if (err < 0) {\n error:\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE)\n fs_error_archive(oi);\n fs_wget_set_error(n);\n } else {\n if (oi->dec_state) {\n if (decrypt_file(oi->dec_state, data, size) < 0)\n goto error;\n if (err == 0) {\n if (decrypt_file_flush(oi->dec_state) < 0)\n goto error;\n }\n } else {\n fs_open_write_cb(oi, data, size);\n }\n\n if (err == 0) {\n /* end of transfer */\n if (oi->cur_pos != n->u.reg.size)\n goto error;\n#ifdef DUMP_CACHE_LOAD\n dump_loaded_file(oi->fs, n);\n#endif\n if (oi->open_type == FS_OPEN_WGET_ARCHIVE)\n fs_read_archive(oi);\n fs_wget_set_loaded(n);\n }\n }\n}\n\n\nstatic int fs_open_wget(FSDevice *fs1, FSINode *n, FSOpenWgetEnum open_type)\n{\n char *url;\n FSOpenInfo *oi;\n char fname[FILEID_SIZE_MAX];\n FSBaseURL *bu;\n\n assert(n->u.reg.state == REG_STATE_UNLOADED);\n \n fs_trim_cache(fs1, n->u.reg.size);\n \n if (file_buffer_resize(&n->u.reg.fbuf, n->u.reg.size) < 0)\n return -P9_EIO;\n n->u.reg.state = REG_STATE_LOADING;\n oi = mallocz(sizeof(*oi));\n oi->cur_pos = 0;\n oi->fs = fs1;\n oi->n = n;\n oi->open_type = open_type;\n if (open_type != FS_OPEN_WGET_ARCHIVE_FILE) {\n if (open_type == FS_OPEN_WGET_ARCHIVE)\n init_list_head(&oi->archive_file_list);\n file_id_to_filename(fname, n->u.reg.file_id);\n bu = n->u.reg.base_url;\n url = compose_path(bu->url, fname);\n if (bu->encrypted) {\n oi->dec_state = decrypt_file_init(&bu->aes_state, fs_open_write_cb, oi);\n }\n oi->xhr = fs_wget(url, bu->user, bu->password, oi, fs_open_cb, FALSE);\n }\n n->u.reg.open_info = oi;\n return 0;\n}\n\n\nstatic void fs_preload_file(FSDevice *fs1, const char *filename)\n{\n FSINode *n;\n\n n = inode_search_path(fs1, filename);\n if (n && n->type == FT_REG && n->u.reg.state == REG_STATE_UNLOADED) {\n#if defined(DEBUG_CACHE)\n printf(\"preload: %s\\n\", filename);\n#endif\n fs_open_wget(fs1, n, FS_OPEN_WGET_REG);\n }\n}\n\nstatic PreloadArchive *find_preload_archive(FSDeviceMem *fs,\n const char *filename)\n{\n PreloadArchive *pa;\n struct list_head *el;\n list_for_each(el, &fs->preload_archive_list) {\n pa = list_entry(el, PreloadArchive, link);\n if (!strcmp(pa->name, filename))\n return pa;\n }\n return NULL;\n}\n\nstatic void fs_preload_archive(FSDevice *fs1, const char *filename)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n PreloadArchive *pa;\n PreloadArchiveFile *paf;\n struct list_head *el;\n FSINode *n, *n1;\n uint64_t offset;\n BOOL has_unloaded;\n \n pa = find_preload_archive(fs, filename);\n if (!pa)\n return;\n#if defined(DEBUG_CACHE)\n printf(\"preload archive: %s\\n\", filename);\n#endif\n n = inode_search_path(fs1, filename);\n if (n && n->type == FT_REG && n->u.reg.state == REG_STATE_UNLOADED) {\n /* if all the files are loaded, no need to load the archive */\n offset = 0;\n has_unloaded = FALSE;\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n n1 = inode_search_path(fs1, paf->name);\n if (n1 && n1->type == FT_REG &&\n n1->u.reg.state == REG_STATE_UNLOADED) {\n has_unloaded = TRUE;\n }\n offset += paf->size;\n }\n if (!has_unloaded) {\n#if defined(DEBUG_CACHE)\n printf(\"archive files already loaded\\n\");\n#endif\n return;\n }\n /* check archive size consistency */\n if (offset != n->u.reg.size) {\n#if defined(DEBUG_CACHE)\n printf(\" inconsistent archive size: %\" PRId64 \" %\" PRId64 \"\\n\",\n offset, n->u.reg.size);\n#endif\n goto load_fallback;\n }\n\n /* start loading the archive */\n fs_open_wget(fs1, n, FS_OPEN_WGET_ARCHIVE);\n \n /* indicate that all the archive files are being loaded. Also\n check consistency of size and file id */\n offset = 0;\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n n1 = inode_search_path(fs1, paf->name);\n if (n1 && n1->type == FT_REG &&\n n1->u.reg.state == REG_STATE_UNLOADED) {\n if (n1->u.reg.size == paf->size &&\n n1->u.reg.file_id == paf->file_id) {\n fs_open_wget(fs1, n1, FS_OPEN_WGET_ARCHIVE_FILE);\n list_add_tail(&n1->u.reg.open_info->archive_link,\n &n->u.reg.open_info->archive_file_list);\n n1->u.reg.open_info->archive_offset = offset;\n } else {\n#if defined(DEBUG_CACHE)\n printf(\" inconsistent archive file: %s\\n\", paf->name);\n#endif\n /* fallback to file preload */\n fs_preload_file(fs1, paf->name);\n }\n }\n offset += paf->size;\n }\n } else {\n load_fallback:\n /* if the archive is already loaded or not loaded, we load the\n files separately (XXX: not optimal if the archive is\n already loaded, but it should not happen often) */\n list_for_each(el, &pa->file_list) {\n paf = list_entry(el, PreloadArchiveFile, link);\n fs_preload_file(fs1, paf->name);\n }\n }\n}\n\nstatic void fs_preload_files(FSDevice *fs1, FSFileID file_id)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el;\n PreloadEntry *pe;\n PreloadFile *pf;\n \n list_for_each(el, &fs->preload_list) {\n pe = list_entry(el, PreloadEntry, link);\n if (pe->file_id == file_id)\n goto found;\n }\n return;\n found:\n list_for_each(el, &pe->file_list) {\n pf = list_entry(el, PreloadFile, link);\n if (pf->is_archive)\n fs_preload_archive(fs1, pf->name);\n else\n fs_preload_file(fs1, pf->name);\n }\n}\n\n/* return < 0 if error, 0 if OK, 1 if asynchronous completion */\n/* XXX: we don't support several simultaneous asynchronous open on the\n same inode */\nstatic int fs_open(FSDevice *fs1, FSQID *qid, FSFile *f, uint32_t flags,\n FSOpenCompletionFunc *cb, void *opaque)\n{\n FSINode *n = f->inode;\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int ret;\n \n fs_close(fs1, f);\n\n if (flags & P9_O_DIRECTORY) {\n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n } else {\n if (n->type != FT_REG && n->type != FT_DIR)\n return -P9_EINVAL; /* XXX */\n }\n f->open_flags = flags;\n if (n->type == FT_REG) {\n if ((flags & P9_O_TRUNC) && (flags & P9_O_NOACCESS) != P9_O_RDONLY) {\n fs_truncate(fs1, n, 0);\n }\n\n switch(n->u.reg.state) {\n case REG_STATE_UNLOADED:\n {\n FSOpenInfo *oi;\n /* need to load the file */\n fs_preload_files(fs1, n->u.reg.file_id);\n /* The state can be modified by the fs_preload_files */\n if (n->u.reg.state == REG_STATE_LOADING)\n goto handle_loading;\n ret = fs_open_wget(fs1, n, FS_OPEN_WGET_REG);\n if (ret)\n return ret;\n oi = n->u.reg.open_info;\n oi->f = f;\n oi->cb = cb;\n oi->opaque = opaque;\n return 1; /* completion callback will be called later */\n }\n break;\n case REG_STATE_LOADING:\n handle_loading:\n {\n FSOpenInfo *oi;\n /* we only handle the case where the file is being preloaded */\n oi = n->u.reg.open_info;\n if (oi->cb)\n return -P9_EIO;\n oi = n->u.reg.open_info;\n oi->f = f;\n oi->cb = cb;\n oi->opaque = opaque;\n return 1; /* completion callback will be called later */\n }\n break;\n case REG_STATE_LOCAL:\n goto do_open;\n case REG_STATE_LOADED:\n /* move to front */\n list_del(&n->u.reg.link);\n list_add(&n->u.reg.link, &fs->inode_cache_list);\n goto do_open;\n default:\n abort();\n }\n } else {\n do_open:\n f->is_opened = TRUE;\n inode_to_qid(qid, n);\n return 0;\n }\n}\n\nstatic int fs_create(FSDevice *fs, FSQID *qid, FSFile *f, const char *name, \n uint32_t flags, uint32_t mode, uint32_t gid)\n{\n FSINode *n1, *n = f->inode;\n \n if (n->type != FT_DIR)\n return -P9_ENOTDIR;\n if (inode_search(n, name)) {\n /* XXX: support it, but Linux does not seem to use this case */\n return -P9_EEXIST;\n } else {\n fs_close(fs, f);\n \n n1 = inode_new(fs, FT_REG, mode, f->uid, gid);\n inode_dir_add(fs, n, name, n1);\n \n inode_dec_open(fs, f->inode);\n f->inode = inode_inc_open(fs, n1);\n f->is_opened = TRUE;\n f->open_flags = flags;\n inode_to_qid(qid, n1);\n return 0;\n }\n}\n\nstatic int fs_readdir(FSDevice *fs, FSFile *f, uint64_t offset1,\n uint8_t *buf, int count)\n{\n FSINode *n1, *n = f->inode;\n int len, pos, name_len, type;\n struct list_head *el;\n FSDirEntry *de;\n uint64_t offset;\n\n if (!f->is_opened || n->type != FT_DIR)\n return -P9_EPROTO;\n \n el = n->u.dir.de_list.next;\n offset = 0;\n while (offset < offset1) {\n if (el == &n->u.dir.de_list)\n return 0; /* no more entries */\n offset++;\n el = el->next;\n }\n \n pos = 0;\n for(;;) {\n if (el == &n->u.dir.de_list)\n break;\n de = list_entry(el, FSDirEntry, link);\n name_len = strlen(de->name);\n len = 13 + 8 + 1 + 2 + name_len;\n if ((pos + len) > count)\n break;\n offset++;\n n1 = de->inode;\n if (n1->type == FT_DIR)\n type = P9_QTDIR;\n else if (n1->type == FT_LNK)\n type = P9_QTSYMLINK;\n else\n type = P9_QTFILE;\n buf[pos++] = type;\n put_le32(buf + pos, 0); /* version */\n pos += 4;\n put_le64(buf + pos, n1->inode_num);\n pos += 8;\n put_le64(buf + pos, offset);\n pos += 8;\n buf[pos++] = n1->type;\n put_le16(buf + pos, name_len);\n pos += 2;\n memcpy(buf + pos, de->name, name_len);\n pos += name_len;\n el = el->next;\n }\n return pos;\n}\n\nstatic int fs_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n FSINode *n = f->inode;\n uint64_t count1;\n\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n if ((f->open_flags & P9_O_NOACCESS) == P9_O_WRONLY)\n return -P9_EIO;\n if (n->u.reg.is_fscmd)\n return fs_cmd_read(fs, f, offset, buf, count);\n if (offset >= n->u.reg.size)\n return 0;\n count1 = n->u.reg.size - offset;\n if (count1 < count)\n count = count1;\n file_buffer_read(&n->u.reg.fbuf, offset, buf, count);\n return count;\n}\n\nstatic int fs_truncate(FSDevice *fs1, FSINode *n, uint64_t size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n intptr_t diff, diff_blocks;\n size_t new_allocated_size;\n \n if (n->type != FT_REG)\n return -P9_EINVAL;\n if (size > UINTPTR_MAX)\n return -P9_ENOSPC;\n diff = size - n->u.reg.size;\n if (diff == 0)\n return 0;\n diff_blocks = to_blocks(fs, size) - to_blocks(fs, n->u.reg.size);\n /* currently cannot resize while loading */\n switch(n->u.reg.state) {\n case REG_STATE_LOADING:\n return -P9_EIO;\n case REG_STATE_UNLOADED:\n if (size == 0) {\n /* now local content */\n n->u.reg.state = REG_STATE_LOCAL;\n }\n break;\n case REG_STATE_LOADED:\n case REG_STATE_LOCAL:\n if (diff > 0) {\n if ((fs->fs_blocks + diff_blocks) > fs->fs_max_blocks)\n return -P9_ENOSPC;\n if (size > n->u.reg.fbuf.allocated_size) {\n new_allocated_size = n->u.reg.fbuf.allocated_size * 5 / 4;\n if (size > new_allocated_size)\n new_allocated_size = size;\n if (file_buffer_resize(&n->u.reg.fbuf, new_allocated_size) < 0)\n return -P9_ENOSPC;\n }\n file_buffer_set(&n->u.reg.fbuf, n->u.reg.size, 0, diff);\n } else {\n new_allocated_size = n->u.reg.fbuf.allocated_size * 4 / 5;\n if (size <= new_allocated_size) {\n if (file_buffer_resize(&n->u.reg.fbuf, new_allocated_size) < 0)\n return -P9_ENOSPC;\n }\n }\n /* file is modified, so it is now local */\n if (n->u.reg.state == REG_STATE_LOADED) {\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n n->u.reg.state = REG_STATE_LOCAL;\n }\n break;\n default:\n abort();\n }\n fs->fs_blocks += diff_blocks;\n assert(fs->fs_blocks >= 0);\n n->u.reg.size = size;\n return 0;\n}\n\nstatic int fs_write(FSDevice *fs1, FSFile *f, uint64_t offset,\n const uint8_t *buf, int count)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n = f->inode;\n uint64_t end;\n int err;\n \n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n if ((f->open_flags & P9_O_NOACCESS) == P9_O_RDONLY)\n return -P9_EIO;\n if (count == 0)\n return 0;\n if (n->u.reg.is_fscmd) {\n return fs_cmd_write(fs1, f, offset, buf, count);\n }\n end = offset + count;\n if (end > n->u.reg.size) {\n err = fs_truncate(fs1, n, end);\n if (err)\n return err;\n }\n inode_update_mtime(fs1, n);\n /* file is modified, so it is now local */\n if (n->u.reg.state == REG_STATE_LOADED) {\n list_del(&n->u.reg.link);\n fs->inode_cache_size -= n->u.reg.size;\n assert(fs->inode_cache_size >= 0);\n n->u.reg.state = REG_STATE_LOCAL;\n }\n file_buffer_write(&n->u.reg.fbuf, offset, buf, count);\n return count;\n}\n\nstatic void fs_close(FSDevice *fs, FSFile *f)\n{\n if (f->is_opened) {\n f->is_opened = FALSE;\n }\n if (f->req)\n fs_cmd_close(fs, f);\n}\n\nstatic int fs_stat(FSDevice *fs1, FSFile *f, FSStat *st)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSINode *n = f->inode;\n\n inode_to_qid(&st->qid, n);\n st->st_mode = n->mode | (n->type << 12);\n st->st_uid = n->uid;\n st->st_gid = n->gid;\n st->st_nlink = n->refcount;\n if (n->type == FT_BLK || n->type == FT_CHR) {\n /* XXX: check */\n st->st_rdev = (n->u.dev.major << 8) | n->u.dev.minor;\n } else {\n st->st_rdev = 0;\n }\n st->st_blksize = fs->block_size;\n if (n->type == FT_REG) {\n st->st_size = n->u.reg.size;\n } else if (n->type == FT_LNK) {\n st->st_size = strlen(n->u.symlink.name);\n } else if (n->type == FT_DIR) {\n st->st_size = n->u.dir.size;\n } else {\n st->st_size = 0;\n }\n /* in 512 byte blocks */\n st->st_blocks = to_blocks(fs, st->st_size) << (fs->block_size_log2 - 9);\n \n /* Note: atime is not supported */\n st->st_atime_sec = n->mtime_sec;\n st->st_atime_nsec = n->mtime_nsec;\n st->st_mtime_sec = n->mtime_sec;\n st->st_mtime_nsec = n->mtime_nsec;\n st->st_ctime_sec = n->ctime_sec;\n st->st_ctime_nsec = n->ctime_nsec;\n return 0;\n}\n\nstatic int fs_setattr(FSDevice *fs1, FSFile *f, uint32_t mask,\n uint32_t mode, uint32_t uid, uint32_t gid,\n uint64_t size, uint64_t atime_sec, uint64_t atime_nsec,\n uint64_t mtime_sec, uint64_t mtime_nsec)\n{\n FSINode *n = f->inode;\n int ret;\n \n if (mask & P9_SETATTR_MODE) {\n n->mode = mode;\n }\n if (mask & P9_SETATTR_UID) {\n n->uid = uid;\n }\n if (mask & P9_SETATTR_GID) {\n n->gid = gid;\n }\n if (mask & P9_SETATTR_SIZE) {\n ret = fs_truncate(fs1, n, size);\n if (ret)\n return ret;\n }\n if (mask & P9_SETATTR_MTIME) {\n if (mask & P9_SETATTR_MTIME_SET) {\n n->mtime_sec = mtime_sec;\n n->mtime_nsec = mtime_nsec;\n } else {\n inode_update_mtime(fs1, n);\n }\n }\n if (mask & P9_SETATTR_CTIME) {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n n->ctime_sec = tv.tv_sec;\n n->ctime_nsec = tv.tv_usec * 1000;\n }\n return 0;\n}\n\nstatic int fs_link(FSDevice *fs, FSFile *df, FSFile *f, const char *name)\n{\n FSINode *n = df->inode;\n \n if (f->inode->type == FT_DIR)\n return -P9_EPERM;\n if (inode_search(n, name))\n return -P9_EEXIST;\n inode_dir_add(fs, n, name, inode_incref(fs, f->inode));\n return 0;\n}\n\nstatic int fs_symlink(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, const char *symgt, uint32_t gid)\n{\n FSINode *n1, *n = f->inode;\n \n if (inode_search(n, name))\n return -P9_EEXIST;\n\n n1 = inode_new(fs, FT_LNK, 0777, f->uid, gid);\n n1->u.symlink.name = strdup(symgt);\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\nstatic int fs_mknod(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, uint32_t mode, uint32_t major,\n uint32_t minor, uint32_t gid)\n{\n int type;\n FSINode *n1, *n = f->inode;\n\n type = (mode & P9_S_IFMT) >> 12;\n /* XXX: add FT_DIR support */\n if (type != FT_FIFO && type != FT_CHR && type != FT_BLK &&\n type != FT_REG && type != FT_SOCK)\n return -P9_EINVAL;\n if (inode_search(n, name))\n return -P9_EEXIST;\n n1 = inode_new(fs, type, mode, f->uid, gid);\n if (type == FT_CHR || type == FT_BLK) {\n n1->u.dev.major = major;\n n1->u.dev.minor = minor;\n }\n inode_dir_add(fs, n, name, n1);\n inode_to_qid(qid, n1);\n return 0;\n}\n\nstatic int fs_readlink(FSDevice *fs, char *buf, int buf_size, FSFile *f)\n{\n FSINode *n = f->inode;\n int len;\n if (n->type != FT_LNK)\n return -P9_EIO;\n len = min_int(strlen(n->u.symlink.name), buf_size - 1);\n memcpy(buf, n->u.symlink.name, len);\n buf[len] = '\\0';\n return 0;\n}\n\nstatic int fs_renameat(FSDevice *fs, FSFile *f, const char *name, \n FSFile *new_f, const char *new_name)\n{\n FSDirEntry *de, *de1;\n FSINode *n1;\n \n de = inode_search(f->inode, name);\n if (!de)\n return -P9_ENOENT;\n de1 = inode_search(new_f->inode, new_name);\n n1 = NULL;\n if (de1) {\n n1 = de1->inode;\n if (n1->type == FT_DIR)\n return -P9_EEXIST; /* XXX: handle the case */\n inode_dirent_delete_no_decref(fs, new_f->inode, de1);\n }\n inode_dir_add(fs, new_f->inode, new_name, inode_incref(fs, de->inode));\n inode_dirent_delete(fs, f->inode, de);\n if (n1)\n inode_decref(fs, n1);\n return 0;\n}\n\nstatic int fs_unlinkat(FSDevice *fs, FSFile *f, const char *name)\n{\n FSDirEntry *de;\n FSINode *n;\n\n if (!strcmp(name, \".\") || !strcmp(name, \"..\"))\n return -P9_ENOENT;\n de = inode_search(f->inode, name);\n if (!de)\n return -P9_ENOENT;\n n = de->inode;\n if (n->type == FT_DIR) {\n if (!is_empty_dir(fs, n))\n return -P9_ENOTEMPTY;\n flush_dir(fs, n);\n }\n inode_dirent_delete(fs, f->inode, de);\n return 0;\n}\n\nstatic int fs_lock(FSDevice *fs, FSFile *f, const FSLock *lock)\n{\n FSINode *n = f->inode;\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n /* XXX: implement it */\n return P9_LOCK_SUCCESS;\n}\n\nstatic int fs_getlock(FSDevice *fs, FSFile *f, FSLock *lock)\n{\n FSINode *n = f->inode;\n if (!f->is_opened)\n return -P9_EPROTO;\n if (n->type != FT_REG)\n return -P9_EIO;\n /* XXX: implement it */\n return 0;\n}\n\n/* XXX: only used with file lists, so not all the data is released */\nstatic void fs_mem_end(FSDevice *fs1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el, *el1, *el2, *el3;\n FSINode *n;\n FSDirEntry *de;\n\n list_for_each_safe(el, el1, &fs->inode_list) {\n n = list_entry(el, FSINode, link);\n n->refcount = 0;\n if (n->type == FT_DIR) {\n list_for_each_safe(el2, el3, &n->u.dir.de_list) {\n de = list_entry(el2, FSDirEntry, link);\n list_del(&de->link);\n free(de);\n }\n init_list_head(&n->u.dir.de_list);\n }\n inode_free(fs1, n);\n }\n assert(list_empty(&fs->inode_cache_list));\n free(fs->import_dir);\n}\n\nFSDevice *fs_mem_init(void)\n{\n FSDeviceMem *fs;\n FSDevice *fs1;\n FSINode *n;\n\n fs = mallocz(sizeof(*fs));\n fs1 = &fs->common;\n\n fs->common.fs_end = fs_mem_end;\n fs->common.fs_delete = fs_delete;\n fs->common.fs_statfs = fs_statfs;\n fs->common.fs_attach = fs_attach;\n fs->common.fs_walk = fs_walk;\n fs->common.fs_mkdir = fs_mkdir;\n fs->common.fs_open = fs_open;\n fs->common.fs_create = fs_create;\n fs->common.fs_stat = fs_stat;\n fs->common.fs_setattr = fs_setattr;\n fs->common.fs_close = fs_close;\n fs->common.fs_readdir = fs_readdir;\n fs->common.fs_read = fs_read;\n fs->common.fs_write = fs_write;\n fs->common.fs_link = fs_link;\n fs->common.fs_symlink = fs_symlink;\n fs->common.fs_mknod = fs_mknod;\n fs->common.fs_readlink = fs_readlink;\n fs->common.fs_renameat = fs_renameat;\n fs->common.fs_unlinkat = fs_unlinkat;\n fs->common.fs_lock = fs_lock;\n fs->common.fs_getlock = fs_getlock;\n\n init_list_head(&fs->inode_list);\n fs->inode_num_alloc = 1;\n fs->block_size_log2 = FS_BLOCK_SIZE_LOG2;\n fs->block_size = 1 << fs->block_size_log2;\n fs->inode_limit = 1 << 20; /* arbitrary */\n fs->fs_max_blocks = 1 << (30 - fs->block_size_log2); /* arbitrary */\n\n init_list_head(&fs->inode_cache_list);\n fs->inode_cache_size_limit = DEFAULT_INODE_CACHE_SIZE;\n\n init_list_head(&fs->preload_list);\n init_list_head(&fs->preload_archive_list);\n\n init_list_head(&fs->base_url_list);\n\n /* create the root inode */\n n = inode_new(fs1, FT_DIR, 0777, 0, 0);\n inode_dir_add(fs1, n, \".\", inode_incref(fs1, n));\n inode_dir_add(fs1, n, \"..\", inode_incref(fs1, n));\n fs->root_inode = n;\n\n return (FSDevice *)fs;\n}\n\nstatic BOOL fs_is_net(FSDevice *fs)\n{\n return (fs->fs_end == fs_mem_end);\n}\n\nstatic FSBaseURL *fs_find_base_url(FSDevice *fs1,\n const char *base_url_id)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n struct list_head *el;\n FSBaseURL *bu;\n \n list_for_each(el, &fs->base_url_list) {\n bu = list_entry(el, FSBaseURL, link);\n if (!strcmp(bu->base_url_id, base_url_id))\n return bu;\n }\n return NULL;\n}\n\nstatic void fs_base_url_decref(FSDevice *fs, FSBaseURL *bu)\n{\n assert(bu->ref_count >= 1);\n if (--bu->ref_count == 0) {\n free(bu->base_url_id);\n free(bu->url);\n free(bu->user);\n free(bu->password);\n list_del(&bu->link);\n free(bu);\n }\n}\n\nstatic FSBaseURL *fs_net_set_base_url(FSDevice *fs1,\n const char *base_url_id,\n const char *url,\n const char *user, const char *password,\n AES_KEY *aes_state)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSBaseURL *bu;\n \n assert(fs_is_net(fs1));\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu) {\n bu = mallocz(sizeof(*bu));\n bu->base_url_id = strdup(base_url_id);\n bu->ref_count = 1;\n list_add_tail(&bu->link, &fs->base_url_list);\n } else {\n free(bu->url);\n free(bu->user);\n free(bu->password);\n }\n\n bu->url = strdup(url);\n if (user)\n bu->user = strdup(user);\n else\n bu->user = NULL;\n if (password)\n bu->password = strdup(password);\n else\n bu->password = NULL;\n if (aes_state) {\n bu->encrypted = TRUE;\n bu->aes_state = *aes_state;\n } else {\n bu->encrypted = FALSE;\n }\n return bu;\n}\n\nstatic int fs_net_reset_base_url(FSDevice *fs1,\n const char *base_url_id)\n{\n FSBaseURL *bu;\n \n assert(fs_is_net(fs1));\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu)\n return -P9_ENOENT;\n fs_base_url_decref(fs1, bu);\n return 0;\n}\n\nstatic void fs_net_set_fs_max_size(FSDevice *fs1, uint64_t fs_max_size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n\n assert(fs_is_net(fs1));\n fs->fs_max_blocks = to_blocks(fs, fs_max_size);\n}\n\nstatic int fs_net_set_url(FSDevice *fs1, FSINode *n,\n const char *base_url_id, FSFileID file_id, uint64_t size)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n FSBaseURL *bu;\n\n assert(fs_is_net(fs1));\n\n bu = fs_find_base_url(fs1, base_url_id);\n if (!bu)\n return -P9_ENOENT;\n\n /* XXX: could accept more state */\n if (n->type != FT_REG ||\n n->u.reg.state != REG_STATE_LOCAL ||\n n->u.reg.fbuf.allocated_size != 0)\n return -P9_EIO;\n \n if (size > 0) {\n n->u.reg.state = REG_STATE_UNLOADED;\n n->u.reg.base_url = bu;\n bu->ref_count++;\n n->u.reg.size = size;\n fs->fs_blocks += to_blocks(fs, size);\n n->u.reg.file_id = file_id;\n }\n return 0;\n}\n\n#ifdef DUMP_CACHE_LOAD\n\n#include \"json.h\"\n\n#define ARCHIVE_SIZE_MAX (4 << 20)\n\nstatic void fs_dump_add_file(struct list_head *head, const char *name)\n{\n PreloadFile *pf;\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(name);\n list_add_tail(&pf->link, head);\n}\n\nstatic PreloadFile *fs_dump_find_file(struct list_head *head, const char *name)\n{\n PreloadFile *pf;\n struct list_head *el;\n list_for_each(el, head) {\n pf = list_entry(el, PreloadFile, link);\n if (!strcmp(pf->name, name))\n return pf;\n }\n return NULL;\n}\n\nstatic void dump_close_archive(FSDevice *fs1)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (fs->dump_archive_file) {\n fclose(fs->dump_archive_file);\n }\n fs->dump_archive_file = NULL;\n fs->dump_archive_size = 0;\n}\n\nstatic void dump_loaded_file(FSDevice *fs1, FSINode *n)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char filename[1024];\n const char *fname, *p;\n \n if (!fs->dump_cache_load || !n->u.reg.filename)\n return;\n fname = n->u.reg.filename;\n \n if (fs_dump_find_file(&fs->dump_preload_list, fname)) {\n dump_close_archive(fs1);\n p = strrchr(fname, '/');\n if (!p)\n p = fname;\n else\n p++;\n free(fs->dump_archive_name);\n fs->dump_archive_name = strdup(p);\n fs->dump_started = TRUE;\n fs->dump_archive_num = 0;\n\n fprintf(fs->dump_preload_file, \"\\n%s :\\n\", fname);\n }\n if (!fs->dump_started)\n return;\n \n if (!fs->dump_archive_file) {\n snprintf(filename, sizeof(filename), \"%s/%s%d\",\n fs->dump_preload_dir, fs->dump_archive_name,\n fs->dump_archive_num);\n fs->dump_archive_file = fopen(filename, \"wb\");\n if (!fs->dump_archive_file) {\n perror(filename);\n exit(1);\n }\n fprintf(fs->dump_preload_archive_file, \"\\n@.preload2/%s%d :\\n\",\n fs->dump_archive_name, fs->dump_archive_num);\n fprintf(fs->dump_preload_file, \" @.preload2/%s%d\\n\",\n fs->dump_archive_name, fs->dump_archive_num);\n fflush(fs->dump_preload_file);\n fs->dump_archive_num++;\n }\n\n if (n->u.reg.size >= ARCHIVE_SIZE_MAX) {\n /* exclude large files from archive */\n /* add indicative size */\n fprintf(fs->dump_preload_file, \" %s %\" PRId64 \"\\n\",\n fname, n->u.reg.size);\n fflush(fs->dump_preload_file);\n } else {\n fprintf(fs->dump_preload_archive_file, \" %s %\" PRId64 \" %\" PRIx64 \"\\n\",\n n->u.reg.filename, n->u.reg.size, n->u.reg.file_id);\n fflush(fs->dump_preload_archive_file);\n fwrite(n->u.reg.fbuf.data, 1, n->u.reg.size, fs->dump_archive_file);\n fflush(fs->dump_archive_file);\n fs->dump_archive_size += n->u.reg.size;\n if (fs->dump_archive_size >= ARCHIVE_SIZE_MAX) {\n dump_close_archive(fs1);\n }\n }\n}\n\nstatic JSONValue json_load(const char *filename)\n{\n FILE *f;\n JSONValue val;\n size_t size;\n char *buf;\n \n f = fopen(filename, \"rb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n size = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = malloc(size + 1);\n fread(buf, 1, size, f);\n fclose(f);\n val = json_parse_value_len(buf, size);\n free(buf);\n return val;\n}\n\nvoid fs_dump_cache_load(FSDevice *fs1, const char *cfg_filename)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n JSONValue cfg, val, array;\n char *fname;\n const char *preload_dir, *name;\n int i;\n \n if (!fs_is_net(fs1))\n return;\n cfg = json_load(cfg_filename);\n if (json_is_error(cfg)) {\n fprintf(stderr, \"%s\\n\", json_get_error(cfg));\n exit(1);\n }\n\n val = json_object_get(cfg, \"preload_dir\");\n if (json_is_undefined(cfg)) {\n config_error:\n exit(1);\n }\n preload_dir = json_get_str(val);\n if (!preload_dir) {\n fprintf(stderr, \"expecting preload_filename\\n\");\n goto config_error;\n }\n fs->dump_preload_dir = strdup(preload_dir);\n \n init_list_head(&fs->dump_preload_list);\n init_list_head(&fs->dump_exclude_list);\n\n array = json_object_get(cfg, \"preload\");\n if (array.type != JSON_ARRAY) {\n fprintf(stderr, \"expecting preload array\\n\");\n goto config_error;\n }\n for(i = 0; i < array.u.array->len; i++) {\n val = json_array_get(array, i);\n name = json_get_str(val);\n if (!name) {\n fprintf(stderr, \"expecting a string\\n\");\n goto config_error;\n }\n fs_dump_add_file(&fs->dump_preload_list, name);\n }\n json_free(cfg);\n\n fname = compose_path(fs->dump_preload_dir, \"preload.txt\");\n fs->dump_preload_file = fopen(fname, \"w\");\n if (!fs->dump_preload_file) {\n perror(fname);\n exit(1);\n }\n free(fname);\n\n fname = compose_path(fs->dump_preload_dir, \"preload_archive.txt\");\n fs->dump_preload_archive_file = fopen(fname, \"w\");\n if (!fs->dump_preload_archive_file) {\n perror(fname);\n exit(1);\n }\n free(fname);\n\n fs->dump_cache_load = TRUE;\n}\n#else\nvoid fs_dump_cache_load(FSDevice *fs1, const char *cfg_filename)\n{\n}\n#endif\n\n/***********************************************/\n/* file list processing */\n\nstatic int filelist_load_rec(FSDevice *fs1, const char **pp, FSINode *dir,\n const char *path)\n{\n // FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char fname[1024], lname[1024];\n int ret;\n const char *p;\n FSINodeTypeEnum type;\n uint32_t mode, uid, gid;\n uint64_t size;\n FSINode *n;\n\n p = *pp;\n for(;;) {\n /* skip comments or empty lines */\n if (*p == '\\0')\n break;\n if (*p == '#') {\n skip_line(&p);\n continue;\n }\n /* end of directory */\n if (*p == '.') {\n p++;\n skip_line(&p);\n break;\n }\n if (parse_uint32_base(&mode, &p, 8) < 0) {\n fprintf(stderr, \"invalid mode\\n\");\n return -1;\n }\n type = mode >> 12;\n mode &= 0xfff;\n \n if (parse_uint32(&uid, &p) < 0) {\n fprintf(stderr, \"invalid uid\\n\");\n return -1;\n }\n\n if (parse_uint32(&gid, &p) < 0) {\n fprintf(stderr, \"invalid gid\\n\");\n return -1;\n }\n\n n = inode_new(fs1, type, mode, uid, gid);\n \n size = 0;\n switch(type) {\n case FT_CHR:\n case FT_BLK:\n if (parse_uint32(&n->u.dev.major, &p) < 0) {\n fprintf(stderr, \"invalid major\\n\");\n return -1;\n }\n if (parse_uint32(&n->u.dev.minor, &p) < 0) {\n fprintf(stderr, \"invalid minor\\n\");\n return -1;\n }\n break;\n case FT_REG:\n if (parse_uint64(&size, &p) < 0) {\n fprintf(stderr, \"invalid size\\n\");\n return -1;\n }\n break;\n case FT_DIR:\n inode_dir_add(fs1, n, \".\", inode_incref(fs1, n));\n inode_dir_add(fs1, n, \"..\", inode_incref(fs1, dir));\n break;\n default:\n break;\n }\n \n /* modification time */\n if (parse_time(&n->mtime_sec, &n->mtime_nsec, &p) < 0) {\n fprintf(stderr, \"invalid mtime\\n\");\n return -1;\n }\n\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return -1;\n }\n inode_dir_add(fs1, dir, fname, n);\n \n if (type == FT_LNK) {\n if (parse_fname(lname, sizeof(lname), &p) < 0) {\n fprintf(stderr, \"invalid symlink name\\n\");\n return -1;\n }\n n->u.symlink.name = strdup(lname);\n } else if (type == FT_REG && size > 0) {\n FSFileID file_id;\n if (parse_file_id(&file_id, &p) < 0) {\n fprintf(stderr, \"invalid file id\\n\");\n return -1;\n }\n fs_net_set_url(fs1, n, \"/\", file_id, size);\n#ifdef DUMP_CACHE_LOAD\n {\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n if (fs->dump_cache_load\n#ifdef DEBUG_CACHE\n || 1\n#endif\n ) {\n n->u.reg.filename = compose_path(path, fname);\n } else {\n n->u.reg.filename = NULL;\n }\n }\n#endif\n }\n\n skip_line(&p);\n \n if (type == FT_DIR) {\n char *path1;\n path1 = compose_path(path, fname);\n ret = filelist_load_rec(fs1, &p, n, path1);\n free(path1);\n if (ret)\n return ret;\n }\n }\n *pp = p;\n return 0;\n}\n\nstatic int filelist_load(FSDevice *fs1, const char *str)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n int ret;\n const char *p;\n \n if (parse_tag_version(str) != 1)\n return -1;\n p = skip_header(str);\n if (!p)\n return -1;\n ret = filelist_load_rec(fs1, &p, fs->root_inode, \"\");\n return ret;\n}\n\n/************************************************************/\n/* FS init from network */\n\nstatic void __attribute__((format(printf, 1, 2))) fatal_error(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n fprintf(stderr, \"Error: \");\n vfprintf(stderr, fmt, ap);\n fprintf(stderr, \"\\n\");\n va_end(ap);\n exit(1);\n}\n\nstatic void fs_create_cmd(FSDevice *fs)\n{\n FSFile *root_fd;\n FSQID qid;\n FSINode *n;\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\"));\n assert(!fs->fs_create(fs, &qid, root_fd, FSCMD_NAME, P9_O_RDWR | P9_O_TRUNC,\n 0666, 0));\n n = root_fd->inode;\n n->u.reg.is_fscmd = TRUE;\n fs->fs_delete(fs, root_fd);\n}\n\ntypedef struct {\n FSDevice *fs;\n char *url;\n void (*start_cb)(void *opaque);\n void *start_opaque;\n \n FSFile *root_fd;\n FSFile *fd;\n int file_index;\n \n} FSNetInitState;\n\nstatic void fs_initial_sync(FSDevice *fs,\n const char *url, void (*start_cb)(void *opaque),\n void *start_opaque);\nstatic void head_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque);\nstatic void filelist_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque);\nstatic void kernel_load_cb(FSDevice *fs, FSQID *qid, int err,\n void *opaque);\nstatic int preload_parse(FSDevice *fs, const char *fname, BOOL is_new);\n\n#ifdef EMSCRIPTEN\nstatic FSDevice *fs_import_fs;\n#endif\n\n#define DEFAULT_IMPORT_FILE_PATH \"/tmp\"\n\nFSDevice *fs_net_init(const char *url, void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n FSDevice *fs;\n FSDeviceMem *fs1;\n \n fs_wget_init();\n \n fs = fs_mem_init();\n#ifdef EMSCRIPTEN\n if (!fs_import_fs)\n fs_import_fs = fs;\n#endif\n fs1 = (FSDeviceMem *)fs;\n fs1->import_dir = strdup(DEFAULT_IMPORT_FILE_PATH);\n \n fs_create_cmd(fs);\n\n if (url) {\n fs_initial_sync(fs, url, start_cb, start_opaque);\n }\n return fs;\n}\n\nstatic void fs_initial_sync(FSDevice *fs,\n const char *url, void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n FSNetInitState *s;\n FSFile *head_fd;\n FSQID qid;\n char *head_url;\n char buf[128];\n struct timeval tv;\n \n s = mallocz(sizeof(*s));\n s->fs = fs;\n s->url = strdup(url);\n s->start_cb = start_cb;\n s->start_opaque = start_opaque;\n assert(!fs->fs_attach(fs, &s->root_fd, &qid, 0, \"\", \"\"));\n \n /* avoid using cached version */\n gettimeofday(&tv, NULL);\n snprintf(buf, sizeof(buf), HEAD_FILENAME \"?nocache=%\" PRId64,\n (int64_t)tv.tv_sec * 1000000 + tv.tv_usec);\n head_url = compose_url(s->url, buf);\n head_fd = fs_dup(fs, s->root_fd);\n assert(!fs->fs_create(fs, &qid, head_fd, \".head\",\n P9_O_RDWR | P9_O_TRUNC, 0644, 0));\n fs_wget_file2(fs, head_fd, head_url, NULL, NULL, NULL, 0,\n head_loaded, s, NULL);\n free(head_url);\n}\n\nstatic void head_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque)\n{\n FSNetInitState *s = opaque;\n char *buf, *root_url, *url;\n char fname[FILEID_SIZE_MAX];\n FSFileID root_id;\n FSFile *new_filelist_fd;\n FSQID qid;\n uint64_t fs_max_size;\n \n if (size < 0)\n fatal_error(\"could not load 'head' file (HTTP error=%d)\", -(int)size);\n \n buf = malloc(size + 1);\n fs->fs_read(fs, f, 0, (uint8_t *)buf, size);\n buf[size] = '\\0';\n fs->fs_delete(fs, f);\n fs->fs_unlinkat(fs, s->root_fd, \".head\");\n\n if (parse_tag_version(buf) != 1)\n fatal_error(\"invalid head version\");\n\n if (parse_tag_file_id(&root_id, buf, \"RootID\") < 0)\n fatal_error(\"expected RootID tag\");\n\n if (parse_tag_uint64(&fs_max_size, buf, \"FSMaxSize\") == 0 &&\n fs_max_size >= ((uint64_t)1 << 20)) {\n fs_net_set_fs_max_size(fs, fs_max_size);\n }\n \n /* set the Root URL in the filesystem */\n root_url = compose_url(s->url, ROOT_FILENAME);\n fs_net_set_base_url(fs, \"/\", root_url, NULL, NULL, NULL);\n \n new_filelist_fd = fs_dup(fs, s->root_fd);\n assert(!fs->fs_create(fs, &qid, new_filelist_fd, \".filelist.txt\",\n P9_O_RDWR | P9_O_TRUNC, 0644, 0));\n\n file_id_to_filename(fname, root_id);\n url = compose_url(root_url, fname);\n fs_wget_file2(fs, new_filelist_fd, url, NULL, NULL, NULL, 0,\n filelist_loaded, s, NULL);\n free(root_url);\n free(url);\n}\n\nstatic void filelist_loaded(FSDevice *fs, FSFile *f, int64_t size, void *opaque)\n{\n FSNetInitState *s = opaque;\n uint8_t *buf;\n\n if (size < 0)\n fatal_error(\"could not load file list (HTTP error=%d)\", -(int)size);\n \n buf = malloc(size + 1);\n fs->fs_read(fs, f, 0, buf, size);\n buf[size] = '\\0';\n fs->fs_delete(fs, f);\n fs->fs_unlinkat(fs, s->root_fd, \".filelist.txt\");\n \n if (filelist_load(fs, (char *)buf) != 0)\n fatal_error(\"error while parsing file list\");\n\n /* try to load the kernel and the preload file */\n s->file_index = 0;\n kernel_load_cb(fs, NULL, 0, s);\n}\n\n\n#define FILE_LOAD_COUNT 2\n\nstatic const char *kernel_file_list[FILE_LOAD_COUNT] = {\n \".preload\",\n \".preload2/preload.txt\",\n};\n\nstatic void kernel_load_cb(FSDevice *fs, FSQID *qid1, int err,\n void *opaque)\n{\n FSNetInitState *s = opaque;\n FSQID qid;\n\n#ifdef DUMP_CACHE_LOAD\n /* disable preloading if dumping cache load */\n if (((FSDeviceMem *)fs)->dump_cache_load)\n return;\n#endif\n\n if (s->fd) {\n fs->fs_delete(fs, s->fd);\n s->fd = NULL;\n }\n \n if (s->file_index >= FILE_LOAD_COUNT) {\n /* all files are loaded */\n if (preload_parse(fs, \".preload2/preload.txt\", TRUE) < 0) { \n preload_parse(fs, \".preload\", FALSE);\n }\n fs->fs_delete(fs, s->root_fd);\n if (s->start_cb)\n s->start_cb(s->start_opaque);\n free(s);\n } else {\n s->fd = fs_walk_path(fs, s->root_fd, kernel_file_list[s->file_index++]);\n if (!s->fd)\n goto done;\n err = fs->fs_open(fs, &qid, s->fd, P9_O_RDONLY, kernel_load_cb, s);\n if (err <= 0) {\n done:\n kernel_load_cb(fs, NULL, 0, s);\n }\n }\n}\n\nstatic void preload_parse_str_old(FSDevice *fs1, const char *p)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n char fname[1024];\n PreloadEntry *pe;\n PreloadFile *pf;\n FSINode *n;\n\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\n') {\n p++;\n continue;\n }\n if (*p == '\\0')\n break;\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n // printf(\"preload file='%s\\n\", fname);\n n = inode_search_path(fs1, fname);\n if (!n || n->type != FT_REG || n->u.reg.state == REG_STATE_LOCAL) {\n fprintf(stderr, \"invalid preload file: '%s'\\n\", fname);\n while (*p != '\\n' && *p != '\\0')\n p++;\n } else {\n pe = mallocz(sizeof(*pe));\n pe->file_id = n->u.reg.file_id;\n init_list_head(&pe->file_list);\n list_add_tail(&pe->link, &fs->preload_list);\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\0' || *p == '\\n')\n break;\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n // printf(\" adding '%s'\\n\", fname);\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(fname);\n list_add_tail(&pf->link, &pe->file_list); \n }\n }\n }\n}\n\nstatic void preload_parse_str(FSDevice *fs1, const char *p)\n{\n FSDeviceMem *fs = (FSDeviceMem *)fs1;\n PreloadEntry *pe;\n PreloadArchive *pa;\n FSINode *n;\n BOOL is_archive;\n char fname[1024];\n \n pe = NULL;\n pa = NULL;\n for(;;) {\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\n') {\n pe = NULL;\n p++;\n continue;\n }\n if (*p == '#')\n continue; /* comment */\n if (*p == '\\0')\n break;\n\n is_archive = FALSE;\n if (*p == '@') {\n is_archive = TRUE;\n p++;\n }\n if (parse_fname(fname, sizeof(fname), &p) < 0) {\n fprintf(stderr, \"invalid filename\\n\");\n return;\n }\n while (isspace_nolf(*p))\n p++;\n if (*p == ':') {\n p++;\n // printf(\"preload file='%s' archive=%d\\n\", fname, is_archive);\n n = inode_search_path(fs1, fname);\n pe = NULL;\n pa = NULL;\n if (!n || n->type != FT_REG || n->u.reg.state == REG_STATE_LOCAL) {\n fprintf(stderr, \"invalid preload file: '%s'\\n\", fname);\n while (*p != '\\n' && *p != '\\0')\n p++;\n } else if (is_archive) {\n pa = mallocz(sizeof(*pa));\n pa->name = strdup(fname);\n init_list_head(&pa->file_list);\n list_add_tail(&pa->link, &fs->preload_archive_list);\n } else {\n pe = mallocz(sizeof(*pe));\n pe->file_id = n->u.reg.file_id;\n init_list_head(&pe->file_list);\n list_add_tail(&pe->link, &fs->preload_list);\n }\n } else {\n if (!pe && !pa) {\n fprintf(stderr, \"filename without target: %s\\n\", fname);\n return;\n }\n if (pa) {\n PreloadArchiveFile *paf;\n FSFileID file_id;\n uint64_t size;\n\n if (parse_uint64(&size, &p) < 0) {\n fprintf(stderr, \"invalid size\\n\");\n return;\n }\n\n if (parse_file_id(&file_id, &p) < 0) {\n fprintf(stderr, \"invalid file id\\n\");\n return;\n }\n\n paf = mallocz(sizeof(*paf));\n paf->name = strdup(fname);\n paf->file_id = file_id;\n paf->size = size;\n list_add_tail(&paf->link, &pa->file_list);\n } else {\n PreloadFile *pf;\n pf = mallocz(sizeof(*pf));\n pf->name = strdup(fname);\n pf->is_archive = is_archive;\n list_add_tail(&pf->link, &pe->file_list);\n }\n }\n /* skip the rest of the line */\n while (*p != '\\n' && *p != '\\0')\n p++;\n if (*p == '\\n')\n p++;\n }\n}\n\n", "suffix_code": "\n\n\n\n/************************************************************/\n/* FS user interface */\n\ntypedef struct CmdXHRState {\n FSFile *req_fd;\n FSFile *root_fd;\n FSFile *fd;\n FSFile *post_fd;\n AES_KEY aes_state;\n} CmdXHRState;\n\nstatic void fs_cmd_xhr_on_load(FSDevice *fs, FSFile *f, int64_t size,\n void *opaque);\n\nstatic int parse_hex_buf(uint8_t *buf, int buf_size, const char **pp)\n{\n char buf1[1024];\n int len;\n \n if (parse_fname(buf1, sizeof(buf1), pp) < 0)\n return -1;\n len = strlen(buf1);\n if ((len & 1) != 0)\n return -1;\n len >>= 1;\n if (len > buf_size)\n return -1;\n if (decode_hex(buf, buf1, len) < 0)\n return -1;\n return len;\n}\n\nstatic int fs_cmd_xhr(FSDevice *fs, FSFile *f,\n const char *p, uint32_t uid, uint32_t gid)\n{\n char url[1024], post_filename[1024], filename[1024];\n char user_buf[128], *user;\n char password_buf[128], *password;\n FSQID qid;\n FSFile *fd, *root_fd, *post_fd;\n uint64_t post_data_len;\n int err, aes_key_len;\n CmdXHRState *s;\n char *name;\n AES_KEY *paes_state;\n uint8_t aes_key[FS_KEY_LEN];\n uint32_t flags;\n FSCMDRequest *req;\n\n /* a request is already done or in progress */\n if (f->req != NULL)\n return -P9_EIO;\n\n if (parse_fname(url, sizeof(url), &p) < 0)\n goto fail;\n if (parse_fname(user_buf, sizeof(user_buf), &p) < 0)\n goto fail;\n if (parse_fname(password_buf, sizeof(password_buf), &p) < 0)\n goto fail;\n if (parse_fname(post_filename, sizeof(post_filename), &p) < 0)\n goto fail;\n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n aes_key_len = parse_hex_buf(aes_key, FS_KEY_LEN, &p);\n if (aes_key_len < 0)\n goto fail;\n if (parse_uint32(&flags, &p) < 0)\n goto fail;\n if (aes_key_len != 0 && aes_key_len != FS_KEY_LEN)\n goto fail;\n\n if (user_buf[0] != '\\0')\n user = user_buf;\n else\n user = NULL;\n if (password_buf[0] != '\\0')\n password = password_buf;\n else\n password = NULL;\n\n // printf(\"url='%s' '%s' '%s' filename='%s'\\n\", url, user, password, filename);\n assert(!fs->fs_attach(fs, &root_fd, &qid, uid, \"\", \"\"));\n post_fd = NULL;\n\n fd = fs_walk_path1(fs, root_fd, filename, &name);\n if (!fd) {\n err = -P9_ENOENT;\n goto fail1;\n }\n /* XXX: until fs_create is fixed */\n fs->fs_unlinkat(fs, fd, name);\n\n err = fs->fs_create(fs, &qid, fd, name,\n P9_O_RDWR | P9_O_TRUNC, 0600, gid);\n if (err < 0) {\n goto fail1;\n }\n\n if (post_filename[0] != '\\0') {\n FSINode *n;\n \n post_fd = fs_walk_path(fs, root_fd, post_filename);\n if (!post_fd) {\n err = -P9_ENOENT;\n goto fail1;\n }\n err = fs->fs_open(fs, &qid, post_fd, P9_O_RDONLY, NULL, NULL);\n if (err < 0)\n goto fail1;\n n = post_fd->inode;\n assert(n->type == FT_REG && n->u.reg.state == REG_STATE_LOCAL);\n post_data_len = n->u.reg.size;\n } else {\n post_data_len = 0;\n }\n\n s = mallocz(sizeof(*s));\n s->root_fd = root_fd;\n s->fd = fd;\n s->post_fd = post_fd;\n if (aes_key_len != 0) {\n AES_set_decrypt_key(aes_key, FS_KEY_LEN * 8, &s->aes_state);\n paes_state = &s->aes_state;\n } else {\n paes_state = NULL;\n }\n\n req = mallocz(sizeof(*req));\n req->type = FS_CMD_XHR;\n req->reply_len = 0;\n req->xhr_state = s;\n s->req_fd = f;\n f->req = req;\n \n fs_wget_file2(fs, fd, url, user, password, post_fd, post_data_len,\n fs_cmd_xhr_on_load, s, paes_state);\n return 0;\n fail1:\n if (fd)\n fs->fs_delete(fs, fd);\n if (post_fd)\n fs->fs_delete(fs, post_fd);\n fs->fs_delete(fs, root_fd);\n return err;\n fail:\n return -P9_EIO;\n}\n\nstatic void fs_cmd_xhr_on_load(FSDevice *fs, FSFile *f, int64_t size,\n void *opaque)\n{\n CmdXHRState *s = opaque;\n FSCMDRequest *req;\n int ret;\n \n // printf(\"fs_cmd_xhr_on_load: size=%d\\n\", (int)size);\n\n if (s->fd)\n fs->fs_delete(fs, s->fd);\n if (s->post_fd)\n fs->fs_delete(fs, s->post_fd);\n fs->fs_delete(fs, s->root_fd);\n \n if (s->req_fd) {\n req = s->req_fd->req;\n if (size < 0) {\n ret = size;\n } else {\n ret = 0;\n }\n put_le32(req->reply_buf, ret);\n req->reply_len = sizeof(ret);\n req->xhr_state = NULL;\n }\n free(s);\n}\n\nstatic int fs_cmd_set_base_url(FSDevice *fs, const char *p)\n{\n // FSDeviceMem *fs1 = (FSDeviceMem *)fs;\n char url[1024], base_url_id[1024];\n char user_buf[128], *user;\n char password_buf[128], *password;\n AES_KEY aes_state, *paes_state;\n uint8_t aes_key[FS_KEY_LEN];\n int aes_key_len;\n \n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n if (parse_fname(url, sizeof(url), &p) < 0)\n goto fail;\n if (parse_fname(user_buf, sizeof(user_buf), &p) < 0)\n goto fail;\n if (parse_fname(password_buf, sizeof(password_buf), &p) < 0)\n goto fail;\n aes_key_len = parse_hex_buf(aes_key, FS_KEY_LEN, &p);\n if (aes_key_len < 0)\n goto fail;\n\n if (user_buf[0] != '\\0')\n user = user_buf;\n else\n user = NULL;\n if (password_buf[0] != '\\0')\n password = password_buf;\n else\n password = NULL;\n\n if (aes_key_len != 0) {\n if (aes_key_len != FS_KEY_LEN)\n goto fail;\n AES_set_decrypt_key(aes_key, FS_KEY_LEN * 8, &aes_state);\n paes_state = &aes_state;\n } else {\n paes_state = NULL;\n }\n\n fs_net_set_base_url(fs, base_url_id, url, user, password,\n paes_state);\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_reset_base_url(FSDevice *fs, const char *p)\n{\n char base_url_id[1024];\n \n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n fs_net_reset_base_url(fs, base_url_id);\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_set_url(FSDevice *fs, const char *p)\n{\n char base_url_id[1024];\n char filename[1024];\n FSFileID file_id;\n uint64_t size;\n FSINode *n;\n \n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n if (parse_fname(base_url_id, sizeof(base_url_id), &p) < 0)\n goto fail;\n if (parse_file_id(&file_id, &p) < 0)\n goto fail;\n if (parse_uint64(&size, &p) < 0)\n goto fail;\n \n n = inode_search_path(fs, filename);\n if (!n) {\n return -P9_ENOENT;\n }\n return fs_net_set_url(fs, n, base_url_id, file_id, size);\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_export_file(FSDevice *fs, const char *p)\n{\n char filename[1024];\n FSINode *n;\n const char *name;\n uint8_t *buf;\n \n if (parse_fname(filename, sizeof(filename), &p) < 0)\n goto fail;\n n = inode_search_path(fs, filename);\n if (!n)\n return -P9_ENOENT;\n if (n->type != FT_REG ||\n (n->u.reg.state != REG_STATE_LOCAL &&\n n->u.reg.state != REG_STATE_LOADED))\n goto fail;\n name = strrchr(filename, '/');\n if (name)\n name++;\n else\n name = filename;\n /* XXX: pass the buffer to JS to avoid the allocation */\n buf = malloc(n->u.reg.size);\n file_buffer_read(&n->u.reg.fbuf, 0, buf, n->u.reg.size);\n fs_export_file(name, buf, n->u.reg.size);\n free(buf);\n return 0;\n fail:\n return -P9_EIO;\n}\n\n/* PBKDF2 crypto acceleration */\nstatic int fs_cmd_pbkdf2(FSDevice *fs, FSFile *f, const char *p)\n{\n uint8_t pwd[1024];\n uint8_t salt[128];\n uint32_t iter, key_len;\n int pwd_len, salt_len;\n FSCMDRequest *req;\n \n /* a request is already done or in progress */\n if (f->req != NULL)\n return -P9_EIO;\n\n pwd_len = parse_hex_buf(pwd, sizeof(pwd), &p);\n if (pwd_len < 0)\n goto fail;\n salt_len = parse_hex_buf(salt, sizeof(salt), &p);\n if (pwd_len < 0)\n goto fail;\n if (parse_uint32(&iter, &p) < 0)\n goto fail;\n if (parse_uint32(&key_len, &p) < 0)\n goto fail;\n if (key_len > FS_CMD_REPLY_LEN_MAX ||\n key_len == 0)\n goto fail;\n req = mallocz(sizeof(*req));\n req->type = FS_CMD_PBKDF2;\n req->reply_len = key_len;\n pbkdf2_hmac_sha256(pwd, pwd_len, salt, salt_len, iter, key_len,\n req->reply_buf);\n f->req = req;\n return 0;\n fail:\n return -P9_EINVAL;\n}\n\nstatic int fs_cmd_set_import_dir(FSDevice *fs, FSFile *f, const char *p)\n{\n FSDeviceMem *fs1 = (FSDeviceMem *)fs;\n char filename[1024];\n\n if (parse_fname(filename, sizeof(filename), &p) < 0)\n return -P9_EINVAL;\n free(fs1->import_dir);\n fs1->import_dir = strdup(filename);\n return 0;\n}\n\nstatic int fs_cmd_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int buf_len)\n{\n char *buf1;\n const char *p;\n char cmd[64];\n int err;\n \n /* transform into a string */\n buf1 = malloc(buf_len + 1);\n memcpy(buf1, buf, buf_len);\n buf1[buf_len] = '\\0';\n \n err = 0;\n p = buf1;\n if (parse_fname(cmd, sizeof(cmd), &p) < 0)\n goto fail;\n if (!strcmp(cmd, \"xhr\")) {\n err = fs_cmd_xhr(fs, f, p, f->uid, 0);\n } else if (!strcmp(cmd, \"set_base_url\")) {\n err = fs_cmd_set_base_url(fs, p);\n } else if (!strcmp(cmd, \"reset_base_url\")) {\n err = fs_cmd_reset_base_url(fs, p);\n } else if (!strcmp(cmd, \"set_url\")) {\n err = fs_cmd_set_url(fs, p);\n } else if (!strcmp(cmd, \"export_file\")) {\n err = fs_cmd_export_file(fs, p);\n } else if (!strcmp(cmd, \"pbkdf2\")) {\n err = fs_cmd_pbkdf2(fs, f, p);\n } else if (!strcmp(cmd, \"set_import_dir\")) {\n err = fs_cmd_set_import_dir(fs, f, p);\n } else {\n printf(\"unknown command: '%s'\\n\", cmd);\n fail:\n err = -P9_EIO;\n }\n free(buf1);\n if (err == 0)\n return buf_len;\n else\n return err;\n}\n\nstatic int fs_cmd_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int buf_len)\n{\n FSCMDRequest *req;\n int l;\n \n req = f->req;\n if (!req)\n return -P9_EIO;\n l = min_int(req->reply_len, buf_len);\n memcpy(buf, req->reply_buf, l);\n return l;\n}\n\nstatic void fs_cmd_close(FSDevice *fs, FSFile *f)\n{\n FSCMDRequest *req;\n req = f->req;\n\n if (req) {\n if (req->xhr_state) {\n req->xhr_state->req_fd = NULL;\n }\n free(req);\n f->req = NULL;\n }\n}\n\n/* Create a .fscmd_pwd file to avoid passing the password thru the\n Linux command line */\nvoid fs_net_set_pwd(FSDevice *fs, const char *pwd)\n{\n FSFile *root_fd;\n FSQID qid;\n \n assert(fs_is_net(fs));\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\"));\n assert(!fs->fs_create(fs, &qid, root_fd, \".fscmd_pwd\", P9_O_RDWR | P9_O_TRUNC,\n 0600, 0));\n fs->fs_write(fs, root_fd, 0, (uint8_t *)pwd, strlen(pwd));\n fs->fs_delete(fs, root_fd);\n}\n\n/* external file import */\n\n#ifdef EMSCRIPTEN\n\nvoid fs_import_file(const char *filename, uint8_t *buf, int buf_len)\n{\n FSDevice *fs;\n FSDeviceMem *fs1;\n FSFile *fd, *root_fd;\n FSQID qid;\n \n // printf(\"importing file: %s len=%d\\n\", filename, buf_len);\n fs = fs_import_fs;\n if (!fs) {\n free(buf);\n return;\n }\n \n assert(!fs->fs_attach(fs, &root_fd, &qid, 1000, \"\", \"\"));\n fs1 = (FSDeviceMem *)fs;\n fd = fs_walk_path(fs, root_fd, fs1->import_dir);\n if (!fd)\n goto fail;\n fs_unlinkat(fs, root_fd, filename);\n if (fs->fs_create(fs, &qid, fd, filename, P9_O_RDWR | P9_O_TRUNC,\n 0600, 0) < 0)\n goto fail;\n fs->fs_write(fs, fd, 0, buf, buf_len);\n fail:\n if (fd)\n fs->fs_delete(fs, fd);\n if (root_fd)\n fs->fs_delete(fs, root_fd);\n free(buf);\n}\n\n#else\n\nvoid fs_export_file(const char *filename,\n const uint8_t *buf, int buf_len)\n{\n}\n\n#endif\n", "middle_code": "static int preload_parse(FSDevice *fs, const char *fname, BOOL is_new)\n{\n FSINode *n;\n char *buf;\n size_t size;\n n = inode_search_path(fs, fname);\n if (!n || n->type != FT_REG || n->u.reg.state != REG_STATE_LOADED)\n return -1;\n size = n->u.reg.size;\n buf = malloc(size + 1);\n file_buffer_read(&n->u.reg.fbuf, 0, (uint8_t *)buf, size);\n buf[size] = '\\0';\n if (is_new)\n preload_parse_str(fs, buf);\n else\n preload_parse_str_old(fs, buf);\n free(buf);\n return 0;\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c", "sub_task_type": null}, "context_code": [["/linuxpdf/tinyemu/fs_disk.c", "/*\n * Filesystem on disk\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n\ntypedef struct {\n FSDevice common;\n char *root_path;\n} FSDeviceDisk;\n\nstatic void fs_close(FSDevice *fs, FSFile *f);\n\nstruct FSFile {\n uint32_t uid;\n char *path; /* complete path */\n BOOL is_opened;\n BOOL is_dir;\n union {\n int fd;\n DIR *dirp;\n } u;\n};\n\nstatic void fs_delete(FSDevice *fs, FSFile *f)\n{\n if (f->is_opened)\n fs_close(fs, f);\n free(f->path);\n free(f);\n}\n\n/* warning: path belong to fid_create() */\nstatic FSFile *fid_create(FSDevice *s1, char *path, uint32_t uid)\n{\n FSFile *f;\n f = mallocz(sizeof(*f));\n f->path = path;\n f->uid = uid;\n return f;\n}\n\n\nstatic int errno_table[][2] = {\n { P9_EPERM, EPERM },\n { P9_ENOENT, ENOENT },\n { P9_EIO, EIO },\n { P9_EEXIST, EEXIST },\n { P9_EINVAL, EINVAL },\n { P9_ENOSPC, ENOSPC },\n { P9_ENOTEMPTY, ENOTEMPTY },\n { P9_EPROTO, EPROTO },\n { P9_ENOTSUP, ENOTSUP },\n};\n\nstatic int errno_to_p9(int err)\n{\n int i;\n if (err == 0)\n return 0;\n for(i = 0; i < countof(errno_table); i++) {\n if (err == errno_table[i][1])\n return errno_table[i][0];\n }\n return P9_EINVAL;\n}\n\nstatic int open_flags[][2] = {\n { P9_O_CREAT, O_CREAT },\n { P9_O_EXCL, O_EXCL },\n // { P9_O_NOCTTY, O_NOCTTY },\n { P9_O_TRUNC, O_TRUNC },\n { P9_O_APPEND, O_APPEND },\n { P9_O_NONBLOCK, O_NONBLOCK },\n { P9_O_DSYNC, O_DSYNC },\n // { P9_O_FASYNC, O_FASYNC },\n // { P9_O_DIRECT, O_DIRECT },\n // { P9_O_LARGEFILE, O_LARGEFILE },\n // { P9_O_DIRECTORY, O_DIRECTORY },\n { P9_O_NOFOLLOW, O_NOFOLLOW },\n // { P9_O_NOATIME, O_NOATIME },\n // { P9_O_CLOEXEC, O_CLOEXEC },\n { P9_O_SYNC, O_SYNC },\n};\n\nstatic int p9_flags_to_host(int flags)\n{\n int ret, i;\n\n ret = (flags & P9_O_NOACCESS);\n for(i = 0; i < countof(open_flags); i++) {\n if (flags & open_flags[i][0])\n ret |= open_flags[i][1];\n }\n return ret;\n}\n\nstatic void stat_to_qid(FSQID *qid, const struct stat *st)\n{\n if (S_ISDIR(st->st_mode))\n qid->type = P9_QTDIR;\n else if (S_ISLNK(st->st_mode))\n qid->type = P9_QTSYMLINK;\n else\n qid->type = P9_QTFILE;\n qid->version = 0; /* no caching on client */\n qid->path = st->st_ino;\n}\n\nstatic void fs_statfs(FSDevice *fs1, FSStatFS *st)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n struct statfs st1;\n statfs(fs->root_path, &st1);\n st->f_bsize = st1.f_bsize;\n st->f_blocks = st1.f_blocks;\n st->f_bfree = st1.f_bfree;\n st->f_bavail = st1.f_bavail;\n st->f_files = st1.f_files;\n st->f_ffree = st1.f_ffree;\n}\n\nstatic char *compose_path(const char *path, const char *name)\n{\n int path_len, name_len;\n char *d;\n\n path_len = strlen(path);\n name_len = strlen(name);\n d = malloc(path_len + 1 + name_len + 1);\n memcpy(d, path, path_len);\n d[path_len] = '/';\n memcpy(d + path_len + 1, name, name_len + 1);\n return d;\n}\n\nstatic int fs_attach(FSDevice *fs1, FSFile **pf,\n FSQID *qid, uint32_t uid,\n const char *uname, const char *aname)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n struct stat st;\n FSFile *f;\n \n if (lstat(fs->root_path, &st) != 0) {\n *pf = NULL;\n return -errno_to_p9(errno);\n }\n f = fid_create(fs1, strdup(fs->root_path), uid);\n stat_to_qid(qid, &st);\n *pf = f;\n return 0;\n}\n\nstatic int fs_walk(FSDevice *fs, FSFile **pf, FSQID *qids,\n FSFile *f, int n, char **names)\n{\n char *path, *path1;\n struct stat st;\n int i;\n\n path = strdup(f->path);\n for(i = 0; i < n; i++) {\n path1 = compose_path(path, names[i]);\n if (lstat(path1, &st) != 0) {\n free(path1);\n break;\n }\n free(path);\n path = path1;\n stat_to_qid(&qids[i], &st);\n }\n *pf = fid_create(fs, path, f->uid);\n return i;\n}\n\n\nstatic int fs_mkdir(FSDevice *fs, FSQID *qid, FSFile *f,\n const char *name, uint32_t mode, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (mkdir(path, mode) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_open(FSDevice *fs, FSQID *qid, FSFile *f, uint32_t flags,\n FSOpenCompletionFunc *cb, void *opaque)\n{\n struct stat st;\n fs_close(fs, f);\n\n if (stat(f->path, &st) != 0) \n return -errno_to_p9(errno);\n stat_to_qid(qid, &st);\n \n if (flags & P9_O_DIRECTORY) {\n DIR *dirp;\n dirp = opendir(f->path);\n if (!dirp)\n return -errno_to_p9(errno);\n f->is_opened = TRUE;\n f->is_dir = TRUE;\n f->u.dirp = dirp;\n } else {\n int fd;\n fd = open(f->path, p9_flags_to_host(flags) & ~O_CREAT);\n if (fd < 0)\n return -errno_to_p9(errno);\n f->is_opened = TRUE;\n f->is_dir = FALSE;\n f->u.fd = fd;\n }\n return 0;\n}\n\nstatic int fs_create(FSDevice *fs, FSQID *qid, FSFile *f, const char *name, \n uint32_t flags, uint32_t mode, uint32_t gid)\n{\n struct stat st;\n char *path;\n int ret, fd;\n\n fs_close(fs, f);\n \n path = compose_path(f->path, name);\n fd = open(path, p9_flags_to_host(flags) | O_CREAT, mode);\n if (fd < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n ret = lstat(path, &st);\n if (ret != 0) {\n free(path);\n close(fd);\n return -errno_to_p9(errno);\n }\n free(f->path);\n f->path = path;\n f->is_opened = TRUE;\n f->is_dir = FALSE;\n f->u.fd = fd;\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_readdir(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n struct dirent *de;\n int len, pos, name_len, type, d_type;\n\n if (!f->is_opened || !f->is_dir)\n return -P9_EPROTO;\n if (offset == 0)\n rewinddir(f->u.dirp);\n else\n seekdir(f->u.dirp, offset);\n pos = 0;\n for(;;) {\n de = readdir(f->u.dirp);\n if (de == NULL)\n break;\n name_len = strlen(de->d_name);\n len = 13 + 8 + 1 + 2 + name_len;\n if ((pos + len) > count)\n break;\n offset = telldir(f->u.dirp);\n d_type = de->d_type;\n if (d_type == DT_UNKNOWN) {\n char *path;\n struct stat st;\n path = compose_path(f->path, de->d_name);\n if (lstat(path, &st) == 0) {\n d_type = st.st_mode >> 12;\n } else {\n d_type = DT_REG; /* default */\n }\n free(path);\n }\n if (d_type == DT_DIR)\n type = P9_QTDIR;\n else if (d_type == DT_LNK)\n type = P9_QTSYMLINK;\n else\n type = P9_QTFILE;\n buf[pos++] = type;\n put_le32(buf + pos, 0); /* version */\n pos += 4;\n put_le64(buf + pos, de->d_ino);\n pos += 8;\n put_le64(buf + pos, offset);\n pos += 8;\n buf[pos++] = d_type;\n put_le16(buf + pos, name_len);\n pos += 2;\n memcpy(buf + pos, de->d_name, name_len);\n pos += name_len;\n }\n return pos;\n}\n\nstatic int fs_read(FSDevice *fs, FSFile *f, uint64_t offset,\n uint8_t *buf, int count)\n{\n int ret;\n\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n ret = pread(f->u.fd, buf, count, offset);\n if (ret < 0) \n return -errno_to_p9(errno);\n else\n return ret;\n}\n\nstatic int fs_write(FSDevice *fs, FSFile *f, uint64_t offset,\n const uint8_t *buf, int count)\n{\n int ret;\n\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n ret = pwrite(f->u.fd, buf, count, offset);\n if (ret < 0) \n return -errno_to_p9(errno);\n else\n return ret;\n}\n\nstatic void fs_close(FSDevice *fs, FSFile *f)\n{\n if (!f->is_opened)\n return;\n if (f->is_dir)\n closedir(f->u.dirp);\n else\n close(f->u.fd);\n f->is_opened = FALSE;\n}\n\nstatic int fs_stat(FSDevice *fs, FSFile *f, FSStat *st)\n{\n struct stat st1;\n\n if (lstat(f->path, &st1) != 0)\n return -P9_ENOENT;\n stat_to_qid(&st->qid, &st1);\n st->st_mode = st1.st_mode;\n st->st_uid = st1.st_uid;\n st->st_gid = st1.st_gid;\n st->st_nlink = st1.st_nlink;\n st->st_rdev = st1.st_rdev;\n st->st_size = st1.st_size;\n st->st_blksize = st1.st_blksize;\n st->st_blocks = st1.st_blocks;\n st->st_atime_sec = st1.st_atim.tv_sec;\n st->st_atime_nsec = st1.st_atim.tv_nsec;\n st->st_mtime_sec = st1.st_mtim.tv_sec;\n st->st_mtime_nsec = st1.st_mtim.tv_nsec;\n st->st_ctime_sec = st1.st_ctim.tv_sec;\n st->st_ctime_nsec = st1.st_ctim.tv_nsec;\n return 0;\n}\n\nstatic int fs_setattr(FSDevice *fs, FSFile *f, uint32_t mask,\n uint32_t mode, uint32_t uid, uint32_t gid,\n uint64_t size, uint64_t atime_sec, uint64_t atime_nsec,\n uint64_t mtime_sec, uint64_t mtime_nsec)\n{\n BOOL ctime_updated = FALSE;\n\n if (mask & (P9_SETATTR_UID | P9_SETATTR_GID)) {\n if (lchown(f->path, (mask & P9_SETATTR_UID) ? uid : -1,\n (mask & P9_SETATTR_GID) ? gid : -1) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n /* must be done after uid change for suid */\n if (mask & P9_SETATTR_MODE) {\n if (chmod(f->path, mode) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if (mask & P9_SETATTR_SIZE) {\n if (truncate(f->path, size) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if (mask & (P9_SETATTR_ATIME | P9_SETATTR_MTIME)) {\n struct timespec ts[2];\n if (mask & P9_SETATTR_ATIME) {\n if (mask & P9_SETATTR_ATIME_SET) {\n ts[0].tv_sec = atime_sec;\n ts[0].tv_nsec = atime_nsec;\n } else {\n ts[0].tv_sec = 0;\n ts[0].tv_nsec = UTIME_NOW;\n }\n } else {\n ts[0].tv_sec = 0;\n ts[0].tv_nsec = UTIME_OMIT;\n }\n if (mask & P9_SETATTR_MTIME) {\n if (mask & P9_SETATTR_MTIME_SET) {\n ts[1].tv_sec = mtime_sec;\n ts[1].tv_nsec = mtime_nsec;\n } else {\n ts[1].tv_sec = 0;\n ts[1].tv_nsec = UTIME_NOW;\n }\n } else {\n ts[1].tv_sec = 0;\n ts[1].tv_nsec = UTIME_OMIT;\n }\n if (utimensat(AT_FDCWD, f->path, ts, AT_SYMLINK_NOFOLLOW) < 0)\n return -errno_to_p9(errno);\n ctime_updated = TRUE;\n }\n if ((mask & P9_SETATTR_CTIME) && !ctime_updated) {\n if (lchown(f->path, -1, -1) < 0)\n return -errno_to_p9(errno);\n }\n return 0;\n}\n\nstatic int fs_link(FSDevice *fs, FSFile *df, FSFile *f, const char *name)\n{\n char *path;\n \n path = compose_path(df->path, name);\n if (link(f->path, path) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n return 0;\n}\n\nstatic int fs_symlink(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, const char *symgt, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (symlink(symgt, path) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_mknod(FSDevice *fs, FSQID *qid,\n FSFile *f, const char *name, uint32_t mode, uint32_t major,\n uint32_t minor, uint32_t gid)\n{\n char *path;\n struct stat st;\n \n path = compose_path(f->path, name);\n if (mknod(path, mode, makedev(major, minor)) < 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n if (lstat(path, &st) != 0) {\n free(path);\n return -errno_to_p9(errno);\n }\n free(path);\n stat_to_qid(qid, &st);\n return 0;\n}\n\nstatic int fs_readlink(FSDevice *fs, char *buf, int buf_size, FSFile *f)\n{\n int ret;\n ret = readlink(f->path, buf, buf_size - 1);\n if (ret < 0)\n return -errno_to_p9(errno);\n buf[ret] = '\\0';\n return 0;\n}\n\nstatic int fs_renameat(FSDevice *fs, FSFile *f, const char *name, \n FSFile *new_f, const char *new_name)\n{\n char *path, *new_path;\n int ret;\n\n path = compose_path(f->path, name);\n new_path = compose_path(new_f->path, new_name);\n ret = rename(path, new_path);\n free(path);\n free(new_path);\n if (ret < 0)\n return -errno_to_p9(errno);\n return 0;\n}\n\nstatic int fs_unlinkat(FSDevice *fs, FSFile *f, const char *name)\n{\n char *path;\n int ret;\n\n path = compose_path(f->path, name);\n ret = remove(path);\n free(path);\n if (ret < 0)\n return -errno_to_p9(errno);\n return 0;\n \n}\n\nstatic int fs_lock(FSDevice *fs, FSFile *f, const FSLock *lock)\n{\n int ret;\n struct flock fl;\n \n /* XXX: lock directories too */\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n\n fl.l_type = lock->type;\n fl.l_whence = SEEK_SET;\n fl.l_start = lock->start;\n fl.l_len = lock->length;\n \n ret = fcntl(f->u.fd, F_SETLK, &fl);\n if (ret == 0) {\n ret = P9_LOCK_SUCCESS;\n } else if (errno == EAGAIN || errno == EACCES) {\n ret = P9_LOCK_BLOCKED;\n } else {\n ret = -errno_to_p9(errno);\n }\n return ret;\n}\n\nstatic int fs_getlock(FSDevice *fs, FSFile *f, FSLock *lock)\n{\n int ret;\n struct flock fl;\n \n /* XXX: lock directories too */\n if (!f->is_opened || f->is_dir)\n return -P9_EPROTO;\n\n fl.l_type = lock->type;\n fl.l_whence = SEEK_SET;\n fl.l_start = lock->start;\n fl.l_len = lock->length;\n\n ret = fcntl(f->u.fd, F_GETLK, &fl);\n if (ret < 0) {\n ret = -errno_to_p9(errno);\n } else {\n lock->type = fl.l_type;\n lock->start = fl.l_start;\n lock->length = fl.l_len;\n }\n return ret;\n}\n\nstatic void fs_disk_end(FSDevice *fs1)\n{\n FSDeviceDisk *fs = (FSDeviceDisk *)fs1;\n free(fs->root_path);\n}\n\nFSDevice *fs_disk_init(const char *root_path)\n{\n FSDeviceDisk *fs;\n struct stat st;\n\n lstat(root_path, &st);\n if (!S_ISDIR(st.st_mode))\n return NULL;\n\n fs = mallocz(sizeof(*fs));\n\n fs->common.fs_end = fs_disk_end;\n fs->common.fs_delete = fs_delete;\n fs->common.fs_statfs = fs_statfs;\n fs->common.fs_attach = fs_attach;\n fs->common.fs_walk = fs_walk;\n fs->common.fs_mkdir = fs_mkdir;\n fs->common.fs_open = fs_open;\n fs->common.fs_create = fs_create;\n fs->common.fs_stat = fs_stat;\n fs->common.fs_setattr = fs_setattr;\n fs->common.fs_close = fs_close;\n fs->common.fs_readdir = fs_readdir;\n fs->common.fs_read = fs_read;\n fs->common.fs_write = fs_write;\n fs->common.fs_link = fs_link;\n fs->common.fs_symlink = fs_symlink;\n fs->common.fs_mknod = fs_mknod;\n fs->common.fs_readlink = fs_readlink;\n fs->common.fs_renameat = fs_renameat;\n fs->common.fs_unlinkat = fs_unlinkat;\n fs->common.fs_lock = fs_lock;\n fs->common.fs_getlock = fs_getlock;\n \n fs->root_path = strdup(root_path);\n return (FSDevice *)fs;\n}\n"], ["/linuxpdf/tinyemu/virtio.c", "/*\n * VIRTIO driver\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"virtio.h\"\n\n//#define DEBUG_VIRTIO\n\n/* MMIO addresses - from the Linux kernel */\n#define VIRTIO_MMIO_MAGIC_VALUE\t\t0x000\n#define VIRTIO_MMIO_VERSION\t\t0x004\n#define VIRTIO_MMIO_DEVICE_ID\t\t0x008\n#define VIRTIO_MMIO_VENDOR_ID\t\t0x00c\n#define VIRTIO_MMIO_DEVICE_FEATURES\t0x010\n#define VIRTIO_MMIO_DEVICE_FEATURES_SEL\t0x014\n#define VIRTIO_MMIO_DRIVER_FEATURES\t0x020\n#define VIRTIO_MMIO_DRIVER_FEATURES_SEL\t0x024\n#define VIRTIO_MMIO_GUEST_PAGE_SIZE\t0x028 /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_SEL\t\t0x030\n#define VIRTIO_MMIO_QUEUE_NUM_MAX\t0x034\n#define VIRTIO_MMIO_QUEUE_NUM\t\t0x038\n#define VIRTIO_MMIO_QUEUE_ALIGN\t\t0x03c /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_PFN\t\t0x040 /* version 1 only */\n#define VIRTIO_MMIO_QUEUE_READY\t\t0x044\n#define VIRTIO_MMIO_QUEUE_NOTIFY\t0x050\n#define VIRTIO_MMIO_INTERRUPT_STATUS\t0x060\n#define VIRTIO_MMIO_INTERRUPT_ACK\t0x064\n#define VIRTIO_MMIO_STATUS\t\t0x070\n#define VIRTIO_MMIO_QUEUE_DESC_LOW\t0x080\n#define VIRTIO_MMIO_QUEUE_DESC_HIGH\t0x084\n#define VIRTIO_MMIO_QUEUE_AVAIL_LOW\t0x090\n#define VIRTIO_MMIO_QUEUE_AVAIL_HIGH\t0x094\n#define VIRTIO_MMIO_QUEUE_USED_LOW\t0x0a0\n#define VIRTIO_MMIO_QUEUE_USED_HIGH\t0x0a4\n#define VIRTIO_MMIO_CONFIG_GENERATION\t0x0fc\n#define VIRTIO_MMIO_CONFIG\t\t0x100\n\n/* PCI registers */\n#define VIRTIO_PCI_DEVICE_FEATURE_SEL\t0x000\n#define VIRTIO_PCI_DEVICE_FEATURE\t0x004\n#define VIRTIO_PCI_GUEST_FEATURE_SEL\t0x008\n#define VIRTIO_PCI_GUEST_FEATURE\t0x00c\n#define VIRTIO_PCI_MSIX_CONFIG 0x010\n#define VIRTIO_PCI_NUM_QUEUES 0x012\n#define VIRTIO_PCI_DEVICE_STATUS 0x014\n#define VIRTIO_PCI_CONFIG_GENERATION 0x015\n#define VIRTIO_PCI_QUEUE_SEL\t\t0x016\n#define VIRTIO_PCI_QUEUE_SIZE\t 0x018\n#define VIRTIO_PCI_QUEUE_MSIX_VECTOR 0x01a\n#define VIRTIO_PCI_QUEUE_ENABLE 0x01c\n#define VIRTIO_PCI_QUEUE_NOTIFY_OFF 0x01e\n#define VIRTIO_PCI_QUEUE_DESC_LOW\t0x020\n#define VIRTIO_PCI_QUEUE_DESC_HIGH\t0x024\n#define VIRTIO_PCI_QUEUE_AVAIL_LOW\t0x028\n#define VIRTIO_PCI_QUEUE_AVAIL_HIGH\t0x02c\n#define VIRTIO_PCI_QUEUE_USED_LOW\t0x030\n#define VIRTIO_PCI_QUEUE_USED_HIGH\t0x034\n\n#define VIRTIO_PCI_CFG_OFFSET 0x0000\n#define VIRTIO_PCI_ISR_OFFSET 0x1000\n#define VIRTIO_PCI_CONFIG_OFFSET 0x2000\n#define VIRTIO_PCI_NOTIFY_OFFSET 0x3000\n\n#define VIRTIO_PCI_CAP_LEN 16\n\n#define MAX_QUEUE 8\n#define MAX_CONFIG_SPACE_SIZE 256\n#define MAX_QUEUE_NUM 16\n\ntypedef struct {\n uint32_t ready; /* 0 or 1 */\n uint32_t num;\n uint16_t last_avail_idx;\n virtio_phys_addr_t desc_addr;\n virtio_phys_addr_t avail_addr;\n virtio_phys_addr_t used_addr;\n BOOL manual_recv; /* if TRUE, the device_recv() callback is not called */\n} QueueState;\n\n#define VRING_DESC_F_NEXT\t1\n#define VRING_DESC_F_WRITE\t2\n#define VRING_DESC_F_INDIRECT\t4\n\ntypedef struct {\n uint64_t addr;\n uint32_t len;\n uint16_t flags; /* VRING_DESC_F_x */\n uint16_t next;\n} VIRTIODesc;\n\n/* return < 0 to stop the notification (it must be manually restarted\n later), 0 if OK */\ntypedef int VIRTIODeviceRecvFunc(VIRTIODevice *s1, int queue_idx,\n int desc_idx, int read_size,\n int write_size);\n\n/* return NULL if no RAM at this address. The mapping is valid for one page */\ntypedef uint8_t *VIRTIOGetRAMPtrFunc(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw);\n\nstruct VIRTIODevice {\n PhysMemoryMap *mem_map;\n PhysMemoryRange *mem_range;\n /* PCI only */\n PCIDevice *pci_dev;\n /* MMIO only */\n IRQSignal *irq;\n VIRTIOGetRAMPtrFunc *get_ram_ptr;\n int debug;\n\n uint32_t int_status;\n uint32_t status;\n uint32_t device_features_sel;\n uint32_t queue_sel; /* currently selected queue */\n QueueState queue[MAX_QUEUE];\n\n /* device specific */\n uint32_t device_id;\n uint32_t vendor_id;\n uint32_t device_features;\n VIRTIODeviceRecvFunc *device_recv;\n void (*config_write)(VIRTIODevice *s); /* called after the config\n is written */\n uint32_t config_space_size; /* in bytes, must be multiple of 4 */\n uint8_t config_space[MAX_CONFIG_SPACE_SIZE];\n};\n\nstatic uint32_t virtio_mmio_read(void *opaque, uint32_t offset1, int size_log2);\nstatic void virtio_mmio_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t virtio_pci_read(void *opaque, uint32_t offset, int size_log2);\nstatic void virtio_pci_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\n\nstatic void virtio_reset(VIRTIODevice *s)\n{\n int i;\n\n s->status = 0;\n s->queue_sel = 0;\n s->device_features_sel = 0;\n s->int_status = 0;\n for(i = 0; i < MAX_QUEUE; i++) {\n QueueState *qs = &s->queue[i];\n qs->ready = 0;\n qs->num = MAX_QUEUE_NUM;\n qs->desc_addr = 0;\n qs->avail_addr = 0;\n qs->used_addr = 0;\n qs->last_avail_idx = 0;\n }\n}\n\nstatic uint8_t *virtio_pci_get_ram_ptr(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw)\n{\n return pci_device_get_dma_ptr(s->pci_dev, paddr, is_rw);\n}\n\nstatic uint8_t *virtio_mmio_get_ram_ptr(VIRTIODevice *s, virtio_phys_addr_t paddr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(s->mem_map, paddr, is_rw);\n}\n\nstatic void virtio_add_pci_capability(VIRTIODevice *s, int cfg_type,\n int bar, uint32_t offset, uint32_t len,\n uint32_t mult)\n{\n uint8_t cap[20];\n int cap_len;\n if (cfg_type == 2)\n cap_len = 20;\n else\n cap_len = 16;\n memset(cap, 0, cap_len);\n cap[0] = 0x09; /* vendor specific */\n cap[2] = cap_len; /* set by pci_add_capability() */\n cap[3] = cfg_type;\n cap[4] = bar;\n put_le32(cap + 8, offset);\n put_le32(cap + 12, len);\n if (cfg_type == 2)\n put_le32(cap + 16, mult);\n pci_add_capability(s->pci_dev, cap, cap_len);\n}\n\nstatic void virtio_pci_bar_set(void *opaque, int bar_num,\n uint32_t addr, BOOL enabled)\n{\n VIRTIODevice *s = opaque;\n phys_mem_set_addr(s->mem_range, addr, enabled);\n}\n\nstatic void virtio_init(VIRTIODevice *s, VIRTIOBusDef *bus,\n uint32_t device_id, int config_space_size,\n VIRTIODeviceRecvFunc *device_recv)\n{\n memset(s, 0, sizeof(*s));\n\n if (bus->pci_bus) {\n uint16_t pci_device_id, class_id;\n char name[32];\n int bar_num;\n \n switch(device_id) {\n case 1:\n pci_device_id = 0x1000; /* net */\n class_id = 0x0200;\n break;\n case 2:\n pci_device_id = 0x1001; /* block */\n class_id = 0x0100; /* XXX: check it */\n break;\n case 3:\n pci_device_id = 0x1003; /* console */\n class_id = 0x0780;\n break;\n case 9:\n pci_device_id = 0x1040 + device_id; /* use new device ID */\n class_id = 0x2;\n break;\n case 18:\n pci_device_id = 0x1040 + device_id; /* use new device ID */\n class_id = 0x0980;\n break;\n default:\n abort();\n }\n snprintf(name, sizeof(name), \"virtio_%04x\", pci_device_id);\n s->pci_dev = pci_register_device(bus->pci_bus, name, -1,\n 0x1af4, pci_device_id, 0x00,\n class_id);\n pci_device_set_config16(s->pci_dev, 0x2c, 0x1af4);\n pci_device_set_config16(s->pci_dev, 0x2e, device_id);\n pci_device_set_config8(s->pci_dev, PCI_INTERRUPT_PIN, 1);\n\n bar_num = 4;\n virtio_add_pci_capability(s, 1, bar_num,\n VIRTIO_PCI_CFG_OFFSET, 0x1000, 0); /* common */\n virtio_add_pci_capability(s, 3, bar_num,\n VIRTIO_PCI_ISR_OFFSET, 0x1000, 0); /* isr */\n virtio_add_pci_capability(s, 4, bar_num,\n VIRTIO_PCI_CONFIG_OFFSET, 0x1000, 0); /* config */\n virtio_add_pci_capability(s, 2, bar_num,\n VIRTIO_PCI_NOTIFY_OFFSET, 0x1000, 0); /* notify */\n \n s->get_ram_ptr = virtio_pci_get_ram_ptr;\n s->irq = pci_device_get_irq(s->pci_dev, 0);\n s->mem_map = pci_device_get_mem_map(s->pci_dev);\n s->mem_range = cpu_register_device(s->mem_map, 0, 0x4000, s,\n virtio_pci_read, virtio_pci_write,\n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32 | DEVIO_DISABLED);\n pci_register_bar(s->pci_dev, bar_num, 0x4000, PCI_ADDRESS_SPACE_MEM,\n s, virtio_pci_bar_set);\n } else {\n /* MMIO case */\n s->mem_map = bus->mem_map;\n s->irq = bus->irq;\n s->mem_range = cpu_register_device(s->mem_map, bus->addr, VIRTIO_PAGE_SIZE,\n s, virtio_mmio_read, virtio_mmio_write,\n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32);\n s->get_ram_ptr = virtio_mmio_get_ram_ptr;\n }\n\n s->device_id = device_id;\n s->vendor_id = 0xffff;\n s->config_space_size = config_space_size;\n s->device_recv = device_recv;\n virtio_reset(s);\n}\n\nstatic uint16_t virtio_read16(VIRTIODevice *s, virtio_phys_addr_t addr)\n{\n uint8_t *ptr;\n if (addr & 1)\n return 0; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, FALSE);\n if (!ptr)\n return 0;\n return *(uint16_t *)ptr;\n}\n\nstatic void virtio_write16(VIRTIODevice *s, virtio_phys_addr_t addr,\n uint16_t val)\n{\n uint8_t *ptr;\n if (addr & 1)\n return; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return;\n *(uint16_t *)ptr = val;\n}\n\nstatic void virtio_write32(VIRTIODevice *s, virtio_phys_addr_t addr,\n uint32_t val)\n{\n uint8_t *ptr;\n if (addr & 3)\n return; /* unaligned access are not supported */\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return;\n *(uint32_t *)ptr = val;\n}\n\nstatic int virtio_memcpy_from_ram(VIRTIODevice *s, uint8_t *buf,\n virtio_phys_addr_t addr, int count)\n{\n uint8_t *ptr;\n int l;\n\n while (count > 0) {\n l = min_int(count, VIRTIO_PAGE_SIZE - (addr & (VIRTIO_PAGE_SIZE - 1)));\n ptr = s->get_ram_ptr(s, addr, FALSE);\n if (!ptr)\n return -1;\n memcpy(buf, ptr, l);\n addr += l;\n buf += l;\n count -= l;\n }\n return 0;\n}\n\nstatic int virtio_memcpy_to_ram(VIRTIODevice *s, virtio_phys_addr_t addr, \n const uint8_t *buf, int count)\n{\n uint8_t *ptr;\n int l;\n\n while (count > 0) {\n l = min_int(count, VIRTIO_PAGE_SIZE - (addr & (VIRTIO_PAGE_SIZE - 1)));\n ptr = s->get_ram_ptr(s, addr, TRUE);\n if (!ptr)\n return -1;\n memcpy(ptr, buf, l);\n addr += l;\n buf += l;\n count -= l;\n }\n return 0;\n}\n\nstatic int get_desc(VIRTIODevice *s, VIRTIODesc *desc, \n int queue_idx, int desc_idx)\n{\n QueueState *qs = &s->queue[queue_idx];\n return virtio_memcpy_from_ram(s, (void *)desc, qs->desc_addr +\n desc_idx * sizeof(VIRTIODesc),\n sizeof(VIRTIODesc));\n}\n\nstatic int memcpy_to_from_queue(VIRTIODevice *s, uint8_t *buf,\n int queue_idx, int desc_idx,\n int offset, int count, BOOL to_queue)\n{\n VIRTIODesc desc;\n int l, f_write_flag;\n\n if (count == 0)\n return 0;\n\n get_desc(s, &desc, queue_idx, desc_idx);\n\n if (to_queue) {\n f_write_flag = VRING_DESC_F_WRITE;\n /* find the first write descriptor */\n for(;;) {\n if ((desc.flags & VRING_DESC_F_WRITE) == f_write_flag)\n break;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n } else {\n f_write_flag = 0;\n }\n\n /* find the descriptor at offset */\n for(;;) {\n if ((desc.flags & VRING_DESC_F_WRITE) != f_write_flag)\n return -1;\n if (offset < desc.len)\n break;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n offset -= desc.len;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n\n for(;;) {\n l = min_int(count, desc.len - offset);\n if (to_queue)\n virtio_memcpy_to_ram(s, desc.addr + offset, buf, l);\n else\n virtio_memcpy_from_ram(s, buf, desc.addr + offset, l);\n count -= l;\n if (count == 0)\n break;\n offset += l;\n buf += l;\n if (offset == desc.len) {\n if (!(desc.flags & VRING_DESC_F_NEXT))\n return -1;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n if ((desc.flags & VRING_DESC_F_WRITE) != f_write_flag)\n return -1;\n offset = 0;\n }\n }\n return 0;\n}\n\nstatic int memcpy_from_queue(VIRTIODevice *s, void *buf,\n int queue_idx, int desc_idx,\n int offset, int count)\n{\n return memcpy_to_from_queue(s, buf, queue_idx, desc_idx, offset, count,\n FALSE);\n}\n\nstatic int memcpy_to_queue(VIRTIODevice *s,\n int queue_idx, int desc_idx,\n int offset, const void *buf, int count)\n{\n return memcpy_to_from_queue(s, (void *)buf, queue_idx, desc_idx, offset,\n count, TRUE);\n}\n\n/* signal that the descriptor has been consumed */\nstatic void virtio_consume_desc(VIRTIODevice *s,\n int queue_idx, int desc_idx, int desc_len)\n{\n QueueState *qs = &s->queue[queue_idx];\n virtio_phys_addr_t addr;\n uint32_t index;\n\n addr = qs->used_addr + 2;\n index = virtio_read16(s, addr);\n virtio_write16(s, addr, index + 1);\n\n addr = qs->used_addr + 4 + (index & (qs->num - 1)) * 8;\n virtio_write32(s, addr, desc_idx);\n virtio_write32(s, addr + 4, desc_len);\n\n s->int_status |= 1;\n set_irq(s->irq, 1);\n}\n\nstatic int get_desc_rw_size(VIRTIODevice *s, \n int *pread_size, int *pwrite_size,\n int queue_idx, int desc_idx)\n{\n VIRTIODesc desc;\n int read_size, write_size;\n\n read_size = 0;\n write_size = 0;\n get_desc(s, &desc, queue_idx, desc_idx);\n\n for(;;) {\n if (desc.flags & VRING_DESC_F_WRITE)\n break;\n read_size += desc.len;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n goto done;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n \n for(;;) {\n if (!(desc.flags & VRING_DESC_F_WRITE))\n return -1;\n write_size += desc.len;\n if (!(desc.flags & VRING_DESC_F_NEXT))\n break;\n desc_idx = desc.next;\n get_desc(s, &desc, queue_idx, desc_idx);\n }\n\n done:\n *pread_size = read_size;\n *pwrite_size = write_size;\n return 0;\n}\n\n/* XXX: test if the queue is ready ? */\nstatic void queue_notify(VIRTIODevice *s, int queue_idx)\n{\n QueueState *qs = &s->queue[queue_idx];\n uint16_t avail_idx;\n int desc_idx, read_size, write_size;\n\n if (qs->manual_recv)\n return;\n\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n while (qs->last_avail_idx != avail_idx) {\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (!get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx)) {\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"queue_notify: idx=%d read_size=%d write_size=%d\\n\",\n queue_idx, read_size, write_size);\n }\n#endif\n if (s->device_recv(s, queue_idx, desc_idx,\n read_size, write_size) < 0)\n break;\n }\n qs->last_avail_idx++;\n }\n}\n\nstatic uint32_t virtio_config_read(VIRTIODevice *s, uint32_t offset,\n int size_log2)\n{\n uint32_t val;\n switch(size_log2) {\n case 0:\n if (offset < s->config_space_size) {\n val = s->config_space[offset];\n } else {\n val = 0;\n }\n break;\n case 1:\n if (offset < (s->config_space_size - 1)) {\n val = get_le16(&s->config_space[offset]);\n } else {\n val = 0;\n }\n break;\n case 2:\n if (offset < (s->config_space_size - 3)) {\n val = get_le32(s->config_space + offset);\n } else {\n val = 0;\n }\n break;\n default:\n abort();\n }\n return val;\n}\n\nstatic void virtio_config_write(VIRTIODevice *s, uint32_t offset,\n uint32_t val, int size_log2)\n{\n switch(size_log2) {\n case 0:\n if (offset < s->config_space_size) {\n s->config_space[offset] = val;\n if (s->config_write)\n s->config_write(s);\n }\n break;\n case 1:\n if (offset < s->config_space_size - 1) {\n put_le16(s->config_space + offset, val);\n if (s->config_write)\n s->config_write(s);\n }\n break;\n case 2:\n if (offset < s->config_space_size - 3) {\n put_le32(s->config_space + offset, val);\n if (s->config_write)\n s->config_write(s);\n }\n break;\n }\n}\n\nstatic uint32_t virtio_mmio_read(void *opaque, uint32_t offset, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t val;\n\n if (offset >= VIRTIO_MMIO_CONFIG) {\n return virtio_config_read(s, offset - VIRTIO_MMIO_CONFIG, size_log2);\n }\n\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_MMIO_MAGIC_VALUE:\n val = 0x74726976;\n break;\n case VIRTIO_MMIO_VERSION:\n val = 2;\n break;\n case VIRTIO_MMIO_DEVICE_ID:\n val = s->device_id;\n break;\n case VIRTIO_MMIO_VENDOR_ID:\n val = s->vendor_id;\n break;\n case VIRTIO_MMIO_DEVICE_FEATURES:\n switch(s->device_features_sel) {\n case 0:\n val = s->device_features;\n break;\n case 1:\n val = 1; /* version 1 */\n break;\n default:\n val = 0;\n break;\n }\n break;\n case VIRTIO_MMIO_DEVICE_FEATURES_SEL:\n val = s->device_features_sel;\n break;\n case VIRTIO_MMIO_QUEUE_SEL:\n val = s->queue_sel;\n break;\n case VIRTIO_MMIO_QUEUE_NUM_MAX:\n val = MAX_QUEUE_NUM;\n break;\n case VIRTIO_MMIO_QUEUE_NUM:\n val = s->queue[s->queue_sel].num;\n break;\n case VIRTIO_MMIO_QUEUE_DESC_LOW:\n val = s->queue[s->queue_sel].desc_addr;\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_LOW:\n val = s->queue[s->queue_sel].avail_addr;\n break;\n case VIRTIO_MMIO_QUEUE_USED_LOW:\n val = s->queue[s->queue_sel].used_addr;\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_MMIO_QUEUE_DESC_HIGH:\n val = s->queue[s->queue_sel].desc_addr >> 32;\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_HIGH:\n val = s->queue[s->queue_sel].avail_addr >> 32;\n break;\n case VIRTIO_MMIO_QUEUE_USED_HIGH:\n val = s->queue[s->queue_sel].used_addr >> 32;\n break;\n#endif\n case VIRTIO_MMIO_QUEUE_READY:\n val = s->queue[s->queue_sel].ready;\n break;\n case VIRTIO_MMIO_INTERRUPT_STATUS:\n val = s->int_status;\n break;\n case VIRTIO_MMIO_STATUS:\n val = s->status;\n break;\n case VIRTIO_MMIO_CONFIG_GENERATION:\n val = 0;\n break;\n default:\n val = 0;\n break;\n }\n } else {\n val = 0;\n }\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_mmio_read: offset=0x%x val=0x%x size=%d\\n\", \n offset, val, 1 << size_log2);\n }\n#endif\n return val;\n}\n\n#if VIRTIO_ADDR_BITS == 64\nstatic void set_low32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = (*paddr & ~(virtio_phys_addr_t)0xffffffff) | val;\n}\n\nstatic void set_high32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = (*paddr & 0xffffffff) | ((virtio_phys_addr_t)val << 32);\n}\n#else\nstatic void set_low32(virtio_phys_addr_t *paddr, uint32_t val)\n{\n *paddr = val;\n}\n#endif\n\nstatic void virtio_mmio_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n VIRTIODevice *s = opaque;\n \n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_mmio_write: offset=0x%x val=0x%x size=%d\\n\",\n offset, val, 1 << size_log2);\n }\n#endif\n\n if (offset >= VIRTIO_MMIO_CONFIG) {\n virtio_config_write(s, offset - VIRTIO_MMIO_CONFIG, val, size_log2);\n return;\n }\n\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_MMIO_DEVICE_FEATURES_SEL:\n s->device_features_sel = val;\n break;\n case VIRTIO_MMIO_QUEUE_SEL:\n if (val < MAX_QUEUE)\n s->queue_sel = val;\n break;\n case VIRTIO_MMIO_QUEUE_NUM:\n if ((val & (val - 1)) == 0 && val > 0) {\n s->queue[s->queue_sel].num = val;\n }\n break;\n case VIRTIO_MMIO_QUEUE_DESC_LOW:\n set_low32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_LOW:\n set_low32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_USED_LOW:\n set_low32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_MMIO_QUEUE_DESC_HIGH:\n set_high32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_AVAIL_HIGH:\n set_high32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_MMIO_QUEUE_USED_HIGH:\n set_high32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#endif\n case VIRTIO_MMIO_STATUS:\n s->status = val;\n if (val == 0) {\n /* reset */\n set_irq(s->irq, 0);\n virtio_reset(s);\n }\n break;\n case VIRTIO_MMIO_QUEUE_READY:\n s->queue[s->queue_sel].ready = val & 1;\n break;\n case VIRTIO_MMIO_QUEUE_NOTIFY:\n if (val < MAX_QUEUE)\n queue_notify(s, val);\n break;\n case VIRTIO_MMIO_INTERRUPT_ACK:\n s->int_status &= ~val;\n if (s->int_status == 0) {\n set_irq(s->irq, 0);\n }\n break;\n }\n }\n}\n\nstatic uint32_t virtio_pci_read(void *opaque, uint32_t offset1, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t offset;\n uint32_t val = 0;\n\n offset = offset1 & 0xfff;\n switch(offset1 >> 12) {\n case VIRTIO_PCI_CFG_OFFSET >> 12:\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_FEATURE:\n switch(s->device_features_sel) {\n case 0:\n val = s->device_features;\n break;\n case 1:\n val = 1; /* version 1 */\n break;\n default:\n val = 0;\n break;\n }\n break;\n case VIRTIO_PCI_DEVICE_FEATURE_SEL:\n val = s->device_features_sel;\n break;\n case VIRTIO_PCI_QUEUE_DESC_LOW:\n val = s->queue[s->queue_sel].desc_addr;\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_LOW:\n val = s->queue[s->queue_sel].avail_addr;\n break;\n case VIRTIO_PCI_QUEUE_USED_LOW:\n val = s->queue[s->queue_sel].used_addr;\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_PCI_QUEUE_DESC_HIGH:\n val = s->queue[s->queue_sel].desc_addr >> 32;\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_HIGH:\n val = s->queue[s->queue_sel].avail_addr >> 32;\n break;\n case VIRTIO_PCI_QUEUE_USED_HIGH:\n val = s->queue[s->queue_sel].used_addr >> 32;\n break;\n#endif\n }\n } else if (size_log2 == 1) {\n switch(offset) {\n case VIRTIO_PCI_NUM_QUEUES:\n val = MAX_QUEUE_NUM;\n break;\n case VIRTIO_PCI_QUEUE_SEL:\n val = s->queue_sel;\n break;\n case VIRTIO_PCI_QUEUE_SIZE:\n val = s->queue[s->queue_sel].num;\n break;\n case VIRTIO_PCI_QUEUE_ENABLE:\n val = s->queue[s->queue_sel].ready;\n break;\n case VIRTIO_PCI_QUEUE_NOTIFY_OFF:\n val = 0;\n break;\n }\n } else if (size_log2 == 0) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_STATUS:\n val = s->status;\n break;\n }\n }\n break;\n case VIRTIO_PCI_ISR_OFFSET >> 12:\n if (offset == 0 && size_log2 == 0) {\n val = s->int_status;\n s->int_status = 0;\n set_irq(s->irq, 0);\n }\n break;\n case VIRTIO_PCI_CONFIG_OFFSET >> 12:\n val = virtio_config_read(s, offset, size_log2);\n break;\n }\n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_pci_read: offset=0x%x val=0x%x size=%d\\n\", \n offset1, val, 1 << size_log2);\n }\n#endif\n return val;\n}\n\nstatic void virtio_pci_write(void *opaque, uint32_t offset1,\n uint32_t val, int size_log2)\n{\n VIRTIODevice *s = opaque;\n uint32_t offset;\n \n#ifdef DEBUG_VIRTIO\n if (s->debug & VIRTIO_DEBUG_IO) {\n printf(\"virto_pci_write: offset=0x%x val=0x%x size=%d\\n\",\n offset1, val, 1 << size_log2);\n }\n#endif\n offset = offset1 & 0xfff;\n switch(offset1 >> 12) {\n case VIRTIO_PCI_CFG_OFFSET >> 12:\n if (size_log2 == 2) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_FEATURE_SEL:\n s->device_features_sel = val;\n break;\n case VIRTIO_PCI_QUEUE_DESC_LOW:\n set_low32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_LOW:\n set_low32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_USED_LOW:\n set_low32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#if VIRTIO_ADDR_BITS == 64\n case VIRTIO_PCI_QUEUE_DESC_HIGH:\n set_high32(&s->queue[s->queue_sel].desc_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_AVAIL_HIGH:\n set_high32(&s->queue[s->queue_sel].avail_addr, val);\n break;\n case VIRTIO_PCI_QUEUE_USED_HIGH:\n set_high32(&s->queue[s->queue_sel].used_addr, val);\n break;\n#endif\n }\n } else if (size_log2 == 1) {\n switch(offset) {\n case VIRTIO_PCI_QUEUE_SEL:\n if (val < MAX_QUEUE)\n s->queue_sel = val;\n break;\n case VIRTIO_PCI_QUEUE_SIZE:\n if ((val & (val - 1)) == 0 && val > 0) {\n s->queue[s->queue_sel].num = val;\n }\n break;\n case VIRTIO_PCI_QUEUE_ENABLE:\n s->queue[s->queue_sel].ready = val & 1;\n break;\n }\n } else if (size_log2 == 0) {\n switch(offset) {\n case VIRTIO_PCI_DEVICE_STATUS:\n s->status = val;\n if (val == 0) {\n /* reset */\n set_irq(s->irq, 0);\n virtio_reset(s);\n }\n break;\n }\n }\n break;\n case VIRTIO_PCI_CONFIG_OFFSET >> 12:\n virtio_config_write(s, offset, val, size_log2);\n break;\n case VIRTIO_PCI_NOTIFY_OFFSET >> 12:\n if (val < MAX_QUEUE)\n queue_notify(s, val);\n break;\n }\n}\n\nvoid virtio_set_debug(VIRTIODevice *s, int debug)\n{\n s->debug = debug;\n}\n\nstatic void virtio_config_change_notify(VIRTIODevice *s)\n{\n /* INT_CONFIG interrupt */\n s->int_status |= 2;\n set_irq(s->irq, 1);\n}\n\n/*********************************************************************/\n/* block device */\n\ntypedef struct {\n uint32_t type;\n uint8_t *buf;\n int write_size;\n int queue_idx;\n int desc_idx;\n} BlockRequest;\n\ntypedef struct VIRTIOBlockDevice {\n VIRTIODevice common;\n BlockDevice *bs;\n\n BOOL req_in_progress;\n BlockRequest req; /* request in progress */\n} VIRTIOBlockDevice;\n\ntypedef struct {\n uint32_t type;\n uint32_t ioprio;\n uint64_t sector_num;\n} BlockRequestHeader;\n\n#define VIRTIO_BLK_T_IN 0\n#define VIRTIO_BLK_T_OUT 1\n#define VIRTIO_BLK_T_FLUSH 4\n#define VIRTIO_BLK_T_FLUSH_OUT 5\n\n#define VIRTIO_BLK_S_OK 0\n#define VIRTIO_BLK_S_IOERR 1\n#define VIRTIO_BLK_S_UNSUPP 2\n\n#define SECTOR_SIZE 512\n\nstatic void virtio_block_req_end(VIRTIODevice *s, int ret)\n{\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n int write_size;\n int queue_idx = s1->req.queue_idx;\n int desc_idx = s1->req.desc_idx;\n uint8_t *buf, buf1[1];\n\n switch(s1->req.type) {\n case VIRTIO_BLK_T_IN:\n write_size = s1->req.write_size;\n buf = s1->req.buf;\n if (ret < 0) {\n buf[write_size - 1] = VIRTIO_BLK_S_IOERR;\n } else {\n buf[write_size - 1] = VIRTIO_BLK_S_OK;\n }\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, write_size);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, write_size);\n break;\n case VIRTIO_BLK_T_OUT:\n if (ret < 0)\n buf1[0] = VIRTIO_BLK_S_IOERR;\n else\n buf1[0] = VIRTIO_BLK_S_OK;\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf1, sizeof(buf1));\n virtio_consume_desc(s, queue_idx, desc_idx, 1);\n break;\n default:\n abort();\n }\n}\n\nstatic void virtio_block_req_cb(void *opaque, int ret)\n{\n VIRTIODevice *s = opaque;\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n\n virtio_block_req_end(s, ret);\n \n s1->req_in_progress = FALSE;\n\n /* handle next requests */\n queue_notify((VIRTIODevice *)s, s1->req.queue_idx);\n}\n\n/* XXX: handle async I/O */\nstatic int virtio_block_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIOBlockDevice *s1 = (VIRTIOBlockDevice *)s;\n BlockDevice *bs = s1->bs;\n BlockRequestHeader h;\n uint8_t *buf;\n int len, ret;\n\n if (s1->req_in_progress)\n return -1;\n \n if (memcpy_from_queue(s, &h, queue_idx, desc_idx, 0, sizeof(h)) < 0)\n return 0;\n s1->req.type = h.type;\n s1->req.queue_idx = queue_idx;\n s1->req.desc_idx = desc_idx;\n switch(h.type) {\n case VIRTIO_BLK_T_IN:\n s1->req.buf = malloc(write_size);\n s1->req.write_size = write_size;\n ret = bs->read_async(bs, h.sector_num, s1->req.buf, \n (write_size - 1) / SECTOR_SIZE,\n virtio_block_req_cb, s);\n if (ret > 0) {\n /* asyncronous read */\n s1->req_in_progress = TRUE;\n } else {\n virtio_block_req_end(s, ret);\n }\n break;\n case VIRTIO_BLK_T_OUT:\n assert(write_size >= 1);\n len = read_size - sizeof(h);\n buf = malloc(len);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, sizeof(h), len);\n ret = bs->write_async(bs, h.sector_num, buf, len / SECTOR_SIZE,\n virtio_block_req_cb, s);\n free(buf);\n if (ret > 0) {\n /* asyncronous write */\n s1->req_in_progress = TRUE;\n } else {\n virtio_block_req_end(s, ret);\n }\n break;\n default:\n break;\n }\n return 0;\n}\n\nVIRTIODevice *virtio_block_init(VIRTIOBusDef *bus, BlockDevice *bs)\n{\n VIRTIOBlockDevice *s;\n uint64_t nb_sectors;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 2, 8, virtio_block_recv_request);\n s->bs = bs;\n \n nb_sectors = bs->get_sector_count(bs);\n put_le32(s->common.config_space, nb_sectors);\n put_le32(s->common.config_space + 4, nb_sectors >> 32);\n\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* network device */\n\ntypedef struct VIRTIONetDevice {\n VIRTIODevice common;\n EthernetDevice *es;\n int header_size;\n} VIRTIONetDevice;\n\ntypedef struct {\n uint8_t flags;\n uint8_t gso_type;\n uint16_t hdr_len;\n uint16_t gso_size;\n uint16_t csum_start;\n uint16_t csum_offset;\n uint16_t num_buffers;\n} VIRTIONetHeader;\n\nstatic int virtio_net_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIONetDevice *s1 = (VIRTIONetDevice *)s;\n EthernetDevice *es = s1->es;\n VIRTIONetHeader h;\n uint8_t *buf;\n int len;\n\n if (queue_idx == 1) {\n /* send to network */\n if (memcpy_from_queue(s, &h, queue_idx, desc_idx, 0, s1->header_size) < 0)\n return 0;\n len = read_size - s1->header_size;\n buf = malloc(len);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, s1->header_size, len);\n es->write_packet(es, buf, len);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\nstatic BOOL virtio_net_can_write_packet(EthernetDevice *es)\n{\n VIRTIODevice *s = es->device_opaque;\n QueueState *qs = &s->queue[0];\n uint16_t avail_idx;\n\n if (!qs->ready)\n return FALSE;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n return qs->last_avail_idx != avail_idx;\n}\n\nstatic void virtio_net_write_packet(EthernetDevice *es, const uint8_t *buf, int buf_len)\n{\n VIRTIODevice *s = es->device_opaque;\n VIRTIONetDevice *s1 = (VIRTIONetDevice *)s;\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n VIRTIONetHeader h;\n int len, read_size, write_size;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx))\n return;\n len = s1->header_size + buf_len; \n if (len > write_size)\n return;\n memset(&h, 0, s1->header_size);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, &h, s1->header_size);\n memcpy_to_queue(s, queue_idx, desc_idx, s1->header_size, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, len);\n qs->last_avail_idx++;\n}\n\nstatic void virtio_net_set_carrier(EthernetDevice *es, BOOL carrier_state)\n{\n#if 0\n VIRTIODevice *s1 = es->device_opaque;\n VIRTIONetDevice *s = (VIRTIONetDevice *)s1;\n int cur_carrier_state;\n\n // printf(\"virtio_net_set_carrier: %d\\n\", carrier_state);\n cur_carrier_state = s->common.config_space[6] & 1;\n if (cur_carrier_state != carrier_state) {\n s->common.config_space[6] = (carrier_state << 0);\n virtio_config_change_notify(s1);\n }\n#endif\n}\n\nVIRTIODevice *virtio_net_init(VIRTIOBusDef *bus, EthernetDevice *es)\n{\n VIRTIONetDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 1, 6 + 2, virtio_net_recv_request);\n /* VIRTIO_NET_F_MAC, VIRTIO_NET_F_STATUS */\n s->common.device_features = (1 << 5) /* | (1 << 16) */;\n s->common.queue[0].manual_recv = TRUE;\n s->es = es;\n memcpy(s->common.config_space, es->mac_addr, 6);\n /* status */\n s->common.config_space[6] = 0;\n s->common.config_space[7] = 0;\n\n s->header_size = sizeof(VIRTIONetHeader);\n \n es->device_opaque = s;\n es->device_can_write_packet = virtio_net_can_write_packet;\n es->device_write_packet = virtio_net_write_packet;\n es->device_set_carrier = virtio_net_set_carrier;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* console device */\n\ntypedef struct VIRTIOConsoleDevice {\n VIRTIODevice common;\n CharacterDevice *cs;\n} VIRTIOConsoleDevice;\n\nstatic int virtio_console_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIOConsoleDevice *s1 = (VIRTIOConsoleDevice *)s;\n CharacterDevice *cs = s1->cs;\n uint8_t *buf;\n\n if (queue_idx == 1) {\n /* send to console */\n buf = malloc(read_size);\n memcpy_from_queue(s, buf, queue_idx, desc_idx, 0, read_size);\n cs->write_data(cs->opaque, buf, read_size);\n free(buf);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\nBOOL virtio_console_can_write_data(VIRTIODevice *s)\n{\n QueueState *qs = &s->queue[0];\n uint16_t avail_idx;\n\n if (!qs->ready)\n return FALSE;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n return qs->last_avail_idx != avail_idx;\n}\n\nint virtio_console_get_write_len(VIRTIODevice *s)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n int read_size, write_size;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return 0;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return 0;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n if (get_desc_rw_size(s, &read_size, &write_size, queue_idx, desc_idx))\n return 0;\n return write_size;\n}\n\nint virtio_console_write_data(VIRTIODevice *s, const uint8_t *buf, int buf_len)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx;\n uint16_t avail_idx;\n\n if (!qs->ready)\n return 0;\n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return 0;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, buf_len);\n qs->last_avail_idx++;\n return buf_len;\n}\n\n/* send a resize event */\nvoid virtio_console_resize_event(VIRTIODevice *s, int width, int height)\n{\n /* indicate the console size */\n put_le16(s->config_space + 0, width);\n put_le16(s->config_space + 2, height);\n\n virtio_config_change_notify(s);\n}\n\nVIRTIODevice *virtio_console_init(VIRTIOBusDef *bus, CharacterDevice *cs)\n{\n VIRTIOConsoleDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 3, 4, virtio_console_recv_request);\n s->common.device_features = (1 << 0); /* VIRTIO_CONSOLE_F_SIZE */\n s->common.queue[0].manual_recv = TRUE;\n \n s->cs = cs;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* input device */\n\nenum {\n VIRTIO_INPUT_CFG_UNSET = 0x00,\n VIRTIO_INPUT_CFG_ID_NAME = 0x01,\n VIRTIO_INPUT_CFG_ID_SERIAL = 0x02,\n VIRTIO_INPUT_CFG_ID_DEVIDS = 0x03,\n VIRTIO_INPUT_CFG_PROP_BITS = 0x10,\n VIRTIO_INPUT_CFG_EV_BITS = 0x11,\n VIRTIO_INPUT_CFG_ABS_INFO = 0x12,\n};\n\n#define VIRTIO_INPUT_EV_SYN 0x00\n#define VIRTIO_INPUT_EV_KEY 0x01\n#define VIRTIO_INPUT_EV_REL 0x02\n#define VIRTIO_INPUT_EV_ABS 0x03\n#define VIRTIO_INPUT_EV_REP 0x14\n\n#define BTN_LEFT 0x110\n#define BTN_RIGHT 0x111\n#define BTN_MIDDLE 0x112\n#define BTN_GEAR_DOWN 0x150\n#define BTN_GEAR_UP 0x151\n\n#define REL_X 0x00\n#define REL_Y 0x01\n#define REL_Z 0x02\n#define REL_WHEEL 0x08\n\n#define ABS_X 0x00\n#define ABS_Y 0x01\n#define ABS_Z 0x02\n\ntypedef struct VIRTIOInputDevice {\n VIRTIODevice common;\n VirtioInputTypeEnum type;\n uint32_t buttons_state;\n} VIRTIOInputDevice;\n\nstatic const uint16_t buttons_list[] = {\n BTN_LEFT, BTN_RIGHT, BTN_MIDDLE\n};\n\nstatic int virtio_input_recv_request(VIRTIODevice *s, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n if (queue_idx == 1) {\n /* led & keyboard updates */\n // printf(\"%s: write_size=%d\\n\", __func__, write_size);\n virtio_consume_desc(s, queue_idx, desc_idx, 0);\n }\n return 0;\n}\n\n/* return < 0 if could not send key event */\nstatic int virtio_input_queue_event(VIRTIODevice *s,\n uint16_t type, uint16_t code,\n uint32_t value)\n{\n int queue_idx = 0;\n QueueState *qs = &s->queue[queue_idx];\n int desc_idx, buf_len;\n uint16_t avail_idx;\n uint8_t buf[8];\n\n if (!qs->ready)\n return -1;\n\n put_le16(buf, type);\n put_le16(buf + 2, code);\n put_le32(buf + 4, value);\n buf_len = 8;\n \n avail_idx = virtio_read16(s, qs->avail_addr + 2);\n if (qs->last_avail_idx == avail_idx)\n return -1;\n desc_idx = virtio_read16(s, qs->avail_addr + 4 + \n (qs->last_avail_idx & (qs->num - 1)) * 2);\n // printf(\"send: queue_idx=%d desc_idx=%d\\n\", queue_idx, desc_idx);\n memcpy_to_queue(s, queue_idx, desc_idx, 0, buf, buf_len);\n virtio_consume_desc(s, queue_idx, desc_idx, buf_len);\n qs->last_avail_idx++;\n return 0;\n}\n\nint virtio_input_send_key_event(VIRTIODevice *s, BOOL is_down,\n uint16_t key_code)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n int ret;\n \n if (s1->type != VIRTIO_INPUT_TYPE_KEYBOARD)\n return -1;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_KEY, key_code, is_down);\n if (ret)\n return ret;\n return virtio_input_queue_event(s, VIRTIO_INPUT_EV_SYN, 0, 0);\n}\n\n/* also used for the tablet */\nint virtio_input_send_mouse_event(VIRTIODevice *s, int dx, int dy, int dz,\n unsigned int buttons)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n int ret, i, b, last_b;\n\n if (s1->type != VIRTIO_INPUT_TYPE_MOUSE &&\n s1->type != VIRTIO_INPUT_TYPE_TABLET)\n return -1;\n if (s1->type == VIRTIO_INPUT_TYPE_MOUSE) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_X, dx);\n if (ret != 0)\n return ret;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_Y, dy);\n if (ret != 0)\n return ret;\n } else {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_ABS, ABS_X, dx);\n if (ret != 0)\n return ret;\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_ABS, ABS_Y, dy);\n if (ret != 0)\n return ret;\n }\n if (dz != 0) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_REL, REL_WHEEL, dz);\n if (ret != 0)\n return ret;\n }\n\n if (buttons != s1->buttons_state) {\n for(i = 0; i < countof(buttons_list); i++) {\n b = (buttons >> i) & 1;\n last_b = (s1->buttons_state >> i) & 1;\n if (b != last_b) {\n ret = virtio_input_queue_event(s, VIRTIO_INPUT_EV_KEY,\n buttons_list[i], b);\n if (ret != 0)\n return ret;\n }\n }\n s1->buttons_state = buttons;\n }\n\n return virtio_input_queue_event(s, VIRTIO_INPUT_EV_SYN, 0, 0);\n}\n\nstatic void set_bit(uint8_t *tab, int k)\n{\n tab[k >> 3] |= 1 << (k & 7);\n}\n\nstatic void virtio_input_config_write(VIRTIODevice *s)\n{\n VIRTIOInputDevice *s1 = (VIRTIOInputDevice *)s;\n uint8_t *config = s->config_space;\n int i;\n \n // printf(\"config_write: %02x %02x\\n\", config[0], config[1]);\n switch(config[0]) {\n case VIRTIO_INPUT_CFG_UNSET:\n break;\n case VIRTIO_INPUT_CFG_ID_NAME:\n {\n const char *name;\n int len;\n switch(s1->type) {\n case VIRTIO_INPUT_TYPE_KEYBOARD:\n name = \"virtio_keyboard\";\n break;\n case VIRTIO_INPUT_TYPE_MOUSE:\n name = \"virtio_mouse\";\n break;\n case VIRTIO_INPUT_TYPE_TABLET:\n name = \"virtio_tablet\";\n break;\n default:\n abort();\n }\n len = strlen(name);\n config[2] = len;\n memcpy(config + 8, name, len);\n }\n break;\n default:\n case VIRTIO_INPUT_CFG_ID_SERIAL:\n case VIRTIO_INPUT_CFG_ID_DEVIDS:\n case VIRTIO_INPUT_CFG_PROP_BITS:\n config[2] = 0; /* size of reply */\n break;\n case VIRTIO_INPUT_CFG_EV_BITS:\n config[2] = 0;\n switch(s1->type) {\n case VIRTIO_INPUT_TYPE_KEYBOARD:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 128 / 8;\n memset(config + 8, 0xff, 128 / 8); /* bitmap */\n break;\n case VIRTIO_INPUT_EV_REP: /* allow key repetition */\n config[2] = 1;\n break;\n default:\n break;\n }\n break;\n case VIRTIO_INPUT_TYPE_MOUSE:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 512 / 8;\n memset(config + 8, 0, 512 / 8); /* bitmap */\n for(i = 0; i < countof(buttons_list); i++)\n set_bit(config + 8, buttons_list[i]);\n break;\n case VIRTIO_INPUT_EV_REL:\n config[2] = 2;\n config[8] = 0;\n config[9] = 0;\n set_bit(config + 8, REL_X);\n set_bit(config + 8, REL_Y);\n set_bit(config + 8, REL_WHEEL);\n break;\n default:\n break;\n }\n break;\n case VIRTIO_INPUT_TYPE_TABLET:\n switch(config[1]) {\n case VIRTIO_INPUT_EV_KEY:\n config[2] = 512 / 8;\n memset(config + 8, 0, 512 / 8); /* bitmap */\n for(i = 0; i < countof(buttons_list); i++)\n set_bit(config + 8, buttons_list[i]);\n break;\n case VIRTIO_INPUT_EV_REL:\n config[2] = 2;\n config[8] = 0;\n config[9] = 0;\n set_bit(config + 8, REL_WHEEL);\n break;\n case VIRTIO_INPUT_EV_ABS:\n config[2] = 1;\n config[8] = 0;\n set_bit(config + 8, ABS_X);\n set_bit(config + 8, ABS_Y);\n break;\n default:\n break;\n }\n break;\n default:\n abort();\n }\n break;\n case VIRTIO_INPUT_CFG_ABS_INFO:\n if (s1->type == VIRTIO_INPUT_TYPE_TABLET && config[1] <= 1) {\n /* for ABS_X and ABS_Y */\n config[2] = 5 * 4;\n put_le32(config + 8, 0); /* min */\n put_le32(config + 12, VIRTIO_INPUT_ABS_SCALE - 1) ; /* max */\n put_le32(config + 16, 0); /* fuzz */\n put_le32(config + 20, 0); /* flat */\n put_le32(config + 24, 0); /* res */\n }\n break;\n }\n}\n\nVIRTIODevice *virtio_input_init(VIRTIOBusDef *bus, VirtioInputTypeEnum type)\n{\n VIRTIOInputDevice *s;\n\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 18, 256, virtio_input_recv_request);\n s->common.queue[0].manual_recv = TRUE;\n s->common.device_features = 0;\n s->common.config_write = virtio_input_config_write;\n s->type = type;\n return (VIRTIODevice *)s;\n}\n\n/*********************************************************************/\n/* 9p filesystem device */\n\ntypedef struct {\n struct list_head link;\n uint32_t fid;\n FSFile *fd;\n} FIDDesc;\n\ntypedef struct VIRTIO9PDevice {\n VIRTIODevice common;\n FSDevice *fs;\n int msize; /* maximum message size */\n struct list_head fid_list; /* list of FIDDesc */\n BOOL req_in_progress;\n} VIRTIO9PDevice;\n\nstatic FIDDesc *fid_find1(VIRTIO9PDevice *s, uint32_t fid)\n{\n struct list_head *el;\n FIDDesc *f;\n\n list_for_each(el, &s->fid_list) {\n f = list_entry(el, FIDDesc, link);\n if (f->fid == fid)\n return f;\n }\n return NULL;\n}\n\nstatic FSFile *fid_find(VIRTIO9PDevice *s, uint32_t fid)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (!f)\n return NULL;\n return f->fd;\n}\n\nstatic void fid_delete(VIRTIO9PDevice *s, uint32_t fid)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (f) {\n s->fs->fs_delete(s->fs, f->fd);\n list_del(&f->link);\n free(f);\n }\n}\n\nstatic void fid_set(VIRTIO9PDevice *s, uint32_t fid, FSFile *fd)\n{\n FIDDesc *f;\n\n f = fid_find1(s, fid);\n if (f) {\n s->fs->fs_delete(s->fs, f->fd);\n f->fd = fd;\n } else {\n f = malloc(sizeof(*f));\n f->fid = fid;\n f->fd = fd;\n list_add(&f->link, &s->fid_list);\n }\n}\n\n#ifdef DEBUG_VIRTIO\n\ntypedef struct {\n uint8_t tag;\n const char *name;\n} Virtio9POPName;\n\nstatic const Virtio9POPName virtio_9p_op_names[] = {\n { 8, \"statfs\" },\n { 12, \"lopen\" },\n { 14, \"lcreate\" },\n { 16, \"symlink\" },\n { 18, \"mknod\" },\n { 22, \"readlink\" },\n { 24, \"getattr\" },\n { 26, \"setattr\" },\n { 30, \"xattrwalk\" },\n { 40, \"readdir\" },\n { 50, \"fsync\" },\n { 52, \"lock\" },\n { 54, \"getlock\" },\n { 70, \"link\" },\n { 72, \"mkdir\" },\n { 74, \"renameat\" },\n { 76, \"unlinkat\" },\n { 100, \"version\" },\n { 104, \"attach\" },\n { 108, \"flush\" },\n { 110, \"walk\" },\n { 116, \"read\" },\n { 118, \"write\" },\n { 120, \"clunk\" },\n { 0, NULL },\n};\n\nstatic const char *get_9p_op_name(int tag)\n{\n const Virtio9POPName *p;\n for(p = virtio_9p_op_names; p->name != NULL; p++) {\n if (p->tag == tag)\n return p->name;\n }\n return NULL;\n}\n\n#endif /* DEBUG_VIRTIO */\n\nstatic int marshall(VIRTIO9PDevice *s, \n uint8_t *buf1, int max_len, const char *fmt, ...)\n{\n va_list ap;\n int c;\n uint32_t val;\n uint64_t val64;\n uint8_t *buf, *buf_end;\n\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" ->\");\n#endif\n va_start(ap, fmt);\n buf = buf1;\n buf_end = buf1 + max_len;\n for(;;) {\n c = *fmt++;\n if (c == '\\0')\n break;\n switch(c) {\n case 'b':\n assert(buf + 1 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" b=%d\", val);\n#endif\n buf[0] = val;\n buf += 1;\n break;\n case 'h':\n assert(buf + 2 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" h=%d\", val);\n#endif\n put_le16(buf, val);\n buf += 2;\n break;\n case 'w':\n assert(buf + 4 <= buf_end);\n val = va_arg(ap, int);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" w=%d\", val);\n#endif\n put_le32(buf, val);\n buf += 4;\n break;\n case 'd':\n assert(buf + 8 <= buf_end);\n val64 = va_arg(ap, uint64_t);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" d=%\" PRId64, val64);\n#endif\n put_le64(buf, val64);\n buf += 8;\n break;\n case 's':\n {\n char *str;\n int len;\n str = va_arg(ap, char *);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" s=\\\"%s\\\"\", str);\n#endif\n len = strlen(str);\n assert(len <= 65535);\n assert(buf + 2 + len <= buf_end);\n put_le16(buf, len);\n buf += 2;\n memcpy(buf, str, len);\n buf += len;\n }\n break;\n case 'Q':\n {\n FSQID *qid;\n assert(buf + 13 <= buf_end);\n qid = va_arg(ap, FSQID *);\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" Q=%d:%d:%\" PRIu64, qid->type, qid->version, qid->path);\n#endif\n buf[0] = qid->type;\n put_le32(buf + 1, qid->version);\n put_le64(buf + 5, qid->path);\n buf += 13;\n }\n break;\n default:\n abort();\n }\n }\n va_end(ap);\n return buf - buf1;\n}\n\n/* return < 0 if error */\n/* XXX: free allocated strings in case of error */\nstatic int unmarshall(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, int *poffset, const char *fmt, ...)\n{\n VIRTIODevice *s1 = (VIRTIODevice *)s;\n va_list ap;\n int offset, c;\n uint8_t buf[16];\n\n offset = *poffset;\n va_start(ap, fmt);\n for(;;) {\n c = *fmt++;\n if (c == '\\0')\n break;\n switch(c) {\n case 'b':\n {\n uint8_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 1))\n return -1;\n ptr = va_arg(ap, uint8_t *);\n *ptr = buf[0];\n offset += 1;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" b=%d\", *ptr);\n#endif\n }\n break;\n case 'h':\n {\n uint16_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 2))\n return -1;\n ptr = va_arg(ap, uint16_t *);\n *ptr = get_le16(buf);\n offset += 2;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" h=%d\", *ptr);\n#endif\n }\n break;\n case 'w':\n {\n uint32_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 4))\n return -1;\n ptr = va_arg(ap, uint32_t *);\n *ptr = get_le32(buf);\n offset += 4;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" w=%d\", *ptr);\n#endif\n }\n break;\n case 'd':\n {\n uint64_t *ptr;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 8))\n return -1;\n ptr = va_arg(ap, uint64_t *);\n *ptr = get_le64(buf);\n offset += 8;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" d=%\" PRId64, *ptr);\n#endif\n }\n break;\n case 's':\n {\n char *str, **ptr;\n int len;\n\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, 2))\n return -1;\n len = get_le16(buf);\n offset += 2;\n str = malloc(len + 1);\n if (memcpy_from_queue(s1, str, queue_idx, desc_idx, offset, len))\n return -1;\n str[len] = '\\0';\n offset += len;\n ptr = va_arg(ap, char **);\n *ptr = str;\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P)\n printf(\" s=\\\"%s\\\"\", *ptr);\n#endif\n }\n break;\n default:\n abort();\n }\n }\n va_end(ap);\n *poffset = offset;\n return 0;\n}\n\nstatic void virtio_9p_send_reply(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, uint8_t id, uint16_t tag, \n uint8_t *buf, int buf_len)\n{\n uint8_t *buf1;\n int len;\n\n#ifdef DEBUG_VIRTIO\n if (s->common.debug & VIRTIO_DEBUG_9P) {\n if (id == 6)\n printf(\" (error)\");\n printf(\"\\n\");\n }\n#endif\n len = buf_len + 7;\n buf1 = malloc(len);\n put_le32(buf1, len);\n buf1[4] = id + 1;\n put_le16(buf1 + 5, tag);\n memcpy(buf1 + 7, buf, buf_len);\n memcpy_to_queue((VIRTIODevice *)s, queue_idx, desc_idx, 0, buf1, len);\n virtio_consume_desc((VIRTIODevice *)s, queue_idx, desc_idx, len);\n free(buf1);\n}\n\nstatic void virtio_9p_send_error(VIRTIO9PDevice *s, int queue_idx,\n int desc_idx, uint16_t tag, uint32_t error)\n{\n uint8_t buf[4];\n int buf_len;\n\n buf_len = marshall(s, buf, sizeof(buf), \"w\", -error);\n virtio_9p_send_reply(s, queue_idx, desc_idx, 6, tag, buf, buf_len);\n}\n\ntypedef struct {\n VIRTIO9PDevice *dev;\n int queue_idx;\n int desc_idx;\n uint16_t tag;\n} P9OpenInfo;\n\nstatic void virtio_9p_open_reply(FSDevice *fs, FSQID *qid, int err,\n P9OpenInfo *oi)\n{\n VIRTIO9PDevice *s = oi->dev;\n uint8_t buf[32];\n int buf_len;\n \n if (err < 0) {\n virtio_9p_send_error(s, oi->queue_idx, oi->desc_idx, oi->tag, err);\n } else {\n buf_len = marshall(s, buf, sizeof(buf),\n \"Qw\", qid, s->msize - 24);\n virtio_9p_send_reply(s, oi->queue_idx, oi->desc_idx, 12, oi->tag,\n buf, buf_len);\n }\n free(oi);\n}\n\nstatic void virtio_9p_open_cb(FSDevice *fs, FSQID *qid, int err,\n void *opaque)\n{\n P9OpenInfo *oi = opaque;\n VIRTIO9PDevice *s = oi->dev;\n int queue_idx = oi->queue_idx;\n \n virtio_9p_open_reply(fs, qid, err, oi);\n\n s->req_in_progress = FALSE;\n\n /* handle next requests */\n queue_notify((VIRTIODevice *)s, queue_idx);\n}\n\nstatic int virtio_9p_recv_request(VIRTIODevice *s1, int queue_idx,\n int desc_idx, int read_size,\n int write_size)\n{\n VIRTIO9PDevice *s = (VIRTIO9PDevice *)s1;\n int offset, header_len;\n uint8_t id;\n uint16_t tag;\n uint8_t buf[1024];\n int buf_len, err;\n FSDevice *fs = s->fs;\n\n if (queue_idx != 0)\n return 0;\n \n if (s->req_in_progress)\n return -1;\n \n offset = 0;\n header_len = 4 + 1 + 2;\n if (memcpy_from_queue(s1, buf, queue_idx, desc_idx, offset, header_len)) {\n tag = 0;\n goto protocol_error;\n }\n //size = get_le32(buf);\n id = buf[4];\n tag = get_le16(buf + 5);\n offset += header_len;\n \n#ifdef DEBUG_VIRTIO\n if (s1->debug & VIRTIO_DEBUG_9P) {\n const char *name;\n name = get_9p_op_name(id);\n printf(\"9p: op=\");\n if (name)\n printf(\"%s\", name);\n else\n printf(\"%d\", id);\n }\n#endif\n /* Note: same subset as JOR1K */\n switch(id) {\n case 8: /* statfs */\n {\n FSStatFS st;\n\n fs->fs_statfs(fs, &st);\n buf_len = marshall(s, buf, sizeof(buf),\n \"wwddddddw\", \n 0,\n st.f_bsize,\n st.f_blocks,\n st.f_bfree,\n st.f_bavail,\n st.f_files,\n st.f_ffree,\n 0, /* id */\n 256 /* max filename length */\n );\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 12: /* lopen */\n {\n uint32_t fid, flags;\n FSFile *f;\n FSQID qid;\n P9OpenInfo *oi;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"ww\", &fid, &flags))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n oi = malloc(sizeof(*oi));\n oi->dev = s;\n oi->queue_idx = queue_idx;\n oi->desc_idx = desc_idx;\n oi->tag = tag;\n err = fs->fs_open(fs, &qid, f, flags, virtio_9p_open_cb, oi);\n if (err <= 0) {\n virtio_9p_open_reply(fs, &qid, err, oi);\n } else {\n s->req_in_progress = TRUE;\n }\n }\n break;\n case 14: /* lcreate */\n {\n uint32_t fid, flags, mode, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wswww\", &fid, &name, &flags, &mode, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_create(fs, &qid, f, name, flags, mode, gid);\n }\n free(name);\n if (err) \n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Qw\", &qid, s->msize - 24);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 16: /* symlink */\n {\n uint32_t fid, gid;\n char *name, *symgt;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wssw\", &fid, &name, &symgt, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_symlink(fs, &qid, f, name, symgt, gid);\n }\n free(name);\n free(symgt);\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 18: /* mknod */\n {\n uint32_t fid, mode, major, minor, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wswwww\", &fid, &name, &mode, &major, &minor, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_mknod(fs, &qid, f, name, mode, major, minor, gid);\n }\n free(name);\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf),\n \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 22: /* readlink */\n {\n uint32_t fid;\n char buf1[1024];\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"w\", &fid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_readlink(fs, buf1, sizeof(buf1), f);\n }\n if (err)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"s\", buf1);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 24: /* getattr */\n {\n uint32_t fid;\n uint64_t mask;\n FSFile *f;\n FSStat st;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wd\", &fid, &mask))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_stat(fs, f, &st);\n if (err)\n goto error;\n\n buf_len = marshall(s, buf, sizeof(buf),\n \"dQwwwddddddddddddddd\", \n mask, &st.qid,\n st.st_mode, st.st_uid, st.st_gid,\n st.st_nlink, st.st_rdev, st.st_size,\n st.st_blksize, st.st_blocks,\n st.st_atime_sec, (uint64_t)st.st_atime_nsec,\n st.st_mtime_sec, (uint64_t)st.st_mtime_nsec,\n st.st_ctime_sec, (uint64_t)st.st_ctime_nsec,\n (uint64_t)0, (uint64_t)0,\n (uint64_t)0, (uint64_t)0);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 26: /* setattr */\n {\n uint32_t fid, mask, mode, uid, gid;\n uint64_t size, atime_sec, atime_nsec, mtime_sec, mtime_nsec;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wwwwwddddd\", &fid, &mask, &mode, &uid, &gid,\n &size, &atime_sec, &atime_nsec, \n &mtime_sec, &mtime_nsec))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_setattr(fs, f, mask, mode, uid, gid, size, atime_sec,\n atime_nsec, mtime_sec, mtime_nsec);\n if (err)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 30: /* xattrwalk */\n {\n /* not supported yet */\n err = -P9_ENOTSUP;\n goto error;\n }\n break;\n case 40: /* readdir */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf = malloc(count + 4);\n n = fs->fs_readdir(fs, f, offs, buf + 4, count);\n if (n < 0) {\n err = n;\n goto error;\n }\n put_le32(buf, n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, n + 4);\n free(buf);\n }\n break;\n case 50: /* fsync */\n {\n uint32_t fid;\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"w\", &fid))\n goto protocol_error;\n /* ignored */\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 52: /* lock */\n {\n uint32_t fid;\n FSFile *f;\n FSLock lock;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wbwddws\", &fid, &lock.type, &lock.flags,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n err = -P9_EPROTO;\n else\n err = fs->fs_lock(fs, f, &lock);\n free(lock.client_id);\n if (err < 0)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"b\", err);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 54: /* getlock */\n {\n uint32_t fid;\n FSFile *f;\n FSLock lock;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wbddws\", &fid, &lock.type,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n err = -P9_EPROTO;\n else\n err = fs->fs_getlock(fs, f, &lock);\n if (err < 0) {\n free(lock.client_id);\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"bddws\",\n &lock.type,\n &lock.start, &lock.length,\n &lock.proc_id, &lock.client_id);\n free(lock.client_id);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 70: /* link */\n {\n uint32_t dfid, fid;\n char *name;\n FSFile *f, *df;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wws\", &dfid, &fid, &name))\n goto protocol_error;\n df = fid_find(s, dfid);\n f = fid_find(s, fid);\n if (!df || !f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_link(fs, df, f, name);\n }\n free(name);\n if (err)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 72: /* mkdir */\n {\n uint32_t fid, mode, gid;\n char *name;\n FSFile *f;\n FSQID qid;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsww\", &fid, &name, &mode, &gid))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n err = fs->fs_mkdir(fs, &qid, f, name, mode, gid);\n if (err != 0)\n goto error;\n buf_len = marshall(s, buf, sizeof(buf), \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 74: /* renameat */\n {\n uint32_t fid, new_fid;\n char *name, *new_name;\n FSFile *f, *new_f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsws\", &fid, &name, &new_fid, &new_name))\n goto protocol_error;\n f = fid_find(s, fid);\n new_f = fid_find(s, new_fid);\n if (!f || !new_f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_renameat(fs, f, name, new_f, new_name);\n }\n free(name);\n free(new_name);\n if (err != 0)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 76: /* unlinkat */\n {\n uint32_t fid, flags;\n char *name;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wsw\", &fid, &name, &flags))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f) {\n err = -P9_EPROTO;\n } else {\n err = fs->fs_unlinkat(fs, f, name);\n }\n free(name);\n if (err != 0)\n goto error;\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 100: /* version */\n {\n uint32_t msize;\n char *version;\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"ws\", &msize, &version))\n goto protocol_error;\n s->msize = msize;\n // printf(\"version: msize=%d version=%s\\n\", msize, version);\n free(version);\n buf_len = marshall(s, buf, sizeof(buf), \"ws\", s->msize, \"9P2000.L\");\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 104: /* attach */\n {\n uint32_t fid, afid, uid;\n char *uname, *aname;\n FSQID qid;\n FSFile *f;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"wwssw\", &fid, &afid, &uname, &aname, &uid))\n goto protocol_error;\n err = fs->fs_attach(fs, &f, &qid, uid, uname, aname);\n if (err != 0)\n goto error;\n fid_set(s, fid, f);\n free(uname);\n free(aname);\n buf_len = marshall(s, buf, sizeof(buf), \"Q\", &qid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 108: /* flush */\n {\n uint16_t oldtag;\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"h\", &oldtag))\n goto protocol_error;\n /* ignored */\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n case 110: /* walk */\n {\n uint32_t fid, newfid;\n uint16_t nwname;\n FSQID *qids;\n char **names;\n FSFile *f;\n int i;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"wwh\", &fid, &newfid, &nwname))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n names = mallocz(sizeof(names[0]) * nwname);\n qids = malloc(sizeof(qids[0]) * nwname);\n for(i = 0; i < nwname; i++) {\n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"s\", &names[i])) {\n err = -P9_EPROTO;\n goto walk_done;\n }\n }\n err = fs->fs_walk(fs, &f, qids, f, nwname, names);\n walk_done:\n for(i = 0; i < nwname; i++) {\n free(names[i]);\n }\n free(names);\n if (err < 0) {\n free(qids);\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"h\", err);\n for(i = 0; i < err; i++) {\n buf_len += marshall(s, buf + buf_len, sizeof(buf) - buf_len,\n \"Q\", &qids[i]);\n }\n free(qids);\n fid_set(s, newfid, f);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 116: /* read */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf = malloc(count + 4);\n n = fs->fs_read(fs, f, offs, buf + 4, count);\n if (n < 0) {\n err = n;\n free(buf);\n goto error;\n }\n put_le32(buf, n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, n + 4);\n free(buf);\n }\n break;\n case 118: /* write */\n {\n uint32_t fid, count;\n uint64_t offs;\n uint8_t *buf1;\n int n;\n FSFile *f;\n\n if (unmarshall(s, queue_idx, desc_idx, &offset,\n \"wdw\", &fid, &offs, &count))\n goto protocol_error;\n f = fid_find(s, fid);\n if (!f)\n goto fid_not_found;\n buf1 = malloc(count);\n if (memcpy_from_queue(s1, buf1, queue_idx, desc_idx, offset,\n count)) {\n free(buf1);\n goto protocol_error;\n }\n n = fs->fs_write(fs, f, offs, buf1, count);\n free(buf1);\n if (n < 0) {\n err = n;\n goto error;\n }\n buf_len = marshall(s, buf, sizeof(buf), \"w\", n);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, buf, buf_len);\n }\n break;\n case 120: /* clunk */\n {\n uint32_t fid;\n \n if (unmarshall(s, queue_idx, desc_idx, &offset, \n \"w\", &fid))\n goto protocol_error;\n fid_delete(s, fid);\n virtio_9p_send_reply(s, queue_idx, desc_idx, id, tag, NULL, 0);\n }\n break;\n default:\n printf(\"9p: unsupported operation id=%d\\n\", id);\n goto protocol_error;\n }\n return 0;\n error:\n virtio_9p_send_error(s, queue_idx, desc_idx, tag, err);\n return 0;\n protocol_error:\n fid_not_found:\n err = -P9_EPROTO;\n goto error;\n}\n\nVIRTIODevice *virtio_9p_init(VIRTIOBusDef *bus, FSDevice *fs,\n const char *mount_tag)\n\n{\n VIRTIO9PDevice *s;\n int len;\n uint8_t *cfg;\n\n len = strlen(mount_tag);\n s = mallocz(sizeof(*s));\n virtio_init(&s->common, bus,\n 9, 2 + len, virtio_9p_recv_request);\n s->common.device_features = 1 << 0;\n\n /* set the mount tag */\n cfg = s->common.config_space;\n cfg[0] = len;\n cfg[1] = len >> 8;\n memcpy(cfg + 2, mount_tag, len);\n\n s->fs = fs;\n s->msize = 8192;\n init_list_head(&s->fid_list);\n \n return (VIRTIODevice *)s;\n}\n\n"], ["/linuxpdf/tinyemu/fs_wget.c", "/*\n * HTTP file download\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs.h\"\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n\n#if defined(EMSCRIPTEN)\n#include \n#else\n#include \n#endif\n\n/***********************************************/\n/* HTTP get */\n\n#ifdef EMSCRIPTEN\n\nstruct XHRState {\n void *opaque;\n WGetWriteCallback *cb;\n};\n\nstatic int downloading_count;\n\nvoid fs_wget_init(void)\n{\n}\n\nextern void fs_wget_update_downloading(int flag);\n\nstatic void fs_wget_update_downloading_count(int incr)\n{\n int prev_state, state;\n prev_state = (downloading_count > 0);\n downloading_count += incr;\n state = (downloading_count > 0);\n if (prev_state != state)\n fs_wget_update_downloading(state);\n}\n\nstatic void fs_wget_onerror(unsigned int handle, void *opaque, int status,\n const char *status_text)\n{\n XHRState *s = opaque;\n if (status <= 0)\n status = -404; /* HTTP not found error */\n else\n status = -status;\n fs_wget_update_downloading_count(-1);\n if (s->cb)\n s->cb(s->opaque, status, NULL, 0);\n}\n\nstatic void fs_wget_onload(unsigned int handle,\n void *opaque, void *data, unsigned int size)\n{\n XHRState *s = opaque;\n fs_wget_update_downloading_count(-1);\n if (s->cb)\n s->cb(s->opaque, 0, data, size);\n}\n\nextern int emscripten_async_wget3_data(const char* url, const char* requesttype, const char *user, const char *password, const uint8_t *post_data, int post_data_len, void *arg, int free, em_async_wget2_data_onload_func onload, em_async_wget2_data_onerror_func onerror, em_async_wget2_data_onprogress_func onprogress);\n\nXHRState *fs_wget2(const char *url, const char *user, const char *password,\n WGetReadCallback *read_cb, uint64_t post_data_len,\n void *opaque, WGetWriteCallback *cb, BOOL single_write)\n{\n XHRState *s;\n const char *request;\n uint8_t *post_data;\n \n s = mallocz(sizeof(*s));\n s->opaque = opaque;\n s->cb = cb;\n\n if (post_data_len != 0) {\n request = \"POST\";\n post_data = malloc(post_data_len);\n read_cb(opaque, post_data, post_data_len);\n } else {\n request = \"GET\";\n post_data = NULL;\n }\n fs_wget_update_downloading_count(1);\n\n emscripten_async_wget3_data(url, request, user, password,\n post_data, post_data_len, s, 1, fs_wget_onload,\n fs_wget_onerror, NULL);\n if (post_data_len != 0)\n free(post_data);\n return s;\n}\n\nvoid fs_wget_free(XHRState *s)\n{\n s->cb = NULL;\n s->opaque = NULL;\n}\n\n#else\n\nstruct XHRState {\n struct list_head link;\n CURL *eh;\n void *opaque;\n WGetWriteCallback *write_cb;\n WGetReadCallback *read_cb;\n\n BOOL single_write;\n DynBuf dbuf; /* used if single_write */\n};\n\ntypedef struct {\n struct list_head link;\n int64_t timeout;\n void (*cb)(void *opaque);\n void *opaque;\n} AsyncCallState;\n\nstatic CURLM *curl_multi_ctx;\nstatic struct list_head xhr_list; /* list of XHRState.link */\n\nvoid fs_wget_init(void)\n{\n if (curl_multi_ctx)\n return;\n curl_global_init(CURL_GLOBAL_ALL);\n curl_multi_ctx = curl_multi_init();\n init_list_head(&xhr_list);\n}\n\nvoid fs_wget_end(void)\n{\n curl_multi_cleanup(curl_multi_ctx);\n curl_global_cleanup();\n}\n\nstatic size_t fs_wget_write_cb(char *ptr, size_t size, size_t nmemb,\n void *userdata)\n{\n XHRState *s = userdata;\n size *= nmemb;\n\n if (s->single_write) {\n dbuf_write(&s->dbuf, s->dbuf.size, (void *)ptr, size);\n } else {\n s->write_cb(s->opaque, 1, ptr, size);\n }\n return size;\n}\n\nstatic size_t fs_wget_read_cb(char *ptr, size_t size, size_t nmemb,\n void *userdata)\n{\n XHRState *s = userdata;\n size *= nmemb;\n return s->read_cb(s->opaque, ptr, size);\n}\n\nXHRState *fs_wget2(const char *url, const char *user, const char *password,\n WGetReadCallback *read_cb, uint64_t post_data_len,\n void *opaque, WGetWriteCallback *write_cb, BOOL single_write)\n{\n XHRState *s;\n s = mallocz(sizeof(*s));\n s->eh = curl_easy_init();\n s->opaque = opaque;\n s->write_cb = write_cb;\n s->read_cb = read_cb;\n s->single_write = single_write;\n dbuf_init(&s->dbuf);\n \n curl_easy_setopt(s->eh, CURLOPT_PRIVATE, s);\n curl_easy_setopt(s->eh, CURLOPT_WRITEDATA, s);\n curl_easy_setopt(s->eh, CURLOPT_WRITEFUNCTION, fs_wget_write_cb);\n curl_easy_setopt(s->eh, CURLOPT_HEADER, 0);\n curl_easy_setopt(s->eh, CURLOPT_URL, url);\n curl_easy_setopt(s->eh, CURLOPT_VERBOSE, 0L);\n curl_easy_setopt(s->eh, CURLOPT_ACCEPT_ENCODING, \"\");\n if (user) {\n curl_easy_setopt(s->eh, CURLOPT_USERNAME, user);\n curl_easy_setopt(s->eh, CURLOPT_PASSWORD, password);\n }\n if (post_data_len != 0) {\n struct curl_slist *headers = NULL;\n headers = curl_slist_append(headers,\n \"Content-Type: application/octet-stream\");\n curl_easy_setopt(s->eh, CURLOPT_HTTPHEADER, headers);\n curl_easy_setopt(s->eh, CURLOPT_POST, 1L);\n curl_easy_setopt(s->eh, CURLOPT_POSTFIELDSIZE_LARGE,\n (curl_off_t)post_data_len);\n curl_easy_setopt(s->eh, CURLOPT_READDATA, s);\n curl_easy_setopt(s->eh, CURLOPT_READFUNCTION, fs_wget_read_cb);\n }\n curl_multi_add_handle(curl_multi_ctx, s->eh);\n list_add_tail(&s->link, &xhr_list);\n return s;\n}\n\nvoid fs_wget_free(XHRState *s)\n{\n dbuf_free(&s->dbuf);\n curl_easy_cleanup(s->eh);\n list_del(&s->link);\n free(s);\n}\n\n/* timeout is in ms */\nvoid fs_net_set_fdset(int *pfd_max, fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *ptimeout)\n{\n long timeout;\n int n, fd_max;\n CURLMsg *msg;\n \n if (!curl_multi_ctx)\n return;\n \n curl_multi_perform(curl_multi_ctx, &n);\n\n for(;;) {\n msg = curl_multi_info_read(curl_multi_ctx, &n);\n if (!msg)\n break;\n if (msg->msg == CURLMSG_DONE) {\n XHRState *s;\n long http_code;\n\n curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char **)&s);\n curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE,\n &http_code);\n /* signal the end of the transfer or error */\n if (http_code == 200) {\n if (s->single_write) {\n s->write_cb(s->opaque, 0, s->dbuf.buf, s->dbuf.size);\n } else {\n s->write_cb(s->opaque, 0, NULL, 0);\n }\n } else {\n s->write_cb(s->opaque, -http_code, NULL, 0);\n }\n curl_multi_remove_handle(curl_multi_ctx, s->eh);\n curl_easy_cleanup(s->eh);\n dbuf_free(&s->dbuf);\n list_del(&s->link);\n free(s);\n }\n }\n\n curl_multi_fdset(curl_multi_ctx, rfds, wfds, efds, &fd_max);\n *pfd_max = max_int(*pfd_max, fd_max);\n curl_multi_timeout(curl_multi_ctx, &timeout);\n if (timeout >= 0)\n *ptimeout = min_int(*ptimeout, timeout);\n}\n\nvoid fs_net_event_loop(FSNetEventLoopCompletionFunc *cb, void *opaque)\n{\n fd_set rfds, wfds, efds;\n int timeout, fd_max;\n struct timeval tv;\n \n if (!curl_multi_ctx)\n return;\n\n for(;;) {\n fd_max = -1;\n FD_ZERO(&rfds);\n FD_ZERO(&wfds);\n FD_ZERO(&efds);\n timeout = 10000;\n fs_net_set_fdset(&fd_max, &rfds, &wfds, &efds, &timeout);\n if (cb) {\n if (cb(opaque))\n break;\n } else {\n if (list_empty(&xhr_list))\n break;\n }\n tv.tv_sec = timeout / 1000;\n tv.tv_usec = (timeout % 1000) * 1000;\n select(fd_max + 1, &rfds, &wfds, &efds, &tv);\n }\n}\n\n#endif /* !EMSCRIPTEN */\n\nXHRState *fs_wget(const char *url, const char *user, const char *password,\n void *opaque, WGetWriteCallback *cb, BOOL single_write)\n{\n return fs_wget2(url, user, password, NULL, 0, opaque, cb, single_write);\n}\n\n/***********************************************/\n/* file decryption */\n\n#define ENCRYPTED_FILE_HEADER_SIZE (4 + AES_BLOCK_SIZE)\n\n#define DEC_BUF_SIZE (256 * AES_BLOCK_SIZE)\n\nstruct DecryptFileState {\n DecryptFileCB *write_cb;\n void *opaque;\n int dec_state;\n int dec_buf_pos;\n AES_KEY *aes_state;\n uint8_t iv[AES_BLOCK_SIZE];\n uint8_t dec_buf[DEC_BUF_SIZE];\n};\n\nDecryptFileState *decrypt_file_init(AES_KEY *aes_state,\n DecryptFileCB *write_cb,\n void *opaque)\n{\n DecryptFileState *s;\n s = mallocz(sizeof(*s));\n s->write_cb = write_cb;\n s->opaque = opaque;\n s->aes_state = aes_state;\n return s;\n}\n \nint decrypt_file(DecryptFileState *s, const uint8_t *data,\n size_t size)\n{\n int l, len, ret;\n\n while (size != 0) {\n switch(s->dec_state) {\n case 0:\n l = min_int(size, ENCRYPTED_FILE_HEADER_SIZE - s->dec_buf_pos);\n memcpy(s->dec_buf + s->dec_buf_pos, data, l);\n s->dec_buf_pos += l;\n if (s->dec_buf_pos >= ENCRYPTED_FILE_HEADER_SIZE) {\n if (memcmp(s->dec_buf, encrypted_file_magic, 4) != 0)\n return -1;\n memcpy(s->iv, s->dec_buf + 4, AES_BLOCK_SIZE);\n s->dec_state = 1;\n s->dec_buf_pos = 0;\n }\n break;\n case 1:\n l = min_int(size, DEC_BUF_SIZE - s->dec_buf_pos);\n memcpy(s->dec_buf + s->dec_buf_pos, data, l);\n s->dec_buf_pos += l;\n if (s->dec_buf_pos >= DEC_BUF_SIZE) {\n /* keep one block in case it is the padding */\n len = s->dec_buf_pos - AES_BLOCK_SIZE;\n AES_cbc_encrypt(s->dec_buf, s->dec_buf, len,\n s->aes_state, s->iv, FALSE);\n ret = s->write_cb(s->opaque, s->dec_buf, len);\n if (ret < 0)\n return ret;\n memcpy(s->dec_buf, s->dec_buf + s->dec_buf_pos - AES_BLOCK_SIZE,\n AES_BLOCK_SIZE);\n s->dec_buf_pos = AES_BLOCK_SIZE;\n }\n break;\n default:\n abort();\n }\n data += l;\n size -= l;\n }\n return 0;\n}\n\n/* write last blocks */\nint decrypt_file_flush(DecryptFileState *s)\n{\n int len, pad_len, ret;\n\n if (s->dec_state != 1)\n return -1;\n len = s->dec_buf_pos;\n if (len == 0 || \n (len % AES_BLOCK_SIZE) != 0)\n return -1;\n AES_cbc_encrypt(s->dec_buf, s->dec_buf, len,\n s->aes_state, s->iv, FALSE);\n pad_len = s->dec_buf[s->dec_buf_pos - 1];\n if (pad_len < 1 || pad_len > AES_BLOCK_SIZE)\n return -1;\n len -= pad_len;\n if (len != 0) {\n ret = s->write_cb(s->opaque, s->dec_buf, len);\n if (ret < 0)\n return ret;\n }\n return 0;\n}\n\nvoid decrypt_file_end(DecryptFileState *s)\n{\n free(s);\n}\n\n/* XHR file */\n\ntypedef struct {\n FSDevice *fs;\n FSFile *f;\n int64_t pos;\n FSWGetFileCB *cb;\n void *opaque;\n FSFile *posted_file;\n int64_t read_pos;\n DecryptFileState *dec_state;\n} FSWGetFileState;\n\nstatic int fs_wget_file_write_cb(void *opaque, const uint8_t *data,\n size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n\n ret = fs->fs_write(fs, s->f, s->pos, data, size);\n if (ret < 0)\n return ret;\n s->pos += ret;\n return ret;\n}\n\nstatic void fs_wget_file_on_load(void *opaque, int err, void *data, size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n int64_t ret_size;\n \n // printf(\"err=%d size=%ld\\n\", err, size);\n if (err < 0) {\n ret_size = err;\n goto done;\n } else {\n if (s->dec_state) {\n ret = decrypt_file(s->dec_state, data, size);\n if (ret >= 0 && err == 0) {\n /* handle the end of file */\n decrypt_file_flush(s->dec_state);\n }\n } else {\n ret = fs_wget_file_write_cb(s, data, size);\n }\n if (ret < 0) {\n ret_size = ret;\n goto done;\n } else if (err == 0) {\n /* end of transfer */\n ret_size = s->pos;\n done:\n s->cb(fs, s->f, ret_size, s->opaque);\n if (s->dec_state)\n decrypt_file_end(s->dec_state);\n free(s);\n }\n }\n}\n\nstatic size_t fs_wget_file_read_cb(void *opaque, void *data, size_t size)\n{\n FSWGetFileState *s = opaque;\n FSDevice *fs = s->fs;\n int ret;\n \n if (!s->posted_file)\n return 0;\n ret = fs->fs_read(fs, s->posted_file, s->read_pos, data, size);\n if (ret < 0)\n return 0;\n s->read_pos += ret;\n return ret;\n}\n\nvoid fs_wget_file2(FSDevice *fs, FSFile *f, const char *url,\n const char *user, const char *password,\n FSFile *posted_file, uint64_t post_data_len,\n FSWGetFileCB *cb, void *opaque,\n AES_KEY *aes_state)\n{\n FSWGetFileState *s;\n s = mallocz(sizeof(*s));\n s->fs = fs;\n s->f = f;\n s->pos = 0;\n s->cb = cb;\n s->opaque = opaque;\n s->posted_file = posted_file;\n s->read_pos = 0;\n if (aes_state) {\n s->dec_state = decrypt_file_init(aes_state, fs_wget_file_write_cb, s);\n }\n \n fs_wget2(url, user, password, fs_wget_file_read_cb, post_data_len,\n s, fs_wget_file_on_load, FALSE);\n}\n\n/***********************************************/\n/* PBKDF2 */\n\n#ifdef USE_BUILTIN_CRYPTO\n\n#define HMAC_BLOCK_SIZE 64\n\ntypedef struct {\n SHA256_CTX ctx;\n uint8_t K[HMAC_BLOCK_SIZE + SHA256_DIGEST_LENGTH];\n} HMAC_SHA256_CTX;\n\nvoid hmac_sha256_init(HMAC_SHA256_CTX *s, const uint8_t *key, int key_len)\n{\n int i, l;\n \n if (key_len > HMAC_BLOCK_SIZE) {\n SHA256(key, key_len, s->K);\n l = SHA256_DIGEST_LENGTH;\n } else {\n memcpy(s->K, key, key_len);\n l = key_len;\n }\n memset(s->K + l, 0, HMAC_BLOCK_SIZE - l);\n for(i = 0; i < HMAC_BLOCK_SIZE; i++)\n s->K[i] ^= 0x36;\n SHA256_Init(&s->ctx);\n SHA256_Update(&s->ctx, s->K, HMAC_BLOCK_SIZE);\n}\n\nvoid hmac_sha256_update(HMAC_SHA256_CTX *s, const uint8_t *buf, int len)\n{\n SHA256_Update(&s->ctx, buf, len);\n}\n\n/* out has a length of SHA256_DIGEST_LENGTH */\nvoid hmac_sha256_final(HMAC_SHA256_CTX *s, uint8_t *out)\n{\n int i;\n \n SHA256_Final(s->K + HMAC_BLOCK_SIZE, &s->ctx);\n for(i = 0; i < HMAC_BLOCK_SIZE; i++)\n s->K[i] ^= (0x36 ^ 0x5c);\n SHA256(s->K, HMAC_BLOCK_SIZE + SHA256_DIGEST_LENGTH, out);\n}\n\n#define SALT_LEN_MAX 32\n\nvoid pbkdf2_hmac_sha256(const uint8_t *pwd, int pwd_len,\n const uint8_t *salt, int salt_len,\n int iter, int key_len, uint8_t *out)\n{\n uint8_t F[SHA256_DIGEST_LENGTH], U[SALT_LEN_MAX + 4];\n HMAC_SHA256_CTX ctx;\n int it, U_len, j, l;\n uint32_t i;\n \n assert(salt_len <= SALT_LEN_MAX);\n i = 1;\n while (key_len > 0) {\n memset(F, 0, SHA256_DIGEST_LENGTH);\n memcpy(U, salt, salt_len);\n U[salt_len] = i >> 24;\n U[salt_len + 1] = i >> 16;\n U[salt_len + 2] = i >> 8;\n U[salt_len + 3] = i;\n U_len = salt_len + 4;\n for(it = 0; it < iter; it++) {\n hmac_sha256_init(&ctx, pwd, pwd_len);\n hmac_sha256_update(&ctx, U, U_len);\n hmac_sha256_final(&ctx, U);\n for(j = 0; j < SHA256_DIGEST_LENGTH; j++)\n F[j] ^= U[j];\n U_len = SHA256_DIGEST_LENGTH;\n }\n l = min_int(key_len, SHA256_DIGEST_LENGTH);\n memcpy(out, F, l);\n out += l;\n key_len -= l;\n i++;\n }\n}\n\n#else\n\nvoid pbkdf2_hmac_sha256(const uint8_t *pwd, int pwd_len,\n const uint8_t *salt, int salt_len,\n int iter, int key_len, uint8_t *out)\n{\n PKCS5_PBKDF2_HMAC((const char *)pwd, pwd_len, salt, salt_len,\n iter, EVP_sha256(), key_len, out);\n}\n\n#endif /* !USE_BUILTIN_CRYPTO */\n"], ["/linuxpdf/tinyemu/temu.c", "/*\n * TinyEMU\n * \n * Copyright (c) 2016-2018 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifndef _WIN32\n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#ifdef CONFIG_FS_NET\n#include \"fs_utils.h\"\n#include \"fs_wget.h\"\n#endif\n#ifdef CONFIG_SLIRP\n#include \"slirp/libslirp.h\"\n#endif\n\n#ifndef _WIN32\n\ntypedef struct {\n int stdin_fd;\n int console_esc_state;\n BOOL resize_pending;\n} STDIODevice;\n\nstatic struct termios oldtty;\nstatic int old_fd0_flags;\nstatic STDIODevice *global_stdio_device;\n\nstatic void term_exit(void)\n{\n tcsetattr (0, TCSANOW, &oldtty);\n fcntl(0, F_SETFL, old_fd0_flags);\n}\n\nstatic void term_init(BOOL allow_ctrlc)\n{\n struct termios tty;\n\n memset(&tty, 0, sizeof(tty));\n tcgetattr (0, &tty);\n oldtty = tty;\n old_fd0_flags = fcntl(0, F_GETFL);\n\n tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP\n |INLCR|IGNCR|ICRNL|IXON);\n tty.c_oflag |= OPOST;\n tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);\n if (!allow_ctrlc)\n tty.c_lflag &= ~ISIG;\n tty.c_cflag &= ~(CSIZE|PARENB);\n tty.c_cflag |= CS8;\n tty.c_cc[VMIN] = 1;\n tty.c_cc[VTIME] = 0;\n\n tcsetattr (0, TCSANOW, &tty);\n\n atexit(term_exit);\n}\n\nstatic void console_write(void *opaque, const uint8_t *buf, int len)\n{\n fwrite(buf, 1, len, stdout);\n fflush(stdout);\n}\n\nstatic int console_read(void *opaque, uint8_t *buf, int len)\n{\n STDIODevice *s = opaque;\n int ret, i, j;\n uint8_t ch;\n \n if (len <= 0)\n return 0;\n\n ret = read(s->stdin_fd, buf, len);\n if (ret < 0)\n return 0;\n if (ret == 0) {\n /* EOF */\n exit(1);\n }\n\n j = 0;\n for(i = 0; i < ret; i++) {\n ch = buf[i];\n if (s->console_esc_state) {\n s->console_esc_state = 0;\n switch(ch) {\n case 'x':\n printf(\"Terminated\\n\");\n exit(0);\n case 'h':\n printf(\"\\n\"\n \"C-a h print this help\\n\"\n \"C-a x exit emulator\\n\"\n \"C-a C-a send C-a\\n\"\n );\n break;\n case 1:\n goto output_char;\n default:\n break;\n }\n } else {\n if (ch == 1) {\n s->console_esc_state = 1;\n } else {\n output_char:\n buf[j++] = ch;\n }\n }\n }\n return j;\n}\n\nstatic void term_resize_handler(int sig)\n{\n if (global_stdio_device)\n global_stdio_device->resize_pending = TRUE;\n}\n\nstatic void console_get_size(STDIODevice *s, int *pw, int *ph)\n{\n struct winsize ws;\n int width, height;\n /* default values */\n width = 80;\n height = 25;\n if (ioctl(s->stdin_fd, TIOCGWINSZ, &ws) == 0 &&\n ws.ws_col >= 4 && ws.ws_row >= 4) {\n width = ws.ws_col;\n height = ws.ws_row;\n }\n *pw = width;\n *ph = height;\n}\n\nCharacterDevice *console_init(BOOL allow_ctrlc)\n{\n CharacterDevice *dev;\n STDIODevice *s;\n struct sigaction sig;\n\n term_init(allow_ctrlc);\n\n dev = mallocz(sizeof(*dev));\n s = mallocz(sizeof(*s));\n s->stdin_fd = 0;\n /* Note: the glibc does not properly tests the return value of\n write() in printf, so some messages on stdout may be lost */\n fcntl(s->stdin_fd, F_SETFL, O_NONBLOCK);\n\n s->resize_pending = TRUE;\n global_stdio_device = s;\n \n /* use a signal to get the host terminal resize events */\n sig.sa_handler = term_resize_handler;\n sigemptyset(&sig.sa_mask);\n sig.sa_flags = 0;\n sigaction(SIGWINCH, &sig, NULL);\n \n dev->opaque = s;\n dev->write_data = console_write;\n dev->read_data = console_read;\n return dev;\n}\n\n#endif /* !_WIN32 */\n\ntypedef enum {\n BF_MODE_RO,\n BF_MODE_RW,\n BF_MODE_SNAPSHOT,\n} BlockDeviceModeEnum;\n\n#define SECTOR_SIZE 512\n\ntypedef struct BlockDeviceFile {\n FILE *f;\n int64_t nb_sectors;\n BlockDeviceModeEnum mode;\n uint8_t **sector_table;\n} BlockDeviceFile;\n\nstatic int64_t bf_get_sector_count(BlockDevice *bs)\n{\n BlockDeviceFile *bf = bs->opaque;\n return bf->nb_sectors;\n}\n\n//#define DUMP_BLOCK_READ\n\nstatic int bf_read_async(BlockDevice *bs,\n uint64_t sector_num, uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceFile *bf = bs->opaque;\n // printf(\"bf_read_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n#ifdef DUMP_BLOCK_READ\n {\n static FILE *f;\n if (!f)\n f = fopen(\"/tmp/read_sect.txt\", \"wb\");\n fprintf(f, \"%\" PRId64 \" %d\\n\", sector_num, n);\n }\n#endif\n if (!bf->f)\n return -1;\n if (bf->mode == BF_MODE_SNAPSHOT) {\n int i;\n for(i = 0; i < n; i++) {\n if (!bf->sector_table[sector_num]) {\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fread(buf, 1, SECTOR_SIZE, bf->f);\n } else {\n memcpy(buf, bf->sector_table[sector_num], SECTOR_SIZE);\n }\n sector_num++;\n buf += SECTOR_SIZE;\n }\n } else {\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fread(buf, 1, n * SECTOR_SIZE, bf->f);\n }\n /* synchronous read */\n return 0;\n}\n\nstatic int bf_write_async(BlockDevice *bs,\n uint64_t sector_num, const uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceFile *bf = bs->opaque;\n int ret;\n\n switch(bf->mode) {\n case BF_MODE_RO:\n ret = -1; /* error */\n break;\n case BF_MODE_RW:\n fseek(bf->f, sector_num * SECTOR_SIZE, SEEK_SET);\n fwrite(buf, 1, n * SECTOR_SIZE, bf->f);\n ret = 0;\n break;\n case BF_MODE_SNAPSHOT:\n {\n int i;\n if ((sector_num + n) > bf->nb_sectors)\n return -1;\n for(i = 0; i < n; i++) {\n if (!bf->sector_table[sector_num]) {\n bf->sector_table[sector_num] = malloc(SECTOR_SIZE);\n }\n memcpy(bf->sector_table[sector_num], buf, SECTOR_SIZE);\n sector_num++;\n buf += SECTOR_SIZE;\n }\n ret = 0;\n }\n break;\n default:\n abort();\n }\n\n return ret;\n}\n\nstatic BlockDevice *block_device_init(const char *filename,\n BlockDeviceModeEnum mode)\n{\n BlockDevice *bs;\n BlockDeviceFile *bf;\n int64_t file_size;\n FILE *f;\n const char *mode_str;\n\n if (mode == BF_MODE_RW) {\n mode_str = \"r+b\";\n } else {\n mode_str = \"rb\";\n }\n \n f = fopen(filename, mode_str);\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n file_size = ftello(f);\n\n bs = mallocz(sizeof(*bs));\n bf = mallocz(sizeof(*bf));\n\n bf->mode = mode;\n bf->nb_sectors = file_size / 512;\n bf->f = f;\n\n if (mode == BF_MODE_SNAPSHOT) {\n bf->sector_table = mallocz(sizeof(bf->sector_table[0]) *\n bf->nb_sectors);\n }\n \n bs->opaque = bf;\n bs->get_sector_count = bf_get_sector_count;\n bs->read_async = bf_read_async;\n bs->write_async = bf_write_async;\n return bs;\n}\n\n#ifndef _WIN32\n\ntypedef struct {\n int fd;\n BOOL select_filled;\n} TunState;\n\nstatic void tun_write_packet(EthernetDevice *net,\n const uint8_t *buf, int len)\n{\n TunState *s = net->opaque;\n write(s->fd, buf, len);\n}\n\nstatic void tun_select_fill(EthernetDevice *net, int *pfd_max,\n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *pdelay)\n{\n TunState *s = net->opaque;\n int net_fd = s->fd;\n\n s->select_filled = net->device_can_write_packet(net);\n if (s->select_filled) {\n FD_SET(net_fd, rfds);\n *pfd_max = max_int(*pfd_max, net_fd);\n }\n}\n\nstatic void tun_select_poll(EthernetDevice *net, \n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int select_ret)\n{\n TunState *s = net->opaque;\n int net_fd = s->fd;\n uint8_t buf[2048];\n int ret;\n \n if (select_ret <= 0)\n return;\n if (s->select_filled && FD_ISSET(net_fd, rfds)) {\n ret = read(net_fd, buf, sizeof(buf));\n if (ret > 0)\n net->device_write_packet(net, buf, ret);\n }\n \n}\n\n/* configure with:\n# bridge configuration (connect tap0 to bridge interface br0)\n ip link add br0 type bridge\n ip tuntap add dev tap0 mode tap [user x] [group x]\n ip link set tap0 master br0\n ip link set dev br0 up\n ip link set dev tap0 up\n\n# NAT configuration (eth1 is the interface connected to internet)\n ifconfig br0 192.168.3.1\n echo 1 > /proc/sys/net/ipv4/ip_forward\n iptables -D FORWARD 1\n iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE\n\n In the VM:\n ifconfig eth0 192.168.3.2\n route add -net 0.0.0.0 netmask 0.0.0.0 gw 192.168.3.1\n*/\nstatic EthernetDevice *tun_open(const char *ifname)\n{\n struct ifreq ifr;\n int fd, ret;\n EthernetDevice *net;\n TunState *s;\n \n fd = open(\"/dev/net/tun\", O_RDWR);\n if (fd < 0) {\n fprintf(stderr, \"Error: could not open /dev/net/tun\\n\");\n return NULL;\n }\n memset(&ifr, 0, sizeof(ifr));\n ifr.ifr_flags = IFF_TAP | IFF_NO_PI;\n pstrcpy(ifr.ifr_name, sizeof(ifr.ifr_name), ifname);\n ret = ioctl(fd, TUNSETIFF, (void *) &ifr);\n if (ret != 0) {\n fprintf(stderr, \"Error: could not configure /dev/net/tun\\n\");\n close(fd);\n return NULL;\n }\n fcntl(fd, F_SETFL, O_NONBLOCK);\n\n net = mallocz(sizeof(*net));\n net->mac_addr[0] = 0x02;\n net->mac_addr[1] = 0x00;\n net->mac_addr[2] = 0x00;\n net->mac_addr[3] = 0x00;\n net->mac_addr[4] = 0x00;\n net->mac_addr[5] = 0x01;\n s = mallocz(sizeof(*s));\n s->fd = fd;\n net->opaque = s;\n net->write_packet = tun_write_packet;\n net->select_fill = tun_select_fill;\n net->select_poll = tun_select_poll;\n return net;\n}\n\n#endif /* !_WIN32 */\n\n#ifdef CONFIG_SLIRP\n\n/*******************************************************/\n/* slirp */\n\nstatic Slirp *slirp_state;\n\nstatic void slirp_write_packet(EthernetDevice *net,\n const uint8_t *buf, int len)\n{\n Slirp *slirp_state = net->opaque;\n slirp_input(slirp_state, buf, len);\n}\n\nint slirp_can_output(void *opaque)\n{\n EthernetDevice *net = opaque;\n return net->device_can_write_packet(net);\n}\n\nvoid slirp_output(void *opaque, const uint8_t *pkt, int pkt_len)\n{\n EthernetDevice *net = opaque;\n return net->device_write_packet(net, pkt, pkt_len);\n}\n\nstatic void slirp_select_fill1(EthernetDevice *net, int *pfd_max,\n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int *pdelay)\n{\n Slirp *slirp_state = net->opaque;\n slirp_select_fill(slirp_state, pfd_max, rfds, wfds, efds);\n}\n\nstatic void slirp_select_poll1(EthernetDevice *net, \n fd_set *rfds, fd_set *wfds, fd_set *efds,\n int select_ret)\n{\n Slirp *slirp_state = net->opaque;\n slirp_select_poll(slirp_state, rfds, wfds, efds, (select_ret <= 0));\n}\n\nstatic EthernetDevice *slirp_open(void)\n{\n EthernetDevice *net;\n struct in_addr net_addr = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */\n struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */\n struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */\n struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */\n struct in_addr dns = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */\n const char *bootfile = NULL;\n const char *vhostname = NULL;\n int restricted = 0;\n \n if (slirp_state) {\n fprintf(stderr, \"Only a single slirp instance is allowed\\n\");\n return NULL;\n }\n net = mallocz(sizeof(*net));\n\n slirp_state = slirp_init(restricted, net_addr, mask, host, vhostname,\n \"\", bootfile, dhcp, dns, net);\n \n net->mac_addr[0] = 0x02;\n net->mac_addr[1] = 0x00;\n net->mac_addr[2] = 0x00;\n net->mac_addr[3] = 0x00;\n net->mac_addr[4] = 0x00;\n net->mac_addr[5] = 0x01;\n net->opaque = slirp_state;\n net->write_packet = slirp_write_packet;\n net->select_fill = slirp_select_fill1;\n net->select_poll = slirp_select_poll1;\n \n return net;\n}\n\n#endif /* CONFIG_SLIRP */\n\n#define MAX_EXEC_CYCLE 500000\n#define MAX_SLEEP_TIME 10 /* in ms */\n\nvoid virt_machine_run(VirtMachine *m)\n{\n fd_set rfds, wfds, efds;\n int fd_max, ret, delay;\n struct timeval tv;\n#ifndef _WIN32\n int stdin_fd;\n#endif\n \n delay = virt_machine_get_sleep_duration(m, MAX_SLEEP_TIME);\n \n /* wait for an event */\n FD_ZERO(&rfds);\n FD_ZERO(&wfds);\n FD_ZERO(&efds);\n fd_max = -1;\n#ifndef _WIN32\n if (m->console_dev && virtio_console_can_write_data(m->console_dev)) {\n STDIODevice *s = m->console->opaque;\n stdin_fd = s->stdin_fd;\n FD_SET(stdin_fd, &rfds);\n fd_max = stdin_fd;\n\n if (s->resize_pending) {\n int width, height;\n console_get_size(s, &width, &height);\n virtio_console_resize_event(m->console_dev, width, height);\n s->resize_pending = FALSE;\n }\n }\n#endif\n if (m->net) {\n m->net->select_fill(m->net, &fd_max, &rfds, &wfds, &efds, &delay);\n }\n#ifdef CONFIG_FS_NET\n fs_net_set_fdset(&fd_max, &rfds, &wfds, &efds, &delay);\n#endif\n tv.tv_sec = delay / 1000;\n tv.tv_usec = (delay % 1000) * 1000;\n ret = select(fd_max + 1, &rfds, &wfds, &efds, &tv);\n if (m->net) {\n m->net->select_poll(m->net, &rfds, &wfds, &efds, ret);\n }\n if (ret > 0) {\n#ifndef _WIN32\n if (m->console_dev && FD_ISSET(stdin_fd, &rfds)) {\n uint8_t buf[128];\n int ret, len;\n len = virtio_console_get_write_len(m->console_dev);\n len = min_int(len, sizeof(buf));\n ret = m->console->read_data(m->console->opaque, buf, len);\n if (ret > 0) {\n virtio_console_write_data(m->console_dev, buf, ret);\n }\n }\n#endif\n }\n\n#ifdef CONFIG_SDL\n sdl_refresh(m);\n#endif\n \n virt_machine_interp(m, MAX_EXEC_CYCLE);\n}\n\n/*******************************************************/\n\nstatic struct option options[] = {\n { \"help\", no_argument, NULL, 'h' },\n { \"ctrlc\", no_argument },\n { \"rw\", no_argument },\n { \"ro\", no_argument },\n { \"append\", required_argument },\n { \"no-accel\", no_argument },\n { \"build-preload\", required_argument },\n { NULL },\n};\n\nvoid help(void)\n{\n printf(\"temu version \" CONFIG_VERSION \", Copyright (c) 2016-2018 Fabrice Bellard\\n\"\n \"usage: riscvemu [options] config_file\\n\"\n \"options are:\\n\"\n \"-m ram_size set the RAM size in MB\\n\"\n \"-rw allow write access to the disk image (default=snapshot)\\n\"\n \"-ctrlc the C-c key stops the emulator instead of being sent to the\\n\"\n \" emulated software\\n\"\n \"-append cmdline append cmdline to the kernel command line\\n\"\n \"-no-accel disable VM acceleration (KVM, x86 machine only)\\n\"\n \"\\n\"\n \"Console keys:\\n\"\n \"Press C-a x to exit the emulator, C-a h to get some help.\\n\");\n exit(1);\n}\n\n#ifdef CONFIG_FS_NET\nstatic BOOL net_completed;\n\nstatic void net_start_cb(void *arg)\n{\n net_completed = TRUE;\n}\n\nstatic BOOL net_poll_cb(void *arg)\n{\n return net_completed;\n}\n\n#endif\n\nint main(int argc, char **argv)\n{\n VirtMachine *s;\n const char *path, *cmdline, *build_preload_file;\n int c, option_index, i, ram_size, accel_enable;\n BOOL allow_ctrlc;\n BlockDeviceModeEnum drive_mode;\n VirtMachineParams p_s, *p = &p_s;\n\n ram_size = -1;\n allow_ctrlc = FALSE;\n (void)allow_ctrlc;\n drive_mode = BF_MODE_SNAPSHOT;\n accel_enable = -1;\n cmdline = NULL;\n build_preload_file = NULL;\n for(;;) {\n c = getopt_long_only(argc, argv, \"hm:\", options, &option_index);\n if (c == -1)\n break;\n switch(c) {\n case 0:\n switch(option_index) {\n case 1: /* ctrlc */\n allow_ctrlc = TRUE;\n break;\n case 2: /* rw */\n drive_mode = BF_MODE_RW;\n break;\n case 3: /* ro */\n drive_mode = BF_MODE_RO;\n break;\n case 4: /* append */\n cmdline = optarg;\n break;\n case 5: /* no-accel */\n accel_enable = FALSE;\n break;\n case 6: /* build-preload */\n build_preload_file = optarg;\n break;\n default:\n fprintf(stderr, \"unknown option index: %d\\n\", option_index);\n exit(1);\n }\n break;\n case 'h':\n help();\n break;\n case 'm':\n ram_size = strtoul(optarg, NULL, 0);\n break;\n default:\n exit(1);\n }\n }\n\n if (optind >= argc) {\n help();\n }\n\n path = argv[optind++];\n\n virt_machine_set_defaults(p);\n#ifdef CONFIG_FS_NET\n fs_wget_init();\n#endif\n virt_machine_load_config_file(p, path, NULL, NULL);\n#ifdef CONFIG_FS_NET\n fs_net_event_loop(NULL, NULL);\n#endif\n\n /* override some config parameters */\n\n if (ram_size > 0) {\n p->ram_size = (uint64_t)ram_size << 20;\n }\n if (accel_enable != -1)\n p->accel_enable = accel_enable;\n if (cmdline) {\n vm_add_cmdline(p, cmdline);\n }\n \n /* open the files & devices */\n for(i = 0; i < p->drive_count; i++) {\n BlockDevice *drive;\n char *fname;\n fname = get_file_path(p->cfg_filename, p->tab_drive[i].filename);\n#ifdef CONFIG_FS_NET\n if (is_url(fname)) {\n net_completed = FALSE;\n drive = block_device_init_http(fname, 128 * 1024,\n net_start_cb, NULL);\n /* wait until the drive is initialized */\n fs_net_event_loop(net_poll_cb, NULL);\n } else\n#endif\n {\n drive = block_device_init(fname, drive_mode);\n }\n free(fname);\n p->tab_drive[i].block_dev = drive;\n }\n\n for(i = 0; i < p->fs_count; i++) {\n FSDevice *fs;\n const char *path;\n path = p->tab_fs[i].filename;\n#ifdef CONFIG_FS_NET\n if (is_url(path)) {\n fs = fs_net_init(path, NULL, NULL);\n if (!fs)\n exit(1);\n if (build_preload_file)\n fs_dump_cache_load(fs, build_preload_file);\n fs_net_event_loop(NULL, NULL);\n } else\n#endif\n {\n#ifdef _WIN32\n fprintf(stderr, \"Filesystem access not supported yet\\n\");\n exit(1);\n#else\n char *fname;\n fname = get_file_path(p->cfg_filename, path);\n fs = fs_disk_init(fname);\n if (!fs) {\n fprintf(stderr, \"%s: must be a directory\\n\", fname);\n exit(1);\n }\n free(fname);\n#endif\n }\n p->tab_fs[i].fs_dev = fs;\n }\n\n for(i = 0; i < p->eth_count; i++) {\n#ifdef CONFIG_SLIRP\n if (!strcmp(p->tab_eth[i].driver, \"user\")) {\n p->tab_eth[i].net = slirp_open();\n if (!p->tab_eth[i].net)\n exit(1);\n } else\n#endif\n#ifndef _WIN32\n if (!strcmp(p->tab_eth[i].driver, \"tap\")) {\n p->tab_eth[i].net = tun_open(p->tab_eth[i].ifname);\n if (!p->tab_eth[i].net)\n exit(1);\n } else\n#endif\n {\n fprintf(stderr, \"Unsupported network driver '%s'\\n\",\n p->tab_eth[i].driver);\n exit(1);\n }\n }\n \n#ifdef CONFIG_SDL\n if (p->display_device) {\n sdl_init(p->width, p->height);\n } else\n#endif\n {\n#ifdef _WIN32\n fprintf(stderr, \"Console not supported yet\\n\");\n exit(1);\n#else\n p->console = console_init(allow_ctrlc);\n#endif\n }\n p->rtc_real_time = TRUE;\n\n s = virt_machine_init(p);\n if (!s)\n exit(1);\n \n virt_machine_free_config(p);\n\n if (s->net) {\n s->net->device_set_carrier(s->net, TRUE);\n }\n \n for(;;) {\n virt_machine_run(s);\n }\n virt_machine_end(s);\n return 0;\n}\n"], ["/linuxpdf/tinyemu/block_net.c", "/*\n * HTTP block device\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"virtio.h\"\n#include \"fs_wget.h\"\n#include \"list.h\"\n#include \"fbuf.h\"\n#include \"machine.h\"\n\ntypedef enum {\n CBLOCK_LOADING,\n CBLOCK_LOADED,\n} CachedBlockStateEnum;\n\ntypedef struct CachedBlock {\n struct list_head link;\n struct BlockDeviceHTTP *bf;\n unsigned int block_num;\n CachedBlockStateEnum state;\n FileBuffer fbuf;\n} CachedBlock;\n\n#define BLK_FMT \"%sblk%09u.bin\"\n#define GROUP_FMT \"%sgrp%09u.bin\"\n#define PREFETCH_GROUP_LEN_MAX 32\n\ntypedef struct {\n struct BlockDeviceHTTP *bf;\n int group_num;\n int n_block_num;\n CachedBlock *tab_block[PREFETCH_GROUP_LEN_MAX];\n} PrefetchGroupRequest;\n\n/* modified data is stored per cluster (smaller than cached blocks to\n avoid losing space) */\ntypedef struct Cluster {\n FileBuffer fbuf;\n} Cluster;\n\ntypedef struct BlockDeviceHTTP {\n BlockDevice *bs;\n int max_cache_size_kb;\n char url[1024];\n int prefetch_count;\n void (*start_cb)(void *opaque);\n void *start_opaque;\n \n int64_t nb_sectors;\n int block_size; /* in sectors, power of two */\n int nb_blocks;\n struct list_head cached_blocks; /* list of CachedBlock */\n int n_cached_blocks;\n int n_cached_blocks_max;\n\n /* write support */\n int sectors_per_cluster; /* power of two */\n Cluster **clusters; /* NULL if no written data */\n int n_clusters;\n int n_allocated_clusters;\n \n /* statistics */\n int64_t n_read_sectors;\n int64_t n_read_blocks;\n int64_t n_write_sectors;\n\n /* current read request */\n BOOL is_write;\n uint64_t sector_num;\n int cur_block_num;\n int sector_index, sector_count;\n BlockDeviceCompletionFunc *cb;\n void *opaque;\n uint8_t *io_buf;\n\n /* prefetch */\n int prefetch_group_len;\n} BlockDeviceHTTP;\n\nstatic void bf_update_block(CachedBlock *b, const uint8_t *data);\nstatic void bf_read_onload(void *opaque, int err, void *data, size_t size);\nstatic void bf_init_onload(void *opaque, int err, void *data, size_t size);\nstatic void bf_prefetch_group_onload(void *opaque, int err, void *data,\n size_t size);\n\nstatic CachedBlock *bf_find_block(BlockDeviceHTTP *bf, unsigned int block_num)\n{\n CachedBlock *b;\n struct list_head *el;\n \n list_for_each(el, &bf->cached_blocks) {\n b = list_entry(el, CachedBlock, link);\n if (b->block_num == block_num) {\n /* move to front */\n if (bf->cached_blocks.next != el) {\n list_del(&b->link);\n list_add(&b->link, &bf->cached_blocks);\n }\n return b;\n }\n }\n return NULL;\n}\n\nstatic void bf_free_block(BlockDeviceHTTP *bf, CachedBlock *b)\n{\n bf->n_cached_blocks--;\n file_buffer_reset(&b->fbuf);\n list_del(&b->link);\n free(b);\n}\n\nstatic CachedBlock *bf_add_block(BlockDeviceHTTP *bf, unsigned int block_num)\n{\n CachedBlock *b;\n if (bf->n_cached_blocks >= bf->n_cached_blocks_max) {\n struct list_head *el, *el1;\n /* start by looking at the least unused blocks */\n list_for_each_prev_safe(el, el1, &bf->cached_blocks) {\n b = list_entry(el, CachedBlock, link);\n if (b->state == CBLOCK_LOADED) {\n bf_free_block(bf, b);\n if (bf->n_cached_blocks < bf->n_cached_blocks_max)\n break;\n }\n }\n }\n b = mallocz(sizeof(CachedBlock));\n b->bf = bf;\n b->block_num = block_num;\n b->state = CBLOCK_LOADING;\n file_buffer_init(&b->fbuf);\n file_buffer_resize(&b->fbuf, bf->block_size * 512);\n list_add(&b->link, &bf->cached_blocks);\n bf->n_cached_blocks++;\n return b;\n}\n\nstatic int64_t bf_get_sector_count(BlockDevice *bs)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n return bf->nb_sectors;\n}\n\nstatic void bf_start_load_block(BlockDevice *bs, int block_num)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n char filename[1024];\n CachedBlock *b;\n b = bf_add_block(bf, block_num);\n bf->n_read_blocks++;\n /* make a XHR to read the block */\n#if 0\n printf(\"%u,\\n\", block_num);\n#endif\n#if 0\n printf(\"load_blk=%d cached=%d read=%d KB (%d KB) write=%d KB (%d KB)\\n\",\n block_num, bf->n_cached_blocks,\n (int)(bf->n_read_sectors / 2),\n (int)(bf->n_read_blocks * bf->block_size / 2),\n (int)(bf->n_write_sectors / 2),\n (int)(bf->n_allocated_clusters * bf->sectors_per_cluster / 2));\n#endif\n snprintf(filename, sizeof(filename), BLK_FMT, bf->url, block_num);\n // printf(\"wget %s\\n\", filename);\n fs_wget(filename, NULL, NULL, b, bf_read_onload, TRUE);\n}\n\nstatic void bf_start_load_prefetch_group(BlockDevice *bs, int group_num,\n const int *tab_block_num,\n int n_block_num)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n CachedBlock *b;\n PrefetchGroupRequest *req;\n char filename[1024];\n BOOL req_flag;\n int i;\n \n req_flag = FALSE;\n req = malloc(sizeof(*req));\n req->bf = bf;\n req->group_num = group_num;\n req->n_block_num = n_block_num;\n for(i = 0; i < n_block_num; i++) {\n b = bf_find_block(bf, tab_block_num[i]);\n if (!b) {\n b = bf_add_block(bf, tab_block_num[i]);\n req_flag = TRUE;\n } else {\n /* no need to read the block if it is already loading or\n loaded */\n b = NULL;\n }\n req->tab_block[i] = b;\n }\n\n if (req_flag) {\n snprintf(filename, sizeof(filename), GROUP_FMT, bf->url, group_num);\n // printf(\"wget %s\\n\", filename);\n fs_wget(filename, NULL, NULL, req, bf_prefetch_group_onload, TRUE);\n /* XXX: should add request in a list to free it for clean exit */\n } else {\n free(req);\n }\n}\n\nstatic void bf_prefetch_group_onload(void *opaque, int err, void *data,\n size_t size)\n{\n PrefetchGroupRequest *req = opaque;\n BlockDeviceHTTP *bf = req->bf;\n CachedBlock *b;\n int block_bytes, i;\n \n if (err < 0) {\n fprintf(stderr, \"Could not load group %u\\n\", req->group_num);\n exit(1);\n }\n block_bytes = bf->block_size * 512;\n assert(size == block_bytes * req->n_block_num);\n for(i = 0; i < req->n_block_num; i++) {\n b = req->tab_block[i];\n if (b) {\n bf_update_block(b, (const uint8_t *)data + block_bytes * i);\n }\n }\n free(req);\n}\n\nstatic int bf_rw_async1(BlockDevice *bs, BOOL is_sync)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n int offset, block_num, n, cluster_num;\n CachedBlock *b;\n Cluster *c;\n \n for(;;) {\n n = bf->sector_count - bf->sector_index;\n if (n == 0)\n break;\n cluster_num = bf->sector_num / bf->sectors_per_cluster;\n c = bf->clusters[cluster_num];\n if (c) {\n offset = bf->sector_num % bf->sectors_per_cluster;\n n = min_int(n, bf->sectors_per_cluster - offset);\n if (bf->is_write) {\n file_buffer_write(&c->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n } else {\n file_buffer_read(&c->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n }\n bf->sector_index += n;\n bf->sector_num += n;\n } else {\n block_num = bf->sector_num / bf->block_size;\n offset = bf->sector_num % bf->block_size;\n n = min_int(n, bf->block_size - offset);\n bf->cur_block_num = block_num;\n \n b = bf_find_block(bf, block_num);\n if (b) {\n if (b->state == CBLOCK_LOADING) {\n /* wait until the block is loaded */\n return 1;\n } else {\n if (bf->is_write) {\n int cluster_size, cluster_offset;\n uint8_t *buf;\n /* allocate a new cluster */\n c = mallocz(sizeof(Cluster));\n cluster_size = bf->sectors_per_cluster * 512;\n buf = malloc(cluster_size);\n file_buffer_init(&c->fbuf);\n file_buffer_resize(&c->fbuf, cluster_size);\n bf->clusters[cluster_num] = c;\n /* copy the cached block data to the cluster */\n cluster_offset = (cluster_num * bf->sectors_per_cluster) &\n (bf->block_size - 1);\n file_buffer_read(&b->fbuf, cluster_offset * 512,\n buf, cluster_size);\n file_buffer_write(&c->fbuf, 0, buf, cluster_size);\n free(buf);\n bf->n_allocated_clusters++;\n continue; /* write to the allocated cluster */\n } else {\n file_buffer_read(&b->fbuf, offset * 512,\n bf->io_buf + bf->sector_index * 512, n * 512);\n }\n bf->sector_index += n;\n bf->sector_num += n;\n }\n } else {\n bf_start_load_block(bs, block_num);\n return 1;\n }\n bf->cur_block_num = -1;\n }\n }\n\n if (!is_sync) {\n // printf(\"end of request\\n\");\n /* end of request */\n bf->cb(bf->opaque, 0);\n } \n return 0;\n}\n\nstatic void bf_update_block(CachedBlock *b, const uint8_t *data)\n{\n BlockDeviceHTTP *bf = b->bf;\n BlockDevice *bs = bf->bs;\n\n assert(b->state == CBLOCK_LOADING);\n file_buffer_write(&b->fbuf, 0, data, bf->block_size * 512);\n b->state = CBLOCK_LOADED;\n \n /* continue I/O read/write if necessary */\n if (b->block_num == bf->cur_block_num) {\n bf_rw_async1(bs, FALSE);\n }\n}\n\nstatic void bf_read_onload(void *opaque, int err, void *data, size_t size)\n{\n CachedBlock *b = opaque;\n BlockDeviceHTTP *bf = b->bf;\n\n if (err < 0) {\n fprintf(stderr, \"Could not load block %u\\n\", b->block_num);\n exit(1);\n }\n \n assert(size == bf->block_size * 512);\n bf_update_block(b, data);\n}\n\nstatic int bf_read_async(BlockDevice *bs,\n uint64_t sector_num, uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n // printf(\"bf_read_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n bf->is_write = FALSE;\n bf->sector_num = sector_num;\n bf->io_buf = buf;\n bf->sector_count = n;\n bf->sector_index = 0;\n bf->cb = cb;\n bf->opaque = opaque;\n bf->n_read_sectors += n;\n return bf_rw_async1(bs, TRUE);\n}\n\nstatic int bf_write_async(BlockDevice *bs,\n uint64_t sector_num, const uint8_t *buf, int n,\n BlockDeviceCompletionFunc *cb, void *opaque)\n{\n BlockDeviceHTTP *bf = bs->opaque;\n // printf(\"bf_write_async: sector_num=%\" PRId64 \" n=%d\\n\", sector_num, n);\n bf->is_write = TRUE;\n bf->sector_num = sector_num;\n bf->io_buf = (uint8_t *)buf;\n bf->sector_count = n;\n bf->sector_index = 0;\n bf->cb = cb;\n bf->opaque = opaque;\n bf->n_write_sectors += n;\n return bf_rw_async1(bs, TRUE);\n}\n\nBlockDevice *block_device_init_http(const char *url,\n int max_cache_size_kb,\n void (*start_cb)(void *opaque),\n void *start_opaque)\n{\n BlockDevice *bs;\n BlockDeviceHTTP *bf;\n char *p;\n\n bs = mallocz(sizeof(*bs));\n bf = mallocz(sizeof(*bf));\n strcpy(bf->url, url);\n /* get the path with the trailing '/' */\n p = strrchr(bf->url, '/');\n if (!p)\n p = bf->url;\n else\n p++;\n *p = '\\0';\n\n init_list_head(&bf->cached_blocks);\n bf->max_cache_size_kb = max_cache_size_kb;\n bf->start_cb = start_cb;\n bf->start_opaque = start_opaque;\n bf->bs = bs;\n \n bs->opaque = bf;\n bs->get_sector_count = bf_get_sector_count;\n bs->read_async = bf_read_async;\n bs->write_async = bf_write_async;\n \n fs_wget(url, NULL, NULL, bs, bf_init_onload, TRUE);\n return bs;\n}\n\nstatic void bf_init_onload(void *opaque, int err, void *data, size_t size)\n{\n BlockDevice *bs = opaque;\n BlockDeviceHTTP *bf = bs->opaque;\n int block_size_kb, block_num;\n JSONValue cfg, array;\n \n if (err < 0) {\n fprintf(stderr, \"Could not load block device file (err=%d)\\n\", -err);\n exit(1);\n }\n\n /* parse the disk image info */\n cfg = json_parse_value_len(data, size);\n if (json_is_error(cfg)) {\n vm_error(\"error: %s\\n\", json_get_error(cfg));\n config_error:\n json_free(cfg);\n exit(1);\n }\n\n if (vm_get_int(cfg, \"block_size\", &block_size_kb) < 0)\n goto config_error;\n bf->block_size = block_size_kb * 2;\n if (bf->block_size <= 0 ||\n (bf->block_size & (bf->block_size - 1)) != 0) {\n vm_error(\"invalid block_size\\n\");\n goto config_error;\n }\n if (vm_get_int(cfg, \"n_block\", &bf->nb_blocks) < 0)\n goto config_error;\n if (bf->nb_blocks <= 0) {\n vm_error(\"invalid n_block\\n\");\n goto config_error;\n }\n\n bf->nb_sectors = bf->block_size * (uint64_t)bf->nb_blocks;\n bf->n_cached_blocks = 0;\n bf->n_cached_blocks_max = max_int(1, bf->max_cache_size_kb / block_size_kb);\n bf->cur_block_num = -1; /* no request in progress */\n \n bf->sectors_per_cluster = 8; /* 4 KB */\n bf->n_clusters = (bf->nb_sectors + bf->sectors_per_cluster - 1) / bf->sectors_per_cluster;\n bf->clusters = mallocz(sizeof(bf->clusters[0]) * bf->n_clusters);\n\n if (vm_get_int_opt(cfg, \"prefetch_group_len\",\n &bf->prefetch_group_len, 1) < 0)\n goto config_error;\n if (bf->prefetch_group_len > PREFETCH_GROUP_LEN_MAX) {\n vm_error(\"prefetch_group_len is too large\");\n goto config_error;\n }\n \n array = json_object_get(cfg, \"prefetch\");\n if (!json_is_undefined(array)) {\n int idx, prefetch_len, l, i;\n JSONValue el;\n int tab_block_num[PREFETCH_GROUP_LEN_MAX];\n \n if (array.type != JSON_ARRAY) {\n vm_error(\"expecting an array\\n\");\n goto config_error;\n }\n prefetch_len = array.u.array->len;\n idx = 0;\n while (idx < prefetch_len) {\n l = min_int(prefetch_len - idx, bf->prefetch_group_len);\n for(i = 0; i < l; i++) {\n el = json_array_get(array, idx + i);\n if (el.type != JSON_INT) {\n vm_error(\"expecting an integer\\n\");\n goto config_error;\n }\n tab_block_num[i] = el.u.int32;\n }\n if (l == 1) {\n block_num = tab_block_num[0];\n if (!bf_find_block(bf, block_num)) {\n bf_start_load_block(bs, block_num);\n }\n } else {\n bf_start_load_prefetch_group(bs, idx / bf->prefetch_group_len,\n tab_block_num, l);\n }\n idx += l;\n }\n }\n json_free(cfg);\n \n if (bf->start_cb) {\n bf->start_cb(bf->start_opaque);\n }\n}\n"], ["/linuxpdf/tinyemu/build_filelist.c", "/*\n * File list builder for RISCVEMU network filesystem\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"fs_utils.h\"\n\nvoid print_str(FILE *f, const char *str)\n{\n const char *s;\n int c;\n s = str;\n while (*s != '\\0') {\n if (*s <= ' ' || *s > '~')\n goto use_quote;\n s++;\n }\n fputs(str, f);\n return;\n use_quote:\n s = str;\n fputc('\"', f);\n while (*s != '\\0') {\n c = *(uint8_t *)s;\n if (c < ' ' || c == 127) {\n fprintf(f, \"\\\\x%02x\", c);\n } else if (c == '\\\\' || c == '\\\"') {\n fprintf(f, \"\\\\%c\", c);\n } else {\n fputc(c, f);\n }\n s++;\n }\n fputc('\"', f);\n}\n\n#define COPY_BUF_LEN (1024 * 1024)\n\nstatic void copy_file(const char *src_filename, const char *dst_filename)\n{\n uint8_t *buf;\n FILE *fi, *fo;\n int len;\n \n buf = malloc(COPY_BUF_LEN);\n fi = fopen(src_filename, \"rb\");\n if (!fi) {\n perror(src_filename);\n exit(1);\n }\n fo = fopen(dst_filename, \"wb\");\n if (!fo) {\n perror(dst_filename);\n exit(1);\n }\n for(;;) {\n len = fread(buf, 1, COPY_BUF_LEN, fi);\n if (len == 0)\n break;\n fwrite(buf, 1, len, fo);\n }\n fclose(fo);\n fclose(fi);\n}\n\ntypedef struct {\n char *files_path;\n uint64_t next_inode_num;\n uint64_t fs_size;\n uint64_t fs_max_size;\n FILE *f;\n} ScanState;\n\nstatic void add_file_size(ScanState *s, uint64_t size)\n{\n s->fs_size += block_align(size, FS_BLOCK_SIZE);\n if (s->fs_size > s->fs_max_size) {\n fprintf(stderr, \"Filesystem Quota exceeded (%\" PRId64 \" bytes)\\n\", s->fs_max_size);\n exit(1);\n }\n}\n\nvoid scan_dir(ScanState *s, const char *path)\n{\n FILE *f = s->f;\n DIR *dirp;\n struct dirent *de;\n const char *name;\n struct stat st;\n char *path1;\n uint32_t mode, v;\n\n dirp = opendir(path);\n if (!dirp) {\n perror(path);\n exit(1);\n }\n for(;;) {\n de = readdir(dirp);\n if (!de)\n break;\n name = de->d_name;\n if (!strcmp(name, \".\") || !strcmp(name, \"..\"))\n continue;\n path1 = compose_path(path, name);\n if (lstat(path1, &st) < 0) {\n perror(path1);\n exit(1);\n }\n\n mode = st.st_mode & 0xffff;\n fprintf(f, \"%06o %u %u\", \n mode, \n (int)st.st_uid,\n (int)st.st_gid);\n if (S_ISCHR(mode) || S_ISBLK(mode)) {\n fprintf(f, \" %u %u\",\n (int)major(st.st_rdev),\n (int)minor(st.st_rdev));\n }\n if (S_ISREG(mode)) {\n fprintf(f, \" %\" PRIu64, st.st_size);\n }\n /* modification time (at most ms resolution) */\n fprintf(f, \" %u\", (int)st.st_mtim.tv_sec);\n v = st.st_mtim.tv_nsec;\n if (v != 0) {\n fprintf(f, \".\");\n while (v != 0) {\n fprintf(f, \"%u\", v / 100000000);\n v = (v % 100000000) * 10;\n }\n }\n \n fprintf(f, \" \");\n print_str(f, name);\n if (S_ISLNK(mode)) {\n char buf[1024];\n int len;\n len = readlink(path1, buf, sizeof(buf) - 1);\n if (len < 0) {\n perror(\"readlink\");\n exit(1);\n }\n buf[len] = '\\0';\n fprintf(f, \" \");\n print_str(f, buf);\n } else if (S_ISREG(mode) && st.st_size > 0) {\n char buf1[FILEID_SIZE_MAX], *fname;\n FSFileID file_id;\n file_id = s->next_inode_num++;\n fprintf(f, \" %\" PRIx64, file_id);\n file_id_to_filename(buf1, file_id);\n fname = compose_path(s->files_path, buf1);\n copy_file(path1, fname);\n add_file_size(s, st.st_size);\n }\n\n fprintf(f, \"\\n\");\n if (S_ISDIR(mode)) {\n scan_dir(s, path1);\n }\n free(path1);\n }\n\n closedir(dirp);\n fprintf(f, \".\\n\"); /* end of directory */\n}\n\nvoid help(void)\n{\n printf(\"usage: build_filelist [options] source_path dest_path\\n\"\n \"\\n\"\n \"Options:\\n\"\n \"-m size_mb set the max filesystem size in MiB\\n\");\n exit(1);\n}\n\n#define LOCK_FILENAME \"lock\"\n\nint main(int argc, char **argv)\n{\n const char *dst_path, *src_path;\n ScanState s_s, *s = &s_s;\n FILE *f;\n char *filename;\n FSFileID root_id;\n char fname[FILEID_SIZE_MAX];\n struct stat st;\n uint64_t first_inode, fs_max_size;\n int c;\n \n first_inode = 1;\n fs_max_size = (uint64_t)1 << 30;\n for(;;) {\n c = getopt(argc, argv, \"hi:m:\");\n if (c == -1)\n break;\n switch(c) {\n case 'h':\n help();\n case 'i':\n first_inode = strtoul(optarg, NULL, 0);\n break;\n case 'm':\n fs_max_size = (uint64_t)strtoul(optarg, NULL, 0) << 20;\n break;\n default:\n exit(1);\n }\n }\n\n if (optind + 1 >= argc)\n help();\n src_path = argv[optind];\n dst_path = argv[optind + 1];\n \n mkdir(dst_path, 0755);\n\n s->files_path = compose_path(dst_path, ROOT_FILENAME);\n s->next_inode_num = first_inode;\n s->fs_size = 0;\n s->fs_max_size = fs_max_size;\n \n mkdir(s->files_path, 0755);\n\n root_id = s->next_inode_num++;\n file_id_to_filename(fname, root_id);\n filename = compose_path(s->files_path, fname);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fprintf(f, \"Version: 1\\n\");\n fprintf(f, \"Revision: 1\\n\");\n fprintf(f, \"\\n\");\n s->f = f;\n scan_dir(s, src_path);\n fclose(f);\n\n /* take into account the filelist size */\n if (stat(filename, &st) < 0) {\n perror(filename);\n exit(1);\n }\n add_file_size(s, st.st_size);\n \n free(filename);\n \n filename = compose_path(dst_path, HEAD_FILENAME);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fprintf(f, \"Version: 1\\n\");\n fprintf(f, \"Revision: 1\\n\");\n fprintf(f, \"NextFileID: %\" PRIx64 \"\\n\", s->next_inode_num);\n fprintf(f, \"FSFileCount: %\" PRIu64 \"\\n\", s->next_inode_num - 1);\n fprintf(f, \"FSSize: %\" PRIu64 \"\\n\", s->fs_size);\n fprintf(f, \"FSMaxSize: %\" PRIu64 \"\\n\", s->fs_max_size);\n fprintf(f, \"Key:\\n\"); /* not encrypted */\n fprintf(f, \"RootID: %\" PRIx64 \"\\n\", root_id);\n fclose(f);\n free(filename);\n \n filename = compose_path(dst_path, LOCK_FILENAME);\n f = fopen(filename, \"wb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fclose(f);\n free(filename);\n\n return 0;\n}\n"], ["/linuxpdf/tinyemu/machine.c", "/*\n * VM utilities\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#include \"fs_utils.h\"\n#ifdef CONFIG_FS_NET\n#include \"fs_wget.h\"\n#endif\n\nvoid __attribute__((format(printf, 1, 2))) vm_error(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n#ifdef EMSCRIPTEN\n vprintf(fmt, ap);\n#else\n vfprintf(stderr, fmt, ap);\n#endif\n va_end(ap);\n}\n\nint vm_get_int(JSONValue obj, const char *name, int *pval)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n vm_error(\"expecting '%s' property\\n\", name);\n return -1;\n }\n if (val.type != JSON_INT) {\n vm_error(\"%s: integer expected\\n\", name);\n return -1;\n }\n *pval = val.u.int32;\n return 0;\n}\n\nint vm_get_int_opt(JSONValue obj, const char *name, int *pval, int def_val)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n *pval = def_val;\n return 0;\n }\n if (val.type != JSON_INT) {\n vm_error(\"%s: integer expected\\n\", name);\n return -1;\n }\n *pval = val.u.int32;\n return 0;\n}\n\nstatic int vm_get_str2(JSONValue obj, const char *name, const char **pstr,\n BOOL is_opt)\n{ \n JSONValue val;\n val = json_object_get(obj, name);\n if (json_is_undefined(val)) {\n if (is_opt) {\n *pstr = NULL;\n return 0;\n } else {\n vm_error(\"expecting '%s' property\\n\", name);\n return -1;\n }\n }\n if (val.type != JSON_STR) {\n vm_error(\"%s: string expected\\n\", name);\n return -1;\n }\n *pstr = val.u.str->data;\n return 0;\n}\n\nstatic int vm_get_str(JSONValue obj, const char *name, const char **pstr)\n{ \n return vm_get_str2(obj, name, pstr, FALSE);\n}\n\nstatic int vm_get_str_opt(JSONValue obj, const char *name, const char **pstr)\n{ \n return vm_get_str2(obj, name, pstr, TRUE);\n}\n\nstatic char *strdup_null(const char *str)\n{\n if (!str)\n return NULL;\n else\n return strdup(str);\n}\n\n/* currently only for \"TZ\" */\nstatic char *cmdline_subst(const char *cmdline)\n{\n DynBuf dbuf;\n const char *p;\n char var_name[32], *q, buf[32];\n \n dbuf_init(&dbuf);\n p = cmdline;\n while (*p != '\\0') {\n if (p[0] == '$' && p[1] == '{') {\n p += 2;\n q = var_name;\n while (*p != '\\0' && *p != '}') {\n if ((q - var_name) < sizeof(var_name) - 1)\n *q++ = *p;\n p++;\n }\n *q = '\\0';\n if (*p == '}')\n p++;\n if (!strcmp(var_name, \"TZ\")) {\n time_t ti;\n struct tm tm;\n int n, sg;\n /* get the offset to UTC */\n time(&ti);\n localtime_r(&ti, &tm);\n n = tm.tm_gmtoff / 60;\n sg = '-';\n if (n < 0) {\n sg = '+';\n n = -n;\n }\n snprintf(buf, sizeof(buf), \"UTC%c%02d:%02d\",\n sg, n / 60, n % 60);\n dbuf_putstr(&dbuf, buf);\n }\n } else {\n dbuf_putc(&dbuf, *p++);\n }\n }\n dbuf_putc(&dbuf, 0);\n return (char *)dbuf.buf;\n}\n\nstatic BOOL find_name(const char *name, const char *name_list)\n{\n size_t len;\n const char *p, *r;\n \n p = name_list;\n for(;;) {\n r = strchr(p, ',');\n if (!r) {\n if (!strcmp(name, p))\n return TRUE;\n break;\n } else {\n len = r - p;\n if (len == strlen(name) && !memcmp(name, p, len))\n return TRUE;\n p = r + 1;\n }\n }\n return FALSE;\n}\n\nstatic const VirtMachineClass *virt_machine_list[] = {\n#if defined(EMSCRIPTEN)\n /* only a single machine in the EMSCRIPTEN target */\n#ifndef CONFIG_X86EMU\n &riscv_machine_class,\n#endif \n#else\n &riscv_machine_class,\n#endif /* !EMSCRIPTEN */\n#ifdef CONFIG_X86EMU\n &pc_machine_class,\n#endif\n NULL,\n};\n\nstatic const VirtMachineClass *virt_machine_find_class(const char *machine_name)\n{\n const VirtMachineClass *vmc, **pvmc;\n \n for(pvmc = virt_machine_list; *pvmc != NULL; pvmc++) {\n vmc = *pvmc;\n if (find_name(machine_name, vmc->machine_names))\n return vmc;\n }\n return NULL;\n}\n\nstatic int virt_machine_parse_config(VirtMachineParams *p,\n char *config_file_str, int len)\n{\n int version, val;\n const char *tag_name, *str;\n char buf1[256];\n JSONValue cfg, obj, el;\n \n cfg = json_parse_value_len(config_file_str, len);\n if (json_is_error(cfg)) {\n vm_error(\"error: %s\\n\", json_get_error(cfg));\n json_free(cfg);\n return -1;\n }\n\n if (vm_get_int(cfg, \"version\", &version) < 0)\n goto tag_fail;\n if (version != VM_CONFIG_VERSION) {\n if (version > VM_CONFIG_VERSION) {\n vm_error(\"The emulator is too old to run this VM: please upgrade\\n\");\n return -1;\n } else {\n vm_error(\"The VM configuration file is too old for this emulator version: please upgrade the VM configuration file\\n\");\n return -1;\n }\n }\n \n if (vm_get_str(cfg, \"machine\", &str) < 0)\n goto tag_fail;\n p->machine_name = strdup(str);\n p->vmc = virt_machine_find_class(p->machine_name);\n if (!p->vmc) {\n vm_error(\"Unknown machine name: %s\\n\", p->machine_name);\n goto tag_fail;\n }\n p->vmc->virt_machine_set_defaults(p);\n\n tag_name = \"memory_size\";\n if (vm_get_int(cfg, tag_name, &val) < 0)\n goto tag_fail;\n p->ram_size = (uint64_t)val << 20;\n \n tag_name = \"bios\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_BIOS].filename = strdup(str);\n }\n\n tag_name = \"kernel\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_KERNEL].filename = strdup(str);\n }\n\n tag_name = \"initrd\";\n if (vm_get_str_opt(cfg, tag_name, &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_INITRD].filename = strdup(str);\n }\n\n if (vm_get_str_opt(cfg, \"cmdline\", &str) < 0)\n goto tag_fail;\n if (str) {\n p->cmdline = cmdline_subst(str);\n }\n \n for(;;) {\n snprintf(buf1, sizeof(buf1), \"drive%d\", p->drive_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->drive_count >= MAX_DRIVE_DEVICE) {\n vm_error(\"Too many drives\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"file\", &str) < 0)\n goto tag_fail;\n p->tab_drive[p->drive_count].filename = strdup(str);\n if (vm_get_str_opt(obj, \"device\", &str) < 0)\n goto tag_fail;\n p->tab_drive[p->drive_count].device = strdup_null(str);\n p->drive_count++;\n }\n\n for(;;) {\n snprintf(buf1, sizeof(buf1), \"fs%d\", p->fs_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->fs_count >= MAX_DRIVE_DEVICE) {\n vm_error(\"Too many filesystems\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"file\", &str) < 0)\n goto tag_fail;\n p->tab_fs[p->fs_count].filename = strdup(str);\n if (vm_get_str_opt(obj, \"tag\", &str) < 0)\n goto tag_fail;\n if (!str) {\n if (p->fs_count == 0)\n strcpy(buf1, \"/dev/root\");\n else\n snprintf(buf1, sizeof(buf1), \"/dev/root%d\", p->fs_count);\n str = buf1;\n }\n p->tab_fs[p->fs_count].tag = strdup(str);\n p->fs_count++;\n }\n\n for(;;) {\n snprintf(buf1, sizeof(buf1), \"eth%d\", p->eth_count);\n obj = json_object_get(cfg, buf1);\n if (json_is_undefined(obj))\n break;\n if (p->eth_count >= MAX_ETH_DEVICE) {\n vm_error(\"Too many ethernet interfaces\\n\");\n return -1;\n }\n if (vm_get_str(obj, \"driver\", &str) < 0)\n goto tag_fail;\n p->tab_eth[p->eth_count].driver = strdup(str);\n if (!strcmp(str, \"tap\")) {\n if (vm_get_str(obj, \"ifname\", &str) < 0)\n goto tag_fail;\n p->tab_eth[p->eth_count].ifname = strdup(str);\n }\n p->eth_count++;\n }\n\n p->display_device = NULL;\n obj = json_object_get(cfg, \"display0\");\n if (!json_is_undefined(obj)) {\n if (vm_get_str(obj, \"device\", &str) < 0)\n goto tag_fail;\n p->display_device = strdup(str);\n if (vm_get_int(obj, \"width\", &p->width) < 0)\n goto tag_fail;\n if (vm_get_int(obj, \"height\", &p->height) < 0)\n goto tag_fail;\n if (vm_get_str_opt(obj, \"vga_bios\", &str) < 0)\n goto tag_fail;\n if (str) {\n p->files[VM_FILE_VGA_BIOS].filename = strdup(str);\n }\n }\n\n if (vm_get_str_opt(cfg, \"input_device\", &str) < 0)\n goto tag_fail;\n p->input_device = strdup_null(str);\n\n if (vm_get_str_opt(cfg, \"accel\", &str) < 0)\n goto tag_fail;\n if (str) {\n if (!strcmp(str, \"none\")) {\n p->accel_enable = FALSE;\n } else if (!strcmp(str, \"auto\")) {\n p->accel_enable = TRUE;\n } else {\n vm_error(\"unsupported 'accel' config: %s\\n\", str);\n return -1;\n }\n }\n\n tag_name = \"rtc_local_time\";\n el = json_object_get(cfg, tag_name);\n if (!json_is_undefined(el)) {\n if (el.type != JSON_BOOL) {\n vm_error(\"%s: boolean expected\\n\", tag_name);\n goto tag_fail;\n }\n p->rtc_local_time = el.u.b;\n }\n \n json_free(cfg);\n return 0;\n tag_fail:\n json_free(cfg);\n return -1;\n}\n\ntypedef void FSLoadFileCB(void *opaque, uint8_t *buf, int buf_len);\n\ntypedef struct {\n VirtMachineParams *vm_params;\n void (*start_cb)(void *opaque);\n void *opaque;\n \n FSLoadFileCB *file_load_cb;\n void *file_load_opaque;\n int file_index;\n} VMConfigLoadState;\n\nstatic void config_file_loaded(void *opaque, uint8_t *buf, int buf_len);\nstatic void config_additional_file_load(VMConfigLoadState *s);\nstatic void config_additional_file_load_cb(void *opaque,\n uint8_t *buf, int buf_len);\n\n/* XXX: win32, URL */\nchar *get_file_path(const char *base_filename, const char *filename)\n{\n int len, len1;\n char *fname, *p;\n \n if (!base_filename)\n goto done;\n if (strchr(filename, ':'))\n goto done; /* full URL */\n if (filename[0] == '/')\n goto done;\n p = strrchr(base_filename, '/');\n if (!p) {\n done:\n return strdup(filename);\n }\n len = p + 1 - base_filename;\n len1 = strlen(filename);\n fname = malloc(len + len1 + 1);\n memcpy(fname, base_filename, len);\n memcpy(fname + len, filename, len1 + 1);\n return fname;\n}\n\n\n#ifdef EMSCRIPTEN\nstatic int load_file(uint8_t **pbuf, const char *filename)\n{\n abort();\n}\n#else\n/* return -1 if error. */\nstatic int load_file(uint8_t **pbuf, const char *filename)\n{\n FILE *f;\n int size;\n uint8_t *buf;\n \n f = fopen(filename, \"rb\");\n if (!f) {\n perror(filename);\n exit(1);\n }\n fseek(f, 0, SEEK_END);\n size = ftell(f);\n fseek(f, 0, SEEK_SET);\n buf = malloc(size);\n if (fread(buf, 1, size, f) != size) {\n fprintf(stderr, \"%s: read error\\n\", filename);\n exit(1);\n }\n fclose(f);\n *pbuf = buf;\n return size;\n}\n#endif\n\n#ifdef CONFIG_FS_NET\nstatic void config_load_file_cb(void *opaque, int err, void *data, size_t size)\n{\n VMConfigLoadState *s = opaque;\n \n // printf(\"err=%d data=%p size=%ld\\n\", err, data, size);\n if (err < 0) {\n vm_error(\"Error %d while loading file\\n\", -err);\n exit(1);\n }\n s->file_load_cb(s->file_load_opaque, data, size);\n}\n#endif\n\nstatic void config_load_file(VMConfigLoadState *s, const char *filename,\n FSLoadFileCB *cb, void *opaque)\n{\n // printf(\"loading %s\\n\", filename);\n#ifdef CONFIG_FS_NET\n if (is_url(filename)) {\n s->file_load_cb = cb;\n s->file_load_opaque = opaque;\n fs_wget(filename, NULL, NULL, s, config_load_file_cb, TRUE);\n } else\n#endif\n {\n uint8_t *buf;\n int size;\n size = load_file(&buf, filename);\n cb(opaque, buf, size);\n free(buf);\n }\n}\n\nvoid virt_machine_load_config_file(VirtMachineParams *p,\n const char *filename,\n void (*start_cb)(void *opaque),\n void *opaque)\n{\n VMConfigLoadState *s;\n \n s = mallocz(sizeof(*s));\n s->vm_params = p;\n s->start_cb = start_cb;\n s->opaque = opaque;\n p->cfg_filename = strdup(filename);\n\n config_load_file(s, filename, config_file_loaded, s);\n}\n\nstatic void config_file_loaded(void *opaque, uint8_t *buf, int buf_len)\n{\n VMConfigLoadState *s = opaque;\n VirtMachineParams *p = s->vm_params;\n\n if (virt_machine_parse_config(p, (char *)buf, buf_len) < 0)\n exit(1);\n \n /* load the additional files */\n s->file_index = 0;\n config_additional_file_load(s);\n}\n\nstatic void config_additional_file_load(VMConfigLoadState *s)\n{\n VirtMachineParams *p = s->vm_params;\n while (s->file_index < VM_FILE_COUNT &&\n p->files[s->file_index].filename == NULL) {\n s->file_index++;\n }\n if (s->file_index == VM_FILE_COUNT) {\n if (s->start_cb)\n s->start_cb(s->opaque);\n free(s);\n } else {\n char *fname;\n \n fname = get_file_path(p->cfg_filename,\n p->files[s->file_index].filename);\n config_load_file(s, fname,\n config_additional_file_load_cb, s);\n free(fname);\n }\n}\n\nstatic void config_additional_file_load_cb(void *opaque,\n uint8_t *buf, int buf_len)\n{\n VMConfigLoadState *s = opaque;\n VirtMachineParams *p = s->vm_params;\n\n p->files[s->file_index].buf = malloc(buf_len);\n memcpy(p->files[s->file_index].buf, buf, buf_len);\n p->files[s->file_index].len = buf_len;\n\n /* load the next files */\n s->file_index++;\n config_additional_file_load(s);\n}\n\nvoid vm_add_cmdline(VirtMachineParams *p, const char *cmdline)\n{\n char *new_cmdline, *old_cmdline;\n if (cmdline[0] == '!') {\n new_cmdline = strdup(cmdline + 1);\n } else {\n old_cmdline = p->cmdline;\n if (!old_cmdline)\n old_cmdline = \"\";\n new_cmdline = malloc(strlen(old_cmdline) + 1 + strlen(cmdline) + 1);\n strcpy(new_cmdline, old_cmdline);\n strcat(new_cmdline, \" \");\n strcat(new_cmdline, cmdline);\n }\n free(p->cmdline);\n p->cmdline = new_cmdline;\n}\n\nvoid virt_machine_free_config(VirtMachineParams *p)\n{\n int i;\n \n free(p->machine_name);\n free(p->cmdline);\n for(i = 0; i < VM_FILE_COUNT; i++) {\n free(p->files[i].filename);\n free(p->files[i].buf);\n }\n for(i = 0; i < p->drive_count; i++) {\n free(p->tab_drive[i].filename);\n free(p->tab_drive[i].device);\n }\n for(i = 0; i < p->fs_count; i++) {\n free(p->tab_fs[i].filename);\n free(p->tab_fs[i].tag);\n }\n for(i = 0; i < p->eth_count; i++) {\n free(p->tab_eth[i].driver);\n free(p->tab_eth[i].ifname);\n }\n free(p->input_device);\n free(p->display_device);\n free(p->cfg_filename);\n}\n\nVirtMachine *virt_machine_init(const VirtMachineParams *p)\n{\n const VirtMachineClass *vmc = p->vmc;\n return vmc->virt_machine_init(p);\n}\n\nvoid virt_machine_set_defaults(VirtMachineParams *p)\n{\n memset(p, 0, sizeof(*p));\n}\n\nvoid virt_machine_end(VirtMachine *s)\n{\n s->vmc->virt_machine_end(s);\n}\n"], ["/linuxpdf/tinyemu/x86_machine.c", "/*\n * PC emulator\n * \n * Copyright (c) 2011-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"x86_cpu.h\"\n#include \"machine.h\"\n#include \"pci.h\"\n#include \"ide.h\"\n#include \"ps2.h\"\n\n#if defined(__linux__) && (defined(__i386__) || defined(__x86_64__))\n#define USE_KVM\n#endif\n\n#ifdef USE_KVM\n#include \n#include \n#include \n#include \n#include \n#endif\n\n//#define DEBUG_BIOS\n//#define DUMP_IOPORT\n\n/***********************************************************/\n/* cmos emulation */\n\n//#define DEBUG_CMOS\n\n#define RTC_SECONDS 0\n#define RTC_SECONDS_ALARM 1\n#define RTC_MINUTES 2\n#define RTC_MINUTES_ALARM 3\n#define RTC_HOURS 4\n#define RTC_HOURS_ALARM 5\n#define RTC_ALARM_DONT_CARE 0xC0\n\n#define RTC_DAY_OF_WEEK 6\n#define RTC_DAY_OF_MONTH 7\n#define RTC_MONTH 8\n#define RTC_YEAR 9\n\n#define RTC_REG_A 10\n#define RTC_REG_B 11\n#define RTC_REG_C 12\n#define RTC_REG_D 13\n\n#define REG_A_UIP 0x80\n\n#define REG_B_SET 0x80\n#define REG_B_PIE 0x40\n#define REG_B_AIE 0x20\n#define REG_B_UIE 0x10\n\ntypedef struct {\n uint8_t cmos_index;\n uint8_t cmos_data[128];\n IRQSignal *irq;\n BOOL use_local_time;\n /* used for the periodic irq */\n uint32_t irq_timeout;\n uint32_t irq_period;\n} CMOSState;\n\nstatic void cmos_write(void *opaque, uint32_t offset,\n uint32_t data, int size_log2);\nstatic uint32_t cmos_read(void *opaque, uint32_t offset, int size_log2);\n\nstatic int to_bcd(CMOSState *s, unsigned int a)\n{\n if (s->cmos_data[RTC_REG_B] & 0x04) {\n return a;\n } else {\n return ((a / 10) << 4) | (a % 10);\n }\n}\n\nstatic void cmos_update_time(CMOSState *s, BOOL set_century)\n{\n struct timeval tv;\n struct tm tm;\n time_t ti;\n int val;\n \n gettimeofday(&tv, NULL);\n ti = tv.tv_sec;\n if (s->use_local_time) {\n localtime_r(&ti, &tm);\n } else {\n gmtime_r(&ti, &tm);\n }\n \n s->cmos_data[RTC_SECONDS] = to_bcd(s, tm.tm_sec);\n s->cmos_data[RTC_MINUTES] = to_bcd(s, tm.tm_min);\n if (s->cmos_data[RTC_REG_B] & 0x02) {\n s->cmos_data[RTC_HOURS] = to_bcd(s, tm.tm_hour);\n } else {\n s->cmos_data[RTC_HOURS] = to_bcd(s, tm.tm_hour % 12);\n if (tm.tm_hour >= 12)\n s->cmos_data[RTC_HOURS] |= 0x80;\n }\n s->cmos_data[RTC_DAY_OF_WEEK] = to_bcd(s, tm.tm_wday);\n s->cmos_data[RTC_DAY_OF_MONTH] = to_bcd(s, tm.tm_mday);\n s->cmos_data[RTC_MONTH] = to_bcd(s, tm.tm_mon + 1);\n s->cmos_data[RTC_YEAR] = to_bcd(s, tm.tm_year % 100);\n\n if (set_century) {\n /* not set by the hardware, but easier to do it here */\n val = to_bcd(s, (tm.tm_year / 100) + 19);\n s->cmos_data[0x32] = val;\n s->cmos_data[0x37] = val;\n }\n \n /* update in progress flag: 8/32768 seconds after change */\n if (tv.tv_usec < 244) {\n s->cmos_data[RTC_REG_A] |= REG_A_UIP;\n } else {\n s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;\n }\n}\n\nCMOSState *cmos_init(PhysMemoryMap *port_map, int addr,\n IRQSignal *irq, BOOL use_local_time)\n{\n CMOSState *s;\n \n s = mallocz(sizeof(*s));\n s->use_local_time = use_local_time;\n \n s->cmos_index = 0;\n\n s->cmos_data[RTC_REG_A] = 0x26;\n s->cmos_data[RTC_REG_B] = 0x02;\n s->cmos_data[RTC_REG_C] = 0x00;\n s->cmos_data[RTC_REG_D] = 0x80;\n\n cmos_update_time(s, TRUE);\n \n s->irq = irq;\n \n cpu_register_device(port_map, addr, 2, s, cmos_read, cmos_write, \n DEVIO_SIZE8);\n return s;\n}\n\n#define CMOS_FREQ 32768\n\nstatic uint32_t cmos_get_timer(CMOSState *s)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint32_t)ts.tv_sec * CMOS_FREQ +\n ((uint64_t)ts.tv_nsec * CMOS_FREQ / 1000000000);\n}\n\nstatic void cmos_update_timer(CMOSState *s)\n{\n int period_code;\n\n period_code = s->cmos_data[RTC_REG_A] & 0x0f;\n if ((s->cmos_data[RTC_REG_B] & REG_B_PIE) &&\n period_code != 0) {\n if (period_code <= 2)\n period_code += 7;\n s->irq_period = 1 << (period_code - 1);\n s->irq_timeout = (cmos_get_timer(s) + s->irq_period) &\n ~(s->irq_period - 1);\n }\n}\n\n/* XXX: could return a delay, but we don't need high precision\n (Windows 2000 uses it for delay calibration) */\nstatic void cmos_update_irq(CMOSState *s)\n{\n uint32_t d;\n if (s->cmos_data[RTC_REG_B] & REG_B_PIE) {\n d = cmos_get_timer(s) - s->irq_timeout;\n if ((int32_t)d >= 0) {\n /* this is not what the real RTC does. Here we sent the IRQ\n immediately */\n s->cmos_data[RTC_REG_C] |= 0xc0;\n set_irq(s->irq, 1);\n /* update for the next irq */\n s->irq_timeout += s->irq_period;\n }\n }\n}\n\nstatic void cmos_write(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n CMOSState *s = opaque;\n\n if (offset == 0) {\n s->cmos_index = data & 0x7f;\n } else {\n#ifdef DEBUG_CMOS\n printf(\"cmos_write: reg=0x%02x val=0x%02x\\n\", s->cmos_index, data);\n#endif\n switch(s->cmos_index) {\n case RTC_REG_A:\n s->cmos_data[RTC_REG_A] = (data & ~REG_A_UIP) |\n (s->cmos_data[RTC_REG_A] & REG_A_UIP);\n cmos_update_timer(s);\n break;\n case RTC_REG_B:\n s->cmos_data[s->cmos_index] = data;\n cmos_update_timer(s);\n break;\n default:\n s->cmos_data[s->cmos_index] = data;\n break;\n }\n }\n}\n\nstatic uint32_t cmos_read(void *opaque, uint32_t offset, int size_log2)\n{\n CMOSState *s = opaque;\n int ret;\n\n if (offset == 0) {\n return 0xff;\n } else {\n switch(s->cmos_index) {\n case RTC_SECONDS:\n case RTC_MINUTES:\n case RTC_HOURS:\n case RTC_DAY_OF_WEEK:\n case RTC_DAY_OF_MONTH:\n case RTC_MONTH:\n case RTC_YEAR:\n case RTC_REG_A:\n cmos_update_time(s, FALSE);\n ret = s->cmos_data[s->cmos_index];\n break;\n case RTC_REG_C:\n ret = s->cmos_data[s->cmos_index];\n s->cmos_data[RTC_REG_C] = 0x00;\n set_irq(s->irq, 0);\n break;\n default:\n ret = s->cmos_data[s->cmos_index];\n }\n#ifdef DEBUG_CMOS\n printf(\"cmos_read: reg=0x%02x val=0x%02x\\n\", s->cmos_index, ret);\n#endif\n return ret;\n }\n}\n\n/***********************************************************/\n/* 8259 pic emulation */\n\n//#define DEBUG_PIC\n\ntypedef void PICUpdateIRQFunc(void *opaque);\n\ntypedef struct {\n uint8_t last_irr; /* edge detection */\n uint8_t irr; /* interrupt request register */\n uint8_t imr; /* interrupt mask register */\n uint8_t isr; /* interrupt service register */\n uint8_t priority_add; /* used to compute irq priority */\n uint8_t irq_base;\n uint8_t read_reg_select;\n uint8_t special_mask;\n uint8_t init_state;\n uint8_t auto_eoi;\n uint8_t rotate_on_autoeoi;\n uint8_t init4; /* true if 4 byte init */\n uint8_t elcr; /* PIIX edge/trigger selection*/\n uint8_t elcr_mask;\n PICUpdateIRQFunc *update_irq;\n void *opaque;\n} PICState;\n\nstatic void pic_reset(PICState *s);\nstatic void pic_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pic_read(void *opaque, uint32_t offset, int size_log2);\nstatic void pic_elcr_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pic_elcr_read(void *opaque, uint32_t offset, int size_log2);\n\nPICState *pic_init(PhysMemoryMap *port_map, int port, int elcr_port,\n int elcr_mask,\n PICUpdateIRQFunc *update_irq, void *opaque)\n{\n PICState *s;\n\n s = mallocz(sizeof(*s));\n s->elcr_mask = elcr_mask;\n s->update_irq = update_irq;\n s->opaque = opaque;\n cpu_register_device(port_map, port, 2, s,\n pic_read, pic_write, DEVIO_SIZE8);\n cpu_register_device(port_map, elcr_port, 1, s,\n pic_elcr_read, pic_elcr_write, DEVIO_SIZE8);\n pic_reset(s);\n return s;\n}\n\nstatic void pic_reset(PICState *s)\n{\n /* all 8 bit registers */\n s->last_irr = 0; /* edge detection */\n s->irr = 0; /* interrupt request register */\n s->imr = 0; /* interrupt mask register */\n s->isr = 0; /* interrupt service register */\n s->priority_add = 0; /* used to compute irq priority */\n s->irq_base = 0;\n s->read_reg_select = 0;\n s->special_mask = 0;\n s->init_state = 0;\n s->auto_eoi = 0;\n s->rotate_on_autoeoi = 0;\n s->init4 = 0; /* true if 4 byte init */\n}\n\n/* set irq level. If an edge is detected, then the IRR is set to 1 */\nstatic void pic_set_irq1(PICState *s, int irq, int level)\n{\n int mask;\n mask = 1 << irq;\n if (s->elcr & mask) {\n /* level triggered */\n if (level) {\n s->irr |= mask;\n s->last_irr |= mask;\n } else {\n s->irr &= ~mask;\n s->last_irr &= ~mask;\n }\n } else {\n /* edge triggered */\n if (level) {\n if ((s->last_irr & mask) == 0)\n s->irr |= mask;\n s->last_irr |= mask;\n } else {\n s->last_irr &= ~mask;\n }\n }\n}\n \nstatic int pic_get_priority(PICState *s, int mask)\n{\n int priority;\n if (mask == 0)\n return -1;\n priority = 7;\n while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)\n priority--;\n return priority;\n}\n\n/* return the pic wanted interrupt. return -1 if none */\nstatic int pic_get_irq(PICState *s)\n{\n int mask, cur_priority, priority;\n\n mask = s->irr & ~s->imr;\n priority = pic_get_priority(s, mask);\n if (priority < 0)\n return -1;\n /* compute current priority */\n cur_priority = pic_get_priority(s, s->isr);\n if (priority > cur_priority) {\n /* higher priority found: an irq should be generated */\n return priority;\n } else {\n return -1;\n }\n}\n \n/* acknowledge interrupt 'irq' */\nstatic void pic_intack(PICState *s, int irq)\n{\n if (s->auto_eoi) {\n if (s->rotate_on_autoeoi)\n s->priority_add = (irq + 1) & 7;\n } else {\n s->isr |= (1 << irq);\n }\n /* We don't clear a level sensitive interrupt here */\n if (!(s->elcr & (1 << irq)))\n s->irr &= ~(1 << irq);\n}\n\nstatic void pic_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PICState *s = opaque;\n int priority, addr;\n \n addr = offset & 1;\n#ifdef DEBUG_PIC\n console.log(\"pic_write: addr=\" + toHex2(addr) + \" val=\" + toHex2(val));\n#endif\n if (addr == 0) {\n if (val & 0x10) {\n /* init */\n pic_reset(s);\n s->init_state = 1;\n s->init4 = val & 1;\n if (val & 0x02)\n abort(); /* \"single mode not supported\" */\n if (val & 0x08)\n abort(); /* \"level sensitive irq not supported\" */\n } else if (val & 0x08) {\n if (val & 0x02)\n s->read_reg_select = val & 1;\n if (val & 0x40)\n s->special_mask = (val >> 5) & 1;\n } else {\n switch(val) {\n case 0x00:\n case 0x80:\n s->rotate_on_autoeoi = val >> 7;\n break;\n case 0x20: /* end of interrupt */\n case 0xa0:\n priority = pic_get_priority(s, s->isr);\n if (priority >= 0) {\n s->isr &= ~(1 << ((priority + s->priority_add) & 7));\n }\n if (val == 0xa0)\n s->priority_add = (s->priority_add + 1) & 7;\n break;\n case 0x60:\n case 0x61:\n case 0x62:\n case 0x63:\n case 0x64:\n case 0x65:\n case 0x66:\n case 0x67:\n priority = val & 7;\n s->isr &= ~(1 << priority);\n break;\n case 0xc0:\n case 0xc1:\n case 0xc2:\n case 0xc3:\n case 0xc4:\n case 0xc5:\n case 0xc6:\n case 0xc7:\n s->priority_add = (val + 1) & 7;\n break;\n case 0xe0:\n case 0xe1:\n case 0xe2:\n case 0xe3:\n case 0xe4:\n case 0xe5:\n case 0xe6:\n case 0xe7:\n priority = val & 7;\n s->isr &= ~(1 << priority);\n s->priority_add = (priority + 1) & 7;\n break;\n }\n }\n } else {\n switch(s->init_state) {\n case 0:\n /* normal mode */\n s->imr = val;\n s->update_irq(s->opaque);\n break;\n case 1:\n s->irq_base = val & 0xf8;\n s->init_state = 2;\n break;\n case 2:\n if (s->init4) {\n s->init_state = 3;\n } else {\n s->init_state = 0;\n }\n break;\n case 3:\n s->auto_eoi = (val >> 1) & 1;\n s->init_state = 0;\n break;\n }\n }\n}\n\nstatic uint32_t pic_read(void *opaque, uint32_t offset, int size_log2)\n{\n PICState *s = opaque;\n int addr, ret;\n\n addr = offset & 1;\n if (addr == 0) {\n if (s->read_reg_select)\n ret = s->isr;\n else\n ret = s->irr;\n } else {\n ret = s->imr;\n }\n#ifdef DEBUG_PIC\n console.log(\"pic_read: addr=\" + toHex2(addr1) + \" val=\" + toHex2(ret));\n#endif\n return ret;\n}\n\nstatic void pic_elcr_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PICState *s = opaque;\n s->elcr = val & s->elcr_mask;\n}\n\nstatic uint32_t pic_elcr_read(void *opaque, uint32_t offset, int size_log2)\n{\n PICState *s = opaque;\n return s->elcr;\n}\n\ntypedef struct {\n PICState *pics[2];\n int irq_requested;\n void (*cpu_set_irq)(void *opaque, int level);\n void *opaque;\n#if defined(DEBUG_PIC)\n uint8_t irq_level[16];\n#endif\n IRQSignal *irqs;\n} PIC2State;\n\nstatic void pic2_update_irq(void *opaque);\nstatic void pic2_set_irq(void *opaque, int irq, int level);\n\nPIC2State *pic2_init(PhysMemoryMap *port_map, uint32_t addr0, uint32_t addr1,\n uint32_t elcr_addr0, uint32_t elcr_addr1, \n void (*cpu_set_irq)(void *opaque, int level),\n void *opaque, IRQSignal *irqs)\n{\n PIC2State *s;\n int i;\n \n s = mallocz(sizeof(*s));\n\n for(i = 0; i < 16; i++) {\n irq_init(&irqs[i], pic2_set_irq, s, i);\n }\n s->cpu_set_irq = cpu_set_irq;\n s->opaque = opaque;\n s->pics[0] = pic_init(port_map, addr0, elcr_addr0, 0xf8, pic2_update_irq, s);\n s->pics[1] = pic_init(port_map, addr1, elcr_addr1, 0xde, pic2_update_irq, s);\n s->irq_requested = 0;\n return s;\n}\n\nvoid pic2_set_elcr(PIC2State *s, const uint8_t *elcr)\n{\n int i;\n for(i = 0; i < 2; i++) {\n s->pics[i]->elcr = elcr[i] & s->pics[i]->elcr_mask;\n }\n}\n\n/* raise irq to CPU if necessary. must be called every time the active\n irq may change */\nstatic void pic2_update_irq(void *opaque)\n{\n PIC2State *s = opaque;\n int irq2, irq;\n\n /* first look at slave pic */\n irq2 = pic_get_irq(s->pics[1]);\n if (irq2 >= 0) {\n /* if irq request by slave pic, signal master PIC */\n pic_set_irq1(s->pics[0], 2, 1);\n pic_set_irq1(s->pics[0], 2, 0);\n }\n /* look at requested irq */\n irq = pic_get_irq(s->pics[0]);\n#if 0\n console.log(\"irr=\" + toHex2(s->pics[0].irr) + \" imr=\" + toHex2(s->pics[0].imr) + \" isr=\" + toHex2(s->pics[0].isr) + \" irq=\"+ irq);\n#endif\n if (irq >= 0) {\n /* raise IRQ request on the CPU */\n s->cpu_set_irq(s->opaque, 1);\n } else {\n /* lower irq */\n s->cpu_set_irq(s->opaque, 0);\n }\n}\n\nstatic void pic2_set_irq(void *opaque, int irq, int level)\n{\n PIC2State *s = opaque;\n#if defined(DEBUG_PIC)\n if (irq != 0 && level != s->irq_level[irq]) {\n console.log(\"pic_set_irq: irq=\" + irq + \" level=\" + level);\n s->irq_level[irq] = level;\n }\n#endif\n pic_set_irq1(s->pics[irq >> 3], irq & 7, level);\n pic2_update_irq(s);\n}\n\n/* called from the CPU to get the hardware interrupt number */\nstatic int pic2_get_hard_intno(PIC2State *s)\n{\n int irq, irq2, intno;\n\n irq = pic_get_irq(s->pics[0]);\n if (irq >= 0) {\n pic_intack(s->pics[0], irq);\n if (irq == 2) {\n irq2 = pic_get_irq(s->pics[1]);\n if (irq2 >= 0) {\n pic_intack(s->pics[1], irq2);\n } else {\n /* spurious IRQ on slave controller */\n irq2 = 7;\n }\n intno = s->pics[1]->irq_base + irq2;\n irq = irq2 + 8;\n } else {\n intno = s->pics[0]->irq_base + irq;\n }\n } else {\n /* spurious IRQ on host controller */\n irq = 7;\n intno = s->pics[0]->irq_base + irq;\n }\n pic2_update_irq(s);\n\n#if defined(DEBUG_PIC)\n if (irq != 0 && irq != 14)\n printf(\"pic_interrupt: irq=%d\\n\", irq);\n#endif\n return intno;\n}\n\n/***********************************************************/\n/* 8253 PIT emulation */\n\n#define PIT_FREQ 1193182\n\n#define RW_STATE_LSB 0\n#define RW_STATE_MSB 1\n#define RW_STATE_WORD0 2\n#define RW_STATE_WORD1 3\n#define RW_STATE_LATCHED_WORD0 4\n#define RW_STATE_LATCHED_WORD1 5\n\n//#define DEBUG_PIT\n\ntypedef int64_t PITGetTicksFunc(void *opaque);\n\ntypedef struct PITState PITState;\n\ntypedef struct {\n PITState *pit_state;\n uint32_t count;\n uint32_t latched_count;\n uint8_t rw_state;\n uint8_t mode;\n uint8_t bcd;\n uint8_t gate;\n int64_t count_load_time;\n int64_t last_irq_time;\n} PITChannel;\n\nstruct PITState {\n PITChannel pit_channels[3];\n uint8_t speaker_data_on;\n PITGetTicksFunc *get_ticks;\n IRQSignal *irq;\n void *opaque;\n};\n\nstatic void pit_load_count(PITChannel *pc, int val);\nstatic void pit_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t pit_read(void *opaque, uint32_t offset, int size_log2);\nstatic void speaker_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t speaker_read(void *opaque, uint32_t offset, int size_log2);\n\nPITState *pit_init(PhysMemoryMap *port_map, int addr0, int addr1,\n IRQSignal *irq,\n PITGetTicksFunc *get_ticks, void *opaque)\n{\n PITState *s;\n PITChannel *pc;\n int i;\n\n s = mallocz(sizeof(*s));\n\n s->irq = irq;\n s->get_ticks = get_ticks;\n s->opaque = opaque;\n \n for(i = 0; i < 3; i++) {\n pc = &s->pit_channels[i];\n pc->pit_state = s;\n pc->mode = 3;\n pc->gate = (i != 2) >> 0;\n pit_load_count(pc, 0);\n }\n s->speaker_data_on = 0;\n\n cpu_register_device(port_map, addr0, 4, s, pit_read, pit_write, \n DEVIO_SIZE8);\n\n cpu_register_device(port_map, addr1, 1, s, speaker_read, speaker_write, \n DEVIO_SIZE8);\n return s;\n}\n\n/* unit = PIT frequency */\nstatic int64_t pit_get_time(PITChannel *pc)\n{\n PITState *s = pc->pit_state;\n return s->get_ticks(s->opaque);\n}\n\nstatic uint32_t pit_get_count(PITChannel *pc)\n{\n uint32_t counter;\n uint64_t d;\n \n d = pit_get_time(pc) - pc->count_load_time;\n switch(pc->mode) {\n case 0:\n case 1:\n case 4:\n case 5:\n counter = (pc->count - d) & 0xffff;\n break;\n default:\n counter = pc->count - (d % pc->count);\n break;\n }\n return counter;\n}\n\n/* get pit output bit */\nstatic int pit_get_out(PITChannel *pc)\n{\n int out;\n int64_t d;\n \n d = pit_get_time(pc) - pc->count_load_time;\n switch(pc->mode) {\n default:\n case 0:\n out = (d >= pc->count) >> 0;\n break;\n case 1:\n out = (d < pc->count) >> 0;\n break;\n case 2:\n /* mode used by Linux */\n if ((d % pc->count) == 0 && d != 0)\n out = 1;\n else\n out = 0;\n break;\n case 3:\n out = ((d % pc->count) < (pc->count >> 1)) >> 0;\n break;\n case 4:\n case 5:\n out = (d == pc->count) >> 0;\n break;\n }\n return out;\n}\n\nstatic void pit_load_count(PITChannel *s, int val)\n{\n if (val == 0)\n val = 0x10000;\n s->count_load_time = pit_get_time(s);\n s->last_irq_time = 0;\n s->count = val;\n}\n\nstatic void pit_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PITState *pit = opaque;\n int channel, access, addr;\n PITChannel *s;\n\n addr = offset & 3;\n#ifdef DEBUG_PIT\n printf(\"pit_write: off=%d val=0x%02x\\n\", addr, val);\n#endif\n if (addr == 3) {\n channel = val >> 6;\n if (channel == 3)\n return;\n s = &pit->pit_channels[channel];\n access = (val >> 4) & 3;\n switch(access) {\n case 0:\n s->latched_count = pit_get_count(s);\n s->rw_state = RW_STATE_LATCHED_WORD0;\n break;\n default:\n s->mode = (val >> 1) & 7;\n s->bcd = val & 1;\n s->rw_state = access - 1 + RW_STATE_LSB;\n break;\n }\n } else {\n s = &pit->pit_channels[addr];\n switch(s->rw_state) {\n case RW_STATE_LSB:\n pit_load_count(s, val);\n break;\n case RW_STATE_MSB:\n pit_load_count(s, val << 8);\n break;\n case RW_STATE_WORD0:\n case RW_STATE_WORD1:\n if (s->rw_state & 1) {\n pit_load_count(s, (s->latched_count & 0xff) | (val << 8));\n } else {\n s->latched_count = val;\n }\n s->rw_state ^= 1;\n break;\n }\n }\n}\n\nstatic uint32_t pit_read(void *opaque, uint32_t offset, int size_log2)\n{\n PITState *pit = opaque;\n PITChannel *s;\n int ret, count, addr;\n \n addr = offset & 3;\n if (addr == 3)\n return 0xff;\n\n s = &pit->pit_channels[addr];\n switch(s->rw_state) {\n case RW_STATE_LSB:\n case RW_STATE_MSB:\n case RW_STATE_WORD0:\n case RW_STATE_WORD1:\n count = pit_get_count(s);\n if (s->rw_state & 1)\n ret = (count >> 8) & 0xff;\n else\n ret = count & 0xff;\n if (s->rw_state & 2)\n s->rw_state ^= 1;\n break;\n default:\n case RW_STATE_LATCHED_WORD0:\n case RW_STATE_LATCHED_WORD1:\n if (s->rw_state & 1)\n ret = s->latched_count >> 8;\n else\n ret = s->latched_count & 0xff;\n s->rw_state ^= 1;\n break;\n }\n#ifdef DEBUG_PIT\n printf(\"pit_read: off=%d val=0x%02x\\n\", addr, ret);\n#endif\n return ret;\n}\n\nstatic void speaker_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n PITState *pit = opaque;\n pit->speaker_data_on = (val >> 1) & 1;\n pit->pit_channels[2].gate = val & 1;\n}\n\nstatic uint32_t speaker_read(void *opaque, uint32_t offset, int size_log2)\n{\n PITState *pit = opaque;\n PITChannel *s;\n int out, val;\n\n s = &pit->pit_channels[2];\n out = pit_get_out(s);\n val = (pit->speaker_data_on << 1) | s->gate | (out << 5);\n#ifdef DEBUG_PIT\n // console.log(\"speaker_read: addr=\" + toHex2(addr) + \" val=\" + toHex2(val));\n#endif\n return val;\n}\n\n/* set the IRQ if necessary and return the delay in ms until the next\n IRQ. Note: The code does not handle all the PIT configurations. */\nstatic int pit_update_irq(PITState *pit)\n{\n PITChannel *s;\n int64_t d, delay;\n \n s = &pit->pit_channels[0];\n \n delay = PIT_FREQ; /* could be infinity delay */\n \n d = pit_get_time(s) - s->count_load_time;\n switch(s->mode) {\n default:\n case 0:\n case 1:\n case 4:\n case 5:\n if (s->last_irq_time == 0) {\n delay = s->count - d;\n if (delay <= 0) {\n set_irq(pit->irq, 1);\n set_irq(pit->irq, 0);\n s->last_irq_time = d;\n }\n }\n break;\n case 2: /* mode used by Linux */\n case 3:\n delay = s->last_irq_time + s->count - d;\n if (delay <= 0) {\n set_irq(pit->irq, 1);\n set_irq(pit->irq, 0);\n s->last_irq_time += s->count;\n }\n break;\n }\n\n if (delay <= 0)\n return 0;\n else\n return delay / (PIT_FREQ / 1000);\n}\n \n/***********************************************************/\n/* serial port emulation */\n\n#define UART_LCR_DLAB\t0x80\t/* Divisor latch access bit */\n\n#define UART_IER_MSI\t0x08\t/* Enable Modem status interrupt */\n#define UART_IER_RLSI\t0x04\t/* Enable receiver line status interrupt */\n#define UART_IER_THRI\t0x02\t/* Enable Transmitter holding register int. */\n#define UART_IER_RDI\t0x01\t/* Enable receiver data interrupt */\n\n#define UART_IIR_NO_INT\t0x01\t/* No interrupts pending */\n#define UART_IIR_ID\t0x06\t/* Mask for the interrupt ID */\n\n#define UART_IIR_MSI\t0x00\t/* Modem status interrupt */\n#define UART_IIR_THRI\t0x02\t/* Transmitter holding register empty */\n#define UART_IIR_RDI\t0x04\t/* Receiver data interrupt */\n#define UART_IIR_RLSI\t0x06\t/* Receiver line status interrupt */\n#define UART_IIR_FE 0xC0 /* Fifo enabled */\n\n#define UART_LSR_TEMT\t0x40\t/* Transmitter empty */\n#define UART_LSR_THRE\t0x20\t/* Transmit-hold-register empty */\n#define UART_LSR_BI\t0x10\t/* Break interrupt indicator */\n#define UART_LSR_FE\t0x08\t/* Frame error indicator */\n#define UART_LSR_PE\t0x04\t/* Parity error indicator */\n#define UART_LSR_OE\t0x02\t/* Overrun error indicator */\n#define UART_LSR_DR\t0x01\t/* Receiver data ready */\n\n#define UART_FCR_XFR 0x04 /* XMIT Fifo Reset */\n#define UART_FCR_RFR 0x02 /* RCVR Fifo Reset */\n#define UART_FCR_FE 0x01 /* FIFO Enable */\n\n#define UART_FIFO_LENGTH 16 /* 16550A Fifo Length */\n\ntypedef struct {\n uint8_t divider; \n uint8_t rbr; /* receive register */\n uint8_t ier;\n uint8_t iir; /* read only */\n uint8_t lcr;\n uint8_t mcr;\n uint8_t lsr; /* read only */\n uint8_t msr;\n uint8_t scr;\n uint8_t fcr;\n IRQSignal *irq;\n void (*write_func)(void *opaque, const uint8_t *buf, int buf_len);\n void *opaque;\n} SerialState;\n\nstatic void serial_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2);\nstatic uint32_t serial_read(void *opaque, uint32_t offset, int size_log2);\n\nSerialState *serial_init(PhysMemoryMap *port_map, int addr,\n IRQSignal *irq,\n void (*write_func)(void *opaque, const uint8_t *buf, int buf_len), void *opaque)\n{\n SerialState *s;\n s = mallocz(sizeof(*s));\n \n /* all 8 bit registers */\n s->divider = 0; \n s->rbr = 0; /* receive register */\n s->ier = 0;\n s->iir = UART_IIR_NO_INT; /* read only */\n s->lcr = 0;\n s->mcr = 0;\n s->lsr = UART_LSR_TEMT | UART_LSR_THRE; /* read only */\n s->msr = 0;\n s->scr = 0;\n s->fcr = 0;\n\n s->irq = irq;\n s->write_func = write_func;\n s->opaque = opaque;\n\n cpu_register_device(port_map, addr, 8, s, serial_read, serial_write, \n DEVIO_SIZE8);\n return s;\n}\n\nstatic void serial_update_irq(SerialState *s)\n{\n if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {\n s->iir = UART_IIR_RDI;\n } else if ((s->lsr & UART_LSR_THRE) && (s->ier & UART_IER_THRI)) {\n s->iir = UART_IIR_THRI;\n } else {\n s->iir = UART_IIR_NO_INT;\n }\n if (s->iir != UART_IIR_NO_INT) {\n set_irq(s->irq, 1);\n } else {\n set_irq(s->irq, 0);\n }\n}\n\n#if 0\n/* send remainining chars in fifo */\nSerial.prototype.write_tx_fifo = function()\n{\n if (s->tx_fifo != \"\") {\n s->write_func(s->tx_fifo);\n s->tx_fifo = \"\";\n \n s->lsr |= UART_LSR_THRE;\n s->lsr |= UART_LSR_TEMT;\n s->update_irq();\n }\n}\n#endif\n \nstatic void serial_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n SerialState *s = opaque;\n int addr;\n\n addr = offset & 7;\n switch(addr) {\n default:\n case 0:\n if (s->lcr & UART_LCR_DLAB) {\n s->divider = (s->divider & 0xff00) | val;\n } else {\n#if 0\n if (s->fcr & UART_FCR_FE) {\n s->tx_fifo += String.fromCharCode(val);\n s->lsr &= ~UART_LSR_THRE;\n serial_update_irq(s);\n if (s->tx_fifo.length >= UART_FIFO_LENGTH) {\n /* write to the terminal */\n s->write_tx_fifo();\n }\n } else\n#endif\n {\n uint8_t ch;\n s->lsr &= ~UART_LSR_THRE;\n serial_update_irq(s);\n \n /* write to the terminal */\n ch = val;\n s->write_func(s->opaque, &ch, 1);\n s->lsr |= UART_LSR_THRE;\n s->lsr |= UART_LSR_TEMT;\n serial_update_irq(s);\n }\n }\n break;\n case 1:\n if (s->lcr & UART_LCR_DLAB) {\n s->divider = (s->divider & 0x00ff) | (val << 8);\n } else {\n s->ier = val;\n serial_update_irq(s);\n }\n break;\n case 2:\n#if 0\n if ((s->fcr ^ val) & UART_FCR_FE) {\n /* clear fifos */\n val |= UART_FCR_XFR | UART_FCR_RFR;\n }\n if (val & UART_FCR_XFR)\n s->tx_fifo = \"\";\n if (val & UART_FCR_RFR)\n s->rx_fifo = \"\";\n s->fcr = val & UART_FCR_FE;\n#endif\n break;\n case 3:\n s->lcr = val;\n break;\n case 4:\n s->mcr = val;\n break;\n case 5:\n break;\n case 6:\n s->msr = val;\n break;\n case 7:\n s->scr = val;\n break;\n }\n}\n\nstatic uint32_t serial_read(void *opaque, uint32_t offset, int size_log2)\n{\n SerialState *s = opaque;\n int ret, addr;\n\n addr = offset & 7;\n switch(addr) {\n default:\n case 0:\n if (s->lcr & UART_LCR_DLAB) {\n ret = s->divider & 0xff; \n } else {\n ret = s->rbr;\n s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);\n serial_update_irq(s);\n#if 0\n /* try to receive next chars */\n s->send_char_from_fifo();\n#endif\n }\n break;\n case 1:\n if (s->lcr & UART_LCR_DLAB) {\n ret = (s->divider >> 8) & 0xff;\n } else {\n ret = s->ier;\n }\n break;\n case 2:\n ret = s->iir;\n if (s->fcr & UART_FCR_FE)\n ret |= UART_IIR_FE;\n break;\n case 3:\n ret = s->lcr;\n break;\n case 4:\n ret = s->mcr;\n break;\n case 5:\n ret = s->lsr;\n break;\n case 6:\n ret = s->msr;\n break;\n case 7:\n ret = s->scr;\n break;\n }\n return ret;\n}\n\nvoid serial_send_break(SerialState *s)\n{\n s->rbr = 0;\n s->lsr |= UART_LSR_BI | UART_LSR_DR;\n serial_update_irq(s);\n}\n\n#if 0\nstatic void serial_send_char(SerialState *s, int ch)\n{\n s->rbr = ch;\n s->lsr |= UART_LSR_DR;\n serial_update_irq(s);\n}\n\nSerial.prototype.send_char_from_fifo = function()\n{\n var fifo;\n\n fifo = s->rx_fifo;\n if (fifo != \"\" && !(s->lsr & UART_LSR_DR)) {\n s->send_char(fifo.charCodeAt(0));\n s->rx_fifo = fifo.substr(1, fifo.length - 1);\n }\n}\n\n/* queue the string in the UART receive fifo and send it ASAP */\nSerial.prototype.send_chars = function(str)\n{\n s->rx_fifo += str;\n s->send_char_from_fifo();\n}\n \n#endif\n\n#ifdef DEBUG_BIOS\nstatic void bios_debug_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n#ifdef EMSCRIPTEN\n static char line_buf[256];\n static int line_buf_index;\n line_buf[line_buf_index++] = val;\n if (val == '\\n' || line_buf_index >= sizeof(line_buf) - 1) {\n line_buf[line_buf_index] = '\\0';\n printf(\"%s\", line_buf);\n line_buf_index = 0;\n }\n#else\n putchar(val & 0xff);\n#endif\n}\n\nstatic uint32_t bios_debug_read(void *opaque, uint32_t offset, int size_log2)\n{\n return 0;\n}\n#endif\n\ntypedef struct PCMachine {\n VirtMachine common;\n uint64_t ram_size;\n PhysMemoryMap *mem_map;\n PhysMemoryMap *port_map;\n \n X86CPUState *cpu_state;\n PIC2State *pic_state;\n IRQSignal pic_irq[16];\n PITState *pit_state;\n I440FXState *i440fx_state;\n CMOSState *cmos_state;\n SerialState *serial_state;\n\n /* input */\n VIRTIODevice *keyboard_dev;\n VIRTIODevice *mouse_dev;\n KBDState *kbd_state;\n PS2MouseState *ps2_mouse;\n VMMouseState *vm_mouse;\n PS2KbdState *ps2_kbd;\n\n#ifdef USE_KVM\n BOOL kvm_enabled;\n int kvm_fd;\n int vm_fd;\n int vcpu_fd;\n int kvm_run_size;\n struct kvm_run *kvm_run;\n#endif\n} PCMachine;\n\nstatic void copy_kernel(PCMachine *s, const uint8_t *buf, int buf_len,\n const char *cmd_line);\n\nstatic void port80_write(void *opaque, uint32_t offset,\n uint32_t val64, int size_log2)\n{\n}\n\nstatic uint32_t port80_read(void *opaque, uint32_t offset, int size_log2)\n{\n return 0xff;\n}\n\nstatic void port92_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n}\n\nstatic uint32_t port92_read(void *opaque, uint32_t offset, int size_log2)\n{\n int a20 = 1; /* A20=0 is not supported */\n return a20 << 1;\n}\n\n#define VMPORT_MAGIC 0x564D5868\n#define REG_EAX 0\n#define REG_EBX 1\n#define REG_ECX 2\n#define REG_EDX 3\n#define REG_ESI 4\n#define REG_EDI 5\n\nstatic uint32_t vmport_read(void *opaque, uint32_t addr, int size_log2)\n{\n PCMachine *s = opaque;\n uint32_t regs[6];\n\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n struct kvm_regs r;\n\n ioctl(s->vcpu_fd, KVM_GET_REGS, &r);\n regs[REG_EAX] = r.rax;\n regs[REG_EBX] = r.rbx;\n regs[REG_ECX] = r.rcx;\n regs[REG_EDX] = r.rdx;\n regs[REG_ESI] = r.rsi;\n regs[REG_EDI] = r.rdi;\n\n if (regs[REG_EAX] == VMPORT_MAGIC) {\n \n vmmouse_handler(s->vm_mouse, regs);\n \n /* Note: in 64 bits the high parts are reset to zero\n in all cases. */\n r.rax = regs[REG_EAX];\n r.rbx = regs[REG_EBX];\n r.rcx = regs[REG_ECX];\n r.rdx = regs[REG_EDX];\n r.rsi = regs[REG_ESI];\n r.rdi = regs[REG_EDI];\n ioctl(s->vcpu_fd, KVM_SET_REGS, &r);\n }\n } else\n#endif\n {\n regs[REG_EAX] = x86_cpu_get_reg(s->cpu_state, 0);\n regs[REG_EBX] = x86_cpu_get_reg(s->cpu_state, 3);\n regs[REG_ECX] = x86_cpu_get_reg(s->cpu_state, 1);\n regs[REG_EDX] = x86_cpu_get_reg(s->cpu_state, 2);\n regs[REG_ESI] = x86_cpu_get_reg(s->cpu_state, 6);\n regs[REG_EDI] = x86_cpu_get_reg(s->cpu_state, 7);\n\n if (regs[REG_EAX] == VMPORT_MAGIC) {\n vmmouse_handler(s->vm_mouse, regs);\n\n x86_cpu_set_reg(s->cpu_state, 0, regs[REG_EAX]);\n x86_cpu_set_reg(s->cpu_state, 3, regs[REG_EBX]);\n x86_cpu_set_reg(s->cpu_state, 1, regs[REG_ECX]);\n x86_cpu_set_reg(s->cpu_state, 2, regs[REG_EDX]);\n x86_cpu_set_reg(s->cpu_state, 6, regs[REG_ESI]);\n x86_cpu_set_reg(s->cpu_state, 7, regs[REG_EDI]);\n }\n }\n return regs[REG_EAX];\n}\n\nstatic void vmport_write(void *opaque, uint32_t addr, uint32_t val,\n int size_log2)\n{\n}\n\nstatic void pic_set_irq_cb(void *opaque, int level)\n{\n PCMachine *s = opaque;\n x86_cpu_set_irq(s->cpu_state, level);\n}\n\nstatic void serial_write_cb(void *opaque, const uint8_t *buf, int buf_len)\n{\n PCMachine *s = opaque;\n if (s->common.console) {\n s->common.console->write_data(s->common.console->opaque, buf, buf_len);\n }\n}\n\nstatic int get_hard_intno_cb(void *opaque)\n{\n PCMachine *s = opaque;\n return pic2_get_hard_intno(s->pic_state);\n}\n\nstatic int64_t pit_get_ticks_cb(void *opaque)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * PIT_FREQ +\n ((uint64_t)ts.tv_nsec * PIT_FREQ / 1000000000);\n}\n\n#define FRAMEBUFFER_BASE_ADDR 0xf0400000\n\nstatic uint8_t *get_ram_ptr(PCMachine *s, uint64_t paddr)\n{\n PhysMemoryRange *pr;\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr || !pr->is_ram)\n return NULL;\n return pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n}\n\n#ifdef DUMP_IOPORT\nstatic BOOL dump_port(int port)\n{\n return !((port >= 0x1f0 && port <= 0x1f7) ||\n (port >= 0x20 && port <= 0x21) ||\n (port >= 0xa0 && port <= 0xa1));\n}\n#endif\n\nstatic void st_port(void *opaque, uint32_t port, uint32_t val, int size_log2)\n{\n PCMachine *s = opaque;\n PhysMemoryRange *pr;\n#ifdef DUMP_IOPORT\n if (dump_port(port))\n printf(\"write port=0x%x val=0x%x s=%d\\n\", port, val, 1 << size_log2);\n#endif\n pr = get_phys_mem_range(s->port_map, port);\n if (!pr) {\n return;\n }\n port -= pr->addr;\n if ((pr->devio_flags >> size_log2) & 1) {\n pr->write_func(pr->opaque, port, (uint32_t)val, size_log2);\n } else if (size_log2 == 1 && (pr->devio_flags & DEVIO_SIZE8)) {\n pr->write_func(pr->opaque, port, val & 0xff, 0);\n pr->write_func(pr->opaque, port + 1, (val >> 8) & 0xff, 0);\n }\n}\n\nstatic uint32_t ld_port(void *opaque, uint32_t port1, int size_log2)\n{\n PCMachine *s = opaque;\n PhysMemoryRange *pr;\n uint32_t val, port;\n \n port = port1;\n pr = get_phys_mem_range(s->port_map, port);\n if (!pr) {\n val = -1;\n } else {\n port -= pr->addr;\n if ((pr->devio_flags >> size_log2) & 1) {\n val = pr->read_func(pr->opaque, port, size_log2);\n } else if (size_log2 == 1 && (pr->devio_flags & DEVIO_SIZE8)) {\n val = pr->read_func(pr->opaque, port, 0) & 0xff;\n val |= (pr->read_func(pr->opaque, port + 1, 0) & 0xff) << 8;\n } else {\n val = -1;\n }\n }\n#ifdef DUMP_IOPORT\n if (dump_port(port1))\n printf(\"read port=0x%x val=0x%x s=%d\\n\", port1, val, 1 << size_log2);\n#endif\n return val;\n}\n\nstatic void pc_machine_set_defaults(VirtMachineParams *p)\n{\n p->accel_enable = TRUE;\n}\n\n#ifdef USE_KVM\n\nstatic void sigalrm_handler(int sig)\n{\n}\n\n#define CPUID_APIC (1 << 9)\n#define CPUID_ACPI (1 << 22)\n\nstatic void kvm_set_cpuid(PCMachine *s)\n{\n struct kvm_cpuid2 *kvm_cpuid;\n int n_ent_max, i;\n struct kvm_cpuid_entry2 *ent;\n \n n_ent_max = 128;\n kvm_cpuid = mallocz(sizeof(struct kvm_cpuid2) + n_ent_max * sizeof(kvm_cpuid->entries[0]));\n \n kvm_cpuid->nent = n_ent_max;\n if (ioctl(s->kvm_fd, KVM_GET_SUPPORTED_CPUID, kvm_cpuid) < 0) {\n perror(\"KVM_GET_SUPPORTED_CPUID\");\n exit(1);\n }\n\n for(i = 0; i < kvm_cpuid->nent; i++) {\n ent = &kvm_cpuid->entries[i];\n /* remove the APIC & ACPI to be in sync with the emulator */\n if (ent->function == 1 || ent->function == 0x80000001) {\n ent->edx &= ~(CPUID_APIC | CPUID_ACPI);\n }\n }\n \n if (ioctl(s->vcpu_fd, KVM_SET_CPUID2, kvm_cpuid) < 0) {\n perror(\"KVM_SET_CPUID2\");\n exit(1);\n }\n free(kvm_cpuid);\n}\n\n/* XXX: should check overlapping mappings */\nstatic void kvm_map_ram(PhysMemoryMap *mem_map, PhysMemoryRange *pr)\n{\n PCMachine *s = mem_map->opaque;\n struct kvm_userspace_memory_region region;\n int flags;\n\n region.slot = pr - mem_map->phys_mem_range;\n flags = 0;\n if (pr->devram_flags & DEVRAM_FLAG_ROM)\n flags |= KVM_MEM_READONLY;\n if (pr->devram_flags & DEVRAM_FLAG_DIRTY_BITS)\n flags |= KVM_MEM_LOG_DIRTY_PAGES;\n region.flags = flags;\n region.guest_phys_addr = pr->addr;\n region.memory_size = pr->size;\n#if 0\n printf(\"map slot %d: %08lx %08lx\\n\",\n region.slot, pr->addr, pr->size);\n#endif\n region.userspace_addr = (uintptr_t)pr->phys_mem;\n if (ioctl(s->vm_fd, KVM_SET_USER_MEMORY_REGION, ®ion) < 0) {\n perror(\"KVM_SET_USER_MEMORY_REGION\");\n exit(1);\n }\n}\n\n/* XXX: just for one region */\nstatic PhysMemoryRange *kvm_register_ram(PhysMemoryMap *mem_map, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n uint8_t *phys_mem;\n \n pr = register_ram_entry(mem_map, addr, size, devram_flags);\n\n phys_mem = mmap(NULL, size, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n if (!phys_mem)\n return NULL;\n pr->phys_mem = phys_mem;\n if (devram_flags & DEVRAM_FLAG_DIRTY_BITS) {\n int n_pages = size >> 12;\n pr->dirty_bits_size = ((n_pages + 63) / 64) * 8;\n pr->dirty_bits = mallocz(pr->dirty_bits_size);\n }\n\n if (pr->size != 0) {\n kvm_map_ram(mem_map, pr);\n }\n return pr;\n}\n\nstatic void kvm_set_ram_addr(PhysMemoryMap *mem_map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n if (enabled) {\n if (pr->size == 0 || addr != pr->addr) {\n /* move or create the region */\n pr->size = pr->org_size;\n pr->addr = addr;\n kvm_map_ram(mem_map, pr);\n }\n } else {\n if (pr->size != 0) {\n pr->addr = 0;\n pr->size = 0;\n /* map a zero size region to disable */\n kvm_map_ram(mem_map, pr);\n }\n }\n}\n\nstatic const uint32_t *kvm_get_dirty_bits(PhysMemoryMap *mem_map,\n PhysMemoryRange *pr)\n{\n PCMachine *s = mem_map->opaque;\n struct kvm_dirty_log dlog;\n \n if (pr->size == 0) {\n /* not mapped: we assume no modification was made */\n memset(pr->dirty_bits, 0, pr->dirty_bits_size);\n } else {\n dlog.slot = pr - mem_map->phys_mem_range;\n dlog.dirty_bitmap = pr->dirty_bits;\n if (ioctl(s->vm_fd, KVM_GET_DIRTY_LOG, &dlog) < 0) {\n perror(\"KVM_GET_DIRTY_LOG\");\n exit(1);\n }\n }\n return pr->dirty_bits;\n}\n\nstatic void kvm_free_ram(PhysMemoryMap *mem_map, PhysMemoryRange *pr)\n{\n /* XXX: do it */\n munmap(pr->phys_mem, pr->org_size);\n free(pr->dirty_bits);\n}\n\nstatic void kvm_pic_set_irq(void *opaque, int irq_num, int level)\n{\n PCMachine *s = opaque;\n struct kvm_irq_level irq_level;\n irq_level.irq = irq_num;\n irq_level.level = level;\n if (ioctl(s->vm_fd, KVM_IRQ_LINE, &irq_level) < 0) {\n perror(\"KVM_IRQ_LINE\");\n exit(1);\n }\n}\n\nstatic void kvm_init(PCMachine *s)\n{\n int ret, i;\n struct sigaction act;\n struct kvm_pit_config pit_config;\n uint64_t base_addr;\n \n s->kvm_enabled = FALSE;\n s->kvm_fd = open(\"/dev/kvm\", O_RDWR);\n if (s->kvm_fd < 0) {\n fprintf(stderr, \"KVM not available\\n\");\n return;\n }\n ret = ioctl(s->kvm_fd, KVM_GET_API_VERSION, 0);\n if (ret < 0) {\n perror(\"KVM_GET_API_VERSION\");\n exit(1);\n }\n if (ret != 12) {\n fprintf(stderr, \"Unsupported KVM version\\n\");\n close(s->kvm_fd);\n s->kvm_fd = -1;\n return;\n }\n s->vm_fd = ioctl(s->kvm_fd, KVM_CREATE_VM, 0);\n if (s->vm_fd < 0) {\n perror(\"KVM_CREATE_VM\");\n exit(1);\n }\n\n /* just before the BIOS */\n base_addr = 0xfffbc000;\n if (ioctl(s->vm_fd, KVM_SET_IDENTITY_MAP_ADDR, &base_addr) < 0) {\n perror(\"KVM_SET_IDENTITY_MAP_ADDR\");\n exit(1);\n }\n \n if (ioctl(s->vm_fd, KVM_SET_TSS_ADDR, (long)(base_addr + 0x1000)) < 0) {\n perror(\"KVM_SET_TSS_ADDR\");\n exit(1);\n }\n \n if (ioctl(s->vm_fd, KVM_CREATE_IRQCHIP, 0) < 0) {\n perror(\"KVM_CREATE_IRQCHIP\");\n exit(1);\n }\n\n memset(&pit_config, 0, sizeof(pit_config));\n pit_config.flags = KVM_PIT_SPEAKER_DUMMY;\n if (ioctl(s->vm_fd, KVM_CREATE_PIT2, &pit_config)) {\n perror(\"KVM_CREATE_PIT2\");\n exit(1);\n }\n \n s->vcpu_fd = ioctl(s->vm_fd, KVM_CREATE_VCPU, 0);\n if (s->vcpu_fd < 0) {\n perror(\"KVM_CREATE_VCPU\");\n exit(1);\n }\n\n kvm_set_cpuid(s);\n \n /* map the kvm_run structure */\n s->kvm_run_size = ioctl(s->kvm_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);\n if (s->kvm_run_size < 0) {\n perror(\"KVM_GET_VCPU_MMAP_SIZE\");\n exit(1);\n }\n\n s->kvm_run = mmap(NULL, s->kvm_run_size, PROT_READ | PROT_WRITE,\n MAP_SHARED, s->vcpu_fd, 0);\n if (!s->kvm_run) {\n perror(\"mmap kvm_run\");\n exit(1);\n }\n\n for(i = 0; i < 16; i++) {\n irq_init(&s->pic_irq[i], kvm_pic_set_irq, s, i);\n }\n\n act.sa_handler = sigalrm_handler;\n sigemptyset(&act.sa_mask);\n act.sa_flags = 0;\n sigaction(SIGALRM, &act, NULL);\n\n s->kvm_enabled = TRUE;\n\n s->mem_map->register_ram = kvm_register_ram;\n s->mem_map->free_ram = kvm_free_ram;\n s->mem_map->get_dirty_bits = kvm_get_dirty_bits;\n s->mem_map->set_ram_addr = kvm_set_ram_addr;\n s->mem_map->opaque = s;\n}\n\nstatic void kvm_exit_io(PCMachine *s, struct kvm_run *run)\n{\n uint8_t *ptr;\n int i;\n \n ptr = (uint8_t *)run + run->io.data_offset;\n // printf(\"port: addr=%04x\\n\", run->io.port);\n \n for(i = 0; i < run->io.count; i++) {\n if (run->io.direction == KVM_EXIT_IO_OUT) {\n switch(run->io.size) {\n case 1:\n st_port(s, run->io.port, *(uint8_t *)ptr, 0);\n break;\n case 2:\n st_port(s, run->io.port, *(uint16_t *)ptr, 1);\n break;\n case 4:\n st_port(s, run->io.port, *(uint32_t *)ptr, 2);\n break;\n default:\n abort();\n }\n } else {\n switch(run->io.size) {\n case 1:\n *(uint8_t *)ptr = ld_port(s, run->io.port, 0);\n break;\n case 2:\n *(uint16_t *)ptr = ld_port(s, run->io.port, 1);\n break;\n case 4:\n *(uint32_t *)ptr = ld_port(s, run->io.port, 2);\n break;\n default:\n abort();\n }\n }\n ptr += run->io.size;\n }\n}\n\nstatic void kvm_exit_mmio(PCMachine *s, struct kvm_run *run)\n{\n uint8_t *data = run->mmio.data;\n PhysMemoryRange *pr;\n uint64_t addr;\n \n pr = get_phys_mem_range(s->mem_map, run->mmio.phys_addr);\n if (run->mmio.is_write) {\n if (!pr || pr->is_ram)\n return;\n addr = run->mmio.phys_addr - pr->addr;\n switch(run->mmio.len) {\n case 1:\n if (pr->devio_flags & DEVIO_SIZE8) {\n pr->write_func(pr->opaque, addr, *(uint8_t *)data, 0);\n }\n break;\n case 2:\n if (pr->devio_flags & DEVIO_SIZE16) {\n pr->write_func(pr->opaque, addr, *(uint16_t *)data, 1);\n }\n break;\n case 4:\n if (pr->devio_flags & DEVIO_SIZE32) {\n pr->write_func(pr->opaque, addr, *(uint32_t *)data, 2);\n }\n break;\n case 8:\n if (pr->devio_flags & DEVIO_SIZE32) {\n pr->write_func(pr->opaque, addr, *(uint32_t *)data, 2);\n pr->write_func(pr->opaque, addr + 4, *(uint32_t *)(data + 4), 2);\n }\n break;\n default:\n abort();\n }\n } else {\n if (!pr || pr->is_ram)\n goto no_dev;\n addr = run->mmio.phys_addr - pr->addr;\n switch(run->mmio.len) {\n case 1:\n if (!(pr->devio_flags & DEVIO_SIZE8))\n goto no_dev;\n *(uint8_t *)data = pr->read_func(pr->opaque, addr, 0);\n break;\n case 2:\n if (!(pr->devio_flags & DEVIO_SIZE16))\n goto no_dev;\n *(uint16_t *)data = pr->read_func(pr->opaque, addr, 1);\n break;\n case 4:\n if (!(pr->devio_flags & DEVIO_SIZE32))\n goto no_dev;\n *(uint32_t *)data = pr->read_func(pr->opaque, addr, 2);\n break;\n case 8:\n if (pr->devio_flags & DEVIO_SIZE32) {\n *(uint32_t *)data =\n pr->read_func(pr->opaque, addr, 2);\n *(uint32_t *)(data + 4) =\n pr->read_func(pr->opaque, addr + 4, 2);\n } else {\n no_dev:\n memset(run->mmio.data, 0, run->mmio.len);\n }\n break;\n default:\n abort();\n }\n \n }\n}\n\nstatic void kvm_exec(PCMachine *s)\n{\n struct kvm_run *run = s->kvm_run;\n struct itimerval ival;\n int ret;\n \n /* Not efficient but simple: we use a timer to interrupt the\n execution after a given time */\n ival.it_interval.tv_sec = 0;\n ival.it_interval.tv_usec = 0;\n ival.it_value.tv_sec = 0;\n ival.it_value.tv_usec = 10 * 1000; /* 10 ms max */\n setitimer(ITIMER_REAL, &ival, NULL);\n\n ret = ioctl(s->vcpu_fd, KVM_RUN, 0);\n if (ret < 0) {\n if (errno == EINTR || errno == EAGAIN) {\n /* timeout */\n return;\n }\n perror(\"KVM_RUN\");\n exit(1);\n }\n // printf(\"exit=%d\\n\", run->exit_reason);\n switch(run->exit_reason) {\n case KVM_EXIT_HLT:\n break;\n case KVM_EXIT_IO:\n kvm_exit_io(s, run);\n break;\n case KVM_EXIT_MMIO:\n kvm_exit_mmio(s, run);\n break;\n case KVM_EXIT_FAIL_ENTRY:\n fprintf(stderr, \"KVM_EXIT_FAIL_ENTRY: reason=0x%\" PRIx64 \"\\n\",\n (uint64_t)run->fail_entry.hardware_entry_failure_reason);\n#if 0\n {\n struct kvm_regs regs;\n if (ioctl(s->vcpu_fd, KVM_GET_REGS, ®s) < 0) {\n perror(\"KVM_SET_REGS\");\n exit(1);\n }\n printf(\"RIP=%016\" PRIx64 \"\\n\", (uint64_t)regs.rip);\n }\n#endif\n exit(1);\n case KVM_EXIT_INTERNAL_ERROR:\n fprintf(stderr, \"KVM_EXIT_INTERNAL_ERROR: suberror=0x%x\\n\",\n (uint32_t)run->internal.suberror);\n exit(1);\n default:\n fprintf(stderr, \"KVM: unsupported exit_reason=%d\\n\", run->exit_reason);\n exit(1);\n }\n}\n#endif\n\n#if defined(EMSCRIPTEN)\n/* with Javascript clock_gettime() is not enough precise enough to\n have a reliable TSC counter. XXX: increment the cycles during the\n power down time */\nstatic uint64_t cpu_get_tsc(void *opaque)\n{\n PCMachine *s = opaque;\n uint64_t c;\n c = x86_cpu_get_cycles(s->cpu_state);\n return c;\n}\n#else\n\n#define TSC_FREQ 100000000\n\nstatic uint64_t cpu_get_tsc(void *opaque)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * TSC_FREQ +\n (ts.tv_nsec / (1000000000 / TSC_FREQ));\n}\n#endif\n\nstatic void pc_flush_tlb_write_range(void *opaque, uint8_t *ram_addr,\n size_t ram_size)\n{\n PCMachine *s = opaque;\n x86_cpu_flush_tlb_write_range_ram(s->cpu_state, ram_addr, ram_size);\n}\n\nstatic VirtMachine *pc_machine_init(const VirtMachineParams *p)\n{\n PCMachine *s;\n int i, piix3_devfn;\n PCIBus *pci_bus;\n VIRTIOBusDef vbus_s, *vbus = &vbus_s;\n \n if (strcmp(p->machine_name, \"pc\") != 0) {\n vm_error(\"unsupported machine: %s\\n\", p->machine_name);\n return NULL;\n }\n\n assert(p->ram_size >= (1 << 20));\n\n s = mallocz(sizeof(*s));\n s->common.vmc = p->vmc;\n s->ram_size = p->ram_size;\n \n s->port_map = phys_mem_map_init();\n s->mem_map = phys_mem_map_init();\n\n#ifdef USE_KVM\n if (p->accel_enable) {\n kvm_init(s);\n }\n#endif\n\n#ifdef USE_KVM\n if (!s->kvm_enabled)\n#endif\n {\n s->cpu_state = x86_cpu_init(s->mem_map);\n x86_cpu_set_get_tsc(s->cpu_state, cpu_get_tsc, s);\n x86_cpu_set_port_io(s->cpu_state, ld_port, st_port, s);\n \n /* needed to handle the RAM dirty bits */\n s->mem_map->opaque = s;\n s->mem_map->flush_tlb_write_range = pc_flush_tlb_write_range;\n }\n\n /* set the RAM mapping and leave the VGA addresses empty */\n cpu_register_ram(s->mem_map, 0xc0000, p->ram_size - 0xc0000, 0);\n cpu_register_ram(s->mem_map, 0, 0xa0000, 0);\n \n /* devices */\n cpu_register_device(s->port_map, 0x80, 2, s, port80_read, port80_write, \n DEVIO_SIZE8);\n cpu_register_device(s->port_map, 0x92, 2, s, port92_read, port92_write, \n DEVIO_SIZE8);\n \n /* setup the bios */\n if (p->files[VM_FILE_BIOS].len > 0) {\n int bios_size, bios_size1;\n uint8_t *bios_buf, *ptr;\n uint32_t bios_addr;\n \n bios_size = p->files[VM_FILE_BIOS].len;\n bios_buf = p->files[VM_FILE_BIOS].buf;\n assert((bios_size % 65536) == 0 && bios_size != 0);\n bios_addr = -bios_size;\n /* at the top of the 4GB memory */\n cpu_register_ram(s->mem_map, bios_addr, bios_size, DEVRAM_FLAG_ROM);\n ptr = get_ram_ptr(s, bios_addr);\n memcpy(ptr, bios_buf, bios_size);\n /* in the lower 1MB memory (currently set as RAM) */\n bios_size1 = min_int(bios_size, 128 * 1024);\n ptr = get_ram_ptr(s, 0x100000 - bios_size1);\n memcpy(ptr, bios_buf + bios_size - bios_size1, bios_size1);\n#ifdef DEBUG_BIOS\n cpu_register_device(s->port_map, 0x402, 2, s,\n bios_debug_read, bios_debug_write, \n DEVIO_SIZE8);\n#endif\n }\n\n#ifdef USE_KVM\n if (!s->kvm_enabled)\n#endif\n {\n s->pic_state = pic2_init(s->port_map, 0x20, 0xa0,\n 0x4d0, 0x4d1,\n pic_set_irq_cb, s,\n s->pic_irq);\n x86_cpu_set_get_hard_intno(s->cpu_state, get_hard_intno_cb, s);\n s->pit_state = pit_init(s->port_map, 0x40, 0x61, &s->pic_irq[0],\n pit_get_ticks_cb, s);\n }\n\n s->cmos_state = cmos_init(s->port_map, 0x70, &s->pic_irq[8],\n p->rtc_local_time);\n\n /* various cmos data */\n {\n int size;\n /* memory size */\n size = min_int((s->ram_size - (1 << 20)) >> 10, 65535);\n put_le16(s->cmos_state->cmos_data + 0x30, size);\n if (s->ram_size >= (16 << 20)) {\n size = min_int((s->ram_size - (16 << 20)) >> 16, 65535);\n put_le16(s->cmos_state->cmos_data + 0x34, size);\n }\n s->cmos_state->cmos_data[0x14] = 0x06; /* mouse + FPU present */\n }\n \n s->i440fx_state = i440fx_init(&pci_bus, &piix3_devfn, s->mem_map,\n s->port_map, s->pic_irq);\n \n s->common.console = p->console;\n /* serial console */\n if (0) {\n s->serial_state = serial_init(s->port_map, 0x3f8, &s->pic_irq[4],\n serial_write_cb, s);\n }\n \n memset(vbus, 0, sizeof(*vbus));\n vbus->pci_bus = pci_bus;\n\n if (p->console) {\n /* virtio console */\n s->common.console_dev = virtio_console_init(vbus, p->console);\n }\n \n /* block devices */\n for(i = 0; i < p->drive_count;) {\n const VMDriveEntry *de = &p->tab_drive[i];\n\n if (!de->device || !strcmp(de->device, \"virtio\")) {\n virtio_block_init(vbus, p->tab_drive[i].block_dev);\n i++;\n } else if (!strcmp(de->device, \"ide\")) {\n BlockDevice *tab_bs[2];\n \n tab_bs[0] = p->tab_drive[i++].block_dev;\n tab_bs[1] = NULL;\n if (i < p->drive_count)\n tab_bs[1] = p->tab_drive[i++].block_dev;\n ide_init(s->port_map, 0x1f0, 0x3f6, &s->pic_irq[14], tab_bs);\n piix3_ide_init(pci_bus, piix3_devfn + 1);\n }\n }\n \n /* virtio filesystem */\n for(i = 0; i < p->fs_count; i++) {\n virtio_9p_init(vbus, p->tab_fs[i].fs_dev,\n p->tab_fs[i].tag);\n }\n\n if (p->display_device) {\n FBDevice *fb_dev;\n\n fb_dev = mallocz(sizeof(*fb_dev));\n s->common.fb_dev = fb_dev;\n if (!strcmp(p->display_device, \"vga\")) {\n int bios_size;\n uint8_t *bios_buf;\n bios_size = p->files[VM_FILE_VGA_BIOS].len;\n bios_buf = p->files[VM_FILE_VGA_BIOS].buf;\n pci_vga_init(pci_bus, fb_dev, p->width, p->height,\n bios_buf, bios_size);\n } else if (!strcmp(p->display_device, \"simplefb\")) {\n simplefb_init(s->mem_map,\n FRAMEBUFFER_BASE_ADDR,\n fb_dev, p->width, p->height);\n } else {\n vm_error(\"unsupported display device: %s\\n\", p->display_device);\n exit(1);\n }\n }\n\n if (p->input_device) {\n if (!strcmp(p->input_device, \"virtio\")) {\n s->keyboard_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_KEYBOARD);\n \n s->mouse_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_TABLET);\n } else if (!strcmp(p->input_device, \"ps2\")) {\n s->kbd_state = i8042_init(&s->ps2_kbd, &s->ps2_mouse,\n s->port_map,\n &s->pic_irq[1], &s->pic_irq[12], 0x60);\n /* vmmouse */\n cpu_register_device(s->port_map, 0x5658, 1, s,\n vmport_read, vmport_write, \n DEVIO_SIZE32);\n s->vm_mouse = vmmouse_init(s->ps2_mouse);\n } else {\n vm_error(\"unsupported input device: %s\\n\", p->input_device);\n exit(1);\n }\n }\n \n /* virtio net device */\n for(i = 0; i < p->eth_count; i++) {\n virtio_net_init(vbus, p->tab_eth[i].net);\n s->common.net = p->tab_eth[i].net;\n }\n\n if (p->files[VM_FILE_KERNEL].buf) {\n copy_kernel(s, p->files[VM_FILE_KERNEL].buf,\n p->files[VM_FILE_KERNEL].len,\n p->cmdline ? p->cmdline : \"\");\n }\n\n return (VirtMachine *)s;\n}\n\nstatic void pc_machine_end(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n /* XXX: free all */\n if (s->cpu_state) {\n x86_cpu_end(s->cpu_state);\n }\n phys_mem_map_end(s->mem_map);\n phys_mem_map_end(s->port_map);\n free(s);\n}\n\nstatic void pc_vm_send_key_event(VirtMachine *s1, BOOL is_down, uint16_t key_code)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->keyboard_dev) {\n virtio_input_send_key_event(s->keyboard_dev, is_down, key_code);\n } else if (s->ps2_kbd) {\n ps2_put_keycode(s->ps2_kbd, is_down, key_code);\n }\n}\n\nstatic BOOL pc_vm_mouse_is_absolute(VirtMachine *s1)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->mouse_dev) {\n return TRUE;\n } else if (s->vm_mouse) {\n return vmmouse_is_absolute(s->vm_mouse);\n } else {\n return FALSE;\n }\n}\n\nstatic void pc_vm_send_mouse_event(VirtMachine *s1, int dx, int dy, int dz,\n unsigned int buttons)\n{\n PCMachine *s = (PCMachine *)s1;\n if (s->mouse_dev) {\n virtio_input_send_mouse_event(s->mouse_dev, dx, dy, dz, buttons);\n } else if (s->vm_mouse) {\n vmmouse_send_mouse_event(s->vm_mouse, dx, dy, dz, buttons);\n }\n}\n\nstruct screen_info {\n} __attribute__((packed));\n\n/* from plex86 (BSD license) */\nstruct __attribute__ ((packed)) linux_params {\n /* screen_info structure */\n uint8_t orig_x;\t\t/* 0x00 */\n uint8_t orig_y;\t\t/* 0x01 */\n uint16_t ext_mem_k;\t/* 0x02 */\n uint16_t orig_video_page;\t/* 0x04 */\n uint8_t orig_video_mode;\t/* 0x06 */\n uint8_t orig_video_cols;\t/* 0x07 */\n uint8_t flags;\t\t/* 0x08 */\n uint8_t unused2;\t\t/* 0x09 */\n uint16_t orig_video_ega_bx;/* 0x0a */\n uint16_t unused3;\t\t/* 0x0c */\n uint8_t orig_video_lines;\t/* 0x0e */\n uint8_t orig_video_isVGA;\t/* 0x0f */\n uint16_t orig_video_points;/* 0x10 */\n \n /* VESA graphic mode -- linear frame buffer */\n uint16_t lfb_width;\t/* 0x12 */\n uint16_t lfb_height;\t/* 0x14 */\n uint16_t lfb_depth;\t/* 0x16 */\n uint32_t lfb_base;\t\t/* 0x18 */\n uint32_t lfb_size;\t\t/* 0x1c */\n uint16_t cl_magic, cl_offset; /* 0x20 */\n uint16_t lfb_linelength;\t/* 0x24 */\n uint8_t red_size;\t\t/* 0x26 */\n uint8_t red_pos;\t\t/* 0x27 */\n uint8_t green_size;\t/* 0x28 */\n uint8_t green_pos;\t/* 0x29 */\n uint8_t blue_size;\t/* 0x2a */\n uint8_t blue_pos;\t\t/* 0x2b */\n uint8_t rsvd_size;\t/* 0x2c */\n uint8_t rsvd_pos;\t\t/* 0x2d */\n uint16_t vesapm_seg;\t/* 0x2e */\n uint16_t vesapm_off;\t/* 0x30 */\n uint16_t pages;\t\t/* 0x32 */\n uint16_t vesa_attributes;\t/* 0x34 */\n uint32_t capabilities; /* 0x36 */\n uint32_t ext_lfb_base;\t/* 0x3a */\n uint8_t _reserved[2];\t/* 0x3e */\n \n /* 0x040 */ uint8_t apm_bios_info[20]; // struct apm_bios_info\n /* 0x054 */ uint8_t pad2[0x80 - 0x54];\n\n // Following 2 from 'struct drive_info_struct' in drivers/block/cciss.h.\n // Might be truncated?\n /* 0x080 */ uint8_t hd0_info[16]; // hd0-disk-parameter from intvector 0x41\n /* 0x090 */ uint8_t hd1_info[16]; // hd1-disk-parameter from intvector 0x46\n\n // System description table truncated to 16 bytes\n // From 'struct sys_desc_table_struct' in linux/arch/i386/kernel/setup.c.\n /* 0x0a0 */ uint16_t sys_description_len;\n /* 0x0a2 */ uint8_t sys_description_table[14];\n // [0] machine id\n // [1] machine submodel id\n // [2] BIOS revision\n // [3] bit1: MCA bus\n\n /* 0x0b0 */ uint8_t pad3[0x1e0 - 0xb0];\n /* 0x1e0 */ uint32_t alt_mem_k;\n /* 0x1e4 */ uint8_t pad4[4];\n /* 0x1e8 */ uint8_t e820map_entries;\n /* 0x1e9 */ uint8_t eddbuf_entries; // EDD_NR\n /* 0x1ea */ uint8_t pad5[0x1f1 - 0x1ea];\n /* 0x1f1 */ uint8_t setup_sects; // size of setup.S, number of sectors\n /* 0x1f2 */ uint16_t mount_root_rdonly; // MOUNT_ROOT_RDONLY (if !=0)\n /* 0x1f4 */ uint16_t sys_size; // size of compressed kernel-part in the\n // (b)zImage-file (in 16 byte units, rounded up)\n /* 0x1f6 */ uint16_t swap_dev; // (unused AFAIK)\n /* 0x1f8 */ uint16_t ramdisk_flags;\n /* 0x1fa */ uint16_t vga_mode; // (old one)\n /* 0x1fc */ uint16_t orig_root_dev; // (high=Major, low=minor)\n /* 0x1fe */ uint8_t pad6[1];\n /* 0x1ff */ uint8_t aux_device_info;\n /* 0x200 */ uint16_t jump_setup; // Jump to start of setup code,\n // aka \"reserved\" field.\n /* 0x202 */ uint8_t setup_signature[4]; // Signature for SETUP-header, =\"HdrS\"\n /* 0x206 */ uint16_t header_format_version; // Version number of header format;\n /* 0x208 */ uint8_t setup_S_temp0[8]; // Used by setup.S for communication with\n // boot loaders, look there.\n /* 0x210 */ uint8_t loader_type;\n // 0 for old one.\n // else 0xTV:\n // T=0: LILO\n // T=1: Loadlin\n // T=2: bootsect-loader\n // T=3: SYSLINUX\n // T=4: ETHERBOOT\n // V=version\n /* 0x211 */ uint8_t loadflags;\n // bit0 = 1: kernel is loaded high (bzImage)\n // bit7 = 1: Heap and pointer (see below) set by boot\n // loader.\n /* 0x212 */ uint16_t setup_S_temp1;\n /* 0x214 */ uint32_t kernel_start;\n /* 0x218 */ uint32_t initrd_start;\n /* 0x21c */ uint32_t initrd_size;\n /* 0x220 */ uint8_t setup_S_temp2[4];\n /* 0x224 */ uint16_t setup_S_heap_end_pointer;\n /* 0x226 */ uint16_t pad70;\n /* 0x228 */ uint32_t cmd_line_ptr;\n /* 0x22c */ uint8_t pad7[0x2d0 - 0x22c];\n\n /* 0x2d0 : Int 15, ax=e820 memory map. */\n // (linux/include/asm-i386/e820.h, 'struct e820entry')\n#define E820MAX 32\n#define E820_RAM 1\n#define E820_RESERVED 2\n#define E820_ACPI 3 /* usable as RAM once ACPI tables have been read */\n#define E820_NVS 4\n struct {\n uint64_t addr;\n uint64_t size;\n uint32_t type;\n } e820map[E820MAX];\n\n /* 0x550 */ uint8_t pad8[0x600 - 0x550];\n\n // BIOS Enhanced Disk Drive Services.\n // (From linux/include/asm-i386/edd.h, 'struct edd_info')\n // Each 'struct edd_info is 78 bytes, times a max of 6 structs in array.\n /* 0x600 */ uint8_t eddbuf[0x7d4 - 0x600];\n\n /* 0x7d4 */ uint8_t pad9[0x800 - 0x7d4];\n /* 0x800 */ uint8_t commandline[0x800];\n\n uint64_t gdt_table[4];\n};\n\n#define KERNEL_PARAMS_ADDR 0x00090000\n\nstatic void copy_kernel(PCMachine *s, const uint8_t *buf, int buf_len,\n const char *cmd_line)\n{\n uint8_t *ram_ptr;\n int setup_sects, header_len, copy_len, setup_hdr_start, setup_hdr_end;\n uint32_t load_address;\n struct linux_params *params;\n FBDevice *fb_dev;\n \n if (buf_len < 1024) {\n too_small:\n fprintf(stderr, \"Kernel too small\\n\");\n exit(1);\n }\n if (buf[0x1fe] != 0x55 || buf[0x1ff] != 0xaa) {\n fprintf(stderr, \"Invalid kernel magic\\n\");\n exit(1);\n }\n setup_sects = buf[0x1f1];\n if (setup_sects == 0)\n setup_sects = 4;\n header_len = (setup_sects + 1) * 512;\n if (buf_len < header_len)\n goto too_small;\n if (memcmp(buf + 0x202, \"HdrS\", 4) != 0) {\n fprintf(stderr, \"Kernel too old\\n\");\n exit(1);\n }\n load_address = 0x100000; /* we don't support older protocols */\n\n ram_ptr = get_ram_ptr(s, load_address);\n copy_len = buf_len - header_len;\n if (copy_len > (s->ram_size - load_address)) {\n fprintf(stderr, \"Not enough RAM\\n\");\n exit(1);\n }\n memcpy(ram_ptr, buf + header_len, copy_len);\n\n params = (void *)get_ram_ptr(s, KERNEL_PARAMS_ADDR);\n \n memset(params, 0, sizeof(struct linux_params));\n\n /* copy the setup header */\n setup_hdr_start = 0x1f1;\n setup_hdr_end = 0x202 + buf[0x201];\n memcpy((uint8_t *)params + setup_hdr_start, buf + setup_hdr_start,\n setup_hdr_end - setup_hdr_start);\n\n strcpy((char *)params->commandline, cmd_line);\n\n params->mount_root_rdonly = 0;\n params->cmd_line_ptr = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, commandline);\n params->alt_mem_k = (s->ram_size / 1024) - 1024;\n params->loader_type = 0x01;\n#if 0\n if (initrd_size > 0) {\n params->initrd_start = INITRD_LOAD_ADDR;\n params->initrd_size = initrd_size;\n }\n#endif\n params->orig_video_lines = 0;\n params->orig_video_cols = 0;\n\n fb_dev = s->common.fb_dev;\n if (fb_dev) {\n \n params->orig_video_isVGA = 0x23; /* VIDEO_TYPE_VLFB */\n\n params->lfb_depth = 32;\n params->red_size = 8;\n params->red_pos = 16;\n params->green_size = 8;\n params->green_pos = 8;\n params->blue_size = 8;\n params->blue_pos = 0;\n params->rsvd_size = 8;\n params->rsvd_pos = 24;\n\n params->lfb_width = fb_dev->width;\n params->lfb_height = fb_dev->height;\n params->lfb_linelength = fb_dev->stride;\n params->lfb_size = fb_dev->fb_size;\n params->lfb_base = FRAMEBUFFER_BASE_ADDR;\n }\n \n params->gdt_table[2] = 0x00cf9b000000ffffLL; /* CS */\n params->gdt_table[3] = 0x00cf93000000ffffLL; /* DS */\n \n#ifdef USE_KVM\n if (s->kvm_enabled) {\n struct kvm_sregs sregs;\n struct kvm_segment seg;\n struct kvm_regs regs;\n \n /* init flat protected mode */\n\n if (ioctl(s->vcpu_fd, KVM_GET_SREGS, &sregs) < 0) {\n perror(\"KVM_GET_SREGS\");\n exit(1);\n }\n\n sregs.cr0 |= (1 << 0); /* CR0_PE */\n sregs.gdt.base = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, gdt_table);\n sregs.gdt.limit = sizeof(params->gdt_table) - 1;\n \n memset(&seg, 0, sizeof(seg));\n seg.limit = 0xffffffff;\n seg.present = 1;\n seg.db = 1;\n seg.s = 1; /* code/data */\n seg.g = 1; /* 4KB granularity */\n\n seg.type = 0xb; /* code */\n seg.selector = 2 << 3;\n sregs.cs = seg;\n\n seg.type = 0x3; /* data */\n seg.selector = 3 << 3;\n sregs.ds = seg;\n sregs.es = seg;\n sregs.ss = seg;\n sregs.fs = seg;\n sregs.gs = seg;\n \n if (ioctl(s->vcpu_fd, KVM_SET_SREGS, &sregs) < 0) {\n perror(\"KVM_SET_SREGS\");\n exit(1);\n }\n \n memset(®s, 0, sizeof(regs));\n regs.rip = load_address;\n regs.rsi = KERNEL_PARAMS_ADDR;\n regs.rflags = 0x2;\n if (ioctl(s->vcpu_fd, KVM_SET_REGS, ®s) < 0) {\n perror(\"KVM_SET_REGS\");\n exit(1);\n }\n } else\n#endif\n {\n int i;\n X86CPUSeg sd;\n uint32_t val;\n val = x86_cpu_get_reg(s->cpu_state, X86_CPU_REG_CR0);\n x86_cpu_set_reg(s->cpu_state, X86_CPU_REG_CR0, val | (1 << 0));\n \n sd.base = KERNEL_PARAMS_ADDR +\n offsetof(struct linux_params, gdt_table);\n sd.limit = sizeof(params->gdt_table) - 1;\n x86_cpu_set_seg(s->cpu_state, X86_CPU_SEG_GDT, &sd);\n sd.sel = 2 << 3;\n sd.base = 0;\n sd.limit = 0xffffffff;\n sd.flags = 0xc09b;\n x86_cpu_set_seg(s->cpu_state, X86_CPU_SEG_CS, &sd);\n sd.sel = 3 << 3;\n sd.flags = 0xc093;\n for(i = 0; i < 6; i++) {\n if (i != X86_CPU_SEG_CS) {\n x86_cpu_set_seg(s->cpu_state, i, &sd);\n }\n }\n \n x86_cpu_set_reg(s->cpu_state, X86_CPU_REG_EIP, load_address);\n x86_cpu_set_reg(s->cpu_state, 6, KERNEL_PARAMS_ADDR); /* esi */\n }\n\n /* map PCI interrupts (no BIOS, so we must do it) */\n {\n uint8_t elcr[2];\n static const uint8_t pci_irqs[4] = { 9, 10, 11, 12 };\n\n i440fx_map_interrupts(s->i440fx_state, elcr, pci_irqs);\n /* XXX: KVM support */\n if (s->pic_state) {\n pic2_set_elcr(s->pic_state, elcr);\n }\n }\n}\n\n/* in ms */\nstatic int pc_machine_get_sleep_duration(VirtMachine *s1, int delay)\n{\n PCMachine *s = (PCMachine *)s1;\n\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n /* XXX: improve */\n cmos_update_irq(s->cmos_state);\n delay = 0;\n } else\n#endif\n {\n cmos_update_irq(s->cmos_state);\n delay = min_int(delay, pit_update_irq(s->pit_state));\n if (!x86_cpu_get_power_down(s->cpu_state))\n delay = 0;\n }\n return delay;\n}\n\nstatic void pc_machine_interp(VirtMachine *s1, int max_exec_cycles)\n{\n PCMachine *s = (PCMachine *)s1;\n#ifdef USE_KVM\n if (s->kvm_enabled) {\n kvm_exec(s);\n } else \n#endif\n {\n x86_cpu_interp(s->cpu_state, max_exec_cycles);\n }\n}\n\nconst VirtMachineClass pc_machine_class = {\n \"pc\",\n pc_machine_set_defaults,\n pc_machine_init,\n pc_machine_end,\n pc_machine_get_sleep_duration,\n pc_machine_interp,\n pc_vm_mouse_is_absolute,\n pc_vm_send_mouse_event,\n pc_vm_send_key_event,\n};\n"], ["/linuxpdf/tinyemu/riscv_machine.c", "/*\n * RISCV machine\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"riscv_cpu.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n/* RISCV machine */\n\ntypedef struct RISCVMachine {\n VirtMachine common;\n PhysMemoryMap *mem_map;\n int max_xlen;\n RISCVCPUState *cpu_state;\n uint64_t ram_size;\n /* RTC */\n BOOL rtc_real_time;\n uint64_t rtc_start_time;\n uint64_t timecmp;\n /* PLIC */\n uint32_t plic_pending_irq, plic_served_irq;\n IRQSignal plic_irq[32]; /* IRQ 0 is not used */\n /* HTIF */\n uint64_t htif_tohost, htif_fromhost;\n\n VIRTIODevice *keyboard_dev;\n VIRTIODevice *mouse_dev;\n\n int virtio_count;\n} RISCVMachine;\n\n#define LOW_RAM_SIZE 0x00010000 /* 64KB */\n#define RAM_BASE_ADDR 0x80000000\n#define CLINT_BASE_ADDR 0x02000000\n#define CLINT_SIZE 0x000c0000\n#define HTIF_BASE_ADDR 0x40008000\n#define IDE_BASE_ADDR 0x40009000\n#define VIRTIO_BASE_ADDR 0x40010000\n#define VIRTIO_SIZE 0x1000\n#define VIRTIO_IRQ 1\n#define PLIC_BASE_ADDR 0x40100000\n#define PLIC_SIZE 0x00400000\n#define FRAMEBUFFER_BASE_ADDR 0x41000000\n\n#define RTC_FREQ 10000000\n#define RTC_FREQ_DIV 16 /* arbitrary, relative to CPU freq to have a\n 10 MHz frequency */\n\nstatic uint64_t rtc_get_real_time(RISCVMachine *s)\n{\n struct timespec ts;\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return (uint64_t)ts.tv_sec * RTC_FREQ +\n (ts.tv_nsec / (1000000000 / RTC_FREQ));\n}\n\nstatic uint64_t rtc_get_time(RISCVMachine *m)\n{\n uint64_t val;\n if (m->rtc_real_time) {\n val = rtc_get_real_time(m) - m->rtc_start_time;\n } else {\n val = riscv_cpu_get_cycles(m->cpu_state) / RTC_FREQ_DIV;\n }\n // printf(\"rtc_time=%\" PRId64 \"\\n\", val);\n return val;\n}\n\nstatic uint32_t htif_read(void *opaque, uint32_t offset,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n uint32_t val;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0:\n val = s->htif_tohost;\n break;\n case 4:\n val = s->htif_tohost >> 32;\n break;\n case 8:\n val = s->htif_fromhost;\n break;\n case 12:\n val = s->htif_fromhost >> 32;\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n\nstatic void htif_handle_cmd(RISCVMachine *s)\n{\n uint32_t device, cmd;\n\n device = s->htif_tohost >> 56;\n cmd = (s->htif_tohost >> 48) & 0xff;\n if (s->htif_tohost == 1) {\n /* shuthost */\n printf(\"\\nPower off.\\n\");\n exit(0);\n } else if (device == 1 && cmd == 1) {\n uint8_t buf[1];\n buf[0] = s->htif_tohost & 0xff;\n s->common.console->write_data(s->common.console->opaque, buf, 1);\n s->htif_tohost = 0;\n s->htif_fromhost = ((uint64_t)device << 56) | ((uint64_t)cmd << 48);\n } else if (device == 1 && cmd == 0) {\n /* request keyboard interrupt */\n s->htif_tohost = 0;\n } else {\n printf(\"HTIF: unsupported tohost=0x%016\" PRIx64 \"\\n\", s->htif_tohost);\n }\n}\n\nstatic void htif_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0:\n s->htif_tohost = (s->htif_tohost & ~0xffffffff) | val;\n break;\n case 4:\n s->htif_tohost = (s->htif_tohost & 0xffffffff) | ((uint64_t)val << 32);\n htif_handle_cmd(s);\n break;\n case 8:\n s->htif_fromhost = (s->htif_fromhost & ~0xffffffff) | val;\n break;\n case 12:\n s->htif_fromhost = (s->htif_fromhost & 0xffffffff) |\n (uint64_t)val << 32;\n break;\n default:\n break;\n }\n}\n\n#if 0\nstatic void htif_poll(RISCVMachine *s)\n{\n uint8_t buf[1];\n int ret;\n\n if (s->htif_fromhost == 0) {\n ret = s->console->read_data(s->console->opaque, buf, 1);\n if (ret == 1) {\n s->htif_fromhost = ((uint64_t)1 << 56) | ((uint64_t)0 << 48) |\n buf[0];\n }\n }\n}\n#endif\n\nstatic uint32_t clint_read(void *opaque, uint32_t offset, int size_log2)\n{\n RISCVMachine *m = opaque;\n uint32_t val;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0xbff8:\n val = rtc_get_time(m);\n break;\n case 0xbffc:\n val = rtc_get_time(m) >> 32;\n break;\n case 0x4000:\n val = m->timecmp;\n break;\n case 0x4004:\n val = m->timecmp >> 32;\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n \nstatic void clint_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *m = opaque;\n\n assert(size_log2 == 2);\n switch(offset) {\n case 0x4000:\n m->timecmp = (m->timecmp & ~0xffffffff) | val;\n riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP);\n break;\n case 0x4004:\n m->timecmp = (m->timecmp & 0xffffffff) | ((uint64_t)val << 32);\n riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP);\n break;\n default:\n break;\n }\n}\n\nstatic void plic_update_mip(RISCVMachine *s)\n{\n RISCVCPUState *cpu = s->cpu_state;\n uint32_t mask;\n mask = s->plic_pending_irq & ~s->plic_served_irq;\n if (mask) {\n riscv_cpu_set_mip(cpu, MIP_MEIP | MIP_SEIP);\n } else {\n riscv_cpu_reset_mip(cpu, MIP_MEIP | MIP_SEIP);\n }\n}\n\n#define PLIC_HART_BASE 0x200000\n#define PLIC_HART_SIZE 0x1000\n\nstatic uint32_t plic_read(void *opaque, uint32_t offset, int size_log2)\n{\n RISCVMachine *s = opaque;\n uint32_t val, mask;\n int i;\n assert(size_log2 == 2);\n switch(offset) {\n case PLIC_HART_BASE:\n val = 0;\n break;\n case PLIC_HART_BASE + 4:\n mask = s->plic_pending_irq & ~s->plic_served_irq;\n if (mask != 0) {\n i = ctz32(mask);\n s->plic_served_irq |= 1 << i;\n plic_update_mip(s);\n val = i + 1;\n } else {\n val = 0;\n }\n break;\n default:\n val = 0;\n break;\n }\n return val;\n}\n\nstatic void plic_write(void *opaque, uint32_t offset, uint32_t val,\n int size_log2)\n{\n RISCVMachine *s = opaque;\n \n assert(size_log2 == 2);\n switch(offset) {\n case PLIC_HART_BASE + 4:\n val--;\n if (val < 32) {\n s->plic_served_irq &= ~(1 << val);\n plic_update_mip(s);\n }\n break;\n default:\n break;\n }\n}\n\nstatic void plic_set_irq(void *opaque, int irq_num, int state)\n{\n RISCVMachine *s = opaque;\n uint32_t mask;\n\n mask = 1 << (irq_num - 1);\n if (state) \n s->plic_pending_irq |= mask;\n else\n s->plic_pending_irq &= ~mask;\n plic_update_mip(s);\n}\n\nstatic uint8_t *get_ram_ptr(RISCVMachine *s, uint64_t paddr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(s->mem_map, paddr, is_rw);\n}\n\n/* FDT machine description */\n\n#define FDT_MAGIC\t0xd00dfeed\n#define FDT_VERSION\t17\n\nstruct fdt_header {\n uint32_t magic;\n uint32_t totalsize;\n uint32_t off_dt_struct;\n uint32_t off_dt_strings;\n uint32_t off_mem_rsvmap;\n uint32_t version;\n uint32_t last_comp_version; /* <= 17 */\n uint32_t boot_cpuid_phys;\n uint32_t size_dt_strings;\n uint32_t size_dt_struct;\n};\n\nstruct fdt_reserve_entry {\n uint64_t address;\n uint64_t size;\n};\n\n#define FDT_BEGIN_NODE\t1\n#define FDT_END_NODE\t2\n#define FDT_PROP\t3\n#define FDT_NOP\t\t4\n#define FDT_END\t\t9\n\ntypedef struct {\n uint32_t *tab;\n int tab_len;\n int tab_size;\n int open_node_count;\n \n char *string_table;\n int string_table_len;\n int string_table_size;\n} FDTState;\n\nstatic FDTState *fdt_init(void)\n{\n FDTState *s;\n s = mallocz(sizeof(*s));\n return s;\n}\n\nstatic void fdt_alloc_len(FDTState *s, int len)\n{\n int new_size;\n if (unlikely(len > s->tab_size)) {\n new_size = max_int(len, s->tab_size * 3 / 2);\n s->tab = realloc(s->tab, new_size * sizeof(uint32_t));\n s->tab_size = new_size;\n }\n}\n\nstatic void fdt_put32(FDTState *s, int v)\n{\n fdt_alloc_len(s, s->tab_len + 1);\n s->tab[s->tab_len++] = cpu_to_be32(v);\n}\n\n/* the data is zero padded */\nstatic void fdt_put_data(FDTState *s, const uint8_t *data, int len)\n{\n int len1;\n \n len1 = (len + 3) / 4;\n fdt_alloc_len(s, s->tab_len + len1);\n memcpy(s->tab + s->tab_len, data, len);\n memset((uint8_t *)(s->tab + s->tab_len) + len, 0, -len & 3);\n s->tab_len += len1;\n}\n\nstatic void fdt_begin_node(FDTState *s, const char *name)\n{\n fdt_put32(s, FDT_BEGIN_NODE);\n fdt_put_data(s, (uint8_t *)name, strlen(name) + 1);\n s->open_node_count++;\n}\n\nstatic void fdt_begin_node_num(FDTState *s, const char *name, uint64_t n)\n{\n char buf[256];\n snprintf(buf, sizeof(buf), \"%s@%\" PRIx64, name, n);\n fdt_begin_node(s, buf);\n}\n\nstatic void fdt_end_node(FDTState *s)\n{\n fdt_put32(s, FDT_END_NODE);\n s->open_node_count--;\n}\n\nstatic int fdt_get_string_offset(FDTState *s, const char *name)\n{\n int pos, new_size, name_size, new_len;\n\n pos = 0;\n while (pos < s->string_table_len) {\n if (!strcmp(s->string_table + pos, name))\n return pos;\n pos += strlen(s->string_table + pos) + 1;\n }\n /* add a new string */\n name_size = strlen(name) + 1;\n new_len = s->string_table_len + name_size;\n if (new_len > s->string_table_size) {\n new_size = max_int(new_len, s->string_table_size * 3 / 2);\n s->string_table = realloc(s->string_table, new_size);\n s->string_table_size = new_size;\n }\n pos = s->string_table_len;\n memcpy(s->string_table + pos, name, name_size);\n s->string_table_len = new_len;\n return pos;\n}\n\nstatic void fdt_prop(FDTState *s, const char *prop_name,\n const void *data, int data_len)\n{\n fdt_put32(s, FDT_PROP);\n fdt_put32(s, data_len);\n fdt_put32(s, fdt_get_string_offset(s, prop_name));\n fdt_put_data(s, data, data_len);\n}\n\nstatic void fdt_prop_tab_u32(FDTState *s, const char *prop_name,\n uint32_t *tab, int tab_len)\n{\n int i;\n fdt_put32(s, FDT_PROP);\n fdt_put32(s, tab_len * sizeof(uint32_t));\n fdt_put32(s, fdt_get_string_offset(s, prop_name));\n for(i = 0; i < tab_len; i++)\n fdt_put32(s, tab[i]);\n}\n\nstatic void fdt_prop_u32(FDTState *s, const char *prop_name, uint32_t val)\n{\n fdt_prop_tab_u32(s, prop_name, &val, 1);\n}\n\nstatic void fdt_prop_tab_u64(FDTState *s, const char *prop_name,\n uint64_t v0)\n{\n uint32_t tab[2];\n tab[0] = v0 >> 32;\n tab[1] = v0;\n fdt_prop_tab_u32(s, prop_name, tab, 2);\n}\n\nstatic void fdt_prop_tab_u64_2(FDTState *s, const char *prop_name,\n uint64_t v0, uint64_t v1)\n{\n uint32_t tab[4];\n tab[0] = v0 >> 32;\n tab[1] = v0;\n tab[2] = v1 >> 32;\n tab[3] = v1;\n fdt_prop_tab_u32(s, prop_name, tab, 4);\n}\n\nstatic void fdt_prop_str(FDTState *s, const char *prop_name,\n const char *str)\n{\n fdt_prop(s, prop_name, str, strlen(str) + 1);\n}\n\n/* NULL terminated string list */\nstatic void fdt_prop_tab_str(FDTState *s, const char *prop_name,\n ...)\n{\n va_list ap;\n int size, str_size;\n char *ptr, *tab;\n\n va_start(ap, prop_name);\n size = 0;\n for(;;) {\n ptr = va_arg(ap, char *);\n if (!ptr)\n break;\n str_size = strlen(ptr) + 1;\n size += str_size;\n }\n va_end(ap);\n \n tab = malloc(size);\n va_start(ap, prop_name);\n size = 0;\n for(;;) {\n ptr = va_arg(ap, char *);\n if (!ptr)\n break;\n str_size = strlen(ptr) + 1;\n memcpy(tab + size, ptr, str_size);\n size += str_size;\n }\n va_end(ap);\n \n fdt_prop(s, prop_name, tab, size);\n free(tab);\n}\n\n/* write the FDT to 'dst1'. return the FDT size in bytes */\nint fdt_output(FDTState *s, uint8_t *dst)\n{\n struct fdt_header *h;\n struct fdt_reserve_entry *re;\n int dt_struct_size;\n int dt_strings_size;\n int pos;\n\n assert(s->open_node_count == 0);\n \n fdt_put32(s, FDT_END);\n \n dt_struct_size = s->tab_len * sizeof(uint32_t);\n dt_strings_size = s->string_table_len;\n\n h = (struct fdt_header *)dst;\n h->magic = cpu_to_be32(FDT_MAGIC);\n h->version = cpu_to_be32(FDT_VERSION);\n h->last_comp_version = cpu_to_be32(16);\n h->boot_cpuid_phys = cpu_to_be32(0);\n h->size_dt_strings = cpu_to_be32(dt_strings_size);\n h->size_dt_struct = cpu_to_be32(dt_struct_size);\n\n pos = sizeof(struct fdt_header);\n\n h->off_dt_struct = cpu_to_be32(pos);\n memcpy(dst + pos, s->tab, dt_struct_size);\n pos += dt_struct_size;\n\n /* align to 8 */\n while ((pos & 7) != 0) {\n dst[pos++] = 0;\n }\n h->off_mem_rsvmap = cpu_to_be32(pos);\n re = (struct fdt_reserve_entry *)(dst + pos);\n re->address = 0; /* no reserved entry */\n re->size = 0;\n pos += sizeof(struct fdt_reserve_entry);\n\n h->off_dt_strings = cpu_to_be32(pos);\n memcpy(dst + pos, s->string_table, dt_strings_size);\n pos += dt_strings_size;\n\n /* align to 8, just in case */\n while ((pos & 7) != 0) {\n dst[pos++] = 0;\n }\n\n h->totalsize = cpu_to_be32(pos);\n return pos;\n}\n\nvoid fdt_end(FDTState *s)\n{\n free(s->tab);\n free(s->string_table);\n free(s);\n}\n\nstatic int riscv_build_fdt(RISCVMachine *m, uint8_t *dst,\n uint64_t kernel_start, uint64_t kernel_size,\n uint64_t initrd_start, uint64_t initrd_size,\n const char *cmd_line)\n{\n FDTState *s;\n int size, max_xlen, i, cur_phandle, intc_phandle, plic_phandle;\n char isa_string[128], *q;\n uint32_t misa;\n uint32_t tab[4];\n FBDevice *fb_dev;\n \n s = fdt_init();\n\n cur_phandle = 1;\n \n fdt_begin_node(s, \"\");\n fdt_prop_u32(s, \"#address-cells\", 2);\n fdt_prop_u32(s, \"#size-cells\", 2);\n fdt_prop_str(s, \"compatible\", \"ucbbar,riscvemu-bar_dev\");\n fdt_prop_str(s, \"model\", \"ucbbar,riscvemu-bare\");\n\n /* CPU list */\n fdt_begin_node(s, \"cpus\");\n fdt_prop_u32(s, \"#address-cells\", 1);\n fdt_prop_u32(s, \"#size-cells\", 0);\n fdt_prop_u32(s, \"timebase-frequency\", RTC_FREQ);\n\n /* cpu */\n fdt_begin_node_num(s, \"cpu\", 0);\n fdt_prop_str(s, \"device_type\", \"cpu\");\n fdt_prop_u32(s, \"reg\", 0);\n fdt_prop_str(s, \"status\", \"okay\");\n fdt_prop_str(s, \"compatible\", \"riscv\");\n\n max_xlen = m->max_xlen;\n misa = riscv_cpu_get_misa(m->cpu_state);\n q = isa_string;\n q += snprintf(isa_string, sizeof(isa_string), \"rv%d\", max_xlen);\n for(i = 0; i < 26; i++) {\n if (misa & (1 << i))\n *q++ = 'a' + i;\n }\n *q = '\\0';\n fdt_prop_str(s, \"riscv,isa\", isa_string);\n \n fdt_prop_str(s, \"mmu-type\", max_xlen <= 32 ? \"riscv,sv32\" : \"riscv,sv48\");\n fdt_prop_u32(s, \"clock-frequency\", 2000000000);\n\n fdt_begin_node(s, \"interrupt-controller\");\n fdt_prop_u32(s, \"#interrupt-cells\", 1);\n fdt_prop(s, \"interrupt-controller\", NULL, 0);\n fdt_prop_str(s, \"compatible\", \"riscv,cpu-intc\");\n intc_phandle = cur_phandle++;\n fdt_prop_u32(s, \"phandle\", intc_phandle);\n fdt_end_node(s); /* interrupt-controller */\n \n fdt_end_node(s); /* cpu */\n \n fdt_end_node(s); /* cpus */\n\n fdt_begin_node_num(s, \"memory\", RAM_BASE_ADDR);\n fdt_prop_str(s, \"device_type\", \"memory\");\n tab[0] = (uint64_t)RAM_BASE_ADDR >> 32;\n tab[1] = RAM_BASE_ADDR;\n tab[2] = m->ram_size >> 32;\n tab[3] = m->ram_size;\n fdt_prop_tab_u32(s, \"reg\", tab, 4);\n \n fdt_end_node(s); /* memory */\n\n fdt_begin_node(s, \"htif\");\n fdt_prop_str(s, \"compatible\", \"ucb,htif0\");\n fdt_end_node(s); /* htif */\n\n fdt_begin_node(s, \"soc\");\n fdt_prop_u32(s, \"#address-cells\", 2);\n fdt_prop_u32(s, \"#size-cells\", 2);\n fdt_prop_tab_str(s, \"compatible\",\n \"ucbbar,riscvemu-bar-soc\", \"simple-bus\", NULL);\n fdt_prop(s, \"ranges\", NULL, 0);\n\n fdt_begin_node_num(s, \"clint\", CLINT_BASE_ADDR);\n fdt_prop_str(s, \"compatible\", \"riscv,clint0\");\n\n tab[0] = intc_phandle;\n tab[1] = 3; /* M IPI irq */\n tab[2] = intc_phandle;\n tab[3] = 7; /* M timer irq */\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 4);\n\n fdt_prop_tab_u64_2(s, \"reg\", CLINT_BASE_ADDR, CLINT_SIZE);\n \n fdt_end_node(s); /* clint */\n\n fdt_begin_node_num(s, \"plic\", PLIC_BASE_ADDR);\n fdt_prop_u32(s, \"#interrupt-cells\", 1);\n fdt_prop(s, \"interrupt-controller\", NULL, 0);\n fdt_prop_str(s, \"compatible\", \"riscv,plic0\");\n fdt_prop_u32(s, \"riscv,ndev\", 31);\n fdt_prop_tab_u64_2(s, \"reg\", PLIC_BASE_ADDR, PLIC_SIZE);\n\n tab[0] = intc_phandle;\n tab[1] = 9; /* S ext irq */\n tab[2] = intc_phandle;\n tab[3] = 11; /* M ext irq */\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 4);\n\n plic_phandle = cur_phandle++;\n fdt_prop_u32(s, \"phandle\", plic_phandle);\n\n fdt_end_node(s); /* plic */\n \n for(i = 0; i < m->virtio_count; i++) {\n fdt_begin_node_num(s, \"virtio\", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE);\n fdt_prop_str(s, \"compatible\", \"virtio,mmio\");\n fdt_prop_tab_u64_2(s, \"reg\", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE,\n VIRTIO_SIZE);\n tab[0] = plic_phandle;\n tab[1] = VIRTIO_IRQ + i;\n fdt_prop_tab_u32(s, \"interrupts-extended\", tab, 2);\n fdt_end_node(s); /* virtio */\n }\n\n fb_dev = m->common.fb_dev;\n if (fb_dev) {\n fdt_begin_node_num(s, \"framebuffer\", FRAMEBUFFER_BASE_ADDR);\n fdt_prop_str(s, \"compatible\", \"simple-framebuffer\");\n fdt_prop_tab_u64_2(s, \"reg\", FRAMEBUFFER_BASE_ADDR, fb_dev->fb_size);\n fdt_prop_u32(s, \"width\", fb_dev->width);\n fdt_prop_u32(s, \"height\", fb_dev->height);\n fdt_prop_u32(s, \"stride\", fb_dev->stride);\n fdt_prop_str(s, \"format\", \"a8r8g8b8\");\n fdt_end_node(s); /* framebuffer */\n }\n \n fdt_end_node(s); /* soc */\n\n fdt_begin_node(s, \"chosen\");\n fdt_prop_str(s, \"bootargs\", cmd_line ? cmd_line : \"\");\n if (kernel_size > 0) {\n fdt_prop_tab_u64(s, \"riscv,kernel-start\", kernel_start);\n fdt_prop_tab_u64(s, \"riscv,kernel-end\", kernel_start + kernel_size);\n }\n if (initrd_size > 0) {\n fdt_prop_tab_u64(s, \"linux,initrd-start\", initrd_start);\n fdt_prop_tab_u64(s, \"linux,initrd-end\", initrd_start + initrd_size);\n }\n \n\n fdt_end_node(s); /* chosen */\n \n fdt_end_node(s); /* / */\n\n size = fdt_output(s, dst);\n#if 0\n {\n FILE *f;\n f = fopen(\"/tmp/riscvemu.dtb\", \"wb\");\n fwrite(dst, 1, size, f);\n fclose(f);\n }\n#endif\n fdt_end(s);\n return size;\n}\n\nstatic void copy_bios(RISCVMachine *s, const uint8_t *buf, int buf_len,\n const uint8_t *kernel_buf, int kernel_buf_len,\n const uint8_t *initrd_buf, int initrd_buf_len,\n const char *cmd_line)\n{\n uint32_t fdt_addr, align, kernel_base, initrd_base;\n uint8_t *ram_ptr;\n uint32_t *q;\n\n if (buf_len > s->ram_size) {\n vm_error(\"BIOS too big\\n\");\n exit(1);\n }\n\n ram_ptr = get_ram_ptr(s, RAM_BASE_ADDR, TRUE);\n memcpy(ram_ptr, buf, buf_len);\n\n kernel_base = 0;\n if (kernel_buf_len > 0) {\n /* copy the kernel if present */\n if (s->max_xlen == 32)\n align = 4 << 20; /* 4 MB page align */\n else\n align = 2 << 20; /* 2 MB page align */\n kernel_base = (buf_len + align - 1) & ~(align - 1);\n memcpy(ram_ptr + kernel_base, kernel_buf, kernel_buf_len);\n if (kernel_buf_len + kernel_base > s->ram_size) {\n vm_error(\"kernel too big\");\n exit(1);\n }\n }\n\n initrd_base = 0;\n if (initrd_buf_len > 0) {\n /* same allocation as QEMU */\n initrd_base = s->ram_size / 2;\n if (initrd_base > (128 << 20))\n initrd_base = 128 << 20;\n memcpy(ram_ptr + initrd_base, initrd_buf, initrd_buf_len);\n if (initrd_buf_len + initrd_base > s->ram_size) {\n vm_error(\"initrd too big\");\n exit(1);\n }\n }\n \n ram_ptr = get_ram_ptr(s, 0, TRUE);\n \n fdt_addr = 0x1000 + 8 * 8;\n\n riscv_build_fdt(s, ram_ptr + fdt_addr,\n RAM_BASE_ADDR + kernel_base, kernel_buf_len,\n RAM_BASE_ADDR + initrd_base, initrd_buf_len,\n cmd_line);\n\n /* jump_addr = 0x80000000 */\n \n q = (uint32_t *)(ram_ptr + 0x1000);\n q[0] = 0x297 + 0x80000000 - 0x1000; /* auipc t0, jump_addr */\n q[1] = 0x597; /* auipc a1, dtb */\n q[2] = 0x58593 + ((fdt_addr - 4) << 20); /* addi a1, a1, dtb */\n q[3] = 0xf1402573; /* csrr a0, mhartid */\n q[4] = 0x00028067; /* jalr zero, t0, jump_addr */\n}\n\nstatic void riscv_flush_tlb_write_range(void *opaque, uint8_t *ram_addr,\n size_t ram_size)\n{\n RISCVMachine *s = opaque;\n riscv_cpu_flush_tlb_write_range_ram(s->cpu_state, ram_addr, ram_size);\n}\n\nstatic void riscv_machine_set_defaults(VirtMachineParams *p)\n{\n}\n\nstatic VirtMachine *riscv_machine_init(const VirtMachineParams *p)\n{\n RISCVMachine *s;\n VIRTIODevice *blk_dev;\n int irq_num, i, max_xlen, ram_flags;\n VIRTIOBusDef vbus_s, *vbus = &vbus_s;\n\n\n if (!strcmp(p->machine_name, \"riscv32\")) {\n max_xlen = 32;\n } else if (!strcmp(p->machine_name, \"riscv64\")) {\n max_xlen = 64;\n } else if (!strcmp(p->machine_name, \"riscv128\")) {\n max_xlen = 128;\n } else {\n vm_error(\"unsupported machine: %s\\n\", p->machine_name);\n return NULL;\n }\n \n s = mallocz(sizeof(*s));\n s->common.vmc = p->vmc;\n s->ram_size = p->ram_size;\n s->max_xlen = max_xlen;\n s->mem_map = phys_mem_map_init();\n /* needed to handle the RAM dirty bits */\n s->mem_map->opaque = s;\n s->mem_map->flush_tlb_write_range = riscv_flush_tlb_write_range;\n\n s->cpu_state = riscv_cpu_init(s->mem_map, max_xlen);\n if (!s->cpu_state) {\n vm_error(\"unsupported max_xlen=%d\\n\", max_xlen);\n /* XXX: should free resources */\n return NULL;\n }\n /* RAM */\n ram_flags = 0;\n cpu_register_ram(s->mem_map, RAM_BASE_ADDR, p->ram_size, ram_flags);\n cpu_register_ram(s->mem_map, 0x00000000, LOW_RAM_SIZE, 0);\n s->rtc_real_time = p->rtc_real_time;\n if (p->rtc_real_time) {\n s->rtc_start_time = rtc_get_real_time(s);\n }\n \n cpu_register_device(s->mem_map, CLINT_BASE_ADDR, CLINT_SIZE, s,\n clint_read, clint_write, DEVIO_SIZE32);\n cpu_register_device(s->mem_map, PLIC_BASE_ADDR, PLIC_SIZE, s,\n plic_read, plic_write, DEVIO_SIZE32);\n for(i = 1; i < 32; i++) {\n irq_init(&s->plic_irq[i], plic_set_irq, s, i);\n }\n\n cpu_register_device(s->mem_map, HTIF_BASE_ADDR, 16,\n s, htif_read, htif_write, DEVIO_SIZE32);\n s->common.console = p->console;\n\n memset(vbus, 0, sizeof(*vbus));\n vbus->mem_map = s->mem_map;\n vbus->addr = VIRTIO_BASE_ADDR;\n irq_num = VIRTIO_IRQ;\n \n /* virtio console */\n if (p->console) {\n vbus->irq = &s->plic_irq[irq_num];\n s->common.console_dev = virtio_console_init(vbus, p->console);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n \n /* virtio net device */\n for(i = 0; i < p->eth_count; i++) {\n vbus->irq = &s->plic_irq[irq_num];\n virtio_net_init(vbus, p->tab_eth[i].net);\n s->common.net = p->tab_eth[i].net;\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n /* virtio block device */\n for(i = 0; i < p->drive_count; i++) {\n vbus->irq = &s->plic_irq[irq_num];\n blk_dev = virtio_block_init(vbus, p->tab_drive[i].block_dev);\n (void)blk_dev;\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n /* virtio filesystem */\n for(i = 0; i < p->fs_count; i++) {\n VIRTIODevice *fs_dev;\n vbus->irq = &s->plic_irq[irq_num];\n fs_dev = virtio_9p_init(vbus, p->tab_fs[i].fs_dev,\n p->tab_fs[i].tag);\n (void)fs_dev;\n // virtio_set_debug(fs_dev, VIRTIO_DEBUG_9P);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n }\n\n if (p->display_device) {\n FBDevice *fb_dev;\n fb_dev = mallocz(sizeof(*fb_dev));\n s->common.fb_dev = fb_dev;\n if (!strcmp(p->display_device, \"simplefb\")) {\n simplefb_init(s->mem_map,\n FRAMEBUFFER_BASE_ADDR,\n fb_dev,\n p->width, p->height);\n \n } else {\n vm_error(\"unsupported display device: %s\\n\", p->display_device);\n exit(1);\n }\n }\n\n if (p->input_device) {\n if (!strcmp(p->input_device, \"virtio\")) {\n vbus->irq = &s->plic_irq[irq_num];\n s->keyboard_dev = virtio_input_init(vbus,\n VIRTIO_INPUT_TYPE_KEYBOARD);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n\n vbus->irq = &s->plic_irq[irq_num];\n s->mouse_dev = virtio_input_init(vbus,\n VIRTIO_INPUT_TYPE_TABLET);\n vbus->addr += VIRTIO_SIZE;\n irq_num++;\n s->virtio_count++;\n } else {\n vm_error(\"unsupported input device: %s\\n\", p->input_device);\n exit(1);\n }\n }\n \n if (!p->files[VM_FILE_BIOS].buf) {\n vm_error(\"No bios found\");\n }\n\n copy_bios(s, p->files[VM_FILE_BIOS].buf, p->files[VM_FILE_BIOS].len,\n p->files[VM_FILE_KERNEL].buf, p->files[VM_FILE_KERNEL].len,\n p->files[VM_FILE_INITRD].buf, p->files[VM_FILE_INITRD].len,\n p->cmdline);\n \n return (VirtMachine *)s;\n}\n\nstatic void riscv_machine_end(VirtMachine *s1)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n /* XXX: stop all */\n riscv_cpu_end(s->cpu_state);\n phys_mem_map_end(s->mem_map);\n free(s);\n}\n\n/* in ms */\nstatic int riscv_machine_get_sleep_duration(VirtMachine *s1, int delay)\n{\n RISCVMachine *m = (RISCVMachine *)s1;\n RISCVCPUState *s = m->cpu_state;\n int64_t delay1;\n \n /* wait for an event: the only asynchronous event is the RTC timer */\n if (!(riscv_cpu_get_mip(s) & MIP_MTIP)) {\n delay1 = m->timecmp - rtc_get_time(m);\n if (delay1 <= 0) {\n riscv_cpu_set_mip(s, MIP_MTIP);\n delay = 0;\n } else {\n /* convert delay to ms */\n delay1 = delay1 / (RTC_FREQ / 1000);\n if (delay1 < delay)\n delay = delay1;\n }\n }\n if (!riscv_cpu_get_power_down(s))\n delay = 0;\n return delay;\n}\n\nstatic void riscv_machine_interp(VirtMachine *s1, int max_exec_cycle)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n riscv_cpu_interp(s->cpu_state, max_exec_cycle);\n}\n\nstatic void riscv_vm_send_key_event(VirtMachine *s1, BOOL is_down,\n uint16_t key_code)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n if (s->keyboard_dev) {\n virtio_input_send_key_event(s->keyboard_dev, is_down, key_code);\n }\n}\n\nstatic BOOL riscv_vm_mouse_is_absolute(VirtMachine *s)\n{\n return TRUE;\n}\n\nstatic void riscv_vm_send_mouse_event(VirtMachine *s1, int dx, int dy, int dz,\n unsigned int buttons)\n{\n RISCVMachine *s = (RISCVMachine *)s1;\n if (s->mouse_dev) {\n virtio_input_send_mouse_event(s->mouse_dev, dx, dy, dz, buttons);\n }\n}\n\nconst VirtMachineClass riscv_machine_class = {\n \"riscv32,riscv64,riscv128\",\n riscv_machine_set_defaults,\n riscv_machine_init,\n riscv_machine_end,\n riscv_machine_get_sleep_duration,\n riscv_machine_interp,\n riscv_vm_mouse_is_absolute,\n riscv_vm_send_mouse_event,\n riscv_vm_send_key_event,\n};\n"], ["/linuxpdf/tinyemu/fs.c", "/*\n * Filesystem utilities\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"fs.h\"\n\nFSFile *fs_dup(FSDevice *fs, FSFile *f)\n{\n FSQID qid;\n fs->fs_walk(fs, &f, &qid, f, 0, NULL);\n return f;\n}\n\nFSFile *fs_walk_path1(FSDevice *fs, FSFile *f, const char *path,\n char **pname)\n{\n const char *p;\n char *name;\n FSFile *f1;\n FSQID qid;\n int len, ret;\n BOOL is_last, is_first;\n\n if (path[0] == '/')\n path++;\n \n is_first = TRUE;\n for(;;) {\n p = strchr(path, '/');\n if (!p) {\n name = (char *)path;\n if (pname) {\n *pname = name;\n if (is_first) {\n ret = fs->fs_walk(fs, &f, &qid, f, 0, NULL);\n if (ret < 0)\n f = NULL;\n }\n return f;\n }\n is_last = TRUE;\n } else {\n len = p - path;\n name = malloc(len + 1);\n memcpy(name, path, len);\n name[len] = '\\0';\n is_last = FALSE;\n }\n ret = fs->fs_walk(fs, &f1, &qid, f, 1, &name);\n if (!is_last)\n free(name);\n if (!is_first)\n fs->fs_delete(fs, f);\n f = f1;\n is_first = FALSE;\n if (ret <= 0) {\n fs->fs_delete(fs, f);\n f = NULL;\n break;\n } else if (is_last) {\n break;\n }\n path = p + 1;\n }\n return f;\n}\n\nFSFile *fs_walk_path(FSDevice *fs, FSFile *f, const char *path)\n{\n return fs_walk_path1(fs, f, path, NULL);\n}\n\nvoid fs_end(FSDevice *fs)\n{\n fs->fs_end(fs);\n free(fs);\n}\n"], ["/linuxpdf/tinyemu/fs_utils.c", "/*\n * Misc FS utilities\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"list.h\"\n#include \"fs_utils.h\"\n\n/* last byte is the version */\nconst uint8_t encrypted_file_magic[4] = { 0xfb, 0xa2, 0xe9, 0x01 };\n\nchar *compose_path(const char *path, const char *name)\n{\n int path_len, name_len;\n char *d, *q;\n\n if (path[0] == '\\0') {\n d = strdup(name);\n } else {\n path_len = strlen(path);\n name_len = strlen(name);\n d = malloc(path_len + 1 + name_len + 1);\n q = d;\n memcpy(q, path, path_len);\n q += path_len;\n if (path[path_len - 1] != '/')\n *q++ = '/';\n memcpy(q, name, name_len + 1);\n }\n return d;\n}\n\nchar *compose_url(const char *base_url, const char *name)\n{\n if (strchr(name, ':')) {\n return strdup(name);\n } else {\n return compose_path(base_url, name);\n }\n}\n\nvoid skip_line(const char **pp)\n{\n const char *p;\n p = *pp;\n while (*p != '\\n' && *p != '\\0')\n p++;\n if (*p == '\\n')\n p++;\n *pp = p;\n}\n\nchar *quoted_str(const char *str)\n{\n const char *s;\n char *q;\n int c;\n char *buf;\n\n if (str[0] == '\\0')\n goto use_quote;\n s = str;\n while (*s != '\\0') {\n if (*s <= ' ' || *s > '~')\n goto use_quote;\n s++;\n }\n return strdup(str);\n use_quote:\n buf = malloc(strlen(str) * 4 + 2 + 1);\n q = buf;\n s = str;\n *q++ = '\"';\n while (*s != '\\0') {\n c = *(uint8_t *)s;\n if (c < ' ' || c == 127) {\n q += sprintf(q, \"\\\\x%02x\", c);\n } else if (c == '\\\\' || c == '\\\"') {\n q += sprintf(q, \"\\\\%c\", c);\n } else {\n *q++ = c;\n }\n s++;\n }\n *q++ = '\"';\n *q = '\\0';\n return buf;\n}\n\nint parse_fname(char *buf, int buf_size, const char **pp)\n{\n const char *p;\n char *q;\n int c, h;\n \n p = *pp;\n while (isspace_nolf(*p))\n p++;\n if (*p == '\\0')\n return -1;\n q = buf;\n if (*p == '\"') {\n p++;\n for(;;) {\n c = *p++;\n if (c == '\\0' || c == '\\n') {\n return -1;\n } else if (c == '\\\"') {\n break;\n } else if (c == '\\\\') {\n c = *p++;\n switch(c) {\n case '\\'':\n case '\\\"':\n case '\\\\':\n goto add_char;\n case 'n':\n c = '\\n';\n goto add_char;\n case 'r':\n c = '\\r';\n goto add_char;\n case 't':\n c = '\\t';\n goto add_char;\n case 'x':\n h = from_hex(*p++);\n if (h < 0)\n return -1;\n c = h << 4;\n h = from_hex(*p++);\n if (h < 0)\n return -1;\n c |= h;\n goto add_char;\n default:\n return -1;\n }\n } else {\n add_char:\n if (q >= buf + buf_size - 1)\n return -1;\n *q++ = c;\n }\n }\n } else {\n while (!isspace_nolf(*p) && *p != '\\0' && *p != '\\n') {\n if (q >= buf + buf_size - 1)\n return -1;\n *q++ = *p++;\n }\n }\n *q = '\\0';\n *pp = p;\n return 0;\n}\n\nint parse_uint32_base(uint32_t *pval, const char **pp, int base)\n{\n const char *p, *p1;\n p = *pp;\n while (isspace_nolf(*p))\n p++;\n *pval = strtoul(p, (char **)&p1, base);\n if (p1 == p)\n return -1;\n *pp = p1;\n return 0;\n}\n\nint parse_uint64_base(uint64_t *pval, const char **pp, int base)\n{\n const char *p, *p1;\n p = *pp;\n while (isspace_nolf(*p))\n p++;\n *pval = strtoull(p, (char **)&p1, base);\n if (p1 == p)\n return -1;\n *pp = p1;\n return 0;\n}\n\nint parse_uint64(uint64_t *pval, const char **pp)\n{\n return parse_uint64_base(pval, pp, 0);\n}\n\nint parse_uint32(uint32_t *pval, const char **pp)\n{\n return parse_uint32_base(pval, pp, 0);\n}\n\nint parse_time(uint32_t *psec, uint32_t *pnsec, const char **pp)\n{\n const char *p;\n uint32_t v, m;\n p = *pp;\n if (parse_uint32(psec, &p) < 0)\n return -1;\n v = 0;\n if (*p == '.') {\n p++;\n /* XXX: inefficient */\n m = 1000000000;\n v = 0;\n while (*p >= '0' && *p <= '9') {\n m /= 10;\n v += (*p - '0') * m;\n p++;\n }\n }\n *pnsec = v;\n *pp = p;\n return 0;\n}\n\nint parse_file_id(FSFileID *pval, const char **pp)\n{\n return parse_uint64_base(pval, pp, 16);\n}\n\nchar *file_id_to_filename(char *buf, FSFileID file_id)\n{\n sprintf(buf, \"%016\" PRIx64, file_id);\n return buf;\n}\n\nvoid encode_hex(char *str, const uint8_t *buf, int len)\n{\n int i;\n for(i = 0; i < len; i++)\n sprintf(str + 2 * i, \"%02x\", buf[i]);\n}\n\nint decode_hex(uint8_t *buf, const char *str, int len)\n{\n int h0, h1, i;\n\n for(i = 0; i < len; i++) {\n h0 = from_hex(str[2 * i]);\n if (h0 < 0)\n return -1;\n h1 = from_hex(str[2 * i + 1]);\n if (h1 < 0)\n return -1;\n buf[i] = (h0 << 4) | h1;\n }\n return 0;\n}\n\n/* return NULL if no end of header found */\nconst char *skip_header(const char *p)\n{\n p = strstr(p, \"\\n\\n\");\n if (!p)\n return NULL;\n return p + 2;\n}\n\n/* return 0 if OK, < 0 if error */\nint parse_tag(char *buf, int buf_size, const char *str, const char *tag)\n{\n char tagname[128], *q;\n const char *p, *p1;\n int len;\n \n p = str;\n for(;;) {\n if (*p == '\\0' || *p == '\\n')\n break;\n q = tagname;\n while (*p != ':' && *p != '\\n' && *p != '\\0') {\n if ((q - tagname) < sizeof(tagname) - 1)\n *q++ = *p;\n p++;\n }\n *q = '\\0';\n if (*p != ':')\n return -1;\n p++;\n while (isspace_nolf(*p))\n p++;\n p1 = p;\n p = strchr(p, '\\n');\n if (!p)\n len = strlen(p1);\n else\n len = p - p1;\n if (!strcmp(tagname, tag)) {\n if (len > buf_size - 1)\n len = buf_size - 1;\n memcpy(buf, p1, len);\n buf[len] = '\\0';\n return 0;\n }\n if (!p)\n break;\n else\n p++;\n }\n return -1;\n}\n\nint parse_tag_uint64(uint64_t *pval, const char *str, const char *tag)\n{\n char buf[64];\n const char *p;\n if (parse_tag(buf, sizeof(buf), str, tag))\n return -1;\n p = buf;\n return parse_uint64(pval, &p);\n}\n\nint parse_tag_file_id(FSFileID *pval, const char *str, const char *tag)\n{\n char buf[64];\n const char *p;\n if (parse_tag(buf, sizeof(buf), str, tag))\n return -1;\n p = buf;\n return parse_uint64_base(pval, &p, 16);\n}\n\nint parse_tag_version(const char *str)\n{\n uint64_t version;\n if (parse_tag_uint64(&version, str, \"Version\"))\n return -1;\n return version;\n}\n\nBOOL is_url(const char *path)\n{\n return (strstart(path, \"http:\", NULL) ||\n strstart(path, \"https:\", NULL) ||\n strstart(path, \"file:\", NULL));\n}\n"], ["/linuxpdf/tinyemu/riscv_cpu.c", "/*\n * RISCV CPU emulator\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"riscv_cpu.h\"\n\n#ifndef MAX_XLEN\n#error MAX_XLEN must be defined\n#endif\n#ifndef CONFIG_RISCV_MAX_XLEN\n#error CONFIG_RISCV_MAX_XLEN must be defined\n#endif\n\n//#define DUMP_INVALID_MEM_ACCESS\n//#define DUMP_MMU_EXCEPTIONS\n//#define DUMP_INTERRUPTS\n//#define DUMP_INVALID_CSR\n//#define DUMP_EXCEPTIONS\n//#define DUMP_CSR\n//#define CONFIG_LOGFILE\n\n#include \"riscv_cpu_priv.h\"\n\n#if FLEN > 0\n#include \"softfp.h\"\n#endif\n\n#ifdef USE_GLOBAL_STATE\nstatic RISCVCPUState riscv_cpu_global_state;\n#endif\n#ifdef USE_GLOBAL_VARIABLES\n#define code_ptr s->__code_ptr\n#define code_end s->__code_end\n#define code_to_pc_addend s->__code_to_pc_addend\n#endif\n\n#ifdef CONFIG_LOGFILE\nstatic FILE *log_file;\n\nstatic void log_vprintf(const char *fmt, va_list ap)\n{\n if (!log_file)\n log_file = fopen(\"/tmp/riscemu.log\", \"wb\");\n vfprintf(log_file, fmt, ap);\n}\n#else\nstatic void log_vprintf(const char *fmt, va_list ap)\n{\n vprintf(fmt, ap);\n}\n#endif\n\nstatic void __attribute__((format(printf, 1, 2), unused)) log_printf(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n log_vprintf(fmt, ap);\n va_end(ap);\n}\n\n#if MAX_XLEN == 128\nstatic void fprint_target_ulong(FILE *f, target_ulong a)\n{\n fprintf(f, \"%016\" PRIx64 \"%016\" PRIx64, (uint64_t)(a >> 64), (uint64_t)a);\n}\n#else\nstatic void fprint_target_ulong(FILE *f, target_ulong a)\n{\n fprintf(f, \"%\" PR_target_ulong, a);\n}\n#endif\n\nstatic void print_target_ulong(target_ulong a)\n{\n fprint_target_ulong(stdout, a);\n}\n\nstatic char *reg_name[32] = {\n\"zero\", \"ra\", \"sp\", \"gp\", \"tp\", \"t0\", \"t1\", \"t2\",\n\"s0\", \"s1\", \"a0\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\",\n\"a6\", \"a7\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\", \"s7\",\n\"s8\", \"s9\", \"s10\", \"s11\", \"t3\", \"t4\", \"t5\", \"t6\"\n};\n\nstatic void dump_regs(RISCVCPUState *s)\n{\n int i, cols;\n const char priv_str[4] = \"USHM\";\n cols = 256 / MAX_XLEN;\n printf(\"pc =\");\n print_target_ulong(s->pc);\n printf(\" \");\n for(i = 1; i < 32; i++) {\n printf(\"%-3s=\", reg_name[i]);\n print_target_ulong(s->reg[i]);\n if ((i & (cols - 1)) == (cols - 1))\n printf(\"\\n\");\n else\n printf(\" \");\n }\n printf(\"priv=%c\", priv_str[s->priv]);\n printf(\" mstatus=\");\n print_target_ulong(s->mstatus);\n printf(\" cycles=%\" PRId64, s->insn_counter);\n printf(\"\\n\");\n#if 1\n printf(\" mideleg=\");\n print_target_ulong(s->mideleg);\n printf(\" mie=\");\n print_target_ulong(s->mie);\n printf(\" mip=\");\n print_target_ulong(s->mip);\n printf(\"\\n\");\n#endif\n}\n\nstatic __attribute__((unused)) void cpu_abort(RISCVCPUState *s)\n{\n dump_regs(s);\n abort();\n}\n\n/* addr must be aligned. Only RAM accesses are supported */\n#define PHYS_MEM_READ_WRITE(size, uint_type) \\\nstatic __maybe_unused inline void phys_write_u ## size(RISCVCPUState *s, target_ulong addr,\\\n uint_type val) \\\n{\\\n PhysMemoryRange *pr = get_phys_mem_range(s->mem_map, addr);\\\n if (!pr || !pr->is_ram)\\\n return;\\\n *(uint_type *)(pr->phys_mem + \\\n (uintptr_t)(addr - pr->addr)) = val;\\\n}\\\n\\\nstatic __maybe_unused inline uint_type phys_read_u ## size(RISCVCPUState *s, target_ulong addr) \\\n{\\\n PhysMemoryRange *pr = get_phys_mem_range(s->mem_map, addr);\\\n if (!pr || !pr->is_ram)\\\n return 0;\\\n return *(uint_type *)(pr->phys_mem + \\\n (uintptr_t)(addr - pr->addr)); \\\n}\n\nPHYS_MEM_READ_WRITE(8, uint8_t)\nPHYS_MEM_READ_WRITE(32, uint32_t)\nPHYS_MEM_READ_WRITE(64, uint64_t)\n\n#define PTE_V_MASK (1 << 0)\n#define PTE_U_MASK (1 << 4)\n#define PTE_A_MASK (1 << 6)\n#define PTE_D_MASK (1 << 7)\n\n#define ACCESS_READ 0\n#define ACCESS_WRITE 1\n#define ACCESS_CODE 2\n\n/* access = 0: read, 1 = write, 2 = code. Set the exception_pending\n field if necessary. return 0 if OK, -1 if translation error */\nstatic int get_phys_addr(RISCVCPUState *s,\n target_ulong *ppaddr, target_ulong vaddr,\n int access)\n{\n int mode, levels, pte_bits, pte_idx, pte_mask, pte_size_log2, xwr, priv;\n int need_write, vaddr_shift, i, pte_addr_bits;\n target_ulong pte_addr, pte, vaddr_mask, paddr;\n\n if ((s->mstatus & MSTATUS_MPRV) && access != ACCESS_CODE) {\n /* use previous priviledge */\n priv = (s->mstatus >> MSTATUS_MPP_SHIFT) & 3;\n } else {\n priv = s->priv;\n }\n\n if (priv == PRV_M) {\n if (s->cur_xlen < MAX_XLEN) {\n /* truncate virtual address */\n *ppaddr = vaddr & (((target_ulong)1 << s->cur_xlen) - 1);\n } else {\n *ppaddr = vaddr;\n }\n return 0;\n }\n#if MAX_XLEN == 32\n /* 32 bits */\n mode = s->satp >> 31;\n if (mode == 0) {\n /* bare: no translation */\n *ppaddr = vaddr;\n return 0;\n } else {\n /* sv32 */\n levels = 2;\n pte_size_log2 = 2;\n pte_addr_bits = 22;\n }\n#else\n mode = (s->satp >> 60) & 0xf;\n if (mode == 0) {\n /* bare: no translation */\n *ppaddr = vaddr;\n return 0;\n } else {\n /* sv39/sv48 */\n levels = mode - 8 + 3;\n pte_size_log2 = 3;\n vaddr_shift = MAX_XLEN - (PG_SHIFT + levels * 9);\n if ((((target_long)vaddr << vaddr_shift) >> vaddr_shift) != vaddr)\n return -1;\n pte_addr_bits = 44;\n }\n#endif\n pte_addr = (s->satp & (((target_ulong)1 << pte_addr_bits) - 1)) << PG_SHIFT;\n pte_bits = 12 - pte_size_log2;\n pte_mask = (1 << pte_bits) - 1;\n for(i = 0; i < levels; i++) {\n vaddr_shift = PG_SHIFT + pte_bits * (levels - 1 - i);\n pte_idx = (vaddr >> vaddr_shift) & pte_mask;\n pte_addr += pte_idx << pte_size_log2;\n if (pte_size_log2 == 2)\n pte = phys_read_u32(s, pte_addr);\n else\n pte = phys_read_u64(s, pte_addr);\n //printf(\"pte=0x%08\" PRIx64 \"\\n\", pte);\n if (!(pte & PTE_V_MASK))\n return -1; /* invalid PTE */\n paddr = (pte >> 10) << PG_SHIFT;\n xwr = (pte >> 1) & 7;\n if (xwr != 0) {\n if (xwr == 2 || xwr == 6)\n return -1;\n /* priviledge check */\n if (priv == PRV_S) {\n if ((pte & PTE_U_MASK) && !(s->mstatus & MSTATUS_SUM))\n return -1;\n } else {\n if (!(pte & PTE_U_MASK))\n return -1;\n }\n /* protection check */\n /* MXR allows read access to execute-only pages */\n if (s->mstatus & MSTATUS_MXR)\n xwr |= (xwr >> 2);\n\n if (((xwr >> access) & 1) == 0)\n return -1;\n need_write = !(pte & PTE_A_MASK) ||\n (!(pte & PTE_D_MASK) && access == ACCESS_WRITE);\n pte |= PTE_A_MASK;\n if (access == ACCESS_WRITE)\n pte |= PTE_D_MASK;\n if (need_write) {\n if (pte_size_log2 == 2)\n phys_write_u32(s, pte_addr, pte);\n else\n phys_write_u64(s, pte_addr, pte);\n }\n vaddr_mask = ((target_ulong)1 << vaddr_shift) - 1;\n *ppaddr = (vaddr & vaddr_mask) | (paddr & ~vaddr_mask);\n return 0;\n } else {\n pte_addr = paddr;\n }\n }\n return -1;\n}\n\n/* return 0 if OK, != 0 if exception */\nint target_read_slow(RISCVCPUState *s, mem_uint_t *pval,\n target_ulong addr, int size_log2)\n{\n int size, tlb_idx, err, al;\n target_ulong paddr, offset;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n mem_uint_t ret;\n\n /* first handle unaligned accesses */\n size = 1 << size_log2;\n al = addr & (size - 1);\n if (al != 0) {\n switch(size_log2) {\n case 1:\n {\n uint8_t v0, v1;\n err = target_read_u8(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u8(s, &v1, addr + 1);\n if (err)\n return err;\n ret = v0 | (v1 << 8);\n }\n break;\n case 2:\n {\n uint32_t v0, v1;\n addr -= al;\n err = target_read_u32(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u32(s, &v1, addr + 4);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (32 - al * 8));\n }\n break;\n#if MLEN >= 64\n case 3:\n {\n uint64_t v0, v1;\n addr -= al;\n err = target_read_u64(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u64(s, &v1, addr + 8);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (64 - al * 8));\n }\n break;\n#endif\n#if MLEN >= 128\n case 4:\n {\n uint128_t v0, v1;\n addr -= al;\n err = target_read_u128(s, &v0, addr);\n if (err)\n return err;\n err = target_read_u128(s, &v1, addr + 16);\n if (err)\n return err;\n ret = (v0 >> (al * 8)) | (v1 << (128 - al * 8));\n }\n break;\n#endif\n default:\n abort();\n }\n } else {\n if (get_phys_addr(s, &paddr, addr, ACCESS_READ)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_LOAD_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr) {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"target_read_slow: invalid physical address 0x\");\n print_target_ulong(paddr);\n printf(\"\\n\");\n#endif\n return 0;\n } else if (pr->is_ram) {\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_read[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_read[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n switch(size_log2) {\n case 0:\n ret = *(uint8_t *)ptr;\n break;\n case 1:\n ret = *(uint16_t *)ptr;\n break;\n case 2:\n ret = *(uint32_t *)ptr;\n break;\n#if MLEN >= 64\n case 3:\n ret = *(uint64_t *)ptr;\n break;\n#endif\n#if MLEN >= 128\n case 4:\n ret = *(uint128_t *)ptr;\n break;\n#endif\n default:\n abort();\n }\n } else {\n offset = paddr - pr->addr;\n if (((pr->devio_flags >> size_log2) & 1) != 0) {\n ret = pr->read_func(pr->opaque, offset, size_log2);\n }\n#if MLEN >= 64\n else if ((pr->devio_flags & DEVIO_SIZE32) && size_log2 == 3) {\n /* emulate 64 bit access */\n ret = pr->read_func(pr->opaque, offset, 2);\n ret |= (uint64_t)pr->read_func(pr->opaque, offset + 4, 2) << 32;\n \n }\n#endif\n else {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"unsupported device read access: addr=0x\");\n print_target_ulong(paddr);\n printf(\" width=%d bits\\n\", 1 << (3 + size_log2));\n#endif\n ret = 0;\n }\n }\n }\n *pval = ret;\n return 0;\n}\n\n/* return 0 if OK, != 0 if exception */\nint target_write_slow(RISCVCPUState *s, target_ulong addr,\n mem_uint_t val, int size_log2)\n{\n int size, i, tlb_idx, err;\n target_ulong paddr, offset;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n \n /* first handle unaligned accesses */\n size = 1 << size_log2;\n if ((addr & (size - 1)) != 0) {\n /* XXX: should avoid modifying the memory in case of exception */\n for(i = 0; i < size; i++) {\n err = target_write_u8(s, addr + i, (val >> (8 * i)) & 0xff);\n if (err)\n return err;\n }\n } else {\n if (get_phys_addr(s, &paddr, addr, ACCESS_WRITE)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_STORE_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr) {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"target_write_slow: invalid physical address 0x\");\n print_target_ulong(paddr);\n printf(\"\\n\");\n#endif\n } else if (pr->is_ram) {\n phys_mem_set_dirty_bit(pr, paddr - pr->addr);\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_write[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_write[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n switch(size_log2) {\n case 0:\n *(uint8_t *)ptr = val;\n break;\n case 1:\n *(uint16_t *)ptr = val;\n break;\n case 2:\n *(uint32_t *)ptr = val;\n break;\n#if MLEN >= 64\n case 3:\n *(uint64_t *)ptr = val;\n break;\n#endif\n#if MLEN >= 128\n case 4:\n *(uint128_t *)ptr = val;\n break;\n#endif\n default:\n abort();\n }\n } else {\n offset = paddr - pr->addr;\n if (((pr->devio_flags >> size_log2) & 1) != 0) {\n pr->write_func(pr->opaque, offset, val, size_log2);\n }\n#if MLEN >= 64\n else if ((pr->devio_flags & DEVIO_SIZE32) && size_log2 == 3) {\n /* emulate 64 bit access */\n pr->write_func(pr->opaque, offset,\n val & 0xffffffff, 2);\n pr->write_func(pr->opaque, offset + 4,\n (val >> 32) & 0xffffffff, 2);\n }\n#endif\n else {\n#ifdef DUMP_INVALID_MEM_ACCESS\n printf(\"unsupported device write access: addr=0x\");\n print_target_ulong(paddr);\n printf(\" width=%d bits\\n\", 1 << (3 + size_log2));\n#endif\n }\n }\n }\n return 0;\n}\n\nstruct __attribute__((packed)) unaligned_u32 {\n uint32_t u32;\n};\n\n/* unaligned access at an address known to be a multiple of 2 */\nstatic uint32_t get_insn32(uint8_t *ptr)\n{\n#if defined(EMSCRIPTEN)\n return ((uint16_t *)ptr)[0] | (((uint16_t *)ptr)[1] << 16);\n#else\n return ((struct unaligned_u32 *)ptr)->u32;\n#endif\n}\n\n/* return 0 if OK, != 0 if exception */\nstatic no_inline __exception int target_read_insn_slow(RISCVCPUState *s,\n uint8_t **pptr,\n target_ulong addr)\n{\n int tlb_idx;\n target_ulong paddr;\n uint8_t *ptr;\n PhysMemoryRange *pr;\n \n if (get_phys_addr(s, &paddr, addr, ACCESS_CODE)) {\n s->pending_tval = addr;\n s->pending_exception = CAUSE_FETCH_PAGE_FAULT;\n return -1;\n }\n pr = get_phys_mem_range(s->mem_map, paddr);\n if (!pr || !pr->is_ram) {\n /* XXX: we only access to execute code from RAM */\n s->pending_tval = addr;\n s->pending_exception = CAUSE_FAULT_FETCH;\n return -1;\n }\n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n ptr = pr->phys_mem + (uintptr_t)(paddr - pr->addr);\n s->tlb_code[tlb_idx].vaddr = addr & ~PG_MASK;\n s->tlb_code[tlb_idx].mem_addend = (uintptr_t)ptr - addr;\n *pptr = ptr;\n return 0;\n}\n\n/* addr must be aligned */\nstatic inline __exception int target_read_insn_u16(RISCVCPUState *s, uint16_t *pinsn,\n target_ulong addr)\n{\n uint32_t tlb_idx;\n uint8_t *ptr;\n \n tlb_idx = (addr >> PG_SHIFT) & (TLB_SIZE - 1);\n if (likely(s->tlb_code[tlb_idx].vaddr == (addr & ~PG_MASK))) {\n ptr = (uint8_t *)(s->tlb_code[tlb_idx].mem_addend +\n (uintptr_t)addr);\n } else {\n if (target_read_insn_slow(s, &ptr, addr))\n return -1;\n }\n *pinsn = *(uint16_t *)ptr;\n return 0;\n}\n\nstatic void tlb_init(RISCVCPUState *s)\n{\n int i;\n \n for(i = 0; i < TLB_SIZE; i++) {\n s->tlb_read[i].vaddr = -1;\n s->tlb_write[i].vaddr = -1;\n s->tlb_code[i].vaddr = -1;\n }\n}\n\nstatic void tlb_flush_all(RISCVCPUState *s)\n{\n tlb_init(s);\n}\n\nstatic void tlb_flush_vaddr(RISCVCPUState *s, target_ulong vaddr)\n{\n tlb_flush_all(s);\n}\n\n/* XXX: inefficient but not critical as long as it is seldom used */\nstatic void glue(riscv_cpu_flush_tlb_write_range_ram,\n MAX_XLEN)(RISCVCPUState *s,\n uint8_t *ram_ptr, size_t ram_size)\n{\n uint8_t *ptr, *ram_end;\n int i;\n \n ram_end = ram_ptr + ram_size;\n for(i = 0; i < TLB_SIZE; i++) {\n if (s->tlb_write[i].vaddr != -1) {\n ptr = (uint8_t *)(s->tlb_write[i].mem_addend +\n (uintptr_t)s->tlb_write[i].vaddr);\n if (ptr >= ram_ptr && ptr < ram_end) {\n s->tlb_write[i].vaddr = -1;\n }\n }\n }\n}\n\n\n#define SSTATUS_MASK0 (MSTATUS_UIE | MSTATUS_SIE | \\\n MSTATUS_UPIE | MSTATUS_SPIE | \\\n MSTATUS_SPP | \\\n MSTATUS_FS | MSTATUS_XS | \\\n MSTATUS_SUM | MSTATUS_MXR)\n#if MAX_XLEN >= 64\n#define SSTATUS_MASK (SSTATUS_MASK0 | MSTATUS_UXL_MASK)\n#else\n#define SSTATUS_MASK SSTATUS_MASK0\n#endif\n\n\n#define MSTATUS_MASK (MSTATUS_UIE | MSTATUS_SIE | MSTATUS_MIE | \\\n MSTATUS_UPIE | MSTATUS_SPIE | MSTATUS_MPIE | \\\n MSTATUS_SPP | MSTATUS_MPP | \\\n MSTATUS_FS | \\\n MSTATUS_MPRV | MSTATUS_SUM | MSTATUS_MXR)\n\n/* cycle and insn counters */\n#define COUNTEREN_MASK ((1 << 0) | (1 << 2))\n\n/* return the complete mstatus with the SD bit */\nstatic target_ulong get_mstatus(RISCVCPUState *s, target_ulong mask)\n{\n target_ulong val;\n BOOL sd;\n val = s->mstatus | (s->fs << MSTATUS_FS_SHIFT);\n val &= mask;\n sd = ((val & MSTATUS_FS) == MSTATUS_FS) |\n ((val & MSTATUS_XS) == MSTATUS_XS);\n if (sd)\n val |= (target_ulong)1 << (s->cur_xlen - 1);\n return val;\n}\n \nstatic int get_base_from_xlen(int xlen)\n{\n if (xlen == 32)\n return 1;\n else if (xlen == 64)\n return 2;\n else\n return 3;\n}\n\nstatic void set_mstatus(RISCVCPUState *s, target_ulong val)\n{\n target_ulong mod, mask;\n \n /* flush the TLBs if change of MMU config */\n mod = s->mstatus ^ val;\n if ((mod & (MSTATUS_MPRV | MSTATUS_SUM | MSTATUS_MXR)) != 0 ||\n ((s->mstatus & MSTATUS_MPRV) && (mod & MSTATUS_MPP) != 0)) {\n tlb_flush_all(s);\n }\n s->fs = (val >> MSTATUS_FS_SHIFT) & 3;\n\n mask = MSTATUS_MASK & ~MSTATUS_FS;\n#if MAX_XLEN >= 64\n {\n int uxl, sxl;\n uxl = (val >> MSTATUS_UXL_SHIFT) & 3;\n if (uxl >= 1 && uxl <= get_base_from_xlen(MAX_XLEN))\n mask |= MSTATUS_UXL_MASK;\n sxl = (val >> MSTATUS_UXL_SHIFT) & 3;\n if (sxl >= 1 && sxl <= get_base_from_xlen(MAX_XLEN))\n mask |= MSTATUS_SXL_MASK;\n }\n#endif\n s->mstatus = (s->mstatus & ~mask) | (val & mask);\n}\n\n/* return -1 if invalid CSR. 0 if OK. 'will_write' indicate that the\n csr will be written after (used for CSR access check) */\nstatic int csr_read(RISCVCPUState *s, target_ulong *pval, uint32_t csr,\n BOOL will_write)\n{\n target_ulong val;\n\n if (((csr & 0xc00) == 0xc00) && will_write)\n return -1; /* read-only CSR */\n if (s->priv < ((csr >> 8) & 3))\n return -1; /* not enough priviledge */\n \n switch(csr) {\n#if FLEN > 0\n case 0x001: /* fflags */\n if (s->fs == 0)\n return -1;\n val = s->fflags;\n break;\n case 0x002: /* frm */\n if (s->fs == 0)\n return -1;\n val = s->frm;\n break;\n case 0x003:\n if (s->fs == 0)\n return -1;\n val = s->fflags | (s->frm << 5);\n break;\n#endif\n case 0xc00: /* ucycle */\n case 0xc02: /* uinstret */\n {\n uint32_t counteren;\n if (s->priv < PRV_M) {\n if (s->priv < PRV_S)\n counteren = s->scounteren;\n else\n counteren = s->mcounteren;\n if (((counteren >> (csr & 0x1f)) & 1) == 0)\n goto invalid_csr;\n }\n }\n val = (int64_t)s->insn_counter;\n break;\n case 0xc80: /* mcycleh */\n case 0xc82: /* minstreth */\n if (s->cur_xlen != 32)\n goto invalid_csr;\n {\n uint32_t counteren;\n if (s->priv < PRV_M) {\n if (s->priv < PRV_S)\n counteren = s->scounteren;\n else\n counteren = s->mcounteren;\n if (((counteren >> (csr & 0x1f)) & 1) == 0)\n goto invalid_csr;\n }\n }\n val = s->insn_counter >> 32;\n break;\n \n case 0x100:\n val = get_mstatus(s, SSTATUS_MASK);\n break;\n case 0x104: /* sie */\n val = s->mie & s->mideleg;\n break;\n case 0x105:\n val = s->stvec;\n break;\n case 0x106:\n val = s->scounteren;\n break;\n case 0x140:\n val = s->sscratch;\n break;\n case 0x141:\n val = s->sepc;\n break;\n case 0x142:\n val = s->scause;\n break;\n case 0x143:\n val = s->stval;\n break;\n case 0x144: /* sip */\n val = s->mip & s->mideleg;\n break;\n case 0x180:\n val = s->satp;\n break;\n case 0x300:\n val = get_mstatus(s, (target_ulong)-1);\n break;\n case 0x301:\n val = s->misa;\n val |= (target_ulong)s->mxl << (s->cur_xlen - 2);\n break;\n case 0x302:\n val = s->medeleg;\n break;\n case 0x303:\n val = s->mideleg;\n break;\n case 0x304:\n val = s->mie;\n break;\n case 0x305:\n val = s->mtvec;\n break;\n case 0x306:\n val = s->mcounteren;\n break;\n case 0x340:\n val = s->mscratch;\n break;\n case 0x341:\n val = s->mepc;\n break;\n case 0x342:\n val = s->mcause;\n break;\n case 0x343:\n val = s->mtval;\n break;\n case 0x344:\n val = s->mip;\n break;\n case 0xb00: /* mcycle */\n case 0xb02: /* minstret */\n val = (int64_t)s->insn_counter;\n break;\n case 0xb80: /* mcycleh */\n case 0xb82: /* minstreth */\n if (s->cur_xlen != 32)\n goto invalid_csr;\n val = s->insn_counter >> 32;\n break;\n case 0xf14:\n val = s->mhartid;\n break;\n default:\n invalid_csr:\n#ifdef DUMP_INVALID_CSR\n /* the 'time' counter is usually emulated */\n if (csr != 0xc01 && csr != 0xc81) {\n printf(\"csr_read: invalid CSR=0x%x\\n\", csr);\n }\n#endif\n *pval = 0;\n return -1;\n }\n *pval = val;\n return 0;\n}\n\n#if FLEN > 0\nstatic void set_frm(RISCVCPUState *s, unsigned int val)\n{\n if (val >= 5)\n val = 0;\n s->frm = val;\n}\n\n/* return -1 if invalid roundind mode */\nstatic int get_insn_rm(RISCVCPUState *s, unsigned int rm)\n{\n if (rm == 7)\n return s->frm;\n if (rm >= 5)\n return -1;\n else\n return rm;\n}\n#endif\n\n/* return -1 if invalid CSR, 0 if OK, 1 if the interpreter loop must be\n exited (e.g. XLEN was modified), 2 if TLBs have been flushed. */\nstatic int csr_write(RISCVCPUState *s, uint32_t csr, target_ulong val)\n{\n target_ulong mask;\n\n#if defined(DUMP_CSR)\n printf(\"csr_write: csr=0x%03x val=0x\", csr);\n print_target_ulong(val);\n printf(\"\\n\");\n#endif\n switch(csr) {\n#if FLEN > 0\n case 0x001: /* fflags */\n s->fflags = val & 0x1f;\n s->fs = 3;\n break;\n case 0x002: /* frm */\n set_frm(s, val & 7);\n s->fs = 3;\n break;\n case 0x003: /* fcsr */\n set_frm(s, (val >> 5) & 7);\n s->fflags = val & 0x1f;\n s->fs = 3;\n break;\n#endif\n case 0x100: /* sstatus */\n set_mstatus(s, (s->mstatus & ~SSTATUS_MASK) | (val & SSTATUS_MASK));\n break;\n case 0x104: /* sie */\n mask = s->mideleg;\n s->mie = (s->mie & ~mask) | (val & mask);\n break;\n case 0x105:\n s->stvec = val & ~3;\n break;\n case 0x106:\n s->scounteren = val & COUNTEREN_MASK;\n break;\n case 0x140:\n s->sscratch = val;\n break;\n case 0x141:\n s->sepc = val & ~1;\n break;\n case 0x142:\n s->scause = val;\n break;\n case 0x143:\n s->stval = val;\n break;\n case 0x144: /* sip */\n mask = s->mideleg;\n s->mip = (s->mip & ~mask) | (val & mask);\n break;\n case 0x180:\n /* no ASID implemented */\n#if MAX_XLEN == 32\n {\n int new_mode;\n new_mode = (val >> 31) & 1;\n s->satp = (val & (((target_ulong)1 << 22) - 1)) |\n (new_mode << 31);\n }\n#else\n {\n int mode, new_mode;\n mode = s->satp >> 60;\n new_mode = (val >> 60) & 0xf;\n if (new_mode == 0 || (new_mode >= 8 && new_mode <= 9))\n mode = new_mode;\n s->satp = (val & (((uint64_t)1 << 44) - 1)) |\n ((uint64_t)mode << 60);\n }\n#endif\n tlb_flush_all(s);\n return 2;\n \n case 0x300:\n set_mstatus(s, val);\n break;\n case 0x301: /* misa */\n#if MAX_XLEN >= 64\n {\n int new_mxl;\n new_mxl = (val >> (s->cur_xlen - 2)) & 3;\n if (new_mxl >= 1 && new_mxl <= get_base_from_xlen(MAX_XLEN)) {\n /* Note: misa is only modified in M level, so cur_xlen\n = 2^(mxl + 4) */\n if (s->mxl != new_mxl) {\n s->mxl = new_mxl;\n s->cur_xlen = 1 << (new_mxl + 4);\n return 1;\n }\n }\n }\n#endif\n break;\n case 0x302:\n mask = (1 << (CAUSE_STORE_PAGE_FAULT + 1)) - 1;\n s->medeleg = (s->medeleg & ~mask) | (val & mask);\n break;\n case 0x303:\n mask = MIP_SSIP | MIP_STIP | MIP_SEIP;\n s->mideleg = (s->mideleg & ~mask) | (val & mask);\n break;\n case 0x304:\n mask = MIP_MSIP | MIP_MTIP | MIP_SSIP | MIP_STIP | MIP_SEIP;\n s->mie = (s->mie & ~mask) | (val & mask);\n break;\n case 0x305:\n s->mtvec = val & ~3;\n break;\n case 0x306:\n s->mcounteren = val & COUNTEREN_MASK;\n break;\n case 0x340:\n s->mscratch = val;\n break;\n case 0x341:\n s->mepc = val & ~1;\n break;\n case 0x342:\n s->mcause = val;\n break;\n case 0x343:\n s->mtval = val;\n break;\n case 0x344:\n mask = MIP_SSIP | MIP_STIP;\n s->mip = (s->mip & ~mask) | (val & mask);\n break;\n default:\n#ifdef DUMP_INVALID_CSR\n printf(\"csr_write: invalid CSR=0x%x\\n\", csr);\n#endif\n return -1;\n }\n return 0;\n}\n\nstatic void set_priv(RISCVCPUState *s, int priv)\n{\n if (s->priv != priv) {\n tlb_flush_all(s);\n#if MAX_XLEN >= 64\n /* change the current xlen */\n {\n int mxl;\n if (priv == PRV_S)\n mxl = (s->mstatus >> MSTATUS_SXL_SHIFT) & 3;\n else if (priv == PRV_U)\n mxl = (s->mstatus >> MSTATUS_UXL_SHIFT) & 3;\n else\n mxl = s->mxl;\n s->cur_xlen = 1 << (4 + mxl);\n }\n#endif\n s->priv = priv;\n }\n}\n\nstatic void raise_exception2(RISCVCPUState *s, uint32_t cause,\n target_ulong tval)\n{\n BOOL deleg;\n target_ulong causel;\n \n#if defined(DUMP_EXCEPTIONS) || defined(DUMP_MMU_EXCEPTIONS) || defined(DUMP_INTERRUPTS)\n {\n int flag;\n flag = 0;\n#ifdef DUMP_MMU_EXCEPTIONS\n if (cause == CAUSE_FAULT_FETCH ||\n cause == CAUSE_FAULT_LOAD ||\n cause == CAUSE_FAULT_STORE ||\n cause == CAUSE_FETCH_PAGE_FAULT ||\n cause == CAUSE_LOAD_PAGE_FAULT ||\n cause == CAUSE_STORE_PAGE_FAULT)\n flag = 1;\n#endif\n#ifdef DUMP_INTERRUPTS\n flag |= (cause & CAUSE_INTERRUPT) != 0;\n#endif\n#ifdef DUMP_EXCEPTIONS\n flag = 1;\n flag = (cause & CAUSE_INTERRUPT) == 0;\n if (cause == CAUSE_SUPERVISOR_ECALL || cause == CAUSE_ILLEGAL_INSTRUCTION)\n flag = 0;\n#endif\n if (flag) {\n log_printf(\"raise_exception: cause=0x%08x tval=0x\", cause);\n#ifdef CONFIG_LOGFILE\n fprint_target_ulong(log_file, tval);\n#else\n print_target_ulong(tval);\n#endif\n log_printf(\"\\n\");\n dump_regs(s);\n }\n }\n#endif\n\n if (s->priv <= PRV_S) {\n /* delegate the exception to the supervisor priviledge */\n if (cause & CAUSE_INTERRUPT)\n deleg = (s->mideleg >> (cause & (MAX_XLEN - 1))) & 1;\n else\n deleg = (s->medeleg >> cause) & 1;\n } else {\n deleg = 0;\n }\n \n causel = cause & 0x7fffffff;\n if (cause & CAUSE_INTERRUPT)\n causel |= (target_ulong)1 << (s->cur_xlen - 1);\n \n if (deleg) {\n s->scause = causel;\n s->sepc = s->pc;\n s->stval = tval;\n s->mstatus = (s->mstatus & ~MSTATUS_SPIE) |\n (((s->mstatus >> s->priv) & 1) << MSTATUS_SPIE_SHIFT);\n s->mstatus = (s->mstatus & ~MSTATUS_SPP) |\n (s->priv << MSTATUS_SPP_SHIFT);\n s->mstatus &= ~MSTATUS_SIE;\n set_priv(s, PRV_S);\n s->pc = s->stvec;\n } else {\n s->mcause = causel;\n s->mepc = s->pc;\n s->mtval = tval;\n s->mstatus = (s->mstatus & ~MSTATUS_MPIE) |\n (((s->mstatus >> s->priv) & 1) << MSTATUS_MPIE_SHIFT);\n s->mstatus = (s->mstatus & ~MSTATUS_MPP) |\n (s->priv << MSTATUS_MPP_SHIFT);\n s->mstatus &= ~MSTATUS_MIE;\n set_priv(s, PRV_M);\n s->pc = s->mtvec;\n }\n}\n\nstatic void raise_exception(RISCVCPUState *s, uint32_t cause)\n{\n raise_exception2(s, cause, 0);\n}\n\nstatic void handle_sret(RISCVCPUState *s)\n{\n int spp, spie;\n spp = (s->mstatus >> MSTATUS_SPP_SHIFT) & 1;\n /* set the IE state to previous IE state */\n spie = (s->mstatus >> MSTATUS_SPIE_SHIFT) & 1;\n s->mstatus = (s->mstatus & ~(1 << spp)) |\n (spie << spp);\n /* set SPIE to 1 */\n s->mstatus |= MSTATUS_SPIE;\n /* set SPP to U */\n s->mstatus &= ~MSTATUS_SPP;\n set_priv(s, spp);\n s->pc = s->sepc;\n}\n\nstatic void handle_mret(RISCVCPUState *s)\n{\n int mpp, mpie;\n mpp = (s->mstatus >> MSTATUS_MPP_SHIFT) & 3;\n /* set the IE state to previous IE state */\n mpie = (s->mstatus >> MSTATUS_MPIE_SHIFT) & 1;\n s->mstatus = (s->mstatus & ~(1 << mpp)) |\n (mpie << mpp);\n /* set MPIE to 1 */\n s->mstatus |= MSTATUS_MPIE;\n /* set MPP to U */\n s->mstatus &= ~MSTATUS_MPP;\n set_priv(s, mpp);\n s->pc = s->mepc;\n}\n\nstatic inline uint32_t get_pending_irq_mask(RISCVCPUState *s)\n{\n uint32_t pending_ints, enabled_ints;\n\n pending_ints = s->mip & s->mie;\n if (pending_ints == 0)\n return 0;\n\n enabled_ints = 0;\n switch(s->priv) {\n case PRV_M:\n if (s->mstatus & MSTATUS_MIE)\n enabled_ints = ~s->mideleg;\n break;\n case PRV_S:\n enabled_ints = ~s->mideleg;\n if (s->mstatus & MSTATUS_SIE)\n enabled_ints |= s->mideleg;\n break;\n default:\n case PRV_U:\n enabled_ints = -1;\n break;\n }\n return pending_ints & enabled_ints;\n}\n\nstatic __exception int raise_interrupt(RISCVCPUState *s)\n{\n uint32_t mask;\n int irq_num;\n\n mask = get_pending_irq_mask(s);\n if (mask == 0)\n return 0;\n irq_num = ctz32(mask);\n raise_exception(s, irq_num | CAUSE_INTERRUPT);\n return -1;\n}\n\nstatic inline int32_t sext(int32_t val, int n)\n{\n return (val << (32 - n)) >> (32 - n);\n}\n\nstatic inline uint32_t get_field1(uint32_t val, int src_pos, \n int dst_pos, int dst_pos_max)\n{\n int mask;\n assert(dst_pos_max >= dst_pos);\n mask = ((1 << (dst_pos_max - dst_pos + 1)) - 1) << dst_pos;\n if (dst_pos >= src_pos)\n return (val << (dst_pos - src_pos)) & mask;\n else\n return (val >> (src_pos - dst_pos)) & mask;\n}\n\n#define XLEN 32\n#include \"riscv_cpu_template.h\"\n\n#if MAX_XLEN >= 64\n#define XLEN 64\n#include \"riscv_cpu_template.h\"\n#endif\n\n#if MAX_XLEN >= 128\n#define XLEN 128\n#include \"riscv_cpu_template.h\"\n#endif\n\nstatic void glue(riscv_cpu_interp, MAX_XLEN)(RISCVCPUState *s, int n_cycles)\n{\n#ifdef USE_GLOBAL_STATE\n s = &riscv_cpu_global_state;\n#endif\n uint64_t timeout;\n\n timeout = s->insn_counter + n_cycles;\n while (!s->power_down_flag &&\n (int)(timeout - s->insn_counter) > 0) {\n n_cycles = timeout - s->insn_counter;\n switch(s->cur_xlen) {\n case 32:\n riscv_cpu_interp_x32(s, n_cycles);\n break;\n#if MAX_XLEN >= 64\n case 64:\n riscv_cpu_interp_x64(s, n_cycles);\n break;\n#endif\n#if MAX_XLEN >= 128\n case 128:\n riscv_cpu_interp_x128(s, n_cycles);\n break;\n#endif\n default:\n abort();\n }\n }\n}\n\n/* Note: the value is not accurate when called in riscv_cpu_interp() */\nstatic uint64_t glue(riscv_cpu_get_cycles, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->insn_counter;\n}\n\nstatic void glue(riscv_cpu_set_mip, MAX_XLEN)(RISCVCPUState *s, uint32_t mask)\n{\n s->mip |= mask;\n /* exit from power down if an interrupt is pending */\n if (s->power_down_flag && (s->mip & s->mie) != 0)\n s->power_down_flag = FALSE;\n}\n\nstatic void glue(riscv_cpu_reset_mip, MAX_XLEN)(RISCVCPUState *s, uint32_t mask)\n{\n s->mip &= ~mask;\n}\n\nstatic uint32_t glue(riscv_cpu_get_mip, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->mip;\n}\n\nstatic BOOL glue(riscv_cpu_get_power_down, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->power_down_flag;\n}\n\nstatic RISCVCPUState *glue(riscv_cpu_init, MAX_XLEN)(PhysMemoryMap *mem_map)\n{\n RISCVCPUState *s;\n \n#ifdef USE_GLOBAL_STATE\n s = &riscv_cpu_global_state;\n#else\n s = mallocz(sizeof(*s));\n#endif\n s->common.class_ptr = &glue(riscv_cpu_class, MAX_XLEN);\n s->mem_map = mem_map;\n s->pc = 0x1000;\n s->priv = PRV_M;\n s->cur_xlen = MAX_XLEN;\n s->mxl = get_base_from_xlen(MAX_XLEN);\n s->mstatus = ((uint64_t)s->mxl << MSTATUS_UXL_SHIFT) |\n ((uint64_t)s->mxl << MSTATUS_SXL_SHIFT);\n s->misa |= MCPUID_SUPER | MCPUID_USER | MCPUID_I | MCPUID_M | MCPUID_A;\n#if FLEN >= 32\n s->misa |= MCPUID_F;\n#endif\n#if FLEN >= 64\n s->misa |= MCPUID_D;\n#endif\n#if FLEN >= 128\n s->misa |= MCPUID_Q;\n#endif\n#ifdef CONFIG_EXT_C\n s->misa |= MCPUID_C;\n#endif\n tlb_init(s);\n return s;\n}\n\nstatic void glue(riscv_cpu_end, MAX_XLEN)(RISCVCPUState *s)\n{\n#ifdef USE_GLOBAL_STATE\n free(s);\n#endif\n}\n\nstatic uint32_t glue(riscv_cpu_get_misa, MAX_XLEN)(RISCVCPUState *s)\n{\n return s->misa;\n}\n\nconst RISCVCPUClass glue(riscv_cpu_class, MAX_XLEN) = {\n glue(riscv_cpu_init, MAX_XLEN),\n glue(riscv_cpu_end, MAX_XLEN),\n glue(riscv_cpu_interp, MAX_XLEN),\n glue(riscv_cpu_get_cycles, MAX_XLEN),\n glue(riscv_cpu_set_mip, MAX_XLEN),\n glue(riscv_cpu_reset_mip, MAX_XLEN),\n glue(riscv_cpu_get_mip, MAX_XLEN),\n glue(riscv_cpu_get_power_down, MAX_XLEN),\n glue(riscv_cpu_get_misa, MAX_XLEN),\n glue(riscv_cpu_flush_tlb_write_range_ram, MAX_XLEN),\n};\n\n#if CONFIG_RISCV_MAX_XLEN == MAX_XLEN\nRISCVCPUState *riscv_cpu_init(PhysMemoryMap *mem_map, int max_xlen)\n{\n const RISCVCPUClass *c;\n switch(max_xlen) {\n /* with emscripten we compile a single CPU */\n#if defined(EMSCRIPTEN)\n case MAX_XLEN:\n c = &glue(riscv_cpu_class, MAX_XLEN);\n break;\n#else\n case 32:\n c = &riscv_cpu_class32;\n break;\n case 64:\n c = &riscv_cpu_class64;\n break;\n#if CONFIG_RISCV_MAX_XLEN == 128\n case 128:\n c = &riscv_cpu_class128;\n break;\n#endif\n#endif /* !EMSCRIPTEN */\n default:\n return NULL;\n }\n return c->riscv_cpu_init(mem_map);\n}\n#endif /* CONFIG_RISCV_MAX_XLEN == MAX_XLEN */\n\n"], ["/linuxpdf/tinyemu/jsemu.c", "/*\n * JS emulator main\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n#include \"list.h\"\n#include \"fbuf.h\"\n\nint virt_machine_run(void *opaque);\n\n/* provided in lib.js */\nextern void console_write(void *opaque, const uint8_t *buf, int len);\nextern void console_get_size(int *pw, int *ph);\nextern void fb_refresh(void *opaque, void *data,\n int x, int y, int w, int h, int stride);\nextern void net_recv_packet(EthernetDevice *bs,\n const uint8_t *buf, int len);\n\nstatic uint8_t console_fifo[1024];\nstatic int console_fifo_windex;\nstatic int console_fifo_rindex;\nstatic int console_fifo_count;\nstatic BOOL console_resize_pending;\n\nstatic int global_width;\nstatic int global_height;\nstatic VirtMachine *global_vm;\nstatic BOOL global_carrier_state;\n\nstatic int console_read(void *opaque, uint8_t *buf, int len)\n{\n int out_len, l;\n len = min_int(len, console_fifo_count);\n console_fifo_count -= len;\n out_len = 0;\n while (len != 0) {\n l = min_int(len, sizeof(console_fifo) - console_fifo_rindex);\n memcpy(buf + out_len, console_fifo + console_fifo_rindex, l);\n len -= l;\n out_len += l;\n console_fifo_rindex += l;\n if (console_fifo_rindex == sizeof(console_fifo))\n console_fifo_rindex = 0;\n }\n return out_len;\n}\n\n/* called from JS */\nvoid console_queue_char(int c)\n{\n if (console_fifo_count < sizeof(console_fifo)) {\n console_fifo[console_fifo_windex] = c;\n if (++console_fifo_windex == sizeof(console_fifo))\n console_fifo_windex = 0;\n console_fifo_count++;\n }\n}\n\n/* called from JS */\nvoid display_key_event(int is_down, int key_code)\n{\n if (global_vm) {\n vm_send_key_event(global_vm, is_down, key_code);\n }\n}\n\n/* called from JS */\nstatic int mouse_last_x, mouse_last_y, mouse_last_buttons;\n\nvoid display_mouse_event(int dx, int dy, int buttons)\n{\n if (global_vm) {\n if (vm_mouse_is_absolute(global_vm) || 1) {\n dx = min_int(dx, global_width - 1);\n dy = min_int(dy, global_height - 1);\n dx = (dx * VIRTIO_INPUT_ABS_SCALE) / global_width;\n dy = (dy * VIRTIO_INPUT_ABS_SCALE) / global_height;\n } else {\n /* relative mouse is not supported */\n dx = 0;\n dy = 0;\n }\n mouse_last_x = dx;\n mouse_last_y = dy;\n mouse_last_buttons = buttons;\n vm_send_mouse_event(global_vm, dx, dy, 0, buttons);\n }\n}\n\n/* called from JS */\nvoid display_wheel_event(int dz)\n{\n if (global_vm) {\n vm_send_mouse_event(global_vm, mouse_last_x, mouse_last_y, dz,\n mouse_last_buttons);\n }\n}\n\n/* called from JS */\nvoid net_write_packet(const uint8_t *buf, int buf_len)\n{\n EthernetDevice *net = global_vm->net;\n if (net) {\n net->device_write_packet(net, buf, buf_len);\n }\n}\n\n/* called from JS */\nvoid net_set_carrier(BOOL carrier_state)\n{\n EthernetDevice *net;\n global_carrier_state = carrier_state;\n if (global_vm && global_vm->net) {\n net = global_vm->net;\n net->device_set_carrier(net, carrier_state);\n }\n}\n\nstatic void fb_refresh1(FBDevice *fb_dev, void *opaque,\n int x, int y, int w, int h)\n{\n int stride = fb_dev->stride;\n fb_refresh(opaque, fb_dev->fb_data + y * stride + x * 4, x, y, w, h,\n stride);\n}\n\nstatic CharacterDevice *console_init(void)\n{\n CharacterDevice *dev;\n console_resize_pending = TRUE;\n dev = mallocz(sizeof(*dev));\n dev->write_data = console_write;\n dev->read_data = console_read;\n return dev;\n}\n\ntypedef struct {\n VirtMachineParams *p;\n int ram_size;\n char *cmdline;\n BOOL has_network;\n char *pwd;\n} VMStartState;\n\nstatic void init_vm(void *arg);\nstatic void init_vm_fs(void *arg);\nstatic void init_vm_drive(void *arg);\n\nvoid vm_start(const char *url, int ram_size, const char *cmdline,\n const char *pwd, int width, int height, BOOL has_network)\n{\n VMStartState *s;\n\n s = mallocz(sizeof(*s));\n s->ram_size = ram_size;\n s->cmdline = strdup(cmdline);\n if (pwd)\n s->pwd = strdup(pwd);\n global_width = width;\n global_height = height;\n s->has_network = has_network;\n s->p = mallocz(sizeof(VirtMachineParams));\n virt_machine_set_defaults(s->p);\n virt_machine_load_config_file(s->p, url, init_vm_fs, s);\n}\n\nstatic void init_vm_fs(void *arg)\n{\n VMStartState *s = arg;\n VirtMachineParams *p = s->p;\n\n if (p->fs_count > 0) {\n assert(p->fs_count == 1);\n p->tab_fs[0].fs_dev = fs_net_init(p->tab_fs[0].filename,\n init_vm_drive, s);\n if (s->pwd) {\n fs_net_set_pwd(p->tab_fs[0].fs_dev, s->pwd);\n }\n } else {\n init_vm_drive(s);\n }\n}\n\nstatic void init_vm_drive(void *arg)\n{\n VMStartState *s = arg;\n VirtMachineParams *p = s->p;\n\n if (p->drive_count > 0) {\n assert(p->drive_count == 1);\n p->tab_drive[0].block_dev =\n block_device_init_http(p->tab_drive[0].filename,\n 131072,\n init_vm, s);\n } else {\n init_vm(s);\n }\n}\n\nstatic void init_vm(void *arg)\n{\n VMStartState *s = arg;\n VirtMachine *m;\n VirtMachineParams *p = s->p;\n int i;\n \n p->rtc_real_time = TRUE;\n p->ram_size = s->ram_size << 20;\n if (s->cmdline && s->cmdline[0] != '\\0') {\n vm_add_cmdline(s->p, s->cmdline);\n }\n\n if (global_width > 0 && global_height > 0) {\n /* enable graphic output if needed */\n if (!p->display_device)\n p->display_device = strdup(\"simplefb\");\n p->width = global_width;\n p->height = global_height;\n } else {\n p->console = console_init();\n }\n \n if (p->eth_count > 0 && !s->has_network) {\n /* remove the interfaces */\n for(i = 0; i < p->eth_count; i++) {\n free(p->tab_eth[i].ifname);\n free(p->tab_eth[i].driver);\n }\n p->eth_count = 0;\n }\n\n if (p->eth_count > 0) {\n EthernetDevice *net;\n int i;\n assert(p->eth_count == 1);\n net = mallocz(sizeof(EthernetDevice));\n net->mac_addr[0] = 0x02;\n for(i = 1; i < 6; i++)\n net->mac_addr[i] = (int)(emscripten_random() * 256);\n net->write_packet = net_recv_packet;\n net->opaque = NULL;\n p->tab_eth[0].net = net;\n }\n\n m = virt_machine_init(p);\n global_vm = m;\n\n virt_machine_free_config(s->p);\n\n if (m->net) {\n m->net->device_set_carrier(m->net, global_carrier_state);\n }\n \n free(s->p);\n free(s->cmdline);\n if (s->pwd) {\n memset(s->pwd, 0, strlen(s->pwd));\n free(s->pwd);\n }\n free(s);\n \n EM_ASM({\n start_machine_interval($0);\n }, m);\n}\n\n/* need to be long enough to hide the non zero delay of setTimeout(_, 0) */\n#define MAX_EXEC_TOTAL_CYCLE 100000\n#define MAX_EXEC_CYCLE 1000\n\n#define MAX_SLEEP_TIME 10 /* in ms */\n\nint virt_machine_run(void *opaque)\n{\n VirtMachine *m = opaque;\n int delay, i;\n FBDevice *fb_dev;\n \n if (m->console_dev && virtio_console_can_write_data(m->console_dev)) {\n uint8_t buf[128];\n int ret, len;\n len = virtio_console_get_write_len(m->console_dev);\n len = min_int(len, sizeof(buf));\n ret = m->console->read_data(m->console->opaque, buf, len);\n if (ret > 0)\n virtio_console_write_data(m->console_dev, buf, ret);\n if (console_resize_pending) {\n int w, h;\n console_get_size(&w, &h);\n virtio_console_resize_event(m->console_dev, w, h);\n console_resize_pending = FALSE;\n }\n }\n\n fb_dev = m->fb_dev;\n if (fb_dev) {\n /* refresh the display */\n fb_dev->refresh(fb_dev, fb_refresh1, NULL);\n }\n \n i = 0;\n for(;;) {\n /* wait for an event: the only asynchronous event is the RTC timer */\n delay = virt_machine_get_sleep_duration(m, MAX_SLEEP_TIME);\n if (delay != 0 || i >= MAX_EXEC_TOTAL_CYCLE / MAX_EXEC_CYCLE)\n break;\n virt_machine_interp(m, MAX_EXEC_CYCLE);\n i++;\n }\n return i * MAX_EXEC_CYCLE;\n \n /*\n if (delay == 0) {\n emscripten_async_call(virt_machine_run, m, 0);\n } else {\n emscripten_async_call(virt_machine_run, m, MAX_SLEEP_TIME);\n }\n */\n}\n\n"], ["/linuxpdf/tinyemu/slirp/slirp.c", "/*\n * libslirp glue\n *\n * Copyright (c) 2004-2008 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"slirp.h\"\n\n/* host loopback address */\nstruct in_addr loopback_addr;\n\n/* emulated hosts use the MAC addr 52:55:IP:IP:IP:IP */\nstatic const uint8_t special_ethaddr[6] = {\n 0x52, 0x55, 0x00, 0x00, 0x00, 0x00\n};\n\nstatic const uint8_t zero_ethaddr[6] = { 0, 0, 0, 0, 0, 0 };\n\n/* XXX: suppress those select globals */\nfd_set *global_readfds, *global_writefds, *global_xfds;\n\nu_int curtime;\nstatic u_int time_fasttimo, last_slowtimo;\nstatic int do_slowtimo;\n\nstatic struct in_addr dns_addr;\nstatic u_int dns_addr_time;\n\n#ifdef _WIN32\n\nint get_dns_addr(struct in_addr *pdns_addr)\n{\n FIXED_INFO *FixedInfo=NULL;\n ULONG BufLen;\n DWORD ret;\n IP_ADDR_STRING *pIPAddr;\n struct in_addr tmp_addr;\n\n if (dns_addr.s_addr != 0 && (curtime - dns_addr_time) < 1000) {\n *pdns_addr = dns_addr;\n return 0;\n }\n\n FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));\n BufLen = sizeof(FIXED_INFO);\n\n if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen)) {\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n FixedInfo = GlobalAlloc(GPTR, BufLen);\n }\n\n if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS) {\n printf(\"GetNetworkParams failed. ret = %08x\\n\", (u_int)ret );\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n return -1;\n }\n\n pIPAddr = &(FixedInfo->DnsServerList);\n inet_aton(pIPAddr->IpAddress.String, &tmp_addr);\n *pdns_addr = tmp_addr;\n dns_addr = tmp_addr;\n dns_addr_time = curtime;\n if (FixedInfo) {\n GlobalFree(FixedInfo);\n FixedInfo = NULL;\n }\n return 0;\n}\n\nstatic void winsock_cleanup(void)\n{\n WSACleanup();\n}\n\n#else\n\nstatic struct stat dns_addr_stat;\n\nint get_dns_addr(struct in_addr *pdns_addr)\n{\n char buff[512];\n char buff2[257];\n FILE *f;\n int found = 0;\n struct in_addr tmp_addr;\n\n if (dns_addr.s_addr != 0) {\n struct stat old_stat;\n if ((curtime - dns_addr_time) < 1000) {\n *pdns_addr = dns_addr;\n return 0;\n }\n old_stat = dns_addr_stat;\n if (stat(\"/etc/resolv.conf\", &dns_addr_stat) != 0)\n return -1;\n if ((dns_addr_stat.st_dev == old_stat.st_dev)\n && (dns_addr_stat.st_ino == old_stat.st_ino)\n && (dns_addr_stat.st_size == old_stat.st_size)\n && (dns_addr_stat.st_mtime == old_stat.st_mtime)) {\n *pdns_addr = dns_addr;\n return 0;\n }\n }\n\n f = fopen(\"/etc/resolv.conf\", \"r\");\n if (!f)\n return -1;\n\n#ifdef DEBUG\n lprint(\"IP address of your DNS(s): \");\n#endif\n while (fgets(buff, 512, f) != NULL) {\n if (sscanf(buff, \"nameserver%*[ \\t]%256s\", buff2) == 1) {\n if (!inet_aton(buff2, &tmp_addr))\n continue;\n /* If it's the first one, set it to dns_addr */\n if (!found) {\n *pdns_addr = tmp_addr;\n dns_addr = tmp_addr;\n dns_addr_time = curtime;\n }\n#ifdef DEBUG\n else\n lprint(\", \");\n#endif\n if (++found > 3) {\n#ifdef DEBUG\n lprint(\"(more)\");\n#endif\n break;\n }\n#ifdef DEBUG\n else\n lprint(\"%s\", inet_ntoa(tmp_addr));\n#endif\n }\n }\n fclose(f);\n if (!found)\n return -1;\n return 0;\n}\n\n#endif\n\nstatic void slirp_init_once(void)\n{\n static int initialized;\n#ifdef _WIN32\n WSADATA Data;\n#endif\n\n if (initialized) {\n return;\n }\n initialized = 1;\n\n#ifdef _WIN32\n WSAStartup(MAKEWORD(2,0), &Data);\n atexit(winsock_cleanup);\n#endif\n\n loopback_addr.s_addr = htonl(INADDR_LOOPBACK);\n}\n\nSlirp *slirp_init(int restricted, struct in_addr vnetwork,\n struct in_addr vnetmask, struct in_addr vhost,\n const char *vhostname, const char *tftp_path,\n const char *bootfile, struct in_addr vdhcp_start,\n struct in_addr vnameserver, void *opaque)\n{\n Slirp *slirp = mallocz(sizeof(Slirp));\n\n slirp_init_once();\n\n slirp->restricted = restricted;\n\n if_init(slirp);\n ip_init(slirp);\n\n /* Initialise mbufs *after* setting the MTU */\n m_init(slirp);\n\n slirp->vnetwork_addr = vnetwork;\n slirp->vnetwork_mask = vnetmask;\n slirp->vhost_addr = vhost;\n if (vhostname) {\n pstrcpy(slirp->client_hostname, sizeof(slirp->client_hostname),\n vhostname);\n }\n if (tftp_path) {\n slirp->tftp_prefix = strdup(tftp_path);\n }\n if (bootfile) {\n slirp->bootp_filename = strdup(bootfile);\n }\n slirp->vdhcp_startaddr = vdhcp_start;\n slirp->vnameserver_addr = vnameserver;\n\n slirp->opaque = opaque;\n\n return slirp;\n}\n\nvoid slirp_cleanup(Slirp *slirp)\n{\n free(slirp->tftp_prefix);\n free(slirp->bootp_filename);\n free(slirp);\n}\n\n#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)\n#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)\n#define UPD_NFDS(x) if (nfds < (x)) nfds = (x)\n\nvoid slirp_select_fill(Slirp *slirp, int *pnfds,\n fd_set *readfds, fd_set *writefds, fd_set *xfds)\n{\n struct socket *so, *so_next;\n int nfds;\n\n /* fail safe */\n global_readfds = NULL;\n global_writefds = NULL;\n global_xfds = NULL;\n\n nfds = *pnfds;\n\t/*\n\t * First, TCP sockets\n\t */\n\tdo_slowtimo = 0;\n\n\t{\n\t\t/*\n\t\t * *_slowtimo needs calling if there are IP fragments\n\t\t * in the fragment queue, or there are TCP connections active\n\t\t */\n\t\tdo_slowtimo |= ((slirp->tcb.so_next != &slirp->tcb) ||\n\t\t (&slirp->ipq.ip_link != slirp->ipq.ip_link.next));\n\n\t\tfor (so = slirp->tcb.so_next; so != &slirp->tcb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * See if we need a tcp_fasttimo\n\t\t\t */\n\t\t\tif (time_fasttimo == 0 && so->so_tcpcb->t_flags & TF_DELACK)\n\t\t\t time_fasttimo = curtime; /* Flag when we want a fasttimo */\n\n\t\t\t/*\n\t\t\t * NOFDREF can include still connecting to local-host,\n\t\t\t * newly socreated() sockets etc. Don't want to select these.\n\t \t\t */\n\t\t\tif (so->so_state & SS_NOFDREF || so->s == -1)\n\t\t\t continue;\n\n\t\t\t/*\n\t\t\t * Set for reading sockets which are accepting\n\t\t\t */\n\t\t\tif (so->so_state & SS_FACCEPTCONN) {\n FD_SET(so->s, readfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for writing sockets which are connecting\n\t\t\t */\n\t\t\tif (so->so_state & SS_ISFCONNECTING) {\n\t\t\t\tFD_SET(so->s, writefds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for writing if we are connected, can send more, and\n\t\t\t * we have something to send\n\t\t\t */\n\t\t\tif (CONN_CANFSEND(so) && so->so_rcv.sb_cc) {\n\t\t\t\tFD_SET(so->s, writefds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set for reading (and urgent data) if we are connected, can\n\t\t\t * receive more, and we have room for it XXX /2 ?\n\t\t\t */\n\t\t\tif (CONN_CANFRCV(so) && (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2))) {\n\t\t\t\tFD_SET(so->s, readfds);\n\t\t\t\tFD_SET(so->s, xfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * UDP sockets\n\t\t */\n\t\tfor (so = slirp->udb.so_next; so != &slirp->udb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * See if it's timed out\n\t\t\t */\n\t\t\tif (so->so_expire) {\n\t\t\t\tif (so->so_expire <= curtime) {\n\t\t\t\t\tudp_detach(so);\n\t\t\t\t\tcontinue;\n\t\t\t\t} else\n\t\t\t\t\tdo_slowtimo = 1; /* Let socket expire */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * When UDP packets are received from over the\n\t\t\t * link, they're sendto()'d straight away, so\n\t\t\t * no need for setting for writing\n\t\t\t * Limit the number of packets queued by this session\n\t\t\t * to 4. Note that even though we try and limit this\n\t\t\t * to 4 packets, the session could have more queued\n\t\t\t * if the packets needed to be fragmented\n\t\t\t * (XXX <= 4 ?)\n\t\t\t */\n\t\t\tif ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4) {\n\t\t\t\tFD_SET(so->s, readfds);\n\t\t\t\tUPD_NFDS(so->s);\n\t\t\t}\n\t\t}\n\t}\n\n *pnfds = nfds;\n}\n\nvoid slirp_select_poll(Slirp *slirp,\n fd_set *readfds, fd_set *writefds, fd_set *xfds,\n int select_error)\n{\n struct socket *so, *so_next;\n int ret;\n\n global_readfds = readfds;\n global_writefds = writefds;\n global_xfds = xfds;\n\n curtime = os_get_time_ms();\n\n {\n\t/*\n\t * See if anything has timed out\n\t */\n\t\tif (time_fasttimo && ((curtime - time_fasttimo) >= 2)) {\n\t\t\ttcp_fasttimo(slirp);\n\t\t\ttime_fasttimo = 0;\n\t\t}\n\t\tif (do_slowtimo && ((curtime - last_slowtimo) >= 499)) {\n\t\t\tip_slowtimo(slirp);\n\t\t\ttcp_slowtimo(slirp);\n\t\t\tlast_slowtimo = curtime;\n\t\t}\n\n\t/*\n\t * Check sockets\n\t */\n\tif (!select_error) {\n\t\t/*\n\t\t * Check TCP sockets\n\t\t */\n\t\tfor (so = slirp->tcb.so_next; so != &slirp->tcb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\t/*\n\t\t\t * FD_ISSET is meaningless on these sockets\n\t\t\t * (and they can crash the program)\n\t\t\t */\n\t\t\tif (so->so_state & SS_NOFDREF || so->s == -1)\n\t\t\t continue;\n\n\t\t\t/*\n\t\t\t * Check for URG data\n\t\t\t * This will soread as well, so no need to\n\t\t\t * test for readfds below if this succeeds\n\t\t\t */\n\t\t\tif (FD_ISSET(so->s, xfds))\n\t\t\t sorecvoob(so);\n\t\t\t/*\n\t\t\t * Check sockets for reading\n\t\t\t */\n\t\t\telse if (FD_ISSET(so->s, readfds)) {\n\t\t\t\t/*\n\t\t\t\t * Check for incoming connections\n\t\t\t\t */\n\t\t\t\tif (so->so_state & SS_FACCEPTCONN) {\n\t\t\t\t\ttcp_connect(so);\n\t\t\t\t\tcontinue;\n\t\t\t\t} /* else */\n\t\t\t\tret = soread(so);\n\n\t\t\t\t/* Output it if we read something */\n\t\t\t\tif (ret > 0)\n\t\t\t\t tcp_output(sototcpcb(so));\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Check sockets for writing\n\t\t\t */\n\t\t\tif (FD_ISSET(so->s, writefds)) {\n\t\t\t /*\n\t\t\t * Check for non-blocking, still-connecting sockets\n\t\t\t */\n\t\t\t if (so->so_state & SS_ISFCONNECTING) {\n\t\t\t /* Connected */\n\t\t\t so->so_state &= ~SS_ISFCONNECTING;\n\n\t\t\t ret = send(so->s, (const void *) &ret, 0, 0);\n\t\t\t if (ret < 0) {\n\t\t\t /* XXXXX Must fix, zero bytes is a NOP */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\t errno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t\tcontinue;\n\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\t\t\t }\n\t\t\t /* else so->so_state &= ~SS_ISFCONNECTING; */\n\n\t\t\t /*\n\t\t\t * Continue tcp_input\n\t\t\t */\n\t\t\t tcp_input((struct mbuf *)NULL, sizeof(struct ip), so);\n\t\t\t /* continue; */\n\t\t\t } else\n\t\t\t ret = sowrite(so);\n\t\t\t /*\n\t\t\t * XXXXX If we wrote something (a lot), there\n\t\t\t * could be a need for a window update.\n\t\t\t * In the worst case, the remote will send\n\t\t\t * a window probe to get things going again\n\t\t\t */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Probe a still-connecting, non-blocking socket\n\t\t\t * to check if it's still alive\n\t \t \t */\n#ifdef PROBE_CONN\n\t\t\tif (so->so_state & SS_ISFCONNECTING) {\n\t\t\t ret = recv(so->s, (char *)&ret, 0,0);\n\n\t\t\t if (ret < 0) {\n\t\t\t /* XXX */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\terrno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t continue; /* Still connecting, continue */\n\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\n\t\t\t /* tcp_input will take care of it */\n\t\t\t } else {\n\t\t\t ret = send(so->s, &ret, 0,0);\n\t\t\t if (ret < 0) {\n\t\t\t /* XXX */\n\t\t\t if (errno == EAGAIN || errno == EWOULDBLOCK ||\n\t\t\t\t errno == EINPROGRESS || errno == ENOTCONN)\n\t\t\t\tcontinue;\n\t\t\t /* else failed */\n\t\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t\t so->so_state |= SS_NOFDREF;\n\t\t\t } else\n\t\t\t so->so_state &= ~SS_ISFCONNECTING;\n\n\t\t\t }\n\t\t\t tcp_input((struct mbuf *)NULL, sizeof(struct ip),so);\n\t\t\t} /* SS_ISFCONNECTING */\n#endif\n\t\t}\n\n\t\t/*\n\t\t * Now UDP sockets.\n\t\t * Incoming packets are sent straight away, they're not buffered.\n\t\t * Incoming UDP data isn't buffered either.\n\t\t */\n\t\tfor (so = slirp->udb.so_next; so != &slirp->udb;\n\t\t so = so_next) {\n\t\t\tso_next = so->so_next;\n\n\t\t\tif (so->s != -1 && FD_ISSET(so->s, readfds)) {\n sorecvfrom(so);\n }\n\t\t}\n\t}\n\n\t/*\n\t * See if we can start outputting\n\t */\n\tif (slirp->if_queued) {\n\t if_start(slirp);\n\t}\n }\n\n\t/* clear global file descriptor sets.\n\t * these reside on the stack in vl.c\n\t * so they're unusable if we're not in\n\t * slirp_select_fill or slirp_select_poll.\n\t */\n\t global_readfds = NULL;\n\t global_writefds = NULL;\n\t global_xfds = NULL;\n}\n\n#define ETH_ALEN 6\n#define ETH_HLEN 14\n\n#define ETH_P_IP\t0x0800\t\t/* Internet Protocol packet\t*/\n#define ETH_P_ARP\t0x0806\t\t/* Address Resolution packet\t*/\n\n#define\tARPOP_REQUEST\t1\t\t/* ARP request\t\t\t*/\n#define\tARPOP_REPLY\t2\t\t/* ARP reply\t\t\t*/\n\nstruct ethhdr\n{\n\tunsigned char\th_dest[ETH_ALEN];\t/* destination eth addr\t*/\n\tunsigned char\th_source[ETH_ALEN];\t/* source ether addr\t*/\n\tunsigned short\th_proto;\t\t/* packet type ID field\t*/\n};\n\nstruct arphdr\n{\n\tunsigned short\tar_hrd;\t\t/* format of hardware address\t*/\n\tunsigned short\tar_pro;\t\t/* format of protocol address\t*/\n\tunsigned char\tar_hln;\t\t/* length of hardware address\t*/\n\tunsigned char\tar_pln;\t\t/* length of protocol address\t*/\n\tunsigned short\tar_op;\t\t/* ARP opcode (command)\t\t*/\n\n\t /*\n\t *\t Ethernet looks like this : This bit is variable sized however...\n\t */\n\tunsigned char\t\tar_sha[ETH_ALEN];\t/* sender hardware address\t*/\n\tuint32_t\t\tar_sip;\t\t\t/* sender IP address\t\t*/\n\tunsigned char\t\tar_tha[ETH_ALEN];\t/* target hardware address\t*/\n\tuint32_t\t\tar_tip\t;\t\t/* target IP address\t\t*/\n} __attribute__((packed));\n\nstatic void arp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)\n{\n struct ethhdr *eh = (struct ethhdr *)pkt;\n struct arphdr *ah = (struct arphdr *)(pkt + ETH_HLEN);\n uint8_t arp_reply[max(ETH_HLEN + sizeof(struct arphdr), 64)];\n struct ethhdr *reh = (struct ethhdr *)arp_reply;\n struct arphdr *rah = (struct arphdr *)(arp_reply + ETH_HLEN);\n int ar_op;\n struct ex_list *ex_ptr;\n\n ar_op = ntohs(ah->ar_op);\n switch(ar_op) {\n case ARPOP_REQUEST:\n if ((ah->ar_tip & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n if (ah->ar_tip == slirp->vnameserver_addr.s_addr ||\n ah->ar_tip == slirp->vhost_addr.s_addr)\n goto arp_ok;\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_addr.s_addr == ah->ar_tip)\n goto arp_ok;\n }\n return;\n arp_ok:\n memset(arp_reply, 0, sizeof(arp_reply));\n /* XXX: make an ARP request to have the client address */\n memcpy(slirp->client_ethaddr, eh->h_source, ETH_ALEN);\n\n /* ARP request for alias/dns mac address */\n memcpy(reh->h_dest, pkt + ETH_ALEN, ETH_ALEN);\n memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);\n memcpy(&reh->h_source[2], &ah->ar_tip, 4);\n reh->h_proto = htons(ETH_P_ARP);\n\n rah->ar_hrd = htons(1);\n rah->ar_pro = htons(ETH_P_IP);\n rah->ar_hln = ETH_ALEN;\n rah->ar_pln = 4;\n rah->ar_op = htons(ARPOP_REPLY);\n memcpy(rah->ar_sha, reh->h_source, ETH_ALEN);\n rah->ar_sip = ah->ar_tip;\n memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);\n rah->ar_tip = ah->ar_sip;\n slirp_output(slirp->opaque, arp_reply, sizeof(arp_reply));\n }\n break;\n case ARPOP_REPLY:\n /* reply to request of client mac address ? */\n if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN) &&\n ah->ar_sip == slirp->client_ipaddr.s_addr) {\n memcpy(slirp->client_ethaddr, ah->ar_sha, ETH_ALEN);\n }\n break;\n default:\n break;\n }\n}\n\nvoid slirp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)\n{\n struct mbuf *m;\n int proto;\n\n if (pkt_len < ETH_HLEN)\n return;\n\n proto = ntohs(*(uint16_t *)(pkt + 12));\n switch(proto) {\n case ETH_P_ARP:\n arp_input(slirp, pkt, pkt_len);\n break;\n case ETH_P_IP:\n m = m_get(slirp);\n if (!m)\n return;\n /* Note: we add to align the IP header */\n if (M_FREEROOM(m) < pkt_len + 2) {\n m_inc(m, pkt_len + 2);\n }\n m->m_len = pkt_len + 2;\n memcpy(m->m_data + 2, pkt, pkt_len);\n\n m->m_data += 2 + ETH_HLEN;\n m->m_len -= 2 + ETH_HLEN;\n\n ip_input(m);\n break;\n default:\n break;\n }\n}\n\n/* output the IP packet to the ethernet device */\nvoid if_encap(Slirp *slirp, const uint8_t *ip_data, int ip_data_len)\n{\n uint8_t buf[1600];\n struct ethhdr *eh = (struct ethhdr *)buf;\n\n if (ip_data_len + ETH_HLEN > sizeof(buf))\n return;\n \n if (!memcmp(slirp->client_ethaddr, zero_ethaddr, ETH_ALEN)) {\n uint8_t arp_req[ETH_HLEN + sizeof(struct arphdr)];\n struct ethhdr *reh = (struct ethhdr *)arp_req;\n struct arphdr *rah = (struct arphdr *)(arp_req + ETH_HLEN);\n const struct ip *iph = (const struct ip *)ip_data;\n\n /* If the client addr is not known, there is no point in\n sending the packet to it. Normally the sender should have\n done an ARP request to get its MAC address. Here we do it\n in place of sending the packet and we hope that the sender\n will retry sending its packet. */\n memset(reh->h_dest, 0xff, ETH_ALEN);\n memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);\n memcpy(&reh->h_source[2], &slirp->vhost_addr, 4);\n reh->h_proto = htons(ETH_P_ARP);\n rah->ar_hrd = htons(1);\n rah->ar_pro = htons(ETH_P_IP);\n rah->ar_hln = ETH_ALEN;\n rah->ar_pln = 4;\n rah->ar_op = htons(ARPOP_REQUEST);\n /* source hw addr */\n memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN - 4);\n memcpy(&rah->ar_sha[2], &slirp->vhost_addr, 4);\n /* source IP */\n rah->ar_sip = slirp->vhost_addr.s_addr;\n /* target hw addr (none) */\n memset(rah->ar_tha, 0, ETH_ALEN);\n /* target IP */\n rah->ar_tip = iph->ip_dst.s_addr;\n slirp->client_ipaddr = iph->ip_dst;\n slirp_output(slirp->opaque, arp_req, sizeof(arp_req));\n } else {\n memcpy(eh->h_dest, slirp->client_ethaddr, ETH_ALEN);\n memcpy(eh->h_source, special_ethaddr, ETH_ALEN - 4);\n /* XXX: not correct */\n memcpy(&eh->h_source[2], &slirp->vhost_addr, 4);\n eh->h_proto = htons(ETH_P_IP);\n memcpy(buf + sizeof(struct ethhdr), ip_data, ip_data_len);\n slirp_output(slirp->opaque, buf, ip_data_len + ETH_HLEN);\n }\n}\n\n/* Drop host forwarding rule, return 0 if found. */\nint slirp_remove_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,\n int host_port)\n{\n struct socket *so;\n struct socket *head = (is_udp ? &slirp->udb : &slirp->tcb);\n struct sockaddr_in addr;\n int port = htons(host_port);\n socklen_t addr_len;\n\n for (so = head->so_next; so != head; so = so->so_next) {\n addr_len = sizeof(addr);\n if ((so->so_state & SS_HOSTFWD) &&\n getsockname(so->s, (struct sockaddr *)&addr, &addr_len) == 0 &&\n addr.sin_addr.s_addr == host_addr.s_addr &&\n addr.sin_port == port) {\n close(so->s);\n sofree(so);\n return 0;\n }\n }\n\n return -1;\n}\n\nint slirp_add_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,\n int host_port, struct in_addr guest_addr, int guest_port)\n{\n if (!guest_addr.s_addr) {\n guest_addr = slirp->vdhcp_startaddr;\n }\n if (is_udp) {\n if (!udp_listen(slirp, host_addr.s_addr, htons(host_port),\n guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))\n return -1;\n } else {\n if (!tcp_listen(slirp, host_addr.s_addr, htons(host_port),\n guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))\n return -1;\n }\n return 0;\n}\n\nint slirp_add_exec(Slirp *slirp, int do_pty, const void *args,\n struct in_addr *guest_addr, int guest_port)\n{\n if (!guest_addr->s_addr) {\n guest_addr->s_addr = slirp->vnetwork_addr.s_addr |\n (htonl(0x0204) & ~slirp->vnetwork_mask.s_addr);\n }\n if ((guest_addr->s_addr & slirp->vnetwork_mask.s_addr) !=\n slirp->vnetwork_addr.s_addr ||\n guest_addr->s_addr == slirp->vhost_addr.s_addr ||\n guest_addr->s_addr == slirp->vnameserver_addr.s_addr) {\n return -1;\n }\n return add_exec(&slirp->exec_list, do_pty, (char *)args, *guest_addr,\n htons(guest_port));\n}\n\nssize_t slirp_send(struct socket *so, const void *buf, size_t len, int flags)\n{\n#if 0\n if (so->s == -1 && so->extra) {\n\t\tqemu_chr_write(so->extra, buf, len);\n\t\treturn len;\n\t}\n#endif\n\treturn send(so->s, buf, len, flags);\n}\n\nstatic struct socket *\nslirp_find_ctl_socket(Slirp *slirp, struct in_addr guest_addr, int guest_port)\n{\n struct socket *so;\n\n for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {\n if (so->so_faddr.s_addr == guest_addr.s_addr &&\n htons(so->so_fport) == guest_port) {\n return so;\n }\n }\n return NULL;\n}\n\nsize_t slirp_socket_can_recv(Slirp *slirp, struct in_addr guest_addr,\n int guest_port)\n{\n\tstruct iovec iov[2];\n\tstruct socket *so;\n\n\tso = slirp_find_ctl_socket(slirp, guest_addr, guest_port);\n\n\tif (!so || so->so_state & SS_NOFDREF)\n\t\treturn 0;\n\n\tif (!CONN_CANFRCV(so) || so->so_snd.sb_cc >= (so->so_snd.sb_datalen/2))\n\t\treturn 0;\n\n\treturn sopreprbuf(so, iov, NULL);\n}\n\nvoid slirp_socket_recv(Slirp *slirp, struct in_addr guest_addr, int guest_port,\n const uint8_t *buf, int size)\n{\n int ret;\n struct socket *so = slirp_find_ctl_socket(slirp, guest_addr, guest_port);\n\n if (!so)\n return;\n\n ret = soreadbuf(so, (const char *)buf, size);\n\n if (ret > 0)\n tcp_output(sototcpcb(so));\n}\n"], ["/linuxpdf/tinyemu/json.c", "/*\n * Pseudo JSON parser\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"json.h\"\n#include \"fs_utils.h\"\n\nstatic JSONValue parse_string(const char **pp)\n{\n char buf[4096], *q;\n const char *p;\n int c, h;\n \n q = buf;\n p = *pp;\n p++;\n for(;;) {\n c = *p++;\n if (c == '\\0' || c == '\\n') {\n return json_error_new(\"unterminated string\");\n } else if (c == '\\\"') {\n break;\n } else if (c == '\\\\') {\n c = *p++;\n switch(c) {\n case '\\'':\n case '\\\"':\n case '\\\\':\n goto add_char;\n case 'n':\n c = '\\n';\n goto add_char;\n case 'r':\n c = '\\r';\n goto add_char;\n case 't':\n c = '\\t';\n goto add_char;\n case 'x':\n h = from_hex(*p++);\n if (h < 0)\n return json_error_new(\"invalig hex digit\");\n c = h << 4;\n h = from_hex(*p++);\n if (h < 0)\n return json_error_new(\"invalig hex digit\");\n c |= h;\n goto add_char;\n default:\n return json_error_new(\"unknown escape code\");\n }\n } else {\n add_char:\n if (q >= buf + sizeof(buf) - 1)\n return json_error_new(\"string too long\");\n *q++ = c;\n }\n }\n *q = '\\0';\n *pp = p;\n return json_string_new(buf);\n}\n\nstatic JSONProperty *json_object_get2(JSONObject *obj, const char *name)\n{\n JSONProperty *f;\n int i;\n for(i = 0; i < obj->len; i++) {\n f = &obj->props[i];\n if (!strcmp(f->name.u.str->data, name))\n return f;\n }\n return NULL;\n}\n\nJSONValue json_object_get(JSONValue val, const char *name)\n{\n JSONProperty *f;\n JSONObject *obj;\n \n if (val.type != JSON_OBJ)\n return json_undefined_new();\n obj = val.u.obj;\n f = json_object_get2(obj, name);\n if (!f)\n return json_undefined_new();\n return f->value;\n}\n\nint json_object_set(JSONValue val, const char *name, JSONValue prop_val)\n{\n JSONObject *obj;\n JSONProperty *f;\n int new_size;\n \n if (val.type != JSON_OBJ)\n return -1;\n obj = val.u.obj;\n f = json_object_get2(obj, name);\n if (f) {\n json_free(f->value);\n f->value = prop_val;\n } else {\n if (obj->len >= obj->size) {\n new_size = max_int(obj->len + 1, obj->size * 3 / 2);\n obj->props = realloc(obj->props, new_size * sizeof(JSONProperty));\n obj->size = new_size;\n }\n f = &obj->props[obj->len++];\n f->name = json_string_new(name);\n f->value = prop_val;\n }\n return 0;\n}\n\nJSONValue json_array_get(JSONValue val, unsigned int idx)\n{\n JSONArray *array;\n \n if (val.type != JSON_ARRAY)\n return json_undefined_new();\n array = val.u.array;\n if (idx < array->len) {\n return array->tab[idx];\n } else {\n return json_undefined_new();\n }\n}\n\nint json_array_set(JSONValue val, unsigned int idx, JSONValue prop_val)\n{\n JSONArray *array;\n int new_size;\n \n if (val.type != JSON_ARRAY)\n return -1;\n array = val.u.array;\n if (idx < array->len) {\n json_free(array->tab[idx]);\n array->tab[idx] = prop_val;\n } else if (idx == array->len) {\n if (array->len >= array->size) {\n new_size = max_int(array->len + 1, array->size * 3 / 2);\n array->tab = realloc(array->tab, new_size * sizeof(JSONValue));\n array->size = new_size;\n }\n array->tab[array->len++] = prop_val;\n } else {\n return -1;\n }\n return 0;\n}\n\nconst char *json_get_str(JSONValue val)\n{\n if (val.type != JSON_STR)\n return NULL;\n return val.u.str->data;\n}\n\nconst char *json_get_error(JSONValue val)\n{\n if (val.type != JSON_EXCEPTION)\n return NULL;\n return val.u.str->data;\n}\n\nJSONValue json_string_new2(const char *str, int len)\n{\n JSONValue val;\n JSONString *str1;\n\n str1 = malloc(sizeof(JSONString) + len + 1);\n str1->len = len;\n memcpy(str1->data, str, len + 1);\n val.type = JSON_STR;\n val.u.str = str1;\n return val;\n}\n\nJSONValue json_string_new(const char *str)\n{\n return json_string_new2(str, strlen(str));\n}\n\nJSONValue __attribute__((format(printf, 1, 2))) json_error_new(const char *fmt, ...)\n{\n JSONValue val;\n va_list ap;\n char buf[256];\n \n va_start(ap, fmt);\n vsnprintf(buf, sizeof(buf), fmt, ap);\n va_end(ap);\n val = json_string_new(buf);\n val.type = JSON_EXCEPTION;\n return val;\n}\n\nJSONValue json_object_new(void)\n{\n JSONValue val;\n JSONObject *obj;\n obj = mallocz(sizeof(JSONObject));\n val.type = JSON_OBJ;\n val.u.obj = obj;\n return val;\n}\n\nJSONValue json_array_new(void)\n{\n JSONValue val;\n JSONArray *array;\n array = mallocz(sizeof(JSONArray));\n val.type = JSON_ARRAY;\n val.u.array = array;\n return val;\n}\n\nvoid json_free(JSONValue val)\n{\n switch(val.type) {\n case JSON_STR:\n case JSON_EXCEPTION:\n free(val.u.str);\n break;\n case JSON_INT:\n case JSON_BOOL:\n case JSON_NULL:\n case JSON_UNDEFINED:\n break;\n case JSON_ARRAY:\n {\n JSONArray *array = val.u.array;\n int i;\n \n for(i = 0; i < array->len; i++) {\n json_free(array->tab[i]);\n }\n free(array);\n }\n break;\n case JSON_OBJ:\n {\n JSONObject *obj = val.u.obj;\n JSONProperty *f;\n int i;\n \n for(i = 0; i < obj->len; i++) {\n f = &obj->props[i];\n json_free(f->name);\n json_free(f->value);\n }\n free(obj);\n }\n break;\n default:\n abort();\n }\n}\n\nstatic void skip_spaces(const char **pp)\n{\n const char *p;\n p = *pp;\n for(;;) {\n if (isspace(*p)) {\n p++;\n } else if (p[0] == '/' && p[1] == '/') {\n p += 2;\n while (*p != '\\0' && *p != '\\n')\n p++;\n } else if (p[0] == '/' && p[1] == '*') {\n p += 2;\n while (*p != '\\0' && (p[0] != '*' || p[1] != '/'))\n p++;\n if (*p != '\\0')\n p += 2;\n } else {\n break;\n }\n }\n *pp = p;\n}\n\nstatic inline BOOL is_ident_first(int c)\n{\n return (c >= 'a' && c <= 'z') ||\n (c >= 'A' && c <= 'Z') ||\n c == '_' || c == '$';\n}\n\nstatic int parse_ident(char *buf, int buf_size, const char **pp)\n{\n char *q;\n const char *p;\n p = *pp;\n q = buf;\n *q++ = *p++; /* first char is already tested */\n while (is_ident_first(*p) || isdigit(*p)) {\n if ((q - buf) >= buf_size - 1)\n return -1;\n *q++ = *p++;\n }\n *pp = p;\n *q = '\\0';\n return 0;\n}\n\nJSONValue json_parse_value2(const char **pp)\n{\n char buf[128];\n const char *p;\n JSONValue val, val1, tag;\n \n p = *pp;\n skip_spaces(&p);\n if (*p == '\\0') {\n return json_error_new(\"unexpected end of file\");\n }\n if (isdigit(*p)) {\n val = json_int32_new(strtol(p, (char **)&p, 0));\n } else if (*p == '\"') {\n val = parse_string(&p);\n } else if (*p == '{') {\n p++;\n val = json_object_new();\n for(;;) {\n skip_spaces(&p);\n if (*p == '}') {\n p++;\n break;\n }\n if (*p == '\"') {\n tag = parse_string(&p);\n if (json_is_error(tag))\n return tag;\n } else if (is_ident_first(*p)) {\n if (parse_ident(buf, sizeof(buf), &p) < 0)\n goto invalid_prop;\n tag = json_string_new(buf);\n } else {\n goto invalid_prop;\n }\n // printf(\"property: %s\\n\", json_get_str(tag));\n if (tag.u.str->len == 0) {\n invalid_prop:\n return json_error_new(\"Invalid property name\");\n }\n skip_spaces(&p);\n if (*p != ':') {\n return json_error_new(\"':' expected\");\n }\n p++;\n \n val1 = json_parse_value2(&p);\n json_object_set(val, tag.u.str->data, val1);\n\n skip_spaces(&p);\n if (*p == ',') {\n p++;\n } else if (*p != '}') {\n return json_error_new(\"expecting ',' or '}'\");\n }\n }\n } else if (*p == '[') {\n int idx;\n \n p++;\n val = json_array_new();\n idx = 0;\n for(;;) {\n skip_spaces(&p);\n if (*p == ']') {\n p++;\n break;\n }\n val1 = json_parse_value2(&p);\n json_array_set(val, idx++, val1);\n\n skip_spaces(&p);\n if (*p == ',') {\n p++;\n } else if (*p != ']') {\n return json_error_new(\"expecting ',' or ']'\");\n }\n }\n } else if (is_ident_first(*p)) {\n if (parse_ident(buf, sizeof(buf), &p) < 0)\n goto unknown_id;\n if (!strcmp(buf, \"null\")) {\n val = json_null_new();\n } else if (!strcmp(buf, \"true\")) {\n val = json_bool_new(TRUE);\n } else if (!strcmp(buf, \"false\")) {\n val = json_bool_new(FALSE);\n } else {\n unknown_id:\n return json_error_new(\"unknown identifier: '%s'\", buf);\n }\n } else {\n return json_error_new(\"unexpected character\");\n }\n *pp = p;\n return val;\n}\n\nJSONValue json_parse_value(const char *p)\n{\n JSONValue val;\n val = json_parse_value2(&p); \n if (json_is_error(val))\n return val;\n skip_spaces(&p);\n if (*p != '\\0') {\n json_free(val);\n return json_error_new(\"unexpected characters at the end\");\n }\n return val;\n}\n\nJSONValue json_parse_value_len(const char *p, int len)\n{\n char *str;\n JSONValue val;\n str = malloc(len + 1);\n memcpy(str, p, len);\n str[len] = '\\0';\n val = json_parse_value(str);\n free(str);\n return val;\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_subr.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_subr.c\t8.1 (Berkeley) 6/10/93\n * tcp_subr.c,v 1.5 1994/10/08 22:39:58 phk Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n/* patchable/settable parameters for tcp */\n/* Don't do rfc1323 performance enhancements */\n#define TCP_DO_RFC1323 0\n\n/*\n * Tcp initialization\n */\nvoid\ntcp_init(Slirp *slirp)\n{\n slirp->tcp_iss = 1;\t\t/* wrong */\n slirp->tcb.so_next = slirp->tcb.so_prev = &slirp->tcb;\n slirp->tcp_last_so = &slirp->tcb;\n}\n\n/*\n * Create template to be used to send tcp packets on a connection.\n * Call after host entry created, fills\n * in a skeletal tcp/ip header, minimizing the amount of work\n * necessary when the connection is used.\n */\nvoid\ntcp_template(struct tcpcb *tp)\n{\n\tstruct socket *so = tp->t_socket;\n\tregister struct tcpiphdr *n = &tp->t_template;\n\n\tn->ti_mbuf = NULL;\n\tn->ti_x1 = 0;\n\tn->ti_pr = IPPROTO_TCP;\n\tn->ti_len = htons(sizeof (struct tcpiphdr) - sizeof (struct ip));\n\tn->ti_src = so->so_faddr;\n\tn->ti_dst = so->so_laddr;\n\tn->ti_sport = so->so_fport;\n\tn->ti_dport = so->so_lport;\n\n\tn->ti_seq = 0;\n\tn->ti_ack = 0;\n\tn->ti_x2 = 0;\n\tn->ti_off = 5;\n\tn->ti_flags = 0;\n\tn->ti_win = 0;\n\tn->ti_sum = 0;\n\tn->ti_urp = 0;\n}\n\n/*\n * Send a single message to the TCP at address specified by\n * the given TCP/IP header. If m == 0, then we make a copy\n * of the tcpiphdr at ti and send directly to the addressed host.\n * This is used to force keep alive messages out using the TCP\n * template for a connection tp->t_template. If flags are given\n * then we send a message back to the TCP which originated the\n * segment ti, and discard the mbuf containing it and any other\n * attached mbufs.\n *\n * In any case the ack and sequence number of the transmitted\n * segment are as specified by the parameters.\n */\nvoid\ntcp_respond(struct tcpcb *tp, struct tcpiphdr *ti, struct mbuf *m,\n tcp_seq ack, tcp_seq seq, int flags)\n{\n\tregister int tlen;\n\tint win = 0;\n\n\tDEBUG_CALL(\"tcp_respond\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"ti = %lx\", (long)ti);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"ack = %u\", ack);\n\tDEBUG_ARG(\"seq = %u\", seq);\n\tDEBUG_ARG(\"flags = %x\", flags);\n\n\tif (tp)\n\t\twin = sbspace(&tp->t_socket->so_rcv);\n if (m == NULL) {\n\t\tif ((m = m_get(tp->t_socket->slirp)) == NULL)\n\t\t\treturn;\n\t\ttlen = 0;\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\t*mtod(m, struct tcpiphdr *) = *ti;\n\t\tti = mtod(m, struct tcpiphdr *);\n\t\tflags = TH_ACK;\n\t} else {\n\t\t/*\n\t\t * ti points into m so the next line is just making\n\t\t * the mbuf point to ti\n\t\t */\n\t\tm->m_data = (caddr_t)ti;\n\n\t\tm->m_len = sizeof (struct tcpiphdr);\n\t\ttlen = 0;\n#define xchg(a,b,type) { type t; t=a; a=b; b=t; }\n\t\txchg(ti->ti_dst.s_addr, ti->ti_src.s_addr, uint32_t);\n\t\txchg(ti->ti_dport, ti->ti_sport, uint16_t);\n#undef xchg\n\t}\n\tti->ti_len = htons((u_short)(sizeof (struct tcphdr) + tlen));\n\ttlen += sizeof (struct tcpiphdr);\n\tm->m_len = tlen;\n\n ti->ti_mbuf = NULL;\n\tti->ti_x1 = 0;\n\tti->ti_seq = htonl(seq);\n\tti->ti_ack = htonl(ack);\n\tti->ti_x2 = 0;\n\tti->ti_off = sizeof (struct tcphdr) >> 2;\n\tti->ti_flags = flags;\n\tif (tp)\n\t\tti->ti_win = htons((uint16_t) (win >> tp->rcv_scale));\n\telse\n\t\tti->ti_win = htons((uint16_t)win);\n\tti->ti_urp = 0;\n\tti->ti_sum = 0;\n\tti->ti_sum = cksum(m, tlen);\n\t((struct ip *)ti)->ip_len = tlen;\n\n\tif(flags & TH_RST)\n\t ((struct ip *)ti)->ip_ttl = MAXTTL;\n\telse\n\t ((struct ip *)ti)->ip_ttl = IPDEFTTL;\n\n\t(void) ip_output((struct socket *)0, m);\n}\n\n/*\n * Create a new TCP control block, making an\n * empty reassembly queue and hooking it to the argument\n * protocol control block.\n */\nstruct tcpcb *\ntcp_newtcpcb(struct socket *so)\n{\n\tregister struct tcpcb *tp;\n\n\ttp = (struct tcpcb *)malloc(sizeof(*tp));\n\tif (tp == NULL)\n\t\treturn ((struct tcpcb *)0);\n\n\tmemset((char *) tp, 0, sizeof(struct tcpcb));\n\ttp->seg_next = tp->seg_prev = (struct tcpiphdr*)tp;\n\ttp->t_maxseg = TCP_MSS;\n\n\ttp->t_flags = TCP_DO_RFC1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;\n\ttp->t_socket = so;\n\n\t/*\n\t * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no\n\t * rtt estimate. Set rttvar so that srtt + 2 * rttvar gives\n\t * reasonable initial retransmit time.\n\t */\n\ttp->t_srtt = TCPTV_SRTTBASE;\n\ttp->t_rttvar = TCPTV_SRTTDFLT << 2;\n\ttp->t_rttmin = TCPTV_MIN;\n\n\tTCPT_RANGESET(tp->t_rxtcur,\n\t ((TCPTV_SRTTBASE >> 2) + (TCPTV_SRTTDFLT << 2)) >> 1,\n\t TCPTV_MIN, TCPTV_REXMTMAX);\n\n\ttp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;\n\ttp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;\n\ttp->t_state = TCPS_CLOSED;\n\n\tso->so_tcpcb = tp;\n\n\treturn (tp);\n}\n\n/*\n * Drop a TCP connection, reporting\n * the specified error. If connection is synchronized,\n * then send a RST to peer.\n */\nstruct tcpcb *tcp_drop(struct tcpcb *tp, int err)\n{\n\tDEBUG_CALL(\"tcp_drop\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"errno = %d\", errno);\n\n\tif (TCPS_HAVERCVDSYN(tp->t_state)) {\n\t\ttp->t_state = TCPS_CLOSED;\n\t\t(void) tcp_output(tp);\n\t}\n\treturn (tcp_close(tp));\n}\n\n/*\n * Close a TCP control block:\n *\tdiscard all space held by the tcp\n *\tdiscard internet protocol block\n *\twake up any sleepers\n */\nstruct tcpcb *\ntcp_close(struct tcpcb *tp)\n{\n\tregister struct tcpiphdr *t;\n\tstruct socket *so = tp->t_socket;\n\tSlirp *slirp = so->slirp;\n\tregister struct mbuf *m;\n\n\tDEBUG_CALL(\"tcp_close\");\n\tDEBUG_ARG(\"tp = %lx\", (long )tp);\n\n\t/* free the reassembly queue, if any */\n\tt = tcpfrag_list_first(tp);\n\twhile (!tcpfrag_list_end(t, tp)) {\n\t\tt = tcpiphdr_next(t);\n\t\tm = tcpiphdr_prev(t)->ti_mbuf;\n\t\tremque(tcpiphdr2qlink(tcpiphdr_prev(t)));\n\t\tm_freem(m);\n\t}\n\tfree(tp);\n so->so_tcpcb = NULL;\n\t/* clobber input socket cache if we're closing the cached connection */\n\tif (so == slirp->tcp_last_so)\n\t\tslirp->tcp_last_so = &slirp->tcb;\n\tclosesocket(so->s);\n\tsbfree(&so->so_rcv);\n\tsbfree(&so->so_snd);\n\tsofree(so);\n\treturn ((struct tcpcb *)0);\n}\n\n/*\n * TCP protocol interface to socket abstraction.\n */\n\n/*\n * User issued close, and wish to trail through shutdown states:\n * if never received SYN, just forget it. If got a SYN from peer,\n * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.\n * If already got a FIN from peer, then almost done; go to LAST_ACK\n * state. In all other cases, have already sent FIN to peer (e.g.\n * after PRU_SHUTDOWN), and just have to play tedious game waiting\n * for peer to send FIN or not respond to keep-alives, etc.\n * We can let the user exit from the close as soon as the FIN is acked.\n */\nvoid\ntcp_sockclosed(struct tcpcb *tp)\n{\n\n\tDEBUG_CALL(\"tcp_sockclosed\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\n\tswitch (tp->t_state) {\n\n\tcase TCPS_CLOSED:\n\tcase TCPS_LISTEN:\n\tcase TCPS_SYN_SENT:\n\t\ttp->t_state = TCPS_CLOSED;\n\t\ttp = tcp_close(tp);\n\t\tbreak;\n\n\tcase TCPS_SYN_RECEIVED:\n\tcase TCPS_ESTABLISHED:\n\t\ttp->t_state = TCPS_FIN_WAIT_1;\n\t\tbreak;\n\n\tcase TCPS_CLOSE_WAIT:\n\t\ttp->t_state = TCPS_LAST_ACK;\n\t\tbreak;\n\t}\n\tif (tp)\n\t\ttcp_output(tp);\n}\n\n/*\n * Connect to a host on the Internet\n * Called by tcp_input\n * Only do a connect, the tcp fields will be set in tcp_input\n * return 0 if there's a result of the connect,\n * else return -1 means we're still connecting\n * The return value is almost always -1 since the socket is\n * nonblocking. Connect returns after the SYN is sent, and does\n * not wait for ACK+SYN.\n */\nint tcp_fconnect(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n int ret=0;\n\n DEBUG_CALL(\"tcp_fconnect\");\n DEBUG_ARG(\"so = %lx\", (long )so);\n\n if( (ret = so->s = os_socket(AF_INET,SOCK_STREAM,0)) >= 0) {\n int opt, s=so->s;\n struct sockaddr_in addr;\n\n fd_nonblock(s);\n opt = 1;\n setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(opt ));\n opt = 1;\n setsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(opt ));\n\n addr.sin_family = AF_INET;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n /* It's an alias */\n if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\tif (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n } else {\n\taddr.sin_addr = loopback_addr;\n }\n } else\n addr.sin_addr = so->so_faddr;\n addr.sin_port = so->so_fport;\n\n DEBUG_MISC((dfd, \" connect()ing, addr.sin_port=%d, \"\n\t\t\"addr.sin_addr.s_addr=%.16s\\n\",\n\t\tntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));\n /* We don't care what port we get */\n ret = connect(s,(struct sockaddr *)&addr,sizeof (addr));\n\n /*\n * If it's not in progress, it failed, so we just return 0,\n * without clearing SS_NOFDREF\n */\n soisfconnecting(so);\n }\n\n return(ret);\n}\n\n/*\n * Accept the socket and connect to the local-host\n *\n * We have a problem. The correct thing to do would be\n * to first connect to the local-host, and only if the\n * connection is accepted, then do an accept() here.\n * But, a) we need to know who's trying to connect\n * to the socket to be able to SYN the local-host, and\n * b) we are already connected to the foreign host by\n * the time it gets to accept(), so... We simply accept\n * here and SYN the local-host.\n */\nvoid\ntcp_connect(struct socket *inso)\n{\n\tSlirp *slirp = inso->slirp;\n\tstruct socket *so;\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\tstruct tcpcb *tp;\n\tint s, opt;\n\n\tDEBUG_CALL(\"tcp_connect\");\n\tDEBUG_ARG(\"inso = %lx\", (long)inso);\n\n\t/*\n\t * If it's an SS_ACCEPTONCE socket, no need to socreate()\n\t * another socket, just use the accept() socket.\n\t */\n\tif (inso->so_state & SS_FACCEPTONCE) {\n\t\t/* FACCEPTONCE already have a tcpcb */\n\t\tso = inso;\n\t} else {\n\t\tif ((so = socreate(slirp)) == NULL) {\n\t\t\t/* If it failed, get rid of the pending connection */\n\t\t\tclosesocket(accept(inso->s,(struct sockaddr *)&addr,&addrlen));\n\t\t\treturn;\n\t\t}\n\t\tif (tcp_attach(so) < 0) {\n\t\t\tfree(so); /* NOT sofree */\n\t\t\treturn;\n\t\t}\n\t\tso->so_laddr = inso->so_laddr;\n\t\tso->so_lport = inso->so_lport;\n\t}\n\n\t(void) tcp_mss(sototcpcb(so), 0);\n\n\tif ((s = accept(inso->s,(struct sockaddr *)&addr,&addrlen)) < 0) {\n\t\ttcp_close(sototcpcb(so)); /* This will sofree() as well */\n\t\treturn;\n\t}\n\tfd_nonblock(s);\n\topt = 1;\n\tsetsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\topt = 1;\n\tsetsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\topt = 1;\n\tsetsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&opt,sizeof(int));\n\n\tso->so_fport = addr.sin_port;\n\tso->so_faddr = addr.sin_addr;\n\t/* Translate connections from localhost to the real hostname */\n\tif (so->so_faddr.s_addr == 0 || so->so_faddr.s_addr == loopback_addr.s_addr)\n\t so->so_faddr = slirp->vhost_addr;\n\n\t/* Close the accept() socket, set right state */\n\tif (inso->so_state & SS_FACCEPTONCE) {\n\t\tclosesocket(so->s); /* If we only accept once, close the accept() socket */\n\t\tso->so_state = SS_NOFDREF; /* Don't select it yet, even though we have an FD */\n\t\t\t\t\t /* if it's not FACCEPTONCE, it's already NOFDREF */\n\t}\n\tso->s = s;\n\tso->so_state |= SS_INCOMING;\n\n\tso->so_iptos = tcp_tos(so);\n\ttp = sototcpcb(so);\n\n\ttcp_template(tp);\n\n\ttp->t_state = TCPS_SYN_SENT;\n\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\ttp->iss = slirp->tcp_iss;\n\tslirp->tcp_iss += TCP_ISSINCR/2;\n\ttcp_sendseqinit(tp);\n\ttcp_output(tp);\n}\n\n/*\n * Attach a TCPCB to a socket.\n */\nint\ntcp_attach(struct socket *so)\n{\n\tif ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL)\n\t return -1;\n\n\tinsque(so, &so->slirp->tcb);\n\n\treturn 0;\n}\n\n/*\n * Set the socket's type of service field\n */\nstatic const struct tos_t tcptos[] = {\n\t {0, 20, IPTOS_THROUGHPUT, 0},\t/* ftp data */\n\t {21, 21, IPTOS_LOWDELAY, EMU_FTP},\t/* ftp control */\n\t {0, 23, IPTOS_LOWDELAY, 0},\t/* telnet */\n\t {0, 80, IPTOS_THROUGHPUT, 0},\t/* WWW */\n\t {0, 513, IPTOS_LOWDELAY, EMU_RLOGIN|EMU_NOCONNECT},\t/* rlogin */\n\t {0, 514, IPTOS_LOWDELAY, EMU_RSH|EMU_NOCONNECT},\t/* shell */\n\t {0, 544, IPTOS_LOWDELAY, EMU_KSH},\t\t/* kshell */\n\t {0, 543, IPTOS_LOWDELAY, 0},\t/* klogin */\n\t {0, 6667, IPTOS_THROUGHPUT, EMU_IRC},\t/* IRC */\n\t {0, 6668, IPTOS_THROUGHPUT, EMU_IRC},\t/* IRC undernet */\n\t {0, 7070, IPTOS_LOWDELAY, EMU_REALAUDIO }, /* RealAudio control */\n\t {0, 113, IPTOS_LOWDELAY, EMU_IDENT }, /* identd protocol */\n\t {0, 0, 0, 0}\n};\n\nstatic struct emu_t *tcpemu = NULL;\n\n/*\n * Return TOS according to the above table\n */\nuint8_t\ntcp_tos(struct socket *so)\n{\n\tint i = 0;\n\tstruct emu_t *emup;\n\n\twhile(tcptos[i].tos) {\n\t\tif ((tcptos[i].fport && (ntohs(so->so_fport) == tcptos[i].fport)) ||\n\t\t (tcptos[i].lport && (ntohs(so->so_lport) == tcptos[i].lport))) {\n\t\t\tso->so_emu = tcptos[i].emu;\n\t\t\treturn tcptos[i].tos;\n\t\t}\n\t\ti++;\n\t}\n\n\t/* Nope, lets see if there's a user-added one */\n\tfor (emup = tcpemu; emup; emup = emup->next) {\n\t\tif ((emup->fport && (ntohs(so->so_fport) == emup->fport)) ||\n\t\t (emup->lport && (ntohs(so->so_lport) == emup->lport))) {\n\t\t\tso->so_emu = emup->emu;\n\t\t\treturn emup->tos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/*\n * Emulate programs that try and connect to us\n * This includes ftp (the data connection is\n * initiated by the server) and IRC (DCC CHAT and\n * DCC SEND) for now\n *\n * NOTE: It's possible to crash SLiRP by sending it\n * unstandard strings to emulate... if this is a problem,\n * more checks are needed here\n *\n * XXX Assumes the whole command came in one packet\n *\n * XXX Some ftp clients will have their TOS set to\n * LOWDELAY and so Nagel will kick in. Because of this,\n * we'll get the first letter, followed by the rest, so\n * we simply scan for ORT instead of PORT...\n * DCC doesn't have this problem because there's other stuff\n * in the packet before the DCC command.\n *\n * Return 1 if the mbuf m is still valid and should be\n * sbappend()ed\n *\n * NOTE: if you return 0 you MUST m_free() the mbuf!\n */\nint\ntcp_emu(struct socket *so, struct mbuf *m)\n{\n\tSlirp *slirp = so->slirp;\n\tu_int n1, n2, n3, n4, n5, n6;\n char buff[257];\n\tuint32_t laddr;\n\tu_int lport;\n\tchar *bptr;\n\n\tDEBUG_CALL(\"tcp_emu\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n\tswitch(so->so_emu) {\n\t\tint x, i;\n\n\t case EMU_IDENT:\n\t\t/*\n\t\t * Identification protocol as per rfc-1413\n\t\t */\n\n\t\t{\n\t\t\tstruct socket *tmpso;\n\t\t\tstruct sockaddr_in addr;\n\t\t\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\t\t\tstruct sbuf *so_rcv = &so->so_rcv;\n\n\t\t\tmemcpy(so_rcv->sb_wptr, m->m_data, m->m_len);\n\t\t\tso_rcv->sb_wptr += m->m_len;\n\t\t\tso_rcv->sb_rptr += m->m_len;\n\t\t\tm->m_data[m->m_len] = 0; /* NULL terminate */\n\t\t\tif (strchr(m->m_data, '\\r') || strchr(m->m_data, '\\n')) {\n\t\t\t\tif (sscanf(so_rcv->sb_data, \"%u%*[ ,]%u\", &n1, &n2) == 2) {\n\t\t\t\t\tHTONS(n1);\n\t\t\t\t\tHTONS(n2);\n\t\t\t\t\t/* n2 is the one on our host */\n\t\t\t\t\tfor (tmpso = slirp->tcb.so_next;\n\t\t\t\t\t tmpso != &slirp->tcb;\n\t\t\t\t\t tmpso = tmpso->so_next) {\n\t\t\t\t\t\tif (tmpso->so_laddr.s_addr == so->so_laddr.s_addr &&\n\t\t\t\t\t\t tmpso->so_lport == n2 &&\n\t\t\t\t\t\t tmpso->so_faddr.s_addr == so->so_faddr.s_addr &&\n\t\t\t\t\t\t tmpso->so_fport == n1) {\n\t\t\t\t\t\t\tif (getsockname(tmpso->s,\n\t\t\t\t\t\t\t\t(struct sockaddr *)&addr, &addrlen) == 0)\n\t\t\t\t\t\t\t n2 = ntohs(addr.sin_port);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n so_rcv->sb_cc = snprintf(so_rcv->sb_data,\n so_rcv->sb_datalen,\n \"%d,%d\\r\\n\", n1, n2);\n\t\t\t\tso_rcv->sb_rptr = so_rcv->sb_data;\n\t\t\t\tso_rcv->sb_wptr = so_rcv->sb_data + so_rcv->sb_cc;\n\t\t\t}\n\t\t\tm_free(m);\n\t\t\treturn 0;\n\t\t}\n\n case EMU_FTP: /* ftp */\n *(m->m_data+m->m_len) = 0; /* NUL terminate for strstr */\n\t\tif ((bptr = (char *)strstr(m->m_data, \"ORT\")) != NULL) {\n\t\t\t/*\n\t\t\t * Need to emulate the PORT command\n\t\t\t */\n\t\t\tx = sscanf(bptr, \"ORT %u,%u,%u,%u,%u,%u\\r\\n%256[^\\177]\",\n\t\t\t\t &n1, &n2, &n3, &n4, &n5, &n6, buff);\n\t\t\tif (x < 6)\n\t\t\t return 1;\n\n\t\t\tladdr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));\n\t\t\tlport = htons((n5 << 8) | (n6));\n\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr,\n\t\t\t lport, SS_FACCEPTONCE)) == NULL) {\n\t\t\t return 1;\n\t\t\t}\n\t\t\tn6 = ntohs(so->so_fport);\n\n\t\t\tn5 = (n6 >> 8) & 0xff;\n\t\t\tn6 &= 0xff;\n\n\t\t\tladdr = ntohl(so->so_faddr.s_addr);\n\n\t\t\tn1 = ((laddr >> 24) & 0xff);\n\t\t\tn2 = ((laddr >> 16) & 0xff);\n\t\t\tn3 = ((laddr >> 8) & 0xff);\n\t\t\tn4 = (laddr & 0xff);\n\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size - m->m_len,\n \"ORT %d,%d,%d,%d,%d,%d\\r\\n%s\",\n n1, n2, n3, n4, n5, n6, x==7?buff:\"\");\n\t\t\treturn 1;\n\t\t} else if ((bptr = (char *)strstr(m->m_data, \"27 Entering\")) != NULL) {\n\t\t\t/*\n\t\t\t * Need to emulate the PASV response\n\t\t\t */\n\t\t\tx = sscanf(bptr, \"27 Entering Passive Mode (%u,%u,%u,%u,%u,%u)\\r\\n%256[^\\177]\",\n\t\t\t\t &n1, &n2, &n3, &n4, &n5, &n6, buff);\n\t\t\tif (x < 6)\n\t\t\t return 1;\n\n\t\t\tladdr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));\n\t\t\tlport = htons((n5 << 8) | (n6));\n\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr,\n\t\t\t lport, SS_FACCEPTONCE)) == NULL) {\n\t\t\t return 1;\n\t\t\t}\n\t\t\tn6 = ntohs(so->so_fport);\n\n\t\t\tn5 = (n6 >> 8) & 0xff;\n\t\t\tn6 &= 0xff;\n\n\t\t\tladdr = ntohl(so->so_faddr.s_addr);\n\n\t\t\tn1 = ((laddr >> 24) & 0xff);\n\t\t\tn2 = ((laddr >> 16) & 0xff);\n\t\t\tn3 = ((laddr >> 8) & 0xff);\n\t\t\tn4 = (laddr & 0xff);\n\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n\t\t\tm->m_len += snprintf(bptr, m->m_hdr.mh_size - m->m_len,\n \"27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\\r\\n%s\",\n n1, n2, n3, n4, n5, n6, x==7?buff:\"\");\n\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn 1;\n\n\t case EMU_KSH:\n\t\t/*\n\t\t * The kshell (Kerberos rsh) and shell services both pass\n\t\t * a local port port number to carry signals to the server\n\t\t * and stderr to the client. It is passed at the beginning\n\t\t * of the connection as a NUL-terminated decimal ASCII string.\n\t\t */\n\t\tso->so_emu = 0;\n\t\tfor (lport = 0, i = 0; i < m->m_len-1; ++i) {\n\t\t\tif (m->m_data[i] < '0' || m->m_data[i] > '9')\n\t\t\t\treturn 1; /* invalid number */\n\t\t\tlport *= 10;\n\t\t\tlport += m->m_data[i] - '0';\n\t\t}\n\t\tif (m->m_data[m->m_len-1] == '\\0' && lport != 0 &&\n\t\t (so = tcp_listen(slirp, INADDR_ANY, 0, so->so_laddr.s_addr,\n\t\t htons(lport), SS_FACCEPTONCE)) != NULL)\n m->m_len = snprintf(m->m_data, m->m_hdr.mh_size, \"%d\",\n ntohs(so->so_fport)) + 1;\n\t\treturn 1;\n\n\t case EMU_IRC:\n\t\t/*\n\t\t * Need to emulate DCC CHAT, DCC SEND and DCC MOVE\n\t\t */\n\t\t*(m->m_data+m->m_len) = 0; /* NULL terminate the string for strstr */\n\t\tif ((bptr = (char *)strstr(m->m_data, \"DCC\")) == NULL)\n\t\t\t return 1;\n\n\t\t/* The %256s is for the broken mIRC */\n\t\tif (sscanf(bptr, \"DCC CHAT %256s %u %u\", buff, &laddr, &lport) == 3) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC CHAT chat %lu %u%c\\n\",\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), 1);\n\t\t} else if (sscanf(bptr, \"DCC SEND %256s %u %u %u\", buff, &laddr, &lport, &n1) == 4) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC SEND %s %lu %u %u%c\\n\", buff,\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), n1, 1);\n\t\t} else if (sscanf(bptr, \"DCC MOVE %256s %u %u %u\", buff, &laddr, &lport, &n1) == 4) {\n\t\t\tif ((so = tcp_listen(slirp, INADDR_ANY, 0,\n\t\t\t htonl(laddr), htons(lport),\n\t\t\t SS_FACCEPTONCE)) == NULL) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tm->m_len = bptr - m->m_data; /* Adjust length */\n m->m_len += snprintf(bptr, m->m_hdr.mh_size,\n \"DCC MOVE %s %lu %u %u%c\\n\", buff,\n (unsigned long)ntohl(so->so_faddr.s_addr),\n ntohs(so->so_fport), n1, 1);\n\t\t}\n\t\treturn 1;\n\n\t case EMU_REALAUDIO:\n /*\n\t\t * RealAudio emulation - JP. We must try to parse the incoming\n\t\t * data and try to find the two characters that contain the\n\t\t * port number. Then we redirect an udp port and replace the\n\t\t * number with the real port we got.\n\t\t *\n\t\t * The 1.0 beta versions of the player are not supported\n\t\t * any more.\n\t\t *\n\t\t * A typical packet for player version 1.0 (release version):\n\t\t *\n\t\t * 0000:50 4E 41 00 05\n\t\t * 0000:00 01 00 02 1B D7 00 00 67 E6 6C DC 63 00 12 50 ........g.l.c..P\n\t\t * 0010:4E 43 4C 49 45 4E 54 20 31 30 31 20 41 4C 50 48 NCLIENT 101 ALPH\n\t\t * 0020:41 6C 00 00 52 00 17 72 61 66 69 6C 65 73 2F 76 Al..R..rafiles/v\n\t\t * 0030:6F 61 2F 65 6E 67 6C 69 73 68 5F 2E 72 61 79 42 oa/english_.rayB\n\t\t *\n\t\t * Now the port number 0x1BD7 is found at offset 0x04 of the\n\t\t * Now the port number 0x1BD7 is found at offset 0x04 of the\n\t\t * second packet. This time we received five bytes first and\n\t\t * then the rest. You never know how many bytes you get.\n\t\t *\n\t\t * A typical packet for player version 2.0 (beta):\n\t\t *\n\t\t * 0000:50 4E 41 00 06 00 02 00 00 00 01 00 02 1B C1 00 PNA.............\n\t\t * 0010:00 67 75 78 F5 63 00 0A 57 69 6E 32 2E 30 2E 30 .gux.c..Win2.0.0\n\t\t * 0020:2E 35 6C 00 00 52 00 1C 72 61 66 69 6C 65 73 2F .5l..R..rafiles/\n\t\t * 0030:77 65 62 73 69 74 65 2F 32 30 72 65 6C 65 61 73 website/20releas\n\t\t * 0040:65 2E 72 61 79 53 00 00 06 36 42 e.rayS...6B\n\t\t *\n\t\t * Port number 0x1BC1 is found at offset 0x0d.\n\t\t *\n\t\t * This is just a horrible switch statement. Variable ra tells\n\t\t * us where we're going.\n\t\t */\n\n\t\tbptr = m->m_data;\n\t\twhile (bptr < m->m_data + m->m_len) {\n\t\t\tu_short p;\n\t\t\tstatic int ra = 0;\n\t\t\tchar ra_tbl[4];\n\n\t\t\tra_tbl[0] = 0x50;\n\t\t\tra_tbl[1] = 0x4e;\n\t\t\tra_tbl[2] = 0x41;\n\t\t\tra_tbl[3] = 0;\n\n\t\t\tswitch (ra) {\n\t\t\t case 0:\n\t\t\t case 2:\n\t\t\t case 3:\n\t\t\t\tif (*bptr++ != ra_tbl[ra]) {\n\t\t\t\t\tra = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t case 1:\n\t\t\t\t/*\n\t\t\t\t * We may get 0x50 several times, ignore them\n\t\t\t\t */\n\t\t\t\tif (*bptr == 0x50) {\n\t\t\t\t\tra = 1;\n\t\t\t\t\tbptr++;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (*bptr++ != ra_tbl[ra]) {\n\t\t\t\t\tra = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t case 4:\n\t\t\t\t/*\n\t\t\t\t * skip version number\n\t\t\t\t */\n\t\t\t\tbptr++;\n\t\t\t\tbreak;\n\n\t\t\t case 5:\n\t\t\t\t/*\n\t\t\t\t * The difference between versions 1.0 and\n\t\t\t\t * 2.0 is here. For future versions of\n\t\t\t\t * the player this may need to be modified.\n\t\t\t\t */\n\t\t\t\tif (*(bptr + 1) == 0x02)\n\t\t\t\t bptr += 8;\n\t\t\t\telse\n\t\t\t\t bptr += 4;\n\t\t\t\tbreak;\n\n\t\t\t case 6:\n\t\t\t\t/* This is the field containing the port\n\t\t\t\t * number that RA-player is listening to.\n\t\t\t\t */\n\t\t\t\tlport = (((u_char*)bptr)[0] << 8)\n\t\t\t\t+ ((u_char *)bptr)[1];\n\t\t\t\tif (lport < 6970)\n\t\t\t\t lport += 256; /* don't know why */\n\t\t\t\tif (lport < 6970 || lport > 7170)\n\t\t\t\t return 1; /* failed */\n\n\t\t\t\t/* try to get udp port between 6970 - 7170 */\n\t\t\t\tfor (p = 6970; p < 7071; p++) {\n\t\t\t\t\tif (udp_listen(slirp, INADDR_ANY,\n\t\t\t\t\t\t htons(p),\n\t\t\t\t\t\t so->so_laddr.s_addr,\n\t\t\t\t\t\t htons(lport),\n\t\t\t\t\t\t SS_FACCEPTONCE)) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (p == 7071)\n\t\t\t\t p = 0;\n\t\t\t\t*(u_char *)bptr++ = (p >> 8) & 0xff;\n *(u_char *)bptr = p & 0xff;\n\t\t\t\tra = 0;\n\t\t\t\treturn 1; /* port redirected, we're done */\n\t\t\t\tbreak;\n\n\t\t\t default:\n\t\t\t\tra = 0;\n\t\t\t}\n\t\t\tra++;\n\t\t}\n\t\treturn 1;\n\n\t default:\n\t\t/* Ooops, not emulated, won't call tcp_emu again */\n\t\tso->so_emu = 0;\n\t\treturn 1;\n\t}\n}\n\n/*\n * Do misc. config of SLiRP while its running.\n * Return 0 if this connections is to be closed, 1 otherwise,\n * return 2 if this is a command-line connection\n */\nint tcp_ctl(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n struct sbuf *sb = &so->so_snd;\n struct ex_list *ex_ptr;\n int do_pty;\n\n DEBUG_CALL(\"tcp_ctl\");\n DEBUG_ARG(\"so = %lx\", (long )so);\n\n if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {\n /* Check if it's pty_exec */\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_fport == so->so_fport &&\n so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {\n if (ex_ptr->ex_pty == 3) {\n so->s = -1;\n so->extra = (void *)ex_ptr->ex_exec;\n return 1;\n }\n do_pty = ex_ptr->ex_pty;\n DEBUG_MISC((dfd, \" executing %s \\n\",ex_ptr->ex_exec));\n return fork_exec(so, ex_ptr->ex_exec, do_pty);\n }\n }\n }\n sb->sb_cc =\n snprintf(sb->sb_wptr, sb->sb_datalen - (sb->sb_wptr - sb->sb_data),\n \"Error: No application configured.\\r\\n\");\n sb->sb_wptr += sb->sb_cc;\n return 0;\n}\n"], ["/linuxpdf/tinyemu/ide.c", "/*\n * IDE emulation\n * \n * Copyright (c) 2003-2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"ide.h\"\n\n//#define DEBUG_IDE\n\n/* Bits of HD_STATUS */\n#define ERR_STAT\t\t0x01\n#define INDEX_STAT\t\t0x02\n#define ECC_STAT\t\t0x04\t/* Corrected error */\n#define DRQ_STAT\t\t0x08\n#define SEEK_STAT\t\t0x10\n#define SRV_STAT\t\t0x10\n#define WRERR_STAT\t\t0x20\n#define READY_STAT\t\t0x40\n#define BUSY_STAT\t\t0x80\n\n/* Bits for HD_ERROR */\n#define MARK_ERR\t\t0x01\t/* Bad address mark */\n#define TRK0_ERR\t\t0x02\t/* couldn't find track 0 */\n#define ABRT_ERR\t\t0x04\t/* Command aborted */\n#define MCR_ERR\t\t\t0x08\t/* media change request */\n#define ID_ERR\t\t\t0x10\t/* ID field not found */\n#define MC_ERR\t\t\t0x20\t/* media changed */\n#define ECC_ERR\t\t\t0x40\t/* Uncorrectable ECC error */\n#define BBD_ERR\t\t\t0x80\t/* pre-EIDE meaning: block marked bad */\n#define ICRC_ERR\t\t0x80\t/* new meaning: CRC error during transfer */\n\n/* Bits of HD_NSECTOR */\n#define CD\t\t\t0x01\n#define IO\t\t\t0x02\n#define REL\t\t\t0x04\n#define TAG_MASK\t\t0xf8\n\n#define IDE_CMD_RESET 0x04\n#define IDE_CMD_DISABLE_IRQ 0x02\n\n/* ATA/ATAPI Commands pre T13 Spec */\n#define WIN_NOP\t\t\t\t0x00\n/*\n *\t0x01->0x02 Reserved\n */\n#define CFA_REQ_EXT_ERROR_CODE\t\t0x03 /* CFA Request Extended Error Code */\n/*\n *\t0x04->0x07 Reserved\n */\n#define WIN_SRST\t\t\t0x08 /* ATAPI soft reset command */\n#define WIN_DEVICE_RESET\t\t0x08\n/*\n *\t0x09->0x0F Reserved\n */\n#define WIN_RECAL\t\t\t0x10\n#define WIN_RESTORE\t\t\tWIN_RECAL\n/*\n *\t0x10->0x1F Reserved\n */\n#define WIN_READ\t\t\t0x20 /* 28-Bit */\n#define WIN_READ_ONCE\t\t\t0x21 /* 28-Bit without retries */\n#define WIN_READ_LONG\t\t\t0x22 /* 28-Bit */\n#define WIN_READ_LONG_ONCE\t\t0x23 /* 28-Bit without retries */\n#define WIN_READ_EXT\t\t\t0x24 /* 48-Bit */\n#define WIN_READDMA_EXT\t\t\t0x25 /* 48-Bit */\n#define WIN_READDMA_QUEUED_EXT\t\t0x26 /* 48-Bit */\n#define WIN_READ_NATIVE_MAX_EXT\t\t0x27 /* 48-Bit */\n/*\n *\t0x28\n */\n#define WIN_MULTREAD_EXT\t\t0x29 /* 48-Bit */\n/*\n *\t0x2A->0x2F Reserved\n */\n#define WIN_WRITE\t\t\t0x30 /* 28-Bit */\n#define WIN_WRITE_ONCE\t\t\t0x31 /* 28-Bit without retries */\n#define WIN_WRITE_LONG\t\t\t0x32 /* 28-Bit */\n#define WIN_WRITE_LONG_ONCE\t\t0x33 /* 28-Bit without retries */\n#define WIN_WRITE_EXT\t\t\t0x34 /* 48-Bit */\n#define WIN_WRITEDMA_EXT\t\t0x35 /* 48-Bit */\n#define WIN_WRITEDMA_QUEUED_EXT\t\t0x36 /* 48-Bit */\n#define WIN_SET_MAX_EXT\t\t\t0x37 /* 48-Bit */\n#define CFA_WRITE_SECT_WO_ERASE\t\t0x38 /* CFA Write Sectors without erase */\n#define WIN_MULTWRITE_EXT\t\t0x39 /* 48-Bit */\n/*\n *\t0x3A->0x3B Reserved\n */\n#define WIN_WRITE_VERIFY\t\t0x3C /* 28-Bit */\n/*\n *\t0x3D->0x3F Reserved\n */\n#define WIN_VERIFY\t\t\t0x40 /* 28-Bit - Read Verify Sectors */\n#define WIN_VERIFY_ONCE\t\t\t0x41 /* 28-Bit - without retries */\n#define WIN_VERIFY_EXT\t\t\t0x42 /* 48-Bit */\n/*\n *\t0x43->0x4F Reserved\n */\n#define WIN_FORMAT\t\t\t0x50\n/*\n *\t0x51->0x5F Reserved\n */\n#define WIN_INIT\t\t\t0x60\n/*\n *\t0x61->0x5F Reserved\n */\n#define WIN_SEEK\t\t\t0x70 /* 0x70-0x7F Reserved */\n#define CFA_TRANSLATE_SECTOR\t\t0x87 /* CFA Translate Sector */\n#define WIN_DIAGNOSE\t\t\t0x90\n#define WIN_SPECIFY\t\t\t0x91 /* set drive geometry translation */\n#define WIN_DOWNLOAD_MICROCODE\t\t0x92\n#define WIN_STANDBYNOW2\t\t\t0x94\n#define WIN_STANDBY2\t\t\t0x96\n#define WIN_SETIDLE2\t\t\t0x97\n#define WIN_CHECKPOWERMODE2\t\t0x98\n#define WIN_SLEEPNOW2\t\t\t0x99\n/*\n *\t0x9A VENDOR\n */\n#define WIN_PACKETCMD\t\t\t0xA0 /* Send a packet command. */\n#define WIN_PIDENTIFY\t\t\t0xA1 /* identify ATAPI device\t*/\n#define WIN_QUEUED_SERVICE\t\t0xA2\n#define WIN_SMART\t\t\t0xB0 /* self-monitoring and reporting */\n#define CFA_ERASE_SECTORS \t0xC0\n#define WIN_MULTREAD\t\t\t0xC4 /* read sectors using multiple mode*/\n#define WIN_MULTWRITE\t\t\t0xC5 /* write sectors using multiple mode */\n#define WIN_SETMULT\t\t\t0xC6 /* enable/disable multiple mode */\n#define WIN_READDMA_QUEUED\t\t0xC7 /* read sectors using Queued DMA transfers */\n#define WIN_READDMA\t\t\t0xC8 /* read sectors using DMA transfers */\n#define WIN_READDMA_ONCE\t\t0xC9 /* 28-Bit - without retries */\n#define WIN_WRITEDMA\t\t\t0xCA /* write sectors using DMA transfers */\n#define WIN_WRITEDMA_ONCE\t\t0xCB /* 28-Bit - without retries */\n#define WIN_WRITEDMA_QUEUED\t\t0xCC /* write sectors using Queued DMA transfers */\n#define CFA_WRITE_MULTI_WO_ERASE\t0xCD /* CFA Write multiple without erase */\n#define WIN_GETMEDIASTATUS\t\t0xDA\t\n#define WIN_ACKMEDIACHANGE\t\t0xDB /* ATA-1, ATA-2 vendor */\n#define WIN_POSTBOOT\t\t\t0xDC\n#define WIN_PREBOOT\t\t\t0xDD\n#define WIN_DOORLOCK\t\t\t0xDE /* lock door on removable drives */\n#define WIN_DOORUNLOCK\t\t\t0xDF /* unlock door on removable drives */\n#define WIN_STANDBYNOW1\t\t\t0xE0\n#define WIN_IDLEIMMEDIATE\t\t0xE1 /* force drive to become \"ready\" */\n#define WIN_STANDBY \t0xE2 /* Set device in Standby Mode */\n#define WIN_SETIDLE1\t\t\t0xE3\n#define WIN_READ_BUFFER\t\t\t0xE4 /* force read only 1 sector */\n#define WIN_CHECKPOWERMODE1\t\t0xE5\n#define WIN_SLEEPNOW1\t\t\t0xE6\n#define WIN_FLUSH_CACHE\t\t\t0xE7\n#define WIN_WRITE_BUFFER\t\t0xE8 /* force write only 1 sector */\n#define WIN_WRITE_SAME\t\t\t0xE9 /* read ata-2 to use */\n\t/* SET_FEATURES 0x22 or 0xDD */\n#define WIN_FLUSH_CACHE_EXT\t\t0xEA /* 48-Bit */\n#define WIN_IDENTIFY\t\t\t0xEC /* ask drive to identify itself\t*/\n#define WIN_MEDIAEJECT\t\t\t0xED\n#define WIN_IDENTIFY_DMA\t\t0xEE /* same as WIN_IDENTIFY, but DMA */\n#define WIN_SETFEATURES\t\t\t0xEF /* set special drive features */\n#define EXABYTE_ENABLE_NEST\t\t0xF0\n#define WIN_SECURITY_SET_PASS\t\t0xF1\n#define WIN_SECURITY_UNLOCK\t\t0xF2\n#define WIN_SECURITY_ERASE_PREPARE\t0xF3\n#define WIN_SECURITY_ERASE_UNIT\t\t0xF4\n#define WIN_SECURITY_FREEZE_LOCK\t0xF5\n#define WIN_SECURITY_DISABLE\t\t0xF6\n#define WIN_READ_NATIVE_MAX\t\t0xF8 /* return the native maximum address */\n#define WIN_SET_MAX\t\t\t0xF9\n#define DISABLE_SEAGATE\t\t\t0xFB\n\n#define MAX_MULT_SECTORS 128\n\ntypedef struct IDEState IDEState;\n\ntypedef void EndTransferFunc(IDEState *);\n\nstruct IDEState {\n IDEIFState *ide_if;\n BlockDevice *bs;\n int cylinders, heads, sectors;\n int mult_sectors;\n int64_t nb_sectors;\n\n /* ide regs */\n uint8_t feature;\n uint8_t error;\n uint16_t nsector; /* 0 is 256 to ease computations */\n uint8_t sector;\n uint8_t lcyl;\n uint8_t hcyl;\n uint8_t select;\n uint8_t status;\n\n int io_nb_sectors;\n int req_nb_sectors;\n EndTransferFunc *end_transfer_func;\n \n int data_index;\n int data_end;\n uint8_t io_buffer[MAX_MULT_SECTORS*512 + 4];\n};\n\nstruct IDEIFState {\n IRQSignal *irq;\n IDEState *cur_drive;\n IDEState *drives[2];\n /* 0x3f6 command */\n uint8_t cmd;\n};\n\nstatic void ide_sector_read_cb(void *opaque, int ret);\nstatic void ide_sector_read_cb_end(IDEState *s);\nstatic void ide_sector_write_cb2(void *opaque, int ret);\n\nstatic void padstr(char *str, const char *src, int len)\n{\n int i, v;\n for(i = 0; i < len; i++) {\n if (*src)\n v = *src++;\n else\n v = ' ';\n *(char *)((long)str ^ 1) = v;\n str++;\n }\n}\n\n/* little endian assume */\nstatic void stw(uint16_t *buf, int v)\n{\n *buf = v;\n}\n\nstatic void ide_identify(IDEState *s)\n{\n uint16_t *tab;\n uint32_t oldsize;\n \n tab = (uint16_t *)s->io_buffer;\n\n memset(tab, 0, 512 * 2);\n\n stw(tab + 0, 0x0040);\n stw(tab + 1, s->cylinders); \n stw(tab + 3, s->heads);\n stw(tab + 4, 512 * s->sectors); /* sectors */\n stw(tab + 5, 512); /* sector size */\n stw(tab + 6, s->sectors); \n stw(tab + 20, 3); /* buffer type */\n stw(tab + 21, 512); /* cache size in sectors */\n stw(tab + 22, 4); /* ecc bytes */\n padstr((char *)(tab + 27), \"RISCVEMU HARDDISK\", 40);\n stw(tab + 47, 0x8000 | MAX_MULT_SECTORS);\n stw(tab + 48, 0); /* dword I/O */\n stw(tab + 49, 1 << 9); /* LBA supported, no DMA */\n stw(tab + 51, 0x200); /* PIO transfer cycle */\n stw(tab + 52, 0x200); /* DMA transfer cycle */\n stw(tab + 54, s->cylinders);\n stw(tab + 55, s->heads);\n stw(tab + 56, s->sectors);\n oldsize = s->cylinders * s->heads * s->sectors;\n stw(tab + 57, oldsize);\n stw(tab + 58, oldsize >> 16);\n if (s->mult_sectors)\n stw(tab + 59, 0x100 | s->mult_sectors);\n stw(tab + 60, s->nb_sectors);\n stw(tab + 61, s->nb_sectors >> 16);\n stw(tab + 80, (1 << 1) | (1 << 2));\n stw(tab + 82, (1 << 14));\n stw(tab + 83, (1 << 14));\n stw(tab + 84, (1 << 14));\n stw(tab + 85, (1 << 14));\n stw(tab + 86, 0);\n stw(tab + 87, (1 << 14));\n}\n\nstatic void ide_set_signature(IDEState *s) \n{\n s->select &= 0xf0;\n s->nsector = 1;\n s->sector = 1;\n s->lcyl = 0;\n s->hcyl = 0;\n}\n\nstatic void ide_abort_command(IDEState *s) \n{\n s->status = READY_STAT | ERR_STAT;\n s->error = ABRT_ERR;\n}\n\nstatic void ide_set_irq(IDEState *s) \n{\n IDEIFState *ide_if = s->ide_if;\n if (!(ide_if->cmd & IDE_CMD_DISABLE_IRQ)) {\n set_irq(ide_if->irq, 1);\n }\n}\n\n/* prepare data transfer and tell what to do after */\nstatic void ide_transfer_start(IDEState *s, int size,\n EndTransferFunc *end_transfer_func)\n{\n s->end_transfer_func = end_transfer_func;\n s->data_index = 0;\n s->data_end = size;\n}\n\nstatic void ide_transfer_stop(IDEState *s)\n{\n s->end_transfer_func = ide_transfer_stop;\n s->data_index = 0;\n s->data_end = 0;\n}\n\nstatic int64_t ide_get_sector(IDEState *s)\n{\n int64_t sector_num;\n if (s->select & 0x40) {\n /* lba */\n sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) |\n (s->lcyl << 8) | s->sector;\n } else {\n sector_num = ((s->hcyl << 8) | s->lcyl) * \n s->heads * s->sectors +\n (s->select & 0x0f) * s->sectors + (s->sector - 1);\n }\n return sector_num;\n}\n\nstatic void ide_set_sector(IDEState *s, int64_t sector_num)\n{\n unsigned int cyl, r;\n if (s->select & 0x40) {\n s->select = (s->select & 0xf0) | ((sector_num >> 24) & 0x0f);\n s->hcyl = (sector_num >> 16) & 0xff;\n s->lcyl = (sector_num >> 8) & 0xff;\n s->sector = sector_num & 0xff;\n } else {\n cyl = sector_num / (s->heads * s->sectors);\n r = sector_num % (s->heads * s->sectors);\n s->hcyl = (cyl >> 8) & 0xff;\n s->lcyl = cyl & 0xff;\n s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f);\n s->sector = (r % s->sectors) + 1;\n }\n}\n\nstatic void ide_sector_read(IDEState *s)\n{\n int64_t sector_num;\n int ret, n;\n\n sector_num = ide_get_sector(s);\n n = s->nsector;\n if (n == 0) \n n = 256;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n#if defined(DEBUG_IDE)\n printf(\"read sector=%\" PRId64 \" count=%d\\n\", sector_num, n);\n#endif\n s->io_nb_sectors = n;\n ret = s->bs->read_async(s->bs, sector_num, s->io_buffer, n, \n ide_sector_read_cb, s);\n if (ret < 0) {\n /* error */\n ide_abort_command(s);\n ide_set_irq(s);\n } else if (ret == 0) {\n /* synchronous case (needed for performance) */\n ide_sector_read_cb(s, 0);\n } else {\n /* async case */\n s->status = READY_STAT | SEEK_STAT | BUSY_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n }\n}\n\nstatic void ide_sector_read_cb(void *opaque, int ret)\n{\n IDEState *s = opaque;\n int n;\n EndTransferFunc *func;\n \n n = s->io_nb_sectors;\n ide_set_sector(s, ide_get_sector(s) + n);\n s->nsector = (s->nsector - n) & 0xff;\n if (s->nsector == 0)\n func = ide_sector_read_cb_end;\n else\n func = ide_sector_read;\n ide_transfer_start(s, 512 * n, func);\n ide_set_irq(s);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n}\n\nstatic void ide_sector_read_cb_end(IDEState *s)\n{\n /* no more sector to read from disk */\n s->status = READY_STAT | SEEK_STAT;\n s->error = 0; /* not needed by IDE spec, but needed by Windows */\n ide_transfer_stop(s);\n}\n\nstatic void ide_sector_write_cb1(IDEState *s)\n{\n int64_t sector_num;\n int ret;\n\n ide_transfer_stop(s);\n sector_num = ide_get_sector(s);\n#if defined(DEBUG_IDE)\n printf(\"write sector=%\" PRId64 \" count=%d\\n\",\n sector_num, s->io_nb_sectors);\n#endif\n ret = s->bs->write_async(s->bs, sector_num, s->io_buffer, s->io_nb_sectors, \n ide_sector_write_cb2, s);\n if (ret < 0) {\n /* error */\n ide_abort_command(s);\n ide_set_irq(s);\n } else if (ret == 0) {\n /* synchronous case (needed for performance) */\n ide_sector_write_cb2(s, 0);\n } else {\n /* async case */\n s->status = READY_STAT | SEEK_STAT | BUSY_STAT;\n }\n}\n\nstatic void ide_sector_write_cb2(void *opaque, int ret)\n{\n IDEState *s = opaque;\n int n;\n\n n = s->io_nb_sectors;\n ide_set_sector(s, ide_get_sector(s) + n);\n s->nsector = (s->nsector - n) & 0xff;\n if (s->nsector == 0) {\n /* no more sectors to write */\n s->status = READY_STAT | SEEK_STAT;\n } else {\n n = s->nsector;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n s->io_nb_sectors = n;\n ide_transfer_start(s, 512 * n, ide_sector_write_cb1);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n }\n ide_set_irq(s);\n}\n\nstatic void ide_sector_write(IDEState *s)\n{\n int n;\n n = s->nsector;\n if (n == 0)\n n = 256;\n if (n > s->req_nb_sectors)\n n = s->req_nb_sectors;\n s->io_nb_sectors = n;\n ide_transfer_start(s, 512 * n, ide_sector_write_cb1);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n}\n\nstatic void ide_identify_cb(IDEState *s)\n{\n ide_transfer_stop(s);\n s->status = READY_STAT;\n}\n\nstatic void ide_exec_cmd(IDEState *s, int val)\n{\n#if defined(DEBUG_IDE)\n printf(\"ide: exec_cmd=0x%02x\\n\", val);\n#endif\n switch(val) {\n case WIN_IDENTIFY:\n ide_identify(s);\n s->status = READY_STAT | SEEK_STAT | DRQ_STAT;\n ide_transfer_start(s, 512, ide_identify_cb);\n ide_set_irq(s);\n break;\n case WIN_SPECIFY:\n case WIN_RECAL:\n s->error = 0;\n s->status = READY_STAT | SEEK_STAT;\n ide_set_irq(s);\n break;\n case WIN_SETMULT:\n if (s->nsector > MAX_MULT_SECTORS || \n (s->nsector & (s->nsector - 1)) != 0) {\n ide_abort_command(s);\n } else {\n s->mult_sectors = s->nsector;\n#if defined(DEBUG_IDE)\n printf(\"ide: setmult=%d\\n\", s->mult_sectors);\n#endif\n s->status = READY_STAT;\n }\n ide_set_irq(s);\n break;\n case WIN_READ:\n case WIN_READ_ONCE:\n s->req_nb_sectors = 1;\n ide_sector_read(s);\n break;\n case WIN_WRITE:\n case WIN_WRITE_ONCE:\n s->req_nb_sectors = 1;\n ide_sector_write(s);\n break;\n case WIN_MULTREAD:\n if (!s->mult_sectors) {\n ide_abort_command(s);\n ide_set_irq(s);\n } else {\n s->req_nb_sectors = s->mult_sectors;\n ide_sector_read(s);\n }\n break;\n case WIN_MULTWRITE:\n if (!s->mult_sectors) {\n ide_abort_command(s);\n ide_set_irq(s);\n } else {\n s->req_nb_sectors = s->mult_sectors;\n ide_sector_write(s);\n }\n break;\n case WIN_READ_NATIVE_MAX:\n ide_set_sector(s, s->nb_sectors - 1);\n s->status = READY_STAT;\n ide_set_irq(s);\n break;\n default:\n ide_abort_command(s);\n ide_set_irq(s);\n break;\n }\n}\n\nstatic void ide_ioport_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int addr = offset + 1;\n \n#ifdef DEBUG_IDE\n printf(\"ide: write addr=0x%02x val=0x%02x\\n\", addr, val);\n#endif\n switch(addr) {\n case 0:\n break;\n case 1:\n if (s) {\n s->feature = val;\n }\n break;\n case 2:\n if (s) {\n s->nsector = val;\n }\n break;\n case 3:\n if (s) {\n s->sector = val;\n }\n break;\n case 4:\n if (s) {\n s->lcyl = val;\n }\n break;\n case 5:\n if (s) {\n s->hcyl = val;\n }\n break;\n case 6:\n /* select drive */\n s = s1->cur_drive = s1->drives[(val >> 4) & 1];\n if (s) {\n s->select = val;\n }\n break;\n default:\n case 7:\n /* command */\n if (s) {\n ide_exec_cmd(s, val);\n }\n break;\n }\n}\n\nstatic uint32_t ide_ioport_read(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int ret, addr = offset + 1;\n\n if (!s) {\n ret = 0x00;\n } else {\n switch(addr) {\n case 0:\n ret = 0xff;\n break;\n case 1:\n ret = s->error;\n break;\n case 2:\n ret = s->nsector;\n break;\n case 3:\n ret = s->sector;\n break;\n case 4:\n ret = s->lcyl;\n break;\n case 5:\n ret = s->hcyl;\n break;\n case 6:\n ret = s->select;\n break;\n default:\n case 7:\n ret = s->status;\n set_irq(s1->irq, 0);\n break;\n }\n }\n#ifdef DEBUG_IDE\n printf(\"ide: read addr=0x%02x val=0x%02x\\n\", addr, ret);\n#endif\n return ret;\n}\n\nstatic uint32_t ide_status_read(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int ret;\n\n if (s) {\n ret = s->status;\n } else {\n ret = 0;\n }\n#ifdef DEBUG_IDE\n printf(\"ide: read status=0x%02x\\n\", ret);\n#endif\n return ret;\n}\n\nstatic void ide_cmd_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s;\n int i;\n \n#ifdef DEBUG_IDE\n printf(\"ide: cmd write=0x%02x\\n\", val);\n#endif\n if (!(s1->cmd & IDE_CMD_RESET) && (val & IDE_CMD_RESET)) {\n /* low to high */\n for(i = 0; i < 2; i++) {\n s = s1->drives[i];\n if (s) {\n s->status = BUSY_STAT | SEEK_STAT;\n s->error = 0x01;\n }\n }\n } else if ((s1->cmd & IDE_CMD_RESET) && !(val & IDE_CMD_RESET)) {\n /* high to low */\n for(i = 0; i < 2; i++) {\n s = s1->drives[i];\n if (s) {\n s->status = READY_STAT | SEEK_STAT;\n ide_set_signature(s);\n }\n }\n }\n s1->cmd = val;\n}\n\nstatic void ide_data_writew(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int p;\n uint8_t *tab;\n \n if (!s)\n return;\n p = s->data_index;\n tab = s->io_buffer;\n tab[p] = val & 0xff;\n tab[p + 1] = (val >> 8) & 0xff;\n p += 2;\n s->data_index = p;\n if (p >= s->data_end)\n s->end_transfer_func(s);\n}\n\nstatic uint32_t ide_data_readw(void *opaque, uint32_t offset, int size_log2)\n{\n IDEIFState *s1 = opaque;\n IDEState *s = s1->cur_drive;\n int p, ret;\n uint8_t *tab;\n \n if (!s) {\n ret = 0;\n } else {\n p = s->data_index;\n tab = s->io_buffer;\n ret = tab[p] | (tab[p + 1] << 8);\n p += 2;\n s->data_index = p;\n if (p >= s->data_end)\n s->end_transfer_func(s);\n }\n return ret;\n}\n\nstatic IDEState *ide_drive_init(IDEIFState *ide_if, BlockDevice *bs)\n{\n IDEState *s;\n uint32_t cylinders;\n uint64_t nb_sectors;\n\n s = malloc(sizeof(*s));\n memset(s, 0, sizeof(*s));\n\n s->ide_if = ide_if;\n s->bs = bs;\n\n nb_sectors = s->bs->get_sector_count(s->bs);\n cylinders = nb_sectors / (16 * 63);\n if (cylinders > 16383)\n cylinders = 16383;\n else if (cylinders < 2)\n cylinders = 2;\n s->cylinders = cylinders;\n s->heads = 16;\n s->sectors = 63;\n s->nb_sectors = nb_sectors;\n\n s->mult_sectors = MAX_MULT_SECTORS;\n /* ide regs */\n s->feature = 0;\n s->error = 0;\n s->nsector = 0;\n s->sector = 0;\n s->lcyl = 0;\n s->hcyl = 0;\n s->select = 0xa0;\n s->status = READY_STAT | SEEK_STAT;\n\n /* init I/O buffer */\n s->data_index = 0;\n s->data_end = 0;\n s->end_transfer_func = ide_transfer_stop;\n\n s->req_nb_sectors = 0; /* temp for read/write */\n s->io_nb_sectors = 0; /* temp for read/write */\n return s;\n}\n\nIDEIFState *ide_init(PhysMemoryMap *port_map, uint32_t addr, uint32_t addr2,\n IRQSignal *irq, BlockDevice **tab_bs)\n{\n int i;\n IDEIFState *s;\n \n s = malloc(sizeof(IDEIFState));\n memset(s, 0, sizeof(*s));\n \n s->irq = irq;\n s->cmd = 0;\n\n cpu_register_device(port_map, addr, 1, s, ide_data_readw, ide_data_writew, \n DEVIO_SIZE16);\n cpu_register_device(port_map, addr + 1, 7, s, ide_ioport_read, ide_ioport_write, \n DEVIO_SIZE8);\n if (addr2) {\n cpu_register_device(port_map, addr2, 1, s, ide_status_read, ide_cmd_write, \n DEVIO_SIZE8);\n }\n \n for(i = 0; i < 2; i++) {\n if (tab_bs[i])\n s->drives[i] = ide_drive_init(s, tab_bs[i]);\n }\n s->cur_drive = s->drives[0];\n return s;\n}\n\n/* dummy PCI device for the IDE */\nPCIDevice *piix3_ide_init(PCIBus *pci_bus, int devfn)\n{\n PCIDevice *d;\n d = pci_register_device(pci_bus, \"PIIX3 IDE\", devfn, 0x8086, 0x7010, 0x00, 0x0101);\n pci_device_set_config8(d, 0x09, 0x00); /* ISA IDE ports, no DMA */\n return d;\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_input.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_input.c\t8.2 (Berkeley) 1/4/94\n * ip_input.c,v 1.11 1994/11/16 10:17:08 jkh Exp\n */\n\n/*\n * Changes and additions relating to SLiRP are\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n#define container_of(ptr, type, member) ({ \\\n const typeof( ((type *)0)->member ) *__mptr = (ptr); \\\n (type *)( (char *)__mptr - offsetof(type,member) );})\n\nstatic struct ip *ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp);\nstatic void ip_freef(Slirp *slirp, struct ipq *fp);\nstatic void ip_enq(register struct ipasfrag *p,\n register struct ipasfrag *prev);\nstatic void ip_deq(register struct ipasfrag *p);\n\n/*\n * IP initialization: fill in IP protocol switch table.\n * All protocols not implemented in kernel go to raw IP protocol handler.\n */\nvoid\nip_init(Slirp *slirp)\n{\n slirp->ipq.ip_link.next = slirp->ipq.ip_link.prev = &slirp->ipq.ip_link;\n udp_init(slirp);\n tcp_init(slirp);\n}\n\n/*\n * Ip input routine. Checksum and byte swap header. If fragmented\n * try to reassemble. Process options. Pass to next level.\n */\nvoid\nip_input(struct mbuf *m)\n{\n\tSlirp *slirp = m->slirp;\n\tregister struct ip *ip;\n\tint hlen;\n\n\tDEBUG_CALL(\"ip_input\");\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"m_len = %d\", m->m_len);\n\n\tif (m->m_len < sizeof (struct ip)) {\n\t\treturn;\n\t}\n\n\tip = mtod(m, struct ip *);\n\n\tif (ip->ip_v != IPVERSION) {\n\t\tgoto bad;\n\t}\n\n\thlen = ip->ip_hl << 2;\n\tif (hlenm->m_len) {/* min header length */\n\t goto bad; /* or packet too short */\n\t}\n\n /* keep ip header intact for ICMP reply\n\t * ip->ip_sum = cksum(m, hlen);\n\t * if (ip->ip_sum) {\n\t */\n\tif(cksum(m,hlen)) {\n\t goto bad;\n\t}\n\n\t/*\n\t * Convert fields to host representation.\n\t */\n\tNTOHS(ip->ip_len);\n\tif (ip->ip_len < hlen) {\n\t\tgoto bad;\n\t}\n\tNTOHS(ip->ip_id);\n\tNTOHS(ip->ip_off);\n\n\t/*\n\t * Check that the amount of data in the buffers\n\t * is as at least much as the IP header would have us expect.\n\t * Trim mbufs if longer than we expect.\n\t * Drop packet if shorter than we expect.\n\t */\n\tif (m->m_len < ip->ip_len) {\n\t\tgoto bad;\n\t}\n\n if (slirp->restricted) {\n if ((ip->ip_dst.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n if (ip->ip_dst.s_addr == 0xffffffff && ip->ip_p != IPPROTO_UDP)\n goto bad;\n } else {\n uint32_t inv_mask = ~slirp->vnetwork_mask.s_addr;\n struct ex_list *ex_ptr;\n\n if ((ip->ip_dst.s_addr & inv_mask) == inv_mask) {\n goto bad;\n }\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)\n if (ex_ptr->ex_addr.s_addr == ip->ip_dst.s_addr)\n break;\n\n if (!ex_ptr)\n goto bad;\n }\n }\n\n\t/* Should drop packet if mbuf too long? hmmm... */\n\tif (m->m_len > ip->ip_len)\n\t m_adj(m, ip->ip_len - m->m_len);\n\n\t/* check ip_ttl for a correct ICMP reply */\n\tif(ip->ip_ttl==0) {\n\t icmp_error(m, ICMP_TIMXCEED,ICMP_TIMXCEED_INTRANS, 0,\"ttl\");\n\t goto bad;\n\t}\n\n\t/*\n\t * If offset or IP_MF are set, must reassemble.\n\t * Otherwise, nothing need be done.\n\t * (We could look in the reassembly queue to see\n\t * if the packet was previously fragmented,\n\t * but it's not worth the time; just let them time out.)\n\t *\n\t * XXX This should fail, don't fragment yet\n\t */\n\tif (ip->ip_off &~ IP_DF) {\n\t register struct ipq *fp;\n struct qlink *l;\n\t\t/*\n\t\t * Look for queue of fragments\n\t\t * of this datagram.\n\t\t */\n\t\tfor (l = slirp->ipq.ip_link.next; l != &slirp->ipq.ip_link;\n\t\t l = l->next) {\n fp = container_of(l, struct ipq, ip_link);\n if (ip->ip_id == fp->ipq_id &&\n ip->ip_src.s_addr == fp->ipq_src.s_addr &&\n ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&\n ip->ip_p == fp->ipq_p)\n\t\t goto found;\n }\n fp = NULL;\n\tfound:\n\n\t\t/*\n\t\t * Adjust ip_len to not reflect header,\n\t\t * set ip_mff if more fragments are expected,\n\t\t * convert offset of this to bytes.\n\t\t */\n\t\tip->ip_len -= hlen;\n\t\tif (ip->ip_off & IP_MF)\n\t\t ip->ip_tos |= 1;\n\t\telse\n\t\t ip->ip_tos &= ~1;\n\n\t\tip->ip_off <<= 3;\n\n\t\t/*\n\t\t * If datagram marked as having more fragments\n\t\t * or if this is not the first fragment,\n\t\t * attempt reassembly; if it succeeds, proceed.\n\t\t */\n\t\tif (ip->ip_tos & 1 || ip->ip_off) {\n\t\t\tip = ip_reass(slirp, ip, fp);\n if (ip == NULL)\n\t\t\t\treturn;\n\t\t\tm = dtom(slirp, ip);\n\t\t} else\n\t\t\tif (fp)\n\t\t \t ip_freef(slirp, fp);\n\n\t} else\n\t\tip->ip_len -= hlen;\n\n\t/*\n\t * Switch out to protocol's input routine.\n\t */\n\tswitch (ip->ip_p) {\n\t case IPPROTO_TCP:\n\t\ttcp_input(m, hlen, (struct socket *)NULL);\n\t\tbreak;\n\t case IPPROTO_UDP:\n\t\tudp_input(m, hlen);\n\t\tbreak;\n\t case IPPROTO_ICMP:\n\t\ticmp_input(m, hlen);\n\t\tbreak;\n\t default:\n\t\tm_free(m);\n\t}\n\treturn;\nbad:\n\tm_freem(m);\n\treturn;\n}\n\n#define iptofrag(P) ((struct ipasfrag *)(((char*)(P)) - sizeof(struct qlink)))\n#define fragtoip(P) ((struct ip*)(((char*)(P)) + sizeof(struct qlink)))\n/*\n * Take incoming datagram fragment and try to\n * reassemble it into whole datagram. If a chain for\n * reassembly of this datagram already exists, then it\n * is given as fp; otherwise have to make a chain.\n */\nstatic struct ip *\nip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)\n{\n\tregister struct mbuf *m = dtom(slirp, ip);\n\tregister struct ipasfrag *q;\n\tint hlen = ip->ip_hl << 2;\n\tint i, next;\n\n\tDEBUG_CALL(\"ip_reass\");\n\tDEBUG_ARG(\"ip = %lx\", (long)ip);\n\tDEBUG_ARG(\"fp = %lx\", (long)fp);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n\t/*\n\t * Presence of header sizes in mbufs\n\t * would confuse code below.\n * Fragment m_data is concatenated.\n\t */\n\tm->m_data += hlen;\n\tm->m_len -= hlen;\n\n\t/*\n\t * If first fragment to arrive, create a reassembly queue.\n\t */\n if (fp == NULL) {\n\t struct mbuf *t = m_get(slirp);\n\n\t if (t == NULL) {\n\t goto dropfrag;\n\t }\n\t fp = mtod(t, struct ipq *);\n\t insque(&fp->ip_link, &slirp->ipq.ip_link);\n\t fp->ipq_ttl = IPFRAGTTL;\n\t fp->ipq_p = ip->ip_p;\n\t fp->ipq_id = ip->ip_id;\n\t fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;\n\t fp->ipq_src = ip->ip_src;\n\t fp->ipq_dst = ip->ip_dst;\n\t q = (struct ipasfrag *)fp;\n\t goto insert;\n\t}\n\n\t/*\n\t * Find a segment which begins after this one does.\n\t */\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next)\n\t\tif (q->ipf_off > ip->ip_off)\n\t\t\tbreak;\n\n\t/*\n\t * If there is a preceding segment, it may provide some of\n\t * our data already. If so, drop the data from the incoming\n\t * segment. If it provides all of our data, drop us.\n\t */\n\tif (q->ipf_prev != &fp->frag_link) {\n struct ipasfrag *pq = q->ipf_prev;\n\t\ti = pq->ipf_off + pq->ipf_len - ip->ip_off;\n\t\tif (i > 0) {\n\t\t\tif (i >= ip->ip_len)\n\t\t\t\tgoto dropfrag;\n\t\t\tm_adj(dtom(slirp, ip), i);\n\t\t\tip->ip_off += i;\n\t\t\tip->ip_len -= i;\n\t\t}\n\t}\n\n\t/*\n\t * While we overlap succeeding segments trim them or,\n\t * if they are completely covered, dequeue them.\n\t */\n\twhile (q != (struct ipasfrag*)&fp->frag_link &&\n ip->ip_off + ip->ip_len > q->ipf_off) {\n\t\ti = (ip->ip_off + ip->ip_len) - q->ipf_off;\n\t\tif (i < q->ipf_len) {\n\t\t\tq->ipf_len -= i;\n\t\t\tq->ipf_off += i;\n\t\t\tm_adj(dtom(slirp, q), i);\n\t\t\tbreak;\n\t\t}\n\t\tq = q->ipf_next;\n\t\tm_freem(dtom(slirp, q->ipf_prev));\n\t\tip_deq(q->ipf_prev);\n\t}\n\ninsert:\n\t/*\n\t * Stick new segment in its place;\n\t * check for complete reassembly.\n\t */\n\tip_enq(iptofrag(ip), q->ipf_prev);\n\tnext = 0;\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link;\n q = q->ipf_next) {\n\t\tif (q->ipf_off != next)\n return NULL;\n\t\tnext += q->ipf_len;\n\t}\n\tif (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)\n return NULL;\n\n\t/*\n\t * Reassembly is complete; concatenate fragments.\n\t */\n q = fp->frag_link.next;\n\tm = dtom(slirp, q);\n\n\tq = (struct ipasfrag *) q->ipf_next;\n\twhile (q != (struct ipasfrag*)&fp->frag_link) {\n\t struct mbuf *t = dtom(slirp, q);\n\t q = (struct ipasfrag *) q->ipf_next;\n\t m_cat(m, t);\n\t}\n\n\t/*\n\t * Create header for new ip packet by\n\t * modifying header of first packet;\n\t * dequeue and discard fragment reassembly header.\n\t * Make header visible.\n\t */\n\tq = fp->frag_link.next;\n\n\t/*\n\t * If the fragments concatenated to an mbuf that's\n\t * bigger than the total size of the fragment, then and\n\t * m_ext buffer was alloced. But fp->ipq_next points to\n\t * the old buffer (in the mbuf), so we must point ip\n\t * into the new buffer.\n\t */\n\tif (m->m_flags & M_EXT) {\n\t int delta = (char *)q - m->m_dat;\n\t q = (struct ipasfrag *)(m->m_ext + delta);\n\t}\n\n ip = fragtoip(q);\n\tip->ip_len = next;\n\tip->ip_tos &= ~1;\n\tip->ip_src = fp->ipq_src;\n\tip->ip_dst = fp->ipq_dst;\n\tremque(&fp->ip_link);\n\t(void) m_free(dtom(slirp, fp));\n\tm->m_len += (ip->ip_hl << 2);\n\tm->m_data -= (ip->ip_hl << 2);\n\n\treturn ip;\n\ndropfrag:\n\tm_freem(m);\n return NULL;\n}\n\n/*\n * Free a fragment reassembly header and all\n * associated datagrams.\n */\nstatic void\nip_freef(Slirp *slirp, struct ipq *fp)\n{\n\tregister struct ipasfrag *q, *p;\n\n\tfor (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link; q = p) {\n\t\tp = q->ipf_next;\n\t\tip_deq(q);\n\t\tm_freem(dtom(slirp, q));\n\t}\n\tremque(&fp->ip_link);\n\t(void) m_free(dtom(slirp, fp));\n}\n\n/*\n * Put an ip fragment on a reassembly chain.\n * Like insque, but pointers in middle of structure.\n */\nstatic void\nip_enq(register struct ipasfrag *p, register struct ipasfrag *prev)\n{\n\tDEBUG_CALL(\"ip_enq\");\n\tDEBUG_ARG(\"prev = %lx\", (long)prev);\n\tp->ipf_prev = prev;\n\tp->ipf_next = prev->ipf_next;\n\t((struct ipasfrag *)(prev->ipf_next))->ipf_prev = p;\n\tprev->ipf_next = p;\n}\n\n/*\n * To ip_enq as remque is to insque.\n */\nstatic void\nip_deq(register struct ipasfrag *p)\n{\n\t((struct ipasfrag *)(p->ipf_prev))->ipf_next = p->ipf_next;\n\t((struct ipasfrag *)(p->ipf_next))->ipf_prev = p->ipf_prev;\n}\n\n/*\n * IP timer processing;\n * if a timer expires on a reassembly\n * queue, discard it.\n */\nvoid\nip_slowtimo(Slirp *slirp)\n{\n struct qlink *l;\n\n\tDEBUG_CALL(\"ip_slowtimo\");\n\n l = slirp->ipq.ip_link.next;\n\n if (l == NULL)\n\t return;\n\n while (l != &slirp->ipq.ip_link) {\n struct ipq *fp = container_of(l, struct ipq, ip_link);\n l = l->next;\n\t\tif (--fp->ipq_ttl == 0) {\n\t\t\tip_freef(slirp, fp);\n\t\t}\n }\n}\n\n/*\n * Do option processing on a datagram,\n * possibly discarding it if bad options are encountered,\n * or forwarding it if source-routed.\n * Returns 1 if packet has been forwarded/freed,\n * 0 if the packet should be processed further.\n */\n\n#ifdef notdef\n\nint\nip_dooptions(m)\n\tstruct mbuf *m;\n{\n\tregister struct ip *ip = mtod(m, struct ip *);\n\tregister u_char *cp;\n\tregister struct ip_timestamp *ipt;\n\tregister struct in_ifaddr *ia;\n\tint opt, optlen, cnt, off, code, type, forward = 0;\n\tstruct in_addr *sin, dst;\ntypedef uint32_t n_time;\n\tn_time ntime;\n\n\tdst = ip->ip_dst;\n\tcp = (u_char *)(ip + 1);\n\tcnt = (ip->ip_hl << 2) - sizeof (struct ip);\n\tfor (; cnt > 0; cnt -= optlen, cp += optlen) {\n\t\topt = cp[IPOPT_OPTVAL];\n\t\tif (opt == IPOPT_EOL)\n\t\t\tbreak;\n\t\tif (opt == IPOPT_NOP)\n\t\t\toptlen = 1;\n\t\telse {\n\t\t\toptlen = cp[IPOPT_OLEN];\n\t\t\tif (optlen <= 0 || optlen > cnt) {\n\t\t\t\tcode = &cp[IPOPT_OLEN] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t}\n\t\tswitch (opt) {\n\n\t\tdefault:\n\t\t\tbreak;\n\n\t\t/*\n\t\t * Source routing with record.\n\t\t * Find interface with current destination address.\n\t\t * If none on this machine then drop if strictly routed,\n\t\t * or do nothing if loosely routed.\n\t\t * Record interface address and bring up next address\n\t\t * component. If strictly routed make sure next\n\t\t * address is on directly accessible net.\n\t\t */\n\t\tcase IPOPT_LSRR:\n\t\tcase IPOPT_SSRR:\n\t\t\tif ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {\n\t\t\t\tcode = &cp[IPOPT_OFFSET] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tipaddr.sin_addr = ip->ip_dst;\n\t\t\tia = (struct in_ifaddr *)\n\t\t\t\tifa_ifwithaddr((struct sockaddr *)&ipaddr);\n\t\t\tif (ia == 0) {\n\t\t\t\tif (opt == IPOPT_SSRR) {\n\t\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\t\tcode = ICMP_UNREACH_SRCFAIL;\n\t\t\t\t\tgoto bad;\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Loose routing, and not at next destination\n\t\t\t\t * yet; nothing to do except forward.\n\t\t\t\t */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toff--;\t\t\t/ * 0 origin * /\n\t\t\tif (off > optlen - sizeof(struct in_addr)) {\n\t\t\t\t/*\n\t\t\t\t * End of source route. Should be for us.\n\t\t\t\t */\n\t\t\t\tsave_rte(cp, ip->ip_src);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/*\n\t\t\t * locate outgoing interface\n\t\t\t */\n\t\t\tbcopy((caddr_t)(cp + off), (caddr_t)&ipaddr.sin_addr,\n\t\t\t sizeof(ipaddr.sin_addr));\n\t\t\tif (opt == IPOPT_SSRR) {\n#define\tINA\tstruct in_ifaddr *\n#define\tSA\tstruct sockaddr *\n \t\t\t if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)\n\t\t\t\tia = (INA)ifa_ifwithnet((SA)&ipaddr);\n\t\t\t} else\n\t\t\t\tia = ip_rtaddr(ipaddr.sin_addr);\n\t\t\tif (ia == 0) {\n\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\tcode = ICMP_UNREACH_SRCFAIL;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tip->ip_dst = ipaddr.sin_addr;\n\t\t\tbcopy((caddr_t)&(IA_SIN(ia)->sin_addr),\n\t\t\t (caddr_t)(cp + off), sizeof(struct in_addr));\n\t\t\tcp[IPOPT_OFFSET] += sizeof(struct in_addr);\n\t\t\t/*\n\t\t\t * Let ip_intr's mcast routing check handle mcast pkts\n\t\t\t */\n\t\t\tforward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));\n\t\t\tbreak;\n\n\t\tcase IPOPT_RR:\n\t\t\tif ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {\n\t\t\t\tcode = &cp[IPOPT_OFFSET] - (u_char *)ip;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\t/*\n\t\t\t * If no space remains, ignore.\n\t\t\t */\n\t\t\toff--;\t\t\t * 0 origin *\n\t\t\tif (off > optlen - sizeof(struct in_addr))\n\t\t\t\tbreak;\n\t\t\tbcopy((caddr_t)(&ip->ip_dst), (caddr_t)&ipaddr.sin_addr,\n\t\t\t sizeof(ipaddr.sin_addr));\n\t\t\t/*\n\t\t\t * locate outgoing interface; if we're the destination,\n\t\t\t * use the incoming interface (should be same).\n\t\t\t */\n\t\t\tif ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&\n\t\t\t (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {\n\t\t\t\ttype = ICMP_UNREACH;\n\t\t\t\tcode = ICMP_UNREACH_HOST;\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tbcopy((caddr_t)&(IA_SIN(ia)->sin_addr),\n\t\t\t (caddr_t)(cp + off), sizeof(struct in_addr));\n\t\t\tcp[IPOPT_OFFSET] += sizeof(struct in_addr);\n\t\t\tbreak;\n\n\t\tcase IPOPT_TS:\n\t\t\tcode = cp - (u_char *)ip;\n\t\t\tipt = (struct ip_timestamp *)cp;\n\t\t\tif (ipt->ipt_len < 5)\n\t\t\t\tgoto bad;\n\t\t\tif (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {\n\t\t\t\tif (++ipt->ipt_oflw == 0)\n\t\t\t\t\tgoto bad;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);\n\t\t\tswitch (ipt->ipt_flg) {\n\n\t\t\tcase IPOPT_TS_TSONLY:\n\t\t\t\tbreak;\n\n\t\t\tcase IPOPT_TS_TSANDADDR:\n\t\t\t\tif (ipt->ipt_ptr + sizeof(n_time) +\n\t\t\t\t sizeof(struct in_addr) > ipt->ipt_len)\n\t\t\t\t\tgoto bad;\n\t\t\t\tipaddr.sin_addr = dst;\n\t\t\t\tia = (INA)ifaof_ i f p foraddr((SA)&ipaddr,\n\t\t\t\t\t\t\t m->m_pkthdr.rcvif);\n\t\t\t\tif (ia == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tbcopy((caddr_t)&IA_SIN(ia)->sin_addr,\n\t\t\t\t (caddr_t)sin, sizeof(struct in_addr));\n\t\t\t\tipt->ipt_ptr += sizeof(struct in_addr);\n\t\t\t\tbreak;\n\n\t\t\tcase IPOPT_TS_PRESPEC:\n\t\t\t\tif (ipt->ipt_ptr + sizeof(n_time) +\n\t\t\t\t sizeof(struct in_addr) > ipt->ipt_len)\n\t\t\t\t\tgoto bad;\n\t\t\t\tbcopy((caddr_t)sin, (caddr_t)&ipaddr.sin_addr,\n\t\t\t\t sizeof(struct in_addr));\n\t\t\t\tif (ifa_ifwithaddr((SA)&ipaddr) == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tipt->ipt_ptr += sizeof(struct in_addr);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tntime = iptime();\n\t\t\tbcopy((caddr_t)&ntime, (caddr_t)cp + ipt->ipt_ptr - 1,\n\t\t\t sizeof(n_time));\n\t\t\tipt->ipt_ptr += sizeof(n_time);\n\t\t}\n\t}\n\tif (forward) {\n\t\tip_forward(m, 1);\n\t\treturn (1);\n\t}\n\treturn (0);\nbad:\n \ticmp_error(m, type, code, 0, 0);\n\n\treturn (1);\n}\n\n#endif /* notdef */\n\n/*\n * Strip out IP options, at higher\n * level protocol in the kernel.\n * Second argument is buffer to which options\n * will be moved, and return value is their length.\n * (XXX) should be deleted; last arg currently ignored.\n */\nvoid\nip_stripoptions(register struct mbuf *m, struct mbuf *mopt)\n{\n\tregister int i;\n\tstruct ip *ip = mtod(m, struct ip *);\n\tregister caddr_t opts;\n\tint olen;\n\n\tolen = (ip->ip_hl<<2) - sizeof (struct ip);\n\topts = (caddr_t)(ip + 1);\n\ti = m->m_len - (sizeof (struct ip) + olen);\n\tmemcpy(opts, opts + olen, (unsigned)i);\n\tm->m_len -= olen;\n\n\tip->ip_hl = sizeof(struct ip) >> 2;\n}\n"], ["/linuxpdf/tinyemu/slirp/misc.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n#ifdef DEBUG\nint slirp_debug = DBG_CALL|DBG_MISC|DBG_ERROR;\n#endif\n\nstruct quehead {\n\tstruct quehead *qh_link;\n\tstruct quehead *qh_rlink;\n};\n\ninline void\ninsque(void *a, void *b)\n{\n\tregister struct quehead *element = (struct quehead *) a;\n\tregister struct quehead *head = (struct quehead *) b;\n\telement->qh_link = head->qh_link;\n\thead->qh_link = (struct quehead *)element;\n\telement->qh_rlink = (struct quehead *)head;\n\t((struct quehead *)(element->qh_link))->qh_rlink\n\t= (struct quehead *)element;\n}\n\ninline void\nremque(void *a)\n{\n register struct quehead *element = (struct quehead *) a;\n ((struct quehead *)(element->qh_link))->qh_rlink = element->qh_rlink;\n ((struct quehead *)(element->qh_rlink))->qh_link = element->qh_link;\n element->qh_rlink = NULL;\n}\n\nint add_exec(struct ex_list **ex_ptr, int do_pty, char *exec,\n struct in_addr addr, int port)\n{\n\tstruct ex_list *tmp_ptr;\n\n\t/* First, check if the port is \"bound\" */\n\tfor (tmp_ptr = *ex_ptr; tmp_ptr; tmp_ptr = tmp_ptr->ex_next) {\n\t\tif (port == tmp_ptr->ex_fport &&\n\t\t addr.s_addr == tmp_ptr->ex_addr.s_addr)\n\t\t\treturn -1;\n\t}\n\n\ttmp_ptr = *ex_ptr;\n\t*ex_ptr = (struct ex_list *)malloc(sizeof(struct ex_list));\n\t(*ex_ptr)->ex_fport = port;\n\t(*ex_ptr)->ex_addr = addr;\n\t(*ex_ptr)->ex_pty = do_pty;\n\t(*ex_ptr)->ex_exec = (do_pty == 3) ? exec : strdup(exec);\n\t(*ex_ptr)->ex_next = tmp_ptr;\n\treturn 0;\n}\n\n#ifndef HAVE_STRERROR\n\n/*\n * For systems with no strerror\n */\n\nextern int sys_nerr;\nextern char *sys_errlist[];\n\nchar *\nstrerror(error)\n\tint error;\n{\n\tif (error < sys_nerr)\n\t return sys_errlist[error];\n\telse\n\t return \"Unknown error.\";\n}\n\n#endif\n\nint os_socket(int domain, int type, int protocol)\n{\n return socket(domain, type, protocol);\n}\n\nuint32_t os_get_time_ms(void)\n{\n struct timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC, &ts);\n return ts.tv_sec * 1000 +\n (ts.tv_nsec / 1000000);\n}\n\n\n#if 1\n\nint\nfork_exec(struct socket *so, const char *ex, int do_pty)\n{\n /* not implemented */\n return 0;\n}\n\n#else\n\n/*\n * XXX This is ugly\n * We create and bind a socket, then fork off to another\n * process, which connects to this socket, after which we\n * exec the wanted program. If something (strange) happens,\n * the accept() call could block us forever.\n *\n * do_pty = 0 Fork/exec inetd style\n * do_pty = 1 Fork/exec using slirp.telnetd\n * do_ptr = 2 Fork/exec using pty\n */\nint\nfork_exec(struct socket *so, const char *ex, int do_pty)\n{\n\tint s;\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(addr);\n\tint opt;\n int master = -1;\n\tconst char *argv[256];\n\t/* don't want to clobber the original */\n\tchar *bptr;\n\tconst char *curarg;\n\tint c, i, ret;\n\n\tDEBUG_CALL(\"fork_exec\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"ex = %lx\", (long)ex);\n\tDEBUG_ARG(\"do_pty = %lx\", (long)do_pty);\n\n\tif (do_pty == 2) {\n return 0;\n\t} else {\n\t\taddr.sin_family = AF_INET;\n\t\taddr.sin_port = 0;\n\t\taddr.sin_addr.s_addr = INADDR_ANY;\n\n\t\tif ((s = os_socket(AF_INET, SOCK_STREAM, 0)) < 0 ||\n\t\t bind(s, (struct sockaddr *)&addr, addrlen) < 0 ||\n\t\t listen(s, 1) < 0) {\n\t\t\tlprint(\"Error: inet socket: %s\\n\", strerror(errno));\n\t\t\tclosesocket(s);\n\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tswitch(fork()) {\n\t case -1:\n\t\tlprint(\"Error: fork failed: %s\\n\", strerror(errno));\n\t\tclose(s);\n\t\tif (do_pty == 2)\n\t\t close(master);\n\t\treturn 0;\n\n\t case 0:\n\t\t/* Set the DISPLAY */\n\t\tif (do_pty == 2) {\n\t\t\t(void) close(master);\n#ifdef TIOCSCTTY /* XXXXX */\n\t\t\t(void) setsid();\n\t\t\tioctl(s, TIOCSCTTY, (char *)NULL);\n#endif\n\t\t} else {\n\t\t\tgetsockname(s, (struct sockaddr *)&addr, &addrlen);\n\t\t\tclose(s);\n\t\t\t/*\n\t\t\t * Connect to the socket\n\t\t\t * XXX If any of these fail, we're in trouble!\n\t \t\t */\n\t\t\ts = os_socket(AF_INET, SOCK_STREAM, 0);\n\t\t\taddr.sin_addr = loopback_addr;\n do {\n ret = connect(s, (struct sockaddr *)&addr, addrlen);\n } while (ret < 0 && errno == EINTR);\n\t\t}\n\n\t\tdup2(s, 0);\n\t\tdup2(s, 1);\n\t\tdup2(s, 2);\n\t\tfor (s = getdtablesize() - 1; s >= 3; s--)\n\t\t close(s);\n\n\t\ti = 0;\n\t\tbptr = qemu_strdup(ex); /* No need to free() this */\n\t\tif (do_pty == 1) {\n\t\t\t/* Setup \"slirp.telnetd -x\" */\n\t\t\targv[i++] = \"slirp.telnetd\";\n\t\t\targv[i++] = \"-x\";\n\t\t\targv[i++] = bptr;\n\t\t} else\n\t\t do {\n\t\t\t/* Change the string into argv[] */\n\t\t\tcurarg = bptr;\n\t\t\twhile (*bptr != ' ' && *bptr != (char)0)\n\t\t\t bptr++;\n\t\t\tc = *bptr;\n\t\t\t*bptr++ = (char)0;\n\t\t\targv[i++] = strdup(curarg);\n\t\t } while (c);\n\n argv[i] = NULL;\n\t\texecvp(argv[0], (char **)argv);\n\n\t\t/* Ooops, failed, let's tell the user why */\n fprintf(stderr, \"Error: execvp of %s failed: %s\\n\",\n argv[0], strerror(errno));\n\t\tclose(0); close(1); close(2); /* XXX */\n\t\texit(1);\n\n\t default:\n\t\tif (do_pty == 2) {\n\t\t\tclose(s);\n\t\t\tso->s = master;\n\t\t} else {\n\t\t\t/*\n\t\t\t * XXX this could block us...\n\t\t\t * XXX Should set a timer here, and if accept() doesn't\n\t\t \t * return after X seconds, declare it a failure\n\t\t \t * The only reason this will block forever is if socket()\n\t\t \t * of connect() fail in the child process\n\t\t \t */\n do {\n so->s = accept(s, (struct sockaddr *)&addr, &addrlen);\n } while (so->s < 0 && errno == EINTR);\n closesocket(s);\n\t\t\topt = 1;\n\t\t\tsetsockopt(so->s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\t\t\topt = 1;\n\t\t\tsetsockopt(so->s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\t\t}\n\t\tfd_nonblock(so->s);\n\n\t\t/* Append the telnet options now */\n if (so->so_m != NULL && do_pty == 1) {\n\t\t\tsbappend(so, so->so_m);\n so->so_m = NULL;\n\t\t}\n\n\t\treturn 1;\n\t}\n}\n#endif\n\n#ifndef HAVE_STRDUP\nchar *\nstrdup(str)\n\tconst char *str;\n{\n\tchar *bptr;\n\n\tbptr = (char *)malloc(strlen(str)+1);\n\tstrcpy(bptr, str);\n\n\treturn bptr;\n}\n#endif\n\nvoid lprint(const char *format, ...)\n{\n va_list args;\n\n va_start(args, format);\n vprintf(format, args);\n va_end(args);\n}\n\n/*\n * Set fd blocking and non-blocking\n */\n\nvoid\nfd_nonblock(int fd)\n{\n#ifdef FIONBIO\n#ifdef _WIN32\n unsigned long opt = 1;\n#else\n int opt = 1;\n#endif\n\n\tioctlsocket(fd, FIONBIO, &opt);\n#else\n\tint opt;\n\n\topt = fcntl(fd, F_GETFL, 0);\n\topt |= O_NONBLOCK;\n\tfcntl(fd, F_SETFL, opt);\n#endif\n}\n\nvoid\nfd_block(int fd)\n{\n#ifdef FIONBIO\n#ifdef _WIN32\n unsigned long opt = 0;\n#else\n\tint opt = 0;\n#endif\n\n\tioctlsocket(fd, FIONBIO, &opt);\n#else\n\tint opt;\n\n\topt = fcntl(fd, F_GETFL, 0);\n\topt &= ~O_NONBLOCK;\n\tfcntl(fd, F_SETFL, opt);\n#endif\n}\n\n#if 0\nvoid slirp_connection_info(Slirp *slirp, Monitor *mon)\n{\n const char * const tcpstates[] = {\n [TCPS_CLOSED] = \"CLOSED\",\n [TCPS_LISTEN] = \"LISTEN\",\n [TCPS_SYN_SENT] = \"SYN_SENT\",\n [TCPS_SYN_RECEIVED] = \"SYN_RCVD\",\n [TCPS_ESTABLISHED] = \"ESTABLISHED\",\n [TCPS_CLOSE_WAIT] = \"CLOSE_WAIT\",\n [TCPS_FIN_WAIT_1] = \"FIN_WAIT_1\",\n [TCPS_CLOSING] = \"CLOSING\",\n [TCPS_LAST_ACK] = \"LAST_ACK\",\n [TCPS_FIN_WAIT_2] = \"FIN_WAIT_2\",\n [TCPS_TIME_WAIT] = \"TIME_WAIT\",\n };\n struct in_addr dst_addr;\n struct sockaddr_in src;\n socklen_t src_len;\n uint16_t dst_port;\n struct socket *so;\n const char *state;\n char buf[20];\n int n;\n\n monitor_printf(mon, \" Protocol[State] FD Source Address Port \"\n \"Dest. Address Port RecvQ SendQ\\n\");\n\n for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {\n if (so->so_state & SS_HOSTFWD) {\n state = \"HOST_FORWARD\";\n } else if (so->so_tcpcb) {\n state = tcpstates[so->so_tcpcb->t_state];\n } else {\n state = \"NONE\";\n }\n if (so->so_state & (SS_HOSTFWD | SS_INCOMING)) {\n src_len = sizeof(src);\n getsockname(so->s, (struct sockaddr *)&src, &src_len);\n dst_addr = so->so_laddr;\n dst_port = so->so_lport;\n } else {\n src.sin_addr = so->so_laddr;\n src.sin_port = so->so_lport;\n dst_addr = so->so_faddr;\n dst_port = so->so_fport;\n }\n n = snprintf(buf, sizeof(buf), \" TCP[%s]\", state);\n memset(&buf[n], ' ', 19 - n);\n buf[19] = 0;\n monitor_printf(mon, \"%s %3d %15s %5d \", buf, so->s,\n src.sin_addr.s_addr ? inet_ntoa(src.sin_addr) : \"*\",\n ntohs(src.sin_port));\n monitor_printf(mon, \"%15s %5d %5d %5d\\n\",\n inet_ntoa(dst_addr), ntohs(dst_port),\n so->so_rcv.sb_cc, so->so_snd.sb_cc);\n }\n\n for (so = slirp->udb.so_next; so != &slirp->udb; so = so->so_next) {\n if (so->so_state & SS_HOSTFWD) {\n n = snprintf(buf, sizeof(buf), \" UDP[HOST_FORWARD]\");\n src_len = sizeof(src);\n getsockname(so->s, (struct sockaddr *)&src, &src_len);\n dst_addr = so->so_laddr;\n dst_port = so->so_lport;\n } else {\n n = snprintf(buf, sizeof(buf), \" UDP[%d sec]\",\n (so->so_expire - curtime) / 1000);\n src.sin_addr = so->so_laddr;\n src.sin_port = so->so_lport;\n dst_addr = so->so_faddr;\n dst_port = so->so_fport;\n }\n memset(&buf[n], ' ', 19 - n);\n buf[19] = 0;\n monitor_printf(mon, \"%s %3d %15s %5d \", buf, so->s,\n src.sin_addr.s_addr ? inet_ntoa(src.sin_addr) : \"*\",\n ntohs(src.sin_port));\n monitor_printf(mon, \"%15s %5d %5d %5d\\n\",\n inet_ntoa(dst_addr), ntohs(dst_port),\n so->so_rcv.sb_cc, so->so_snd.sb_cc);\n }\n}\n#endif\n"], ["/linuxpdf/tinyemu/slirp/tcp_input.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_input.c\t8.5 (Berkeley) 4/10/94\n * tcp_input.c,v 1.10 1994/10/13 18:36:32 wollman Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n#define\tTCPREXMTTHRESH 3\n\n#define TCP_PAWS_IDLE\t(24 * 24 * 60 * 60 * PR_SLOWHZ)\n\n/* for modulo comparisons of timestamps */\n#define TSTMP_LT(a,b)\t((int)((a)-(b)) < 0)\n#define TSTMP_GEQ(a,b)\t((int)((a)-(b)) >= 0)\n\n/*\n * Insert segment ti into reassembly queue of tcp with\n * control block tp. Return TH_FIN if reassembly now includes\n * a segment with FIN. The macro form does the common case inline\n * (segment is the next to be received on an established connection,\n * and the queue is empty), avoiding linkage into and removal\n * from the queue and repetition of various conversions.\n * Set DELACK for segments received in order, but ack immediately\n * when segments are out of order (so fast retransmit can work).\n */\n#ifdef TCP_ACK_HACK\n#define TCP_REASS(tp, ti, m, so, flags) {\\\n if ((ti)->ti_seq == (tp)->rcv_nxt && \\\n tcpfrag_list_empty(tp) && \\\n (tp)->t_state == TCPS_ESTABLISHED) {\\\n if (ti->ti_flags & TH_PUSH) \\\n tp->t_flags |= TF_ACKNOW; \\\n else \\\n tp->t_flags |= TF_DELACK; \\\n (tp)->rcv_nxt += (ti)->ti_len; \\\n flags = (ti)->ti_flags & TH_FIN; \\\n if (so->so_emu) { \\\n\t\t if (tcp_emu((so),(m))) sbappend((so), (m)); \\\n\t } else \\\n\t \t sbappend((so), (m)); \\\n\t} else {\\\n (flags) = tcp_reass((tp), (ti), (m)); \\\n tp->t_flags |= TF_ACKNOW; \\\n } \\\n}\n#else\n#define\tTCP_REASS(tp, ti, m, so, flags) { \\\n\tif ((ti)->ti_seq == (tp)->rcv_nxt && \\\n tcpfrag_list_empty(tp) && \\\n\t (tp)->t_state == TCPS_ESTABLISHED) { \\\n\t\ttp->t_flags |= TF_DELACK; \\\n\t\t(tp)->rcv_nxt += (ti)->ti_len; \\\n\t\tflags = (ti)->ti_flags & TH_FIN; \\\n\t\tif (so->so_emu) { \\\n\t\t\tif (tcp_emu((so),(m))) sbappend(so, (m)); \\\n\t\t} else \\\n\t\t\tsbappend((so), (m)); \\\n\t} else { \\\n\t\t(flags) = tcp_reass((tp), (ti), (m)); \\\n\t\ttp->t_flags |= TF_ACKNOW; \\\n\t} \\\n}\n#endif\nstatic void tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt,\n struct tcpiphdr *ti);\nstatic void tcp_xmit_timer(register struct tcpcb *tp, int rtt);\n\nstatic int\ntcp_reass(register struct tcpcb *tp, register struct tcpiphdr *ti,\n struct mbuf *m)\n{\n\tregister struct tcpiphdr *q;\n\tstruct socket *so = tp->t_socket;\n\tint flags;\n\n\t/*\n\t * Call with ti==NULL after become established to\n\t * force pre-ESTABLISHED data up to user socket.\n\t */\n if (ti == NULL)\n\t\tgoto present;\n\n\t/*\n\t * Find a segment which begins after this one does.\n\t */\n\tfor (q = tcpfrag_list_first(tp); !tcpfrag_list_end(q, tp);\n q = tcpiphdr_next(q))\n\t\tif (SEQ_GT(q->ti_seq, ti->ti_seq))\n\t\t\tbreak;\n\n\t/*\n\t * If there is a preceding segment, it may provide some of\n\t * our data already. If so, drop the data from the incoming\n\t * segment. If it provides all of our data, drop us.\n\t */\n\tif (!tcpfrag_list_end(tcpiphdr_prev(q), tp)) {\n\t\tregister int i;\n\t\tq = tcpiphdr_prev(q);\n\t\t/* conversion to int (in i) handles seq wraparound */\n\t\ti = q->ti_seq + q->ti_len - ti->ti_seq;\n\t\tif (i > 0) {\n\t\t\tif (i >= ti->ti_len) {\n\t\t\t\tm_freem(m);\n\t\t\t\t/*\n\t\t\t\t * Try to present any queued data\n\t\t\t\t * at the left window edge to the user.\n\t\t\t\t * This is needed after the 3-WHS\n\t\t\t\t * completes.\n\t\t\t\t */\n\t\t\t\tgoto present; /* ??? */\n\t\t\t}\n\t\t\tm_adj(m, i);\n\t\t\tti->ti_len -= i;\n\t\t\tti->ti_seq += i;\n\t\t}\n\t\tq = tcpiphdr_next(q);\n\t}\n\tti->ti_mbuf = m;\n\n\t/*\n\t * While we overlap succeeding segments trim them or,\n\t * if they are completely covered, dequeue them.\n\t */\n\twhile (!tcpfrag_list_end(q, tp)) {\n\t\tregister int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;\n\t\tif (i <= 0)\n\t\t\tbreak;\n\t\tif (i < q->ti_len) {\n\t\t\tq->ti_seq += i;\n\t\t\tq->ti_len -= i;\n\t\t\tm_adj(q->ti_mbuf, i);\n\t\t\tbreak;\n\t\t}\n\t\tq = tcpiphdr_next(q);\n\t\tm = tcpiphdr_prev(q)->ti_mbuf;\n\t\tremque(tcpiphdr2qlink(tcpiphdr_prev(q)));\n\t\tm_freem(m);\n\t}\n\n\t/*\n\t * Stick new segment in its place.\n\t */\n\tinsque(tcpiphdr2qlink(ti), tcpiphdr2qlink(tcpiphdr_prev(q)));\n\npresent:\n\t/*\n\t * Present data to user, advancing rcv_nxt through\n\t * completed sequence space.\n\t */\n\tif (!TCPS_HAVEESTABLISHED(tp->t_state))\n\t\treturn (0);\n\tti = tcpfrag_list_first(tp);\n\tif (tcpfrag_list_end(ti, tp) || ti->ti_seq != tp->rcv_nxt)\n\t\treturn (0);\n\tif (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)\n\t\treturn (0);\n\tdo {\n\t\ttp->rcv_nxt += ti->ti_len;\n\t\tflags = ti->ti_flags & TH_FIN;\n\t\tremque(tcpiphdr2qlink(ti));\n\t\tm = ti->ti_mbuf;\n\t\tti = tcpiphdr_next(ti);\n\t\tif (so->so_state & SS_FCANTSENDMORE)\n\t\t\tm_freem(m);\n\t\telse {\n\t\t\tif (so->so_emu) {\n\t\t\t\tif (tcp_emu(so,m)) sbappend(so, m);\n\t\t\t} else\n\t\t\t\tsbappend(so, m);\n\t\t}\n\t} while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);\n\treturn (flags);\n}\n\n/*\n * TCP input routine, follows pages 65-76 of the\n * protocol specification dated September, 1981 very closely.\n */\nvoid\ntcp_input(struct mbuf *m, int iphlen, struct socket *inso)\n{\n \tstruct ip save_ip, *ip;\n\tregister struct tcpiphdr *ti;\n\tcaddr_t optp = NULL;\n\tint optlen = 0;\n\tint len, tlen, off;\n register struct tcpcb *tp = NULL;\n\tregister int tiflags;\n struct socket *so = NULL;\n\tint todrop, acked, ourfinisacked, needoutput = 0;\n\tint iss = 0;\n\tu_long tiwin;\n\tint ret;\n struct ex_list *ex_ptr;\n Slirp *slirp;\n\n\tDEBUG_CALL(\"tcp_input\");\n\tDEBUG_ARGS((dfd,\" m = %8lx iphlen = %2d inso = %lx\\n\",\n\t\t (long )m, iphlen, (long )inso ));\n\n\t/*\n\t * If called with m == 0, then we're continuing the connect\n\t */\n\tif (m == NULL) {\n\t\tso = inso;\n\t\tslirp = so->slirp;\n\n\t\t/* Re-set a few variables */\n\t\ttp = sototcpcb(so);\n\t\tm = so->so_m;\n so->so_m = NULL;\n\t\tti = so->so_ti;\n\t\ttiwin = ti->ti_win;\n\t\ttiflags = ti->ti_flags;\n\n\t\tgoto cont_conn;\n\t}\n\tslirp = m->slirp;\n\n\t/*\n\t * Get IP and TCP header together in first mbuf.\n\t * Note: IP leaves IP header in first mbuf.\n\t */\n\tti = mtod(m, struct tcpiphdr *);\n\tif (iphlen > sizeof(struct ip )) {\n\t ip_stripoptions(m, (struct mbuf *)0);\n\t iphlen=sizeof(struct ip );\n\t}\n\t/* XXX Check if too short */\n\n\n\t/*\n\t * Save a copy of the IP header in case we want restore it\n\t * for sending an ICMP error message in response.\n\t */\n\tip=mtod(m, struct ip *);\n\tsave_ip = *ip;\n\tsave_ip.ip_len+= iphlen;\n\n\t/*\n\t * Checksum extended TCP header and data.\n\t */\n\ttlen = ((struct ip *)ti)->ip_len;\n tcpiphdr2qlink(ti)->next = tcpiphdr2qlink(ti)->prev = NULL;\n memset(&ti->ti_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));\n\tti->ti_x1 = 0;\n\tti->ti_len = htons((uint16_t)tlen);\n\tlen = sizeof(struct ip ) + tlen;\n\tif(cksum(m, len)) {\n\t goto drop;\n\t}\n\n\t/*\n\t * Check that TCP offset makes sense,\n\t * pull out TCP options and adjust length.\t\tXXX\n\t */\n\toff = ti->ti_off << 2;\n\tif (off < sizeof (struct tcphdr) || off > tlen) {\n\t goto drop;\n\t}\n\ttlen -= off;\n\tti->ti_len = tlen;\n\tif (off > sizeof (struct tcphdr)) {\n\t optlen = off - sizeof (struct tcphdr);\n\t optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);\n\t}\n\ttiflags = ti->ti_flags;\n\n\t/*\n\t * Convert TCP protocol specific fields to host format.\n\t */\n\tNTOHL(ti->ti_seq);\n\tNTOHL(ti->ti_ack);\n\tNTOHS(ti->ti_win);\n\tNTOHS(ti->ti_urp);\n\n\t/*\n\t * Drop TCP, IP headers and TCP options.\n\t */\n\tm->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\tm->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\n if (slirp->restricted) {\n for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {\n if (ex_ptr->ex_fport == ti->ti_dport &&\n ti->ti_dst.s_addr == ex_ptr->ex_addr.s_addr) {\n break;\n }\n }\n if (!ex_ptr)\n goto drop;\n }\n\t/*\n\t * Locate pcb for segment.\n\t */\nfindso:\n\tso = slirp->tcp_last_so;\n\tif (so->so_fport != ti->ti_dport ||\n\t so->so_lport != ti->ti_sport ||\n\t so->so_laddr.s_addr != ti->ti_src.s_addr ||\n\t so->so_faddr.s_addr != ti->ti_dst.s_addr) {\n\t\tso = solookup(&slirp->tcb, ti->ti_src, ti->ti_sport,\n\t\t\t ti->ti_dst, ti->ti_dport);\n\t\tif (so)\n\t\t\tslirp->tcp_last_so = so;\n\t}\n\n\t/*\n\t * If the state is CLOSED (i.e., TCB does not exist) then\n\t * all data in the incoming segment is discarded.\n\t * If the TCB exists but is in CLOSED state, it is embryonic,\n\t * but should either do a listen or a connect soon.\n\t *\n\t * state == CLOSED means we've done socreate() but haven't\n\t * attached it to a protocol yet...\n\t *\n\t * XXX If a TCB does not exist, and the TH_SYN flag is\n\t * the only flag set, then create a session, mark it\n\t * as if it was LISTENING, and continue...\n\t */\n if (so == NULL) {\n\t if ((tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) != TH_SYN)\n\t goto dropwithreset;\n\n\t if ((so = socreate(slirp)) == NULL)\n\t goto dropwithreset;\n\t if (tcp_attach(so) < 0) {\n\t free(so); /* Not sofree (if it failed, it's not insqued) */\n\t goto dropwithreset;\n\t }\n\n\t sbreserve(&so->so_snd, TCP_SNDSPACE);\n\t sbreserve(&so->so_rcv, TCP_RCVSPACE);\n\n\t so->so_laddr = ti->ti_src;\n\t so->so_lport = ti->ti_sport;\n\t so->so_faddr = ti->ti_dst;\n\t so->so_fport = ti->ti_dport;\n\n\t if ((so->so_iptos = tcp_tos(so)) == 0)\n\t so->so_iptos = ((struct ip *)ti)->ip_tos;\n\n\t tp = sototcpcb(so);\n\t tp->t_state = TCPS_LISTEN;\n\t}\n\n /*\n * If this is a still-connecting socket, this probably\n * a retransmit of the SYN. Whether it's a retransmit SYN\n\t * or something else, we nuke it.\n */\n if (so->so_state & SS_ISFCONNECTING)\n goto drop;\n\n\ttp = sototcpcb(so);\n\n\t/* XXX Should never fail */\n if (tp == NULL)\n\t\tgoto dropwithreset;\n\tif (tp->t_state == TCPS_CLOSED)\n\t\tgoto drop;\n\n\ttiwin = ti->ti_win;\n\n\t/*\n\t * Segment received on connection.\n\t * Reset idle time and keep-alive timer.\n\t */\n\ttp->t_idle = 0;\n\tif (SO_OPTIONS)\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;\n\telse\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;\n\n\t/*\n\t * Process options if not in LISTEN state,\n\t * else do it below (after getting remote address).\n\t */\n\tif (optp && tp->t_state != TCPS_LISTEN)\n\t\ttcp_dooptions(tp, (u_char *)optp, optlen, ti);\n\n\t/*\n\t * Header prediction: check for the two common cases\n\t * of a uni-directional data xfer. If the packet has\n\t * no control flags, is in-sequence, the window didn't\n\t * change and we're not retransmitting, it's a\n\t * candidate. If the length is zero and the ack moved\n\t * forward, we're the sender side of the xfer. Just\n\t * free the data acked & wake any higher level process\n\t * that was blocked waiting for space. If the length\n\t * is non-zero and the ack didn't move, we're the\n\t * receiver side. If we're getting packets in-order\n\t * (the reassembly queue is empty), add the data to\n\t * the socket buffer and note that we need a delayed ack.\n\t *\n\t * XXX Some of these tests are not needed\n\t * eg: the tiwin == tp->snd_wnd prevents many more\n\t * predictions.. with no *real* advantage..\n\t */\n\tif (tp->t_state == TCPS_ESTABLISHED &&\n\t (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&\n\t ti->ti_seq == tp->rcv_nxt &&\n\t tiwin && tiwin == tp->snd_wnd &&\n\t tp->snd_nxt == tp->snd_max) {\n\t\tif (ti->ti_len == 0) {\n\t\t\tif (SEQ_GT(ti->ti_ack, tp->snd_una) &&\n\t\t\t SEQ_LEQ(ti->ti_ack, tp->snd_max) &&\n\t\t\t tp->snd_cwnd >= tp->snd_wnd) {\n\t\t\t\t/*\n\t\t\t\t * this is a pure ack for outstanding data.\n\t\t\t\t */\n\t\t\t\tif (tp->t_rtt &&\n\t\t\t\t SEQ_GT(ti->ti_ack, tp->t_rtseq))\n\t\t\t\t\ttcp_xmit_timer(tp, tp->t_rtt);\n\t\t\t\tacked = ti->ti_ack - tp->snd_una;\n\t\t\t\tsbdrop(&so->so_snd, acked);\n\t\t\t\ttp->snd_una = ti->ti_ack;\n\t\t\t\tm_freem(m);\n\n\t\t\t\t/*\n\t\t\t\t * If all outstanding data are acked, stop\n\t\t\t\t * retransmit timer, otherwise restart timer\n\t\t\t\t * using current (possibly backed-off) value.\n\t\t\t\t * If process is waiting for space,\n\t\t\t\t * wakeup/selwakeup/signal. If data\n\t\t\t\t * are ready to send, let tcp_output\n\t\t\t\t * decide between more output or persist.\n\t\t\t\t */\n\t\t\t\tif (tp->snd_una == tp->snd_max)\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\t\telse if (tp->t_timer[TCPT_PERSIST] == 0)\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\n\t\t\t\t/*\n\t\t\t\t * This is called because sowwakeup might have\n\t\t\t\t * put data into so_snd. Since we don't so sowwakeup,\n\t\t\t\t * we don't need this.. XXX???\n\t\t\t\t */\n\t\t\t\tif (so->so_snd.sb_cc)\n\t\t\t\t\t(void) tcp_output(tp);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (ti->ti_ack == tp->snd_una &&\n\t\t tcpfrag_list_empty(tp) &&\n\t\t ti->ti_len <= sbspace(&so->so_rcv)) {\n\t\t\t/*\n\t\t\t * this is a pure, in-sequence data packet\n\t\t\t * with nothing on the reassembly queue and\n\t\t\t * we have enough buffer space to take it.\n\t\t\t */\n\t\t\ttp->rcv_nxt += ti->ti_len;\n\t\t\t/*\n\t\t\t * Add data to socket buffer.\n\t\t\t */\n\t\t\tif (so->so_emu) {\n\t\t\t\tif (tcp_emu(so,m)) sbappend(so, m);\n\t\t\t} else\n\t\t\t\tsbappend(so, m);\n\n\t\t\t/*\n\t\t\t * If this is a short packet, then ACK now - with Nagel\n\t\t\t *\tcongestion avoidance sender won't send more until\n\t\t\t *\the gets an ACK.\n\t\t\t *\n\t\t\t * It is better to not delay acks at all to maximize\n\t\t\t * TCP throughput. See RFC 2581.\n\t\t\t */\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttcp_output(tp);\n\t\t\treturn;\n\t\t}\n\t} /* header prediction */\n\t/*\n\t * Calculate amount of space in receive window,\n\t * and then do TCP input processing.\n\t * Receive window is amount of space in rcv queue,\n\t * but not less than advertised window.\n\t */\n\t{ int win;\n win = sbspace(&so->so_rcv);\n\t if (win < 0)\n\t win = 0;\n\t tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));\n\t}\n\n\tswitch (tp->t_state) {\n\n\t/*\n\t * If the state is LISTEN then ignore segment if it contains an RST.\n\t * If the segment contains an ACK then it is bad and send a RST.\n\t * If it does not contain a SYN then it is not interesting; drop it.\n\t * Don't bother responding if the destination was a broadcast.\n\t * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial\n\t * tp->iss, and send a segment:\n\t * \n\t * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.\n\t * Fill in remote peer address fields if not previously specified.\n\t * Enter SYN_RECEIVED state, and process any other fields of this\n\t * segment in this state.\n\t */\n\tcase TCPS_LISTEN: {\n\n\t if (tiflags & TH_RST)\n\t goto drop;\n\t if (tiflags & TH_ACK)\n\t goto dropwithreset;\n\t if ((tiflags & TH_SYN) == 0)\n\t goto drop;\n\n\t /*\n\t * This has way too many gotos...\n\t * But a bit of spaghetti code never hurt anybody :)\n\t */\n\n\t /*\n\t * If this is destined for the control address, then flag to\n\t * tcp_ctl once connected, otherwise connect\n\t */\n\t if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n\t slirp->vnetwork_addr.s_addr) {\n\t if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr &&\n\t\tso->so_faddr.s_addr != slirp->vnameserver_addr.s_addr) {\n\t\t/* May be an add exec */\n\t\tfor (ex_ptr = slirp->exec_list; ex_ptr;\n\t\t ex_ptr = ex_ptr->ex_next) {\n\t\t if(ex_ptr->ex_fport == so->so_fport &&\n\t\t so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {\n\t\t so->so_state |= SS_CTL;\n\t\t break;\n\t\t }\n\t\t}\n\t\tif (so->so_state & SS_CTL) {\n\t\t goto cont_input;\n\t\t}\n\t }\n\t /* CTL_ALIAS: Do nothing, tcp_fconnect will be called on it */\n\t }\n\n\t if (so->so_emu & EMU_NOCONNECT) {\n\t so->so_emu &= ~EMU_NOCONNECT;\n\t goto cont_input;\n\t }\n\n\t if((tcp_fconnect(so) == -1) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK)) {\n\t u_char code=ICMP_UNREACH_NET;\n\t DEBUG_MISC((dfd,\" tcp fconnect errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t if(errno == ECONNREFUSED) {\n\t /* ACK the SYN, send RST to refuse the connection */\n\t tcp_respond(tp, ti, m, ti->ti_seq+1, (tcp_seq)0,\n\t\t\t TH_RST|TH_ACK);\n\t } else {\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t HTONL(ti->ti_seq); /* restore tcp header */\n\t HTONL(ti->ti_ack);\n\t HTONS(ti->ti_win);\n\t HTONS(ti->ti_urp);\n\t m->m_data -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\t m->m_len += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);\n\t *ip=save_ip;\n\t icmp_error(m, ICMP_UNREACH,code, 0,strerror(errno));\n\t }\n tcp_close(tp);\n\t m_free(m);\n\t } else {\n\t /*\n\t * Haven't connected yet, save the current mbuf\n\t * and ti, and return\n\t * XXX Some OS's don't tell us whether the connect()\n\t * succeeded or not. So we must time it out.\n\t */\n\t so->so_m = m;\n\t so->so_ti = ti;\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\t tp->t_state = TCPS_SYN_RECEIVED;\n\t }\n\t return;\n\n\tcont_conn:\n\t /* m==NULL\n\t * Check if the connect succeeded\n\t */\n\t if (so->so_state & SS_NOFDREF) {\n\t tp = tcp_close(tp);\n\t goto dropwithreset;\n\t }\n\tcont_input:\n\t tcp_template(tp);\n\n\t if (optp)\n\t tcp_dooptions(tp, (u_char *)optp, optlen, ti);\n\n\t if (iss)\n\t tp->iss = iss;\n\t else\n\t tp->iss = slirp->tcp_iss;\n\t slirp->tcp_iss += TCP_ISSINCR/2;\n\t tp->irs = ti->ti_seq;\n\t tcp_sendseqinit(tp);\n\t tcp_rcvseqinit(tp);\n\t tp->t_flags |= TF_ACKNOW;\n\t tp->t_state = TCPS_SYN_RECEIVED;\n\t tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;\n\t goto trimthenstep6;\n\t} /* case TCPS_LISTEN */\n\n\t/*\n\t * If the state is SYN_SENT:\n\t *\tif seg contains an ACK, but not for our SYN, drop the input.\n\t *\tif seg contains a RST, then drop the connection.\n\t *\tif seg does not contain SYN, then drop it.\n\t * Otherwise this is an acceptable SYN segment\n\t *\tinitialize tp->rcv_nxt and tp->irs\n\t *\tif seg contains ack then advance tp->snd_una\n\t *\tif SYN has been acked change to ESTABLISHED else SYN_RCVD state\n\t *\tarrange for segment to be acked (eventually)\n\t *\tcontinue processing rest of data/controls, beginning with URG\n\t */\n\tcase TCPS_SYN_SENT:\n\t\tif ((tiflags & TH_ACK) &&\n\t\t (SEQ_LEQ(ti->ti_ack, tp->iss) ||\n\t\t SEQ_GT(ti->ti_ack, tp->snd_max)))\n\t\t\tgoto dropwithreset;\n\n\t\tif (tiflags & TH_RST) {\n if (tiflags & TH_ACK) {\n tcp_drop(tp, 0); /* XXX Check t_softerror! */\n }\n\t\t\tgoto drop;\n\t\t}\n\n\t\tif ((tiflags & TH_SYN) == 0)\n\t\t\tgoto drop;\n\t\tif (tiflags & TH_ACK) {\n\t\t\ttp->snd_una = ti->ti_ack;\n\t\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_una))\n\t\t\t\ttp->snd_nxt = tp->snd_una;\n\t\t}\n\n\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\ttp->irs = ti->ti_seq;\n\t\ttcp_rcvseqinit(tp);\n\t\ttp->t_flags |= TF_ACKNOW;\n\t\tif (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {\n\t\t\tsoisfconnected(so);\n\t\t\ttp->t_state = TCPS_ESTABLISHED;\n\n\t\t\t(void) tcp_reass(tp, (struct tcpiphdr *)0,\n\t\t\t\t(struct mbuf *)0);\n\t\t\t/*\n\t\t\t * if we didn't have to retransmit the SYN,\n\t\t\t * use its rtt as our initial srtt & rtt var.\n\t\t\t */\n\t\t\tif (tp->t_rtt)\n\t\t\t\ttcp_xmit_timer(tp, tp->t_rtt);\n\t\t} else\n\t\t\ttp->t_state = TCPS_SYN_RECEIVED;\n\ntrimthenstep6:\n\t\t/*\n\t\t * Advance ti->ti_seq to correspond to first data byte.\n\t\t * If data, trim to stay within window,\n\t\t * dropping FIN if necessary.\n\t\t */\n\t\tti->ti_seq++;\n\t\tif (ti->ti_len > tp->rcv_wnd) {\n\t\t\ttodrop = ti->ti_len - tp->rcv_wnd;\n\t\t\tm_adj(m, -todrop);\n\t\t\tti->ti_len = tp->rcv_wnd;\n\t\t\ttiflags &= ~TH_FIN;\n\t\t}\n\t\ttp->snd_wl1 = ti->ti_seq - 1;\n\t\ttp->rcv_up = ti->ti_seq;\n\t\tgoto step6;\n\t} /* switch tp->t_state */\n\t/*\n\t * States other than LISTEN or SYN_SENT.\n\t * Check that at least some bytes of segment are within\n\t * receive window. If segment begins before rcv_nxt,\n\t * drop leading data (and SYN); if nothing left, just ack.\n\t */\n\ttodrop = tp->rcv_nxt - ti->ti_seq;\n\tif (todrop > 0) {\n\t\tif (tiflags & TH_SYN) {\n\t\t\ttiflags &= ~TH_SYN;\n\t\t\tti->ti_seq++;\n\t\t\tif (ti->ti_urp > 1)\n\t\t\t\tti->ti_urp--;\n\t\t\telse\n\t\t\t\ttiflags &= ~TH_URG;\n\t\t\ttodrop--;\n\t\t}\n\t\t/*\n\t\t * Following if statement from Stevens, vol. 2, p. 960.\n\t\t */\n\t\tif (todrop > ti->ti_len\n\t\t || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {\n\t\t\t/*\n\t\t\t * Any valid FIN must be to the left of the window.\n\t\t\t * At this point the FIN must be a duplicate or out\n\t\t\t * of sequence; drop it.\n\t\t\t */\n\t\t\ttiflags &= ~TH_FIN;\n\n\t\t\t/*\n\t\t\t * Send an ACK to resynchronize and drop any data.\n\t\t\t * But keep on processing for RST or ACK.\n\t\t\t */\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttodrop = ti->ti_len;\n\t\t}\n\t\tm_adj(m, todrop);\n\t\tti->ti_seq += todrop;\n\t\tti->ti_len -= todrop;\n\t\tif (ti->ti_urp > todrop)\n\t\t\tti->ti_urp -= todrop;\n\t\telse {\n\t\t\ttiflags &= ~TH_URG;\n\t\t\tti->ti_urp = 0;\n\t\t}\n\t}\n\t/*\n\t * If new data are received on a connection after the\n\t * user processes are gone, then RST the other end.\n\t */\n\tif ((so->so_state & SS_NOFDREF) &&\n\t tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {\n\t\ttp = tcp_close(tp);\n\t\tgoto dropwithreset;\n\t}\n\n\t/*\n\t * If segment ends after window, drop trailing data\n\t * (and PUSH and FIN); if nothing left, just ACK.\n\t */\n\ttodrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);\n\tif (todrop > 0) {\n\t\tif (todrop >= ti->ti_len) {\n\t\t\t/*\n\t\t\t * If a new connection request is received\n\t\t\t * while in TIME_WAIT, drop the old connection\n\t\t\t * and start over if the sequence numbers\n\t\t\t * are above the previous ones.\n\t\t\t */\n\t\t\tif (tiflags & TH_SYN &&\n\t\t\t tp->t_state == TCPS_TIME_WAIT &&\n\t\t\t SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {\n\t\t\t\tiss = tp->rcv_nxt + TCP_ISSINCR;\n\t\t\t\ttp = tcp_close(tp);\n\t\t\t\tgoto findso;\n\t\t\t}\n\t\t\t/*\n\t\t\t * If window is closed can only take segments at\n\t\t\t * window edge, and have to drop data and PUSH from\n\t\t\t * incoming segments. Continue processing, but\n\t\t\t * remember to ack. Otherwise, drop segment\n\t\t\t * and ack.\n\t\t\t */\n\t\t\tif (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {\n\t\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\t} else {\n\t\t\t\tgoto dropafterack;\n\t\t\t}\n\t\t}\n\t\tm_adj(m, -todrop);\n\t\tti->ti_len -= todrop;\n\t\ttiflags &= ~(TH_PUSH|TH_FIN);\n\t}\n\n\t/*\n\t * If the RST bit is set examine the state:\n\t * SYN_RECEIVED STATE:\n\t *\tIf passive open, return to LISTEN state.\n\t *\tIf active open, inform user that connection was refused.\n\t * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:\n\t *\tInform user that connection was reset, and close tcb.\n\t * CLOSING, LAST_ACK, TIME_WAIT STATES\n\t *\tClose the tcb.\n\t */\n\tif (tiflags&TH_RST) switch (tp->t_state) {\n\n\tcase TCPS_SYN_RECEIVED:\n\tcase TCPS_ESTABLISHED:\n\tcase TCPS_FIN_WAIT_1:\n\tcase TCPS_FIN_WAIT_2:\n\tcase TCPS_CLOSE_WAIT:\n\t\ttp->t_state = TCPS_CLOSED;\n tcp_close(tp);\n\t\tgoto drop;\n\n\tcase TCPS_CLOSING:\n\tcase TCPS_LAST_ACK:\n\tcase TCPS_TIME_WAIT:\n tcp_close(tp);\n\t\tgoto drop;\n\t}\n\n\t/*\n\t * If a SYN is in the window, then this is an\n\t * error and we send an RST and drop the connection.\n\t */\n\tif (tiflags & TH_SYN) {\n\t\ttp = tcp_drop(tp,0);\n\t\tgoto dropwithreset;\n\t}\n\n\t/*\n\t * If the ACK bit is off we drop the segment and return.\n\t */\n\tif ((tiflags & TH_ACK) == 0) goto drop;\n\n\t/*\n\t * Ack processing.\n\t */\n\tswitch (tp->t_state) {\n\t/*\n\t * In SYN_RECEIVED state if the ack ACKs our SYN then enter\n\t * ESTABLISHED state and continue processing, otherwise\n\t * send an RST. una<=ack<=max\n\t */\n\tcase TCPS_SYN_RECEIVED:\n\n\t\tif (SEQ_GT(tp->snd_una, ti->ti_ack) ||\n\t\t SEQ_GT(ti->ti_ack, tp->snd_max))\n\t\t\tgoto dropwithreset;\n\t\ttp->t_state = TCPS_ESTABLISHED;\n\t\t/*\n\t\t * The sent SYN is ack'ed with our sequence number +1\n\t\t * The first data byte already in the buffer will get\n\t\t * lost if no correction is made. This is only needed for\n\t\t * SS_CTL since the buffer is empty otherwise.\n\t\t * tp->snd_una++; or:\n\t\t */\n\t\ttp->snd_una=ti->ti_ack;\n\t\tif (so->so_state & SS_CTL) {\n\t\t /* So tcp_ctl reports the right state */\n\t\t ret = tcp_ctl(so);\n\t\t if (ret == 1) {\n\t\t soisfconnected(so);\n\t\t so->so_state &= ~SS_CTL; /* success XXX */\n\t\t } else if (ret == 2) {\n\t\t so->so_state &= SS_PERSISTENT_MASK;\n\t\t so->so_state |= SS_NOFDREF; /* CTL_CMD */\n\t\t } else {\n\t\t needoutput = 1;\n\t\t tp->t_state = TCPS_FIN_WAIT_1;\n\t\t }\n\t\t} else {\n\t\t soisfconnected(so);\n\t\t}\n\n\t\t(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);\n\t\ttp->snd_wl1 = ti->ti_seq - 1;\n\t\t/* Avoid ack processing; snd_una==ti_ack => dup ack */\n\t\tgoto synrx_to_est;\n\t\t/* fall into ... */\n\n\t/*\n\t * In ESTABLISHED state: drop duplicate ACKs; ACK out of range\n\t * ACKs. If the ack is in the range\n\t *\ttp->snd_una < ti->ti_ack <= tp->snd_max\n\t * then advance tp->snd_una to ti->ti_ack and drop\n\t * data from the retransmission queue. If this ACK reflects\n\t * more up to date window information we update our window information.\n\t */\n\tcase TCPS_ESTABLISHED:\n\tcase TCPS_FIN_WAIT_1:\n\tcase TCPS_FIN_WAIT_2:\n\tcase TCPS_CLOSE_WAIT:\n\tcase TCPS_CLOSING:\n\tcase TCPS_LAST_ACK:\n\tcase TCPS_TIME_WAIT:\n\n\t\tif (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {\n\t\t\tif (ti->ti_len == 0 && tiwin == tp->snd_wnd) {\n\t\t\t DEBUG_MISC((dfd,\" dup ack m = %lx so = %lx \\n\",\n\t\t\t\t (long )m, (long )so));\n\t\t\t\t/*\n\t\t\t\t * If we have outstanding data (other than\n\t\t\t\t * a window probe), this is a completely\n\t\t\t\t * duplicate ack (ie, window info didn't\n\t\t\t\t * change), the ack is the biggest we've\n\t\t\t\t * seen and we've seen exactly our rexmt\n\t\t\t\t * threshold of them, assume a packet\n\t\t\t\t * has been dropped and retransmit it.\n\t\t\t\t * Kludge snd_nxt & the congestion\n\t\t\t\t * window so we send only this one\n\t\t\t\t * packet.\n\t\t\t\t *\n\t\t\t\t * We know we're losing at the current\n\t\t\t\t * window size so do congestion avoidance\n\t\t\t\t * (set ssthresh to half the current window\n\t\t\t\t * and pull our congestion window back to\n\t\t\t\t * the new ssthresh).\n\t\t\t\t *\n\t\t\t\t * Dup acks mean that packets have left the\n\t\t\t\t * network (they're now cached at the receiver)\n\t\t\t\t * so bump cwnd by the amount in the receiver\n\t\t\t\t * to keep a constant cwnd packets in the\n\t\t\t\t * network.\n\t\t\t\t */\n\t\t\t\tif (tp->t_timer[TCPT_REXMT] == 0 ||\n\t\t\t\t ti->ti_ack != tp->snd_una)\n\t\t\t\t\ttp->t_dupacks = 0;\n\t\t\t\telse if (++tp->t_dupacks == TCPREXMTTHRESH) {\n\t\t\t\t\ttcp_seq onxt = tp->snd_nxt;\n\t\t\t\t\tu_int win =\n\t\t\t\t\t min(tp->snd_wnd, tp->snd_cwnd) / 2 /\n\t\t\t\t\t\ttp->t_maxseg;\n\n\t\t\t\t\tif (win < 2)\n\t\t\t\t\t\twin = 2;\n\t\t\t\t\ttp->snd_ssthresh = win * tp->t_maxseg;\n\t\t\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\t\t\ttp->t_rtt = 0;\n\t\t\t\t\ttp->snd_nxt = ti->ti_ack;\n\t\t\t\t\ttp->snd_cwnd = tp->t_maxseg;\n\t\t\t\t\t(void) tcp_output(tp);\n\t\t\t\t\ttp->snd_cwnd = tp->snd_ssthresh +\n\t\t\t\t\t tp->t_maxseg * tp->t_dupacks;\n\t\t\t\t\tif (SEQ_GT(onxt, tp->snd_nxt))\n\t\t\t\t\t\ttp->snd_nxt = onxt;\n\t\t\t\t\tgoto drop;\n\t\t\t\t} else if (tp->t_dupacks > TCPREXMTTHRESH) {\n\t\t\t\t\ttp->snd_cwnd += tp->t_maxseg;\n\t\t\t\t\t(void) tcp_output(tp);\n\t\t\t\t\tgoto drop;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\ttp->t_dupacks = 0;\n\t\t\tbreak;\n\t\t}\n\tsynrx_to_est:\n\t\t/*\n\t\t * If the congestion window was inflated to account\n\t\t * for the other side's cached packets, retract it.\n\t\t */\n\t\tif (tp->t_dupacks > TCPREXMTTHRESH &&\n\t\t tp->snd_cwnd > tp->snd_ssthresh)\n\t\t\ttp->snd_cwnd = tp->snd_ssthresh;\n\t\ttp->t_dupacks = 0;\n\t\tif (SEQ_GT(ti->ti_ack, tp->snd_max)) {\n\t\t\tgoto dropafterack;\n\t\t}\n\t\tacked = ti->ti_ack - tp->snd_una;\n\n\t\t/*\n\t\t * If transmit timer is running and timed sequence\n\t\t * number was acked, update smoothed round trip time.\n\t\t * Since we now have an rtt measurement, cancel the\n\t\t * timer backoff (cf., Phil Karn's retransmit alg.).\n\t\t * Recompute the initial retransmit timer.\n\t\t */\n\t\tif (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))\n\t\t\ttcp_xmit_timer(tp,tp->t_rtt);\n\n\t\t/*\n\t\t * If all outstanding data is acked, stop retransmit\n\t\t * timer and remember to restart (more output or persist).\n\t\t * If there is more data to be acked, restart retransmit\n\t\t * timer, using current (possibly backed-off) value.\n\t\t */\n\t\tif (ti->ti_ack == tp->snd_max) {\n\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\tneedoutput = 1;\n\t\t} else if (tp->t_timer[TCPT_PERSIST] == 0)\n\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t/*\n\t\t * When new data is acked, open the congestion window.\n\t\t * If the window gives us less than ssthresh packets\n\t\t * in flight, open exponentially (maxseg per packet).\n\t\t * Otherwise open linearly: maxseg per window\n\t\t * (maxseg^2 / cwnd per packet).\n\t\t */\n\t\t{\n\t\t register u_int cw = tp->snd_cwnd;\n\t\t register u_int incr = tp->t_maxseg;\n\n\t\t if (cw > tp->snd_ssthresh)\n\t\t incr = incr * incr / cw;\n\t\t tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<snd_scale);\n\t\t}\n\t\tif (acked > so->so_snd.sb_cc) {\n\t\t\ttp->snd_wnd -= so->so_snd.sb_cc;\n\t\t\tsbdrop(&so->so_snd, (int )so->so_snd.sb_cc);\n\t\t\tourfinisacked = 1;\n\t\t} else {\n\t\t\tsbdrop(&so->so_snd, acked);\n\t\t\ttp->snd_wnd -= acked;\n\t\t\tourfinisacked = 0;\n\t\t}\n\t\ttp->snd_una = ti->ti_ack;\n\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_una))\n\t\t\ttp->snd_nxt = tp->snd_una;\n\n\t\tswitch (tp->t_state) {\n\n\t\t/*\n\t\t * In FIN_WAIT_1 STATE in addition to the processing\n\t\t * for the ESTABLISHED state if our FIN is now acknowledged\n\t\t * then enter FIN_WAIT_2.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_1:\n\t\t\tif (ourfinisacked) {\n\t\t\t\t/*\n\t\t\t\t * If we can't receive any more\n\t\t\t\t * data, then closing user can proceed.\n\t\t\t\t * Starting the timer is contrary to the\n\t\t\t\t * specification, but if we don't get a FIN\n\t\t\t\t * we'll hang forever.\n\t\t\t\t */\n\t\t\t\tif (so->so_state & SS_FCANTRCVMORE) {\n\t\t\t\t\ttp->t_timer[TCPT_2MSL] = TCP_MAXIDLE;\n\t\t\t\t}\n\t\t\t\ttp->t_state = TCPS_FIN_WAIT_2;\n\t\t\t}\n\t\t\tbreak;\n\n\t \t/*\n\t\t * In CLOSING STATE in addition to the processing for\n\t\t * the ESTABLISHED state if the ACK acknowledges our FIN\n\t\t * then enter the TIME-WAIT state, otherwise ignore\n\t\t * the segment.\n\t\t */\n\t\tcase TCPS_CLOSING:\n\t\t\tif (ourfinisacked) {\n\t\t\t\ttp->t_state = TCPS_TIME_WAIT;\n\t\t\t\ttcp_canceltimers(tp);\n\t\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In LAST_ACK, we may still be waiting for data to drain\n\t\t * and/or to be acked, as well as for the ack of our FIN.\n\t\t * If our FIN is now acknowledged, delete the TCB,\n\t\t * enter the closed state and return.\n\t\t */\n\t\tcase TCPS_LAST_ACK:\n\t\t\tif (ourfinisacked) {\n tcp_close(tp);\n\t\t\t\tgoto drop;\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In TIME_WAIT state the only thing that should arrive\n\t\t * is a retransmission of the remote FIN. Acknowledge\n\t\t * it and restart the finack timer.\n\t\t */\n\t\tcase TCPS_TIME_WAIT:\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tgoto dropafterack;\n\t\t}\n\t} /* switch(tp->t_state) */\n\nstep6:\n\t/*\n\t * Update window information.\n\t * Don't look at window if no ACK: TAC's send garbage on first SYN.\n\t */\n\tif ((tiflags & TH_ACK) &&\n\t (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||\n\t (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||\n\t (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {\n\t\ttp->snd_wnd = tiwin;\n\t\ttp->snd_wl1 = ti->ti_seq;\n\t\ttp->snd_wl2 = ti->ti_ack;\n\t\tif (tp->snd_wnd > tp->max_sndwnd)\n\t\t\ttp->max_sndwnd = tp->snd_wnd;\n\t\tneedoutput = 1;\n\t}\n\n\t/*\n\t * Process segments with URG.\n\t */\n\tif ((tiflags & TH_URG) && ti->ti_urp &&\n\t TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\t/*\n\t\t * This is a kludge, but if we receive and accept\n\t\t * random urgent pointers, we'll crash in\n\t\t * soreceive. It's hard to imagine someone\n\t\t * actually wanting to send this much urgent data.\n\t\t */\n\t\tif (ti->ti_urp + so->so_rcv.sb_cc > so->so_rcv.sb_datalen) {\n\t\t\tti->ti_urp = 0;\n\t\t\ttiflags &= ~TH_URG;\n\t\t\tgoto dodata;\n\t\t}\n\t\t/*\n\t\t * If this segment advances the known urgent pointer,\n\t\t * then mark the data stream. This should not happen\n\t\t * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since\n\t\t * a FIN has been received from the remote side.\n\t\t * In these states we ignore the URG.\n\t\t *\n\t\t * According to RFC961 (Assigned Protocols),\n\t\t * the urgent pointer points to the last octet\n\t\t * of urgent data. We continue, however,\n\t\t * to consider it to indicate the first octet\n\t\t * of data past the urgent section as the original\n\t\t * spec states (in one of two places).\n\t\t */\n\t\tif (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {\n\t\t\ttp->rcv_up = ti->ti_seq + ti->ti_urp;\n\t\t\tso->so_urgc = so->so_rcv.sb_cc +\n\t\t\t\t(tp->rcv_up - tp->rcv_nxt); /* -1; */\n\t\t\ttp->rcv_up = ti->ti_seq + ti->ti_urp;\n\n\t\t}\n\t} else\n\t\t/*\n\t\t * If no out of band data is expected,\n\t\t * pull receive urgent pointer along\n\t\t * with the receive window.\n\t\t */\n\t\tif (SEQ_GT(tp->rcv_nxt, tp->rcv_up))\n\t\t\ttp->rcv_up = tp->rcv_nxt;\ndodata:\n\n\t/*\n\t * Process the segment text, merging it into the TCP sequencing queue,\n\t * and arranging for acknowledgment of receipt if necessary.\n\t * This process logically involves adjusting tp->rcv_wnd as data\n\t * is presented to the user (this happens in tcp_usrreq.c,\n\t * case PRU_RCVD). If a FIN has already been received on this\n\t * connection then we just ignore the text.\n\t */\n\tif ((ti->ti_len || (tiflags&TH_FIN)) &&\n\t TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\tTCP_REASS(tp, ti, m, so, tiflags);\n\t} else {\n\t\tm_free(m);\n\t\ttiflags &= ~TH_FIN;\n\t}\n\n\t/*\n\t * If FIN is received ACK the FIN and let the user know\n\t * that the connection is closing.\n\t */\n\tif (tiflags & TH_FIN) {\n\t\tif (TCPS_HAVERCVDFIN(tp->t_state) == 0) {\n\t\t\t/*\n\t\t\t * If we receive a FIN we can't send more data,\n\t\t\t * set it SS_FDRAIN\n * Shutdown the socket if there is no rx data in the\n\t\t\t * buffer.\n\t\t\t * soread() is called on completion of shutdown() and\n\t\t\t * will got to TCPS_LAST_ACK, and use tcp_output()\n\t\t\t * to send the FIN.\n\t\t\t */\n\t\t\tsofwdrain(so);\n\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\ttp->rcv_nxt++;\n\t\t}\n\t\tswitch (tp->t_state) {\n\n\t \t/*\n\t\t * In SYN_RECEIVED and ESTABLISHED STATES\n\t\t * enter the CLOSE_WAIT state.\n\t\t */\n\t\tcase TCPS_SYN_RECEIVED:\n\t\tcase TCPS_ESTABLISHED:\n\t\t if(so->so_emu == EMU_CTL) /* no shutdown on socket */\n\t\t tp->t_state = TCPS_LAST_ACK;\n\t\t else\n\t\t tp->t_state = TCPS_CLOSE_WAIT;\n\t\t break;\n\n\t \t/*\n\t\t * If still in FIN_WAIT_1 STATE FIN has not been acked so\n\t\t * enter the CLOSING state.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_1:\n\t\t\ttp->t_state = TCPS_CLOSING;\n\t\t\tbreak;\n\n\t \t/*\n\t\t * In FIN_WAIT_2 state enter the TIME_WAIT state,\n\t\t * starting the time-wait timer, turning off the other\n\t\t * standard timers.\n\t\t */\n\t\tcase TCPS_FIN_WAIT_2:\n\t\t\ttp->t_state = TCPS_TIME_WAIT;\n\t\t\ttcp_canceltimers(tp);\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tbreak;\n\n\t\t/*\n\t\t * In TIME_WAIT state restart the 2 MSL time_wait timer.\n\t\t */\n\t\tcase TCPS_TIME_WAIT:\n\t\t\ttp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/*\n\t * If this is a small packet, then ACK now - with Nagel\n\t * congestion avoidance sender won't send more until\n\t * he gets an ACK.\n\t *\n\t * See above.\n\t */\n\tif (ti->ti_len && (unsigned)ti->ti_len <= 5 &&\n\t ((struct tcpiphdr_2 *)ti)->first_char == (char)27) {\n\t\ttp->t_flags |= TF_ACKNOW;\n\t}\n\n\t/*\n\t * Return any desired output.\n\t */\n\tif (needoutput || (tp->t_flags & TF_ACKNOW)) {\n\t\t(void) tcp_output(tp);\n\t}\n\treturn;\n\ndropafterack:\n\t/*\n\t * Generate an ACK dropping incoming segment if it occupies\n\t * sequence space, where the ACK reflects our state.\n\t */\n\tif (tiflags & TH_RST)\n\t\tgoto drop;\n\tm_freem(m);\n\ttp->t_flags |= TF_ACKNOW;\n\t(void) tcp_output(tp);\n\treturn;\n\ndropwithreset:\n\t/* reuses m if m!=NULL, m_free() unnecessary */\n\tif (tiflags & TH_ACK)\n\t\ttcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);\n\telse {\n\t\tif (tiflags & TH_SYN) ti->ti_len++;\n\t\ttcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,\n\t\t TH_RST|TH_ACK);\n\t}\n\n\treturn;\n\ndrop:\n\t/*\n\t * Drop space held by incoming segment and return.\n\t */\n\tm_free(m);\n\n\treturn;\n}\n\nstatic void\ntcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcpiphdr *ti)\n{\n\tuint16_t mss;\n\tint opt, optlen;\n\n\tDEBUG_CALL(\"tcp_dooptions\");\n\tDEBUG_ARGS((dfd,\" tp = %lx cnt=%i \\n\", (long )tp, cnt));\n\n\tfor (; cnt > 0; cnt -= optlen, cp += optlen) {\n\t\topt = cp[0];\n\t\tif (opt == TCPOPT_EOL)\n\t\t\tbreak;\n\t\tif (opt == TCPOPT_NOP)\n\t\t\toptlen = 1;\n\t\telse {\n\t\t\toptlen = cp[1];\n\t\t\tif (optlen <= 0)\n\t\t\t\tbreak;\n\t\t}\n\t\tswitch (opt) {\n\n\t\tdefault:\n\t\t\tcontinue;\n\n\t\tcase TCPOPT_MAXSEG:\n\t\t\tif (optlen != TCPOLEN_MAXSEG)\n\t\t\t\tcontinue;\n\t\t\tif (!(ti->ti_flags & TH_SYN))\n\t\t\t\tcontinue;\n\t\t\tmemcpy((char *) &mss, (char *) cp + 2, sizeof(mss));\n\t\t\tNTOHS(mss);\n\t\t\t(void) tcp_mss(tp, mss);\t/* sets t_maxseg */\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n/*\n * Pull out of band byte out of a segment so\n * it doesn't appear in the user's data queue.\n * It is still reflected in the segment length for\n * sequencing purposes.\n */\n\n#ifdef notdef\n\nvoid\ntcp_pulloutofband(so, ti, m)\n\tstruct socket *so;\n\tstruct tcpiphdr *ti;\n\tregister struct mbuf *m;\n{\n\tint cnt = ti->ti_urp - 1;\n\n\twhile (cnt >= 0) {\n\t\tif (m->m_len > cnt) {\n\t\t\tchar *cp = mtod(m, caddr_t) + cnt;\n\t\t\tstruct tcpcb *tp = sototcpcb(so);\n\n\t\t\ttp->t_iobc = *cp;\n\t\t\ttp->t_oobflags |= TCPOOB_HAVEDATA;\n\t\t\tmemcpy(sp, cp+1, (unsigned)(m->m_len - cnt - 1));\n\t\t\tm->m_len--;\n\t\t\treturn;\n\t\t}\n\t\tcnt -= m->m_len;\n\t\tm = m->m_next; /* XXX WRONG! Fix it! */\n\t\tif (m == 0)\n\t\t\tbreak;\n\t}\n\tpanic(\"tcp_pulloutofband\");\n}\n\n#endif /* notdef */\n\n/*\n * Collect new round-trip time estimate\n * and update averages and current timeout.\n */\n\nstatic void\ntcp_xmit_timer(register struct tcpcb *tp, int rtt)\n{\n\tregister short delta;\n\n\tDEBUG_CALL(\"tcp_xmit_timer\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"rtt = %d\", rtt);\n\n\tif (tp->t_srtt != 0) {\n\t\t/*\n\t\t * srtt is stored as fixed point with 3 bits after the\n\t\t * binary point (i.e., scaled by 8). The following magic\n\t\t * is equivalent to the smoothing algorithm in rfc793 with\n\t\t * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed\n\t\t * point). Adjust rtt to origin 0.\n\t\t */\n\t\tdelta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);\n\t\tif ((tp->t_srtt += delta) <= 0)\n\t\t\ttp->t_srtt = 1;\n\t\t/*\n\t\t * We accumulate a smoothed rtt variance (actually, a\n\t\t * smoothed mean difference), then set the retransmit\n\t\t * timer to smoothed rtt + 4 times the smoothed variance.\n\t\t * rttvar is stored as fixed point with 2 bits after the\n\t\t * binary point (scaled by 4). The following is\n\t\t * equivalent to rfc793 smoothing with an alpha of .75\n\t\t * (rttvar = rttvar*3/4 + |delta| / 4). This replaces\n\t\t * rfc793's wired-in beta.\n\t\t */\n\t\tif (delta < 0)\n\t\t\tdelta = -delta;\n\t\tdelta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);\n\t\tif ((tp->t_rttvar += delta) <= 0)\n\t\t\ttp->t_rttvar = 1;\n\t} else {\n\t\t/*\n\t\t * No rtt measurement yet - use the unsmoothed rtt.\n\t\t * Set the variance to half the rtt (so our first\n\t\t * retransmit happens at 3*rtt).\n\t\t */\n\t\ttp->t_srtt = rtt << TCP_RTT_SHIFT;\n\t\ttp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);\n\t}\n\ttp->t_rtt = 0;\n\ttp->t_rxtshift = 0;\n\n\t/*\n\t * the retransmit should happen at rtt + 4 * rttvar.\n\t * Because of the way we do the smoothing, srtt and rttvar\n\t * will each average +1/2 tick of bias. When we compute\n\t * the retransmit timer, we want 1/2 tick of rounding and\n\t * 1 extra tick because of +-1/2 tick uncertainty in the\n\t * firing of the timer. The bias will give us exactly the\n\t * 1.5 tick we need. But, because the bias is\n\t * statistical, we have to test that we don't drop below\n\t * the minimum feasible timer (which is 2 ticks).\n\t */\n\tTCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),\n\t (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */\n\n\t/*\n\t * We received an ack for a packet that wasn't retransmitted;\n\t * it is probably safe to discard any error indications we've\n\t * received recently. This isn't quite right, but close enough\n\t * for now (a route might have failed after we sent a segment,\n\t * and the return path might not be symmetrical).\n\t */\n\ttp->t_softerror = 0;\n}\n\n/*\n * Determine a reasonable value for maxseg size.\n * If the route is known, check route for mtu.\n * If none, use an mss that can be handled on the outgoing\n * interface without forcing IP to fragment; if bigger than\n * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES\n * to utilize large mbufs. If no route is found, route has no mtu,\n * or the destination isn't local, use a default, hopefully conservative\n * size (usually 512 or the default IP max size, but no more than the mtu\n * of the interface), as we can't discover anything about intervening\n * gateways or networks. We also initialize the congestion/slow start\n * window to be a single segment if the destination isn't local.\n * While looking at the routing entry, we also initialize other path-dependent\n * parameters from pre-set or cached values in the routing entry.\n */\n\nint\ntcp_mss(struct tcpcb *tp, u_int offer)\n{\n\tstruct socket *so = tp->t_socket;\n\tint mss;\n\n\tDEBUG_CALL(\"tcp_mss\");\n\tDEBUG_ARG(\"tp = %lx\", (long)tp);\n\tDEBUG_ARG(\"offer = %d\", offer);\n\n\tmss = min(IF_MTU, IF_MRU) - sizeof(struct tcpiphdr);\n\tif (offer)\n\t\tmss = min(mss, offer);\n\tmss = max(mss, 32);\n\tif (mss < tp->t_maxseg || offer != 0)\n\t tp->t_maxseg = mss;\n\n\ttp->snd_cwnd = mss;\n\n\tsbreserve(&so->so_snd, TCP_SNDSPACE + ((TCP_SNDSPACE % mss) ?\n (mss - (TCP_SNDSPACE % mss)) :\n 0));\n\tsbreserve(&so->so_rcv, TCP_RCVSPACE + ((TCP_RCVSPACE % mss) ?\n (mss - (TCP_RCVSPACE % mss)) :\n 0));\n\n\tDEBUG_MISC((dfd, \" returning mss = %d\\n\", mss));\n\n\treturn mss;\n}\n"], ["/linuxpdf/tinyemu/pci.c", "/*\n * Simple PCI bus driver\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"pci.h\"\n\n//#define DEBUG_CONFIG\n\ntypedef struct {\n uint32_t size; /* 0 means no mapping defined */\n uint8_t type;\n uint8_t enabled; /* true if mapping is enabled */\n void *opaque;\n PCIBarSetFunc *bar_set;\n} PCIIORegion;\n\nstruct PCIDevice {\n PCIBus *bus;\n uint8_t devfn;\n IRQSignal irq[4];\n uint8_t config[256];\n uint8_t next_cap_offset; /* offset of the next capability */\n char *name; /* for debug only */\n PCIIORegion io_regions[PCI_NUM_REGIONS];\n};\n\nstruct PCIBus {\n int bus_num;\n PCIDevice *device[256];\n PhysMemoryMap *mem_map;\n PhysMemoryMap *port_map;\n uint32_t irq_state[4][8]; /* one bit per device */\n IRQSignal irq[4];\n};\n\nstatic int bus_map_irq(PCIDevice *d, int irq_num)\n{\n int slot_addend;\n slot_addend = (d->devfn >> 3) - 1;\n return (irq_num + slot_addend) & 3;\n}\n\nstatic void pci_device_set_irq(void *opaque, int irq_num, int level)\n{\n PCIDevice *d = opaque;\n PCIBus *b = d->bus;\n uint32_t mask;\n int i, irq_level;\n \n // printf(\"%s: pci_device_seq_irq: %d %d\\n\", d->name, irq_num, level);\n irq_num = bus_map_irq(d, irq_num);\n mask = 1 << (d->devfn & 0x1f);\n if (level)\n b->irq_state[irq_num][d->devfn >> 5] |= mask;\n else\n b->irq_state[irq_num][d->devfn >> 5] &= ~mask;\n\n /* compute the IRQ state */\n mask = 0;\n for(i = 0; i < 8; i++)\n mask |= b->irq_state[irq_num][i];\n irq_level = (mask != 0);\n set_irq(&b->irq[irq_num], irq_level);\n}\n\nstatic int devfn_alloc(PCIBus *b)\n{\n int devfn;\n for(devfn = 0; devfn < 256; devfn += 8) {\n if (!b->device[devfn])\n return devfn;\n }\n return -1;\n}\n\n/* devfn < 0 means to allocate it */\nPCIDevice *pci_register_device(PCIBus *b, const char *name, int devfn,\n uint16_t vendor_id, uint16_t device_id,\n uint8_t revision, uint16_t class_id)\n{\n PCIDevice *d;\n int i;\n \n if (devfn < 0) {\n devfn = devfn_alloc(b);\n if (devfn < 0)\n return NULL;\n }\n if (b->device[devfn])\n return NULL;\n\n d = mallocz(sizeof(PCIDevice));\n d->bus = b;\n d->name = strdup(name);\n d->devfn = devfn;\n\n put_le16(d->config + 0x00, vendor_id);\n put_le16(d->config + 0x02, device_id);\n d->config[0x08] = revision;\n put_le16(d->config + 0x0a, class_id);\n d->config[0x0e] = 0x00; /* header type */\n d->next_cap_offset = 0x40;\n \n for(i = 0; i < 4; i++)\n irq_init(&d->irq[i], pci_device_set_irq, d, i);\n b->device[devfn] = d;\n\n return d;\n}\n\nIRQSignal *pci_device_get_irq(PCIDevice *d, unsigned int irq_num)\n{\n assert(irq_num < 4);\n return &d->irq[irq_num];\n}\n\nstatic uint32_t pci_device_config_read(PCIDevice *d, uint32_t addr,\n int size_log2)\n{\n uint32_t val;\n switch(size_log2) {\n case 0:\n val = *(uint8_t *)(d->config + addr);\n break;\n case 1:\n /* Note: may be unaligned */\n if (addr <= 0xfe)\n val = get_le16(d->config + addr);\n else\n val = *(uint8_t *)(d->config + addr);\n break;\n case 2:\n /* always aligned */\n val = get_le32(d->config + addr);\n break;\n default:\n abort();\n }\n#ifdef DEBUG_CONFIG\n printf(\"pci_config_read: dev=%s addr=0x%02x val=0x%x s=%d\\n\",\n d->name, addr, val, 1 << size_log2);\n#endif\n return val;\n}\n\nPhysMemoryMap *pci_device_get_mem_map(PCIDevice *d)\n{\n return d->bus->mem_map;\n}\n\nPhysMemoryMap *pci_device_get_port_map(PCIDevice *d)\n{\n return d->bus->port_map;\n}\n\nvoid pci_register_bar(PCIDevice *d, unsigned int bar_num,\n uint32_t size, int type,\n void *opaque, PCIBarSetFunc *bar_set)\n{\n PCIIORegion *r;\n uint32_t val, config_addr;\n \n assert(bar_num < PCI_NUM_REGIONS);\n assert((size & (size - 1)) == 0); /* power of two */\n assert(size >= 4);\n r = &d->io_regions[bar_num];\n assert(r->size == 0);\n r->size = size;\n r->type = type;\n r->enabled = FALSE;\n r->opaque = opaque;\n r->bar_set = bar_set;\n /* set the config value */\n val = 0;\n if (bar_num == PCI_ROM_SLOT) {\n config_addr = 0x30;\n } else {\n val |= r->type;\n config_addr = 0x10 + 4 * bar_num;\n }\n put_le32(&d->config[config_addr], val);\n}\n\nstatic void pci_update_mappings(PCIDevice *d)\n{\n int cmd, i, offset;\n uint32_t new_addr;\n BOOL new_enabled;\n PCIIORegion *r;\n \n cmd = get_le16(&d->config[PCI_COMMAND]);\n\n for(i = 0; i < PCI_NUM_REGIONS; i++) {\n r = &d->io_regions[i];\n if (i == PCI_ROM_SLOT) {\n offset = 0x30;\n } else {\n offset = 0x10 + i * 4;\n }\n new_addr = get_le32(&d->config[offset]);\n new_enabled = FALSE;\n if (r->size != 0) {\n if ((r->type & PCI_ADDRESS_SPACE_IO) &&\n (cmd & PCI_COMMAND_IO)) {\n new_enabled = TRUE;\n } else {\n if (cmd & PCI_COMMAND_MEMORY) {\n if (i == PCI_ROM_SLOT) {\n new_enabled = (new_addr & 1);\n } else {\n new_enabled = TRUE;\n }\n }\n }\n }\n if (new_enabled) {\n /* new address */\n new_addr = get_le32(&d->config[offset]) & ~(r->size - 1);\n r->bar_set(r->opaque, i, new_addr, TRUE);\n r->enabled = TRUE;\n } else if (r->enabled) {\n r->bar_set(r->opaque, i, 0, FALSE);\n r->enabled = FALSE;\n }\n }\n}\n\n/* return != 0 if write is not handled */\nstatic int pci_write_bar(PCIDevice *d, uint32_t addr,\n uint32_t val)\n{\n PCIIORegion *r;\n int reg;\n \n if (addr == 0x30)\n reg = PCI_ROM_SLOT;\n else\n reg = (addr - 0x10) >> 2;\n // printf(\"%s: write bar addr=%x data=%x\\n\", d->name, addr, val);\n r = &d->io_regions[reg];\n if (r->size == 0)\n return -1;\n if (reg == PCI_ROM_SLOT) {\n val = val & ((~(r->size - 1)) | 1);\n } else {\n val = (val & ~(r->size - 1)) | r->type;\n }\n put_le32(d->config + addr, val);\n pci_update_mappings(d);\n return 0;\n}\n\nstatic void pci_device_config_write8(PCIDevice *d, uint32_t addr,\n uint32_t data)\n{\n int can_write;\n\n if (addr == PCI_STATUS || addr == (PCI_STATUS + 1)) {\n /* write 1 reset bits */\n d->config[addr] &= ~data;\n return;\n }\n \n switch(d->config[0x0e]) {\n case 0x00:\n case 0x80:\n switch(addr) {\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x08:\n case 0x09:\n case 0x0a:\n case 0x0b:\n case 0x0e:\n case 0x10 ... 0x27: /* base */\n case 0x30 ... 0x33: /* rom */\n case 0x3d:\n can_write = 0;\n break;\n default:\n can_write = 1;\n break;\n }\n break;\n default:\n case 0x01:\n switch(addr) {\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x08:\n case 0x09:\n case 0x0a:\n case 0x0b:\n case 0x0e:\n case 0x38 ... 0x3b: /* rom */\n case 0x3d:\n can_write = 0;\n break;\n default:\n can_write = 1;\n break;\n }\n break;\n }\n if (can_write)\n d->config[addr] = data;\n}\n \n\nstatic void pci_device_config_write(PCIDevice *d, uint32_t addr,\n uint32_t data, int size_log2)\n{\n int size, i;\n uint32_t addr1;\n \n#ifdef DEBUG_CONFIG\n printf(\"pci_config_write: dev=%s addr=0x%02x val=0x%x s=%d\\n\",\n d->name, addr, data, 1 << size_log2);\n#endif\n if (size_log2 == 2 &&\n ((addr >= 0x10 && addr < 0x10 + 4 * 6) ||\n addr == 0x30)) {\n if (pci_write_bar(d, addr, data) == 0)\n return;\n }\n size = 1 << size_log2;\n for(i = 0; i < size; i++) {\n addr1 = addr + i;\n if (addr1 <= 0xff) {\n pci_device_config_write8(d, addr1, (data >> (i * 8)) & 0xff);\n }\n }\n if (PCI_COMMAND >= addr && PCI_COMMAND < addr + size) {\n pci_update_mappings(d);\n }\n}\n\n\nstatic void pci_data_write(PCIBus *s, uint32_t addr,\n uint32_t data, int size_log2)\n{\n PCIDevice *d;\n int bus_num, devfn, config_addr;\n \n bus_num = (addr >> 16) & 0xff;\n if (bus_num != s->bus_num)\n return;\n devfn = (addr >> 8) & 0xff;\n d = s->device[devfn];\n if (!d)\n return;\n config_addr = addr & 0xff;\n pci_device_config_write(d, config_addr, data, size_log2);\n}\n\nstatic const uint32_t val_ones[3] = { 0xff, 0xffff, 0xffffffff };\n\nstatic uint32_t pci_data_read(PCIBus *s, uint32_t addr, int size_log2)\n{\n PCIDevice *d;\n int bus_num, devfn, config_addr;\n \n bus_num = (addr >> 16) & 0xff;\n if (bus_num != s->bus_num)\n return val_ones[size_log2];\n devfn = (addr >> 8) & 0xff;\n d = s->device[devfn];\n if (!d)\n return val_ones[size_log2];\n config_addr = addr & 0xff;\n return pci_device_config_read(d, config_addr, size_log2);\n}\n\n/* warning: only valid for one DEVIO page. Return NULL if no memory at\n the given address */\nuint8_t *pci_device_get_dma_ptr(PCIDevice *d, uint64_t addr, BOOL is_rw)\n{\n return phys_mem_get_ram_ptr(d->bus->mem_map, addr, is_rw);\n}\n\nvoid pci_device_set_config8(PCIDevice *d, uint8_t addr, uint8_t val)\n{\n d->config[addr] = val;\n}\n\nvoid pci_device_set_config16(PCIDevice *d, uint8_t addr, uint16_t val)\n{\n put_le16(&d->config[addr], val);\n}\n\nint pci_device_get_devfn(PCIDevice *d)\n{\n return d->devfn;\n}\n\n/* return the offset of the capability or < 0 if error. */\nint pci_add_capability(PCIDevice *d, const uint8_t *buf, int size)\n{\n int offset;\n \n offset = d->next_cap_offset;\n if ((offset + size) > 256)\n return -1;\n d->next_cap_offset += size;\n d->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;\n memcpy(d->config + offset, buf, size);\n d->config[offset + 1] = d->config[PCI_CAPABILITY_LIST];\n d->config[PCI_CAPABILITY_LIST] = offset;\n return offset;\n}\n\n/* i440FX host bridge */\n\nstruct I440FXState {\n PCIBus *pci_bus;\n PCIDevice *pci_dev;\n PCIDevice *piix3_dev;\n uint32_t config_reg;\n uint8_t pic_irq_state[16];\n IRQSignal *pic_irqs; /* 16 irqs */\n};\n\nstatic void i440fx_write_addr(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n I440FXState *s = opaque;\n s->config_reg = data;\n}\n\nstatic uint32_t i440fx_read_addr(void *opaque, uint32_t offset, int size_log2)\n{\n I440FXState *s = opaque;\n return s->config_reg;\n}\n\nstatic void i440fx_write_data(void *opaque, uint32_t offset,\n uint32_t data, int size_log2)\n{\n I440FXState *s = opaque;\n if (s->config_reg & 0x80000000) {\n if (size_log2 == 2) {\n /* it is simpler to assume 32 bit config accesses are\n always aligned */\n pci_data_write(s->pci_bus, s->config_reg & ~3, data, size_log2);\n } else {\n pci_data_write(s->pci_bus, s->config_reg | offset, data, size_log2);\n }\n }\n}\n\nstatic uint32_t i440fx_read_data(void *opaque, uint32_t offset, int size_log2)\n{\n I440FXState *s = opaque;\n if (!(s->config_reg & 0x80000000))\n return val_ones[size_log2];\n if (size_log2 == 2) {\n /* it is simpler to assume 32 bit config accesses are\n always aligned */\n return pci_data_read(s->pci_bus, s->config_reg & ~3, size_log2);\n } else {\n return pci_data_read(s->pci_bus, s->config_reg | offset, size_log2);\n }\n}\n\nstatic void i440fx_set_irq(void *opaque, int irq_num, int irq_level)\n{\n I440FXState *s = opaque;\n PCIDevice *hd = s->piix3_dev;\n int pic_irq;\n \n /* map to the PIC irq (different IRQs can be mapped to the same\n PIC irq) */\n hd->config[0x60 + irq_num] &= ~0x80;\n pic_irq = hd->config[0x60 + irq_num];\n if (pic_irq < 16) {\n if (irq_level)\n s->pic_irq_state[pic_irq] |= 1 << irq_num;\n else\n s->pic_irq_state[pic_irq] &= ~(1 << irq_num);\n set_irq(&s->pic_irqs[pic_irq], (s->pic_irq_state[pic_irq] != 0));\n }\n}\n\nI440FXState *i440fx_init(PCIBus **pbus, int *ppiix3_devfn,\n PhysMemoryMap *mem_map, PhysMemoryMap *port_map,\n IRQSignal *pic_irqs)\n{\n I440FXState *s;\n PCIBus *b;\n PCIDevice *d;\n int i;\n \n s = mallocz(sizeof(*s));\n \n b = mallocz(sizeof(PCIBus));\n b->bus_num = 0;\n b->mem_map = mem_map;\n b->port_map = port_map;\n\n s->pic_irqs = pic_irqs;\n for(i = 0; i < 4; i++) {\n irq_init(&b->irq[i], i440fx_set_irq, s, i);\n }\n \n cpu_register_device(port_map, 0xcf8, 1, s, i440fx_read_addr, i440fx_write_addr, \n DEVIO_SIZE32);\n cpu_register_device(port_map, 0xcfc, 4, s, i440fx_read_data, i440fx_write_data, \n DEVIO_SIZE8 | DEVIO_SIZE16 | DEVIO_SIZE32);\n d = pci_register_device(b, \"i440FX\", 0, 0x8086, 0x1237, 0x02, 0x0600);\n put_le16(&d->config[PCI_SUBSYSTEM_VENDOR_ID], 0x1af4); /* Red Hat, Inc. */\n put_le16(&d->config[PCI_SUBSYSTEM_ID], 0x1100); /* QEMU virtual machine */\n \n s->pci_dev = d;\n s->pci_bus = b;\n\n s->piix3_dev = pci_register_device(b, \"PIIX3\", 8, 0x8086, 0x7000,\n 0x00, 0x0601);\n pci_device_set_config8(s->piix3_dev, 0x0e, 0x80); /* header type */\n\n *pbus = b;\n *ppiix3_devfn = s->piix3_dev->devfn;\n return s;\n}\n\n/* in case no BIOS is used, map the interrupts. */\nvoid i440fx_map_interrupts(I440FXState *s, uint8_t *elcr,\n const uint8_t *pci_irqs)\n{\n PCIBus *b = s->pci_bus;\n PCIDevice *d, *hd;\n int irq_num, pic_irq, devfn, i;\n \n /* set a default PCI IRQ mapping to PIC IRQs */\n hd = s->piix3_dev;\n\n elcr[0] = 0;\n elcr[1] = 0;\n for(i = 0; i < 4; i++) {\n irq_num = pci_irqs[i];\n hd->config[0x60 + i] = irq_num;\n elcr[irq_num >> 3] |= (1 << (irq_num & 7));\n }\n\n for(devfn = 0; devfn < 256; devfn++) {\n d = b->device[devfn];\n if (!d)\n continue;\n if (d->config[PCI_INTERRUPT_PIN]) {\n irq_num = 0;\n irq_num = bus_map_irq(d, irq_num);\n pic_irq = hd->config[0x60 + irq_num];\n if (pic_irq < 16) {\n d->config[PCI_INTERRUPT_LINE] = pic_irq;\n }\n }\n }\n}\n"], ["/linuxpdf/tinyemu/slirp/socket.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\nstatic void sofcantrcvmore(struct socket *so);\nstatic void sofcantsendmore(struct socket *so);\n\nstruct socket *\nsolookup(struct socket *head, struct in_addr laddr, u_int lport,\n struct in_addr faddr, u_int fport)\n{\n\tstruct socket *so;\n\n\tfor (so = head->so_next; so != head; so = so->so_next) {\n\t\tif (so->so_lport == lport &&\n\t\t so->so_laddr.s_addr == laddr.s_addr &&\n\t\t so->so_faddr.s_addr == faddr.s_addr &&\n\t\t so->so_fport == fport)\n\t\t break;\n\t}\n\n\tif (so == head)\n\t return (struct socket *)NULL;\n\treturn so;\n\n}\n\n/*\n * Create a new socket, initialise the fields\n * It is the responsibility of the caller to\n * insque() it into the correct linked-list\n */\nstruct socket *\nsocreate(Slirp *slirp)\n{\n struct socket *so;\n\n so = (struct socket *)malloc(sizeof(struct socket));\n if(so) {\n memset(so, 0, sizeof(struct socket));\n so->so_state = SS_NOFDREF;\n so->s = -1;\n so->slirp = slirp;\n }\n return(so);\n}\n\n/*\n * remque and free a socket, clobber cache\n */\nvoid\nsofree(struct socket *so)\n{\n Slirp *slirp = so->slirp;\n\n if (so->so_emu==EMU_RSH && so->extra) {\n\tsofree(so->extra);\n\tso->extra=NULL;\n }\n if (so == slirp->tcp_last_so) {\n slirp->tcp_last_so = &slirp->tcb;\n } else if (so == slirp->udp_last_so) {\n slirp->udp_last_so = &slirp->udb;\n }\n m_free(so->so_m);\n\n if(so->so_next && so->so_prev)\n remque(so); /* crashes if so is not in a queue */\n\n free(so);\n}\n\nsize_t sopreprbuf(struct socket *so, struct iovec *iov, int *np)\n{\n\tint n, lss, total;\n\tstruct sbuf *sb = &so->so_snd;\n\tint len = sb->sb_datalen - sb->sb_cc;\n\tint mss = so->so_tcpcb->t_maxseg;\n\n\tDEBUG_CALL(\"sopreprbuf\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\tif (len <= 0)\n\t\treturn 0;\n\n\tiov[0].iov_base = sb->sb_wptr;\n iov[1].iov_base = NULL;\n iov[1].iov_len = 0;\n\tif (sb->sb_wptr < sb->sb_rptr) {\n\t\tiov[0].iov_len = sb->sb_rptr - sb->sb_wptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len)\n\t\t iov[0].iov_len = len;\n\t\tif (iov[0].iov_len > mss)\n\t\t iov[0].iov_len -= iov[0].iov_len%mss;\n\t\tn = 1;\n\t} else {\n\t\tiov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_wptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tlen -= iov[0].iov_len;\n\t\tif (len) {\n\t\t\tiov[1].iov_base = sb->sb_data;\n\t\t\tiov[1].iov_len = sb->sb_rptr - sb->sb_data;\n\t\t\tif(iov[1].iov_len > len)\n\t\t\t iov[1].iov_len = len;\n\t\t\ttotal = iov[0].iov_len + iov[1].iov_len;\n\t\t\tif (total > mss) {\n\t\t\t\tlss = total%mss;\n\t\t\t\tif (iov[1].iov_len > lss) {\n\t\t\t\t\tiov[1].iov_len -= lss;\n\t\t\t\t\tn = 2;\n\t\t\t\t} else {\n\t\t\t\t\tlss -= iov[1].iov_len;\n\t\t\t\t\tiov[0].iov_len -= lss;\n\t\t\t\t\tn = 1;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tn = 2;\n\t\t} else {\n\t\t\tif (iov[0].iov_len > mss)\n\t\t\t iov[0].iov_len -= iov[0].iov_len%mss;\n\t\t\tn = 1;\n\t\t}\n\t}\n\tif (np)\n\t\t*np = n;\n\n\treturn iov[0].iov_len + (n - 1) * iov[1].iov_len;\n}\n\n/*\n * Read from so's socket into sb_snd, updating all relevant sbuf fields\n * NOTE: This will only be called if it is select()ed for reading, so\n * a read() of 0 (or less) means it's disconnected\n */\nint\nsoread(struct socket *so)\n{\n\tint n, nn;\n\tstruct sbuf *sb = &so->so_snd;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"soread\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\t/*\n\t * No need to check if there's enough room to read.\n\t * soread wouldn't have been called if there weren't\n\t */\n\tsopreprbuf(so, iov, &n);\n\n#ifdef HAVE_READV\n\tnn = readv(so->s, (struct iovec *)iov, n);\n\tDEBUG_MISC((dfd, \" ... read nn = %d bytes\\n\", nn));\n#else\n\tnn = recv(so->s, iov[0].iov_base, iov[0].iov_len,0);\n#endif\n\tif (nn <= 0) {\n\t\tif (nn < 0 && (errno == EINTR || errno == EAGAIN))\n\t\t\treturn 0;\n\t\telse {\n\t\t\tDEBUG_MISC((dfd, \" --- soread() disconnected, nn = %d, errno = %d-%s\\n\", nn, errno,strerror(errno)));\n\t\t\tsofcantrcvmore(so);\n\t\t\ttcp_sockclosed(sototcpcb(so));\n\t\t\treturn -1;\n\t\t}\n\t}\n\n#ifndef HAVE_READV\n\t/*\n\t * If there was no error, try and read the second time round\n\t * We read again if n = 2 (ie, there's another part of the buffer)\n\t * and we read as much as we could in the first read\n\t * We don't test for <= 0 this time, because there legitimately\n\t * might not be any more data (since the socket is non-blocking),\n\t * a close will be detected on next iteration.\n\t * A return of -1 wont (shouldn't) happen, since it didn't happen above\n\t */\n\tif (n == 2 && nn == iov[0].iov_len) {\n int ret;\n ret = recv(so->s, iov[1].iov_base, iov[1].iov_len,0);\n if (ret > 0)\n nn += ret;\n }\n\n\tDEBUG_MISC((dfd, \" ... read nn = %d bytes\\n\", nn));\n#endif\n\n\t/* Update fields */\n\tsb->sb_cc += nn;\n\tsb->sb_wptr += nn;\n\tif (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_wptr -= sb->sb_datalen;\n\treturn nn;\n}\n\nint soreadbuf(struct socket *so, const char *buf, int size)\n{\n int n, nn, copy = size;\n\tstruct sbuf *sb = &so->so_snd;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"soreadbuf\");\n\tDEBUG_ARG(\"so = %lx\", (long )so);\n\n\t/*\n\t * No need to check if there's enough room to read.\n\t * soread wouldn't have been called if there weren't\n\t */\n\tif (sopreprbuf(so, iov, &n) < size)\n goto err;\n\n nn = min(iov[0].iov_len, copy);\n memcpy(iov[0].iov_base, buf, nn);\n\n copy -= nn;\n buf += nn;\n\n if (copy == 0)\n goto done;\n\n memcpy(iov[1].iov_base, buf, copy);\n\ndone:\n /* Update fields */\n\tsb->sb_cc += size;\n\tsb->sb_wptr += size;\n\tif (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_wptr -= sb->sb_datalen;\n return size;\nerr:\n\n sofcantrcvmore(so);\n tcp_sockclosed(sototcpcb(so));\n fprintf(stderr, \"soreadbuf buffer to small\");\n return -1;\n}\n\n/*\n * Get urgent data\n *\n * When the socket is created, we set it SO_OOBINLINE,\n * so when OOB data arrives, we soread() it and everything\n * in the send buffer is sent as urgent data\n */\nvoid\nsorecvoob(struct socket *so)\n{\n\tstruct tcpcb *tp = sototcpcb(so);\n\n\tDEBUG_CALL(\"sorecvoob\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\t/*\n\t * We take a guess at how much urgent data has arrived.\n\t * In most situations, when urgent data arrives, the next\n\t * read() should get all the urgent data. This guess will\n\t * be wrong however if more data arrives just after the\n\t * urgent data, or the read() doesn't return all the\n\t * urgent data.\n\t */\n\tsoread(so);\n\ttp->snd_up = tp->snd_una + so->so_snd.sb_cc;\n\ttp->t_force = 1;\n\ttcp_output(tp);\n\ttp->t_force = 0;\n}\n\n/*\n * Send urgent data\n * There's a lot duplicated code here, but...\n */\nint\nsosendoob(struct socket *so)\n{\n\tstruct sbuf *sb = &so->so_rcv;\n\tchar buff[2048]; /* XXX Shouldn't be sending more oob data than this */\n\n\tint n, len;\n\n\tDEBUG_CALL(\"sosendoob\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"sb->sb_cc = %d\", sb->sb_cc);\n\n\tif (so->so_urgc > 2048)\n\t so->so_urgc = 2048; /* XXXX */\n\n\tif (sb->sb_rptr < sb->sb_wptr) {\n\t\t/* We can send it directly */\n\t\tn = slirp_send(so, sb->sb_rptr, so->so_urgc, (MSG_OOB)); /* |MSG_DONTWAIT)); */\n\t\tso->so_urgc -= n;\n\n\t\tDEBUG_MISC((dfd, \" --- sent %d bytes urgent data, %d urgent bytes left\\n\", n, so->so_urgc));\n\t} else {\n\t\t/*\n\t\t * Since there's no sendv or sendtov like writev,\n\t\t * we must copy all data to a linear buffer then\n\t\t * send it all\n\t\t */\n\t\tlen = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;\n\t\tif (len > so->so_urgc) len = so->so_urgc;\n\t\tmemcpy(buff, sb->sb_rptr, len);\n\t\tso->so_urgc -= len;\n\t\tif (so->so_urgc) {\n\t\t\tn = sb->sb_wptr - sb->sb_data;\n\t\t\tif (n > so->so_urgc) n = so->so_urgc;\n\t\t\tmemcpy((buff + len), sb->sb_data, n);\n\t\t\tso->so_urgc -= n;\n\t\t\tlen += n;\n\t\t}\n\t\tn = slirp_send(so, buff, len, (MSG_OOB)); /* |MSG_DONTWAIT)); */\n#ifdef DEBUG\n\t\tif (n != len)\n\t\t DEBUG_ERROR((dfd, \"Didn't send all data urgently XXXXX\\n\"));\n#endif\n\t\tDEBUG_MISC((dfd, \" ---2 sent %d bytes urgent data, %d urgent bytes left\\n\", n, so->so_urgc));\n\t}\n\n\tsb->sb_cc -= n;\n\tsb->sb_rptr += n;\n\tif (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n\treturn n;\n}\n\n/*\n * Write data from so_rcv to so's socket,\n * updating all sbuf field as necessary\n */\nint\nsowrite(struct socket *so)\n{\n\tint n,nn;\n\tstruct sbuf *sb = &so->so_rcv;\n\tint len = sb->sb_cc;\n\tstruct iovec iov[2];\n\n\tDEBUG_CALL(\"sowrite\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\tif (so->so_urgc) {\n\t\tsosendoob(so);\n\t\tif (sb->sb_cc == 0)\n\t\t\treturn 0;\n\t}\n\n\t/*\n\t * No need to check if there's something to write,\n\t * sowrite wouldn't have been called otherwise\n\t */\n\n\tiov[0].iov_base = sb->sb_rptr;\n iov[1].iov_base = NULL;\n iov[1].iov_len = 0;\n\tif (sb->sb_rptr < sb->sb_wptr) {\n\t\tiov[0].iov_len = sb->sb_wptr - sb->sb_rptr;\n\t\t/* Should never succeed, but... */\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tn = 1;\n\t} else {\n\t\tiov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;\n\t\tif (iov[0].iov_len > len) iov[0].iov_len = len;\n\t\tlen -= iov[0].iov_len;\n\t\tif (len) {\n\t\t\tiov[1].iov_base = sb->sb_data;\n\t\t\tiov[1].iov_len = sb->sb_wptr - sb->sb_data;\n\t\t\tif (iov[1].iov_len > len) iov[1].iov_len = len;\n\t\t\tn = 2;\n\t\t} else\n\t\t\tn = 1;\n\t}\n\t/* Check if there's urgent data to send, and if so, send it */\n\n#ifdef HAVE_READV\n\tnn = writev(so->s, (const struct iovec *)iov, n);\n\n\tDEBUG_MISC((dfd, \" ... wrote nn = %d bytes\\n\", nn));\n#else\n\tnn = slirp_send(so, iov[0].iov_base, iov[0].iov_len,0);\n#endif\n\t/* This should never happen, but people tell me it does *shrug* */\n\tif (nn < 0 && (errno == EAGAIN || errno == EINTR))\n\t\treturn 0;\n\n\tif (nn <= 0) {\n\t\tDEBUG_MISC((dfd, \" --- sowrite disconnected, so->so_state = %x, errno = %d\\n\",\n\t\t\tso->so_state, errno));\n\t\tsofcantsendmore(so);\n\t\ttcp_sockclosed(sototcpcb(so));\n\t\treturn -1;\n\t}\n\n#ifndef HAVE_READV\n\tif (n == 2 && nn == iov[0].iov_len) {\n int ret;\n ret = slirp_send(so, iov[1].iov_base, iov[1].iov_len,0);\n if (ret > 0)\n nn += ret;\n }\n DEBUG_MISC((dfd, \" ... wrote nn = %d bytes\\n\", nn));\n#endif\n\n\t/* Update sbuf */\n\tsb->sb_cc -= nn;\n\tsb->sb_rptr += nn;\n\tif (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n\t/*\n\t * If in DRAIN mode, and there's no more data, set\n\t * it CANTSENDMORE\n\t */\n\tif ((so->so_state & SS_FWDRAIN) && sb->sb_cc == 0)\n\t\tsofcantsendmore(so);\n\n\treturn nn;\n}\n\n/*\n * recvfrom() a UDP socket\n */\nvoid\nsorecvfrom(struct socket *so)\n{\n\tstruct sockaddr_in addr;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in);\n\n\tDEBUG_CALL(\"sorecvfrom\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\n\tif (so->so_type == IPPROTO_ICMP) { /* This is a \"ping\" reply */\n\t char buff[256];\n\t int len;\n\n\t len = recvfrom(so->s, buff, 256, 0,\n\t\t\t (struct sockaddr *)&addr, &addrlen);\n\t /* XXX Check if reply is \"correct\"? */\n\n\t if(len == -1 || len == 0) {\n\t u_char code=ICMP_UNREACH_PORT;\n\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;\n\n\t DEBUG_MISC((dfd,\" udp icmp rx errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));\n\t } else {\n\t icmp_reflect(so->so_m);\n so->so_m = NULL; /* Don't m_free() it again! */\n\t }\n\t /* No need for this socket anymore, udp_detach it */\n\t udp_detach(so);\n\t} else { \t/* A \"normal\" UDP packet */\n\t struct mbuf *m;\n int len;\n#ifdef _WIN32\n unsigned long n;\n#else\n int n;\n#endif\n\n\t m = m_get(so->slirp);\n\t if (!m) {\n\t return;\n\t }\n\t m->m_data += IF_MAXLINKHDR;\n\n\t /*\n\t * XXX Shouldn't FIONREAD packets destined for port 53,\n\t * but I don't know the max packet size for DNS lookups\n\t */\n\t len = M_FREEROOM(m);\n\t /* if (so->so_fport != htons(53)) { */\n\t ioctlsocket(so->s, FIONREAD, &n);\n\n\t if (n > len) {\n\t n = (m->m_data - m->m_dat) + m->m_len + n + 1;\n\t m_inc(m, n);\n\t len = M_FREEROOM(m);\n\t }\n\t /* } */\n\n\t m->m_len = recvfrom(so->s, m->m_data, len, 0,\n\t\t\t (struct sockaddr *)&addr, &addrlen);\n\t DEBUG_MISC((dfd, \" did recvfrom %d, errno = %d-%s\\n\",\n\t\t m->m_len, errno,strerror(errno)));\n\t if(m->m_len<0) {\n\t u_char code=ICMP_UNREACH_PORT;\n\n\t if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;\n\t else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;\n\n\t DEBUG_MISC((dfd,\" rx error, tx icmp ICMP_UNREACH:%i\\n\", code));\n\t icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));\n\t m_free(m);\n\t } else {\n\t /*\n\t * Hack: domain name lookup will be used the most for UDP,\n\t * and since they'll only be used once there's no need\n\t * for the 4 minute (or whatever) timeout... So we time them\n\t * out much quicker (10 seconds for now...)\n\t */\n\t if (so->so_expire) {\n\t if (so->so_fport == htons(53))\n\t\tso->so_expire = curtime + SO_EXPIREFAST;\n\t else\n\t\tso->so_expire = curtime + SO_EXPIRE;\n\t }\n\n\t /*\n\t * If this packet was destined for CTL_ADDR,\n\t * make it look like that's where it came from, done by udp_output\n\t */\n\t udp_output(so, m, &addr);\n\t } /* rx error */\n\t} /* if ping packet */\n}\n\n/*\n * sendto() a socket\n */\nint\nsosendto(struct socket *so, struct mbuf *m)\n{\n\tSlirp *slirp = so->slirp;\n\tint ret;\n\tstruct sockaddr_in addr;\n\n\tDEBUG_CALL(\"sosendto\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\n addr.sin_family = AF_INET;\n\tif ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n\t slirp->vnetwork_addr.s_addr) {\n\t /* It's an alias */\n\t if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\t if (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n\t } else {\n\t addr.sin_addr = loopback_addr;\n\t }\n\t} else\n\t addr.sin_addr = so->so_faddr;\n\taddr.sin_port = so->so_fport;\n\n\tDEBUG_MISC((dfd, \" sendto()ing, addr.sin_port=%d, addr.sin_addr.s_addr=%.16s\\n\", ntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));\n\n\t/* Don't care what port we get */\n\tret = sendto(so->s, m->m_data, m->m_len, 0,\n\t\t (struct sockaddr *)&addr, sizeof (struct sockaddr));\n\tif (ret < 0)\n\t\treturn -1;\n\n\t/*\n\t * Kill the socket if there's no reply in 4 minutes,\n\t * but only if it's an expirable socket\n\t */\n\tif (so->so_expire)\n\t\tso->so_expire = curtime + SO_EXPIRE;\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= SS_ISFCONNECTED; /* So that it gets select()ed */\n\treturn 0;\n}\n\n/*\n * Listen for incoming TCP connections\n */\nstruct socket *\ntcp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,\n u_int lport, int flags)\n{\n\tstruct sockaddr_in addr;\n\tstruct socket *so;\n\tint s, opt = 1;\n\tsocklen_t addrlen = sizeof(addr);\n\tmemset(&addr, 0, addrlen);\n\n\tDEBUG_CALL(\"tcp_listen\");\n\tDEBUG_ARG(\"haddr = %x\", haddr);\n\tDEBUG_ARG(\"hport = %d\", hport);\n\tDEBUG_ARG(\"laddr = %x\", laddr);\n\tDEBUG_ARG(\"lport = %d\", lport);\n\tDEBUG_ARG(\"flags = %x\", flags);\n\n\tso = socreate(slirp);\n\tif (!so) {\n\t return NULL;\n\t}\n\n\t/* Don't tcp_attach... we don't need so_snd nor so_rcv */\n\tif ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL) {\n\t\tfree(so);\n\t\treturn NULL;\n\t}\n\tinsque(so, &slirp->tcb);\n\n\t/*\n\t * SS_FACCEPTONCE sockets must time out.\n\t */\n\tif (flags & SS_FACCEPTONCE)\n\t so->so_tcpcb->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT*2;\n\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= (SS_FACCEPTCONN | flags);\n\tso->so_lport = lport; /* Kept in network format */\n\tso->so_laddr.s_addr = laddr; /* Ditto */\n\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = haddr;\n\taddr.sin_port = hport;\n\n\tif (((s = os_socket(AF_INET,SOCK_STREAM,0)) < 0) ||\n\t (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int)) < 0) ||\n\t (bind(s,(struct sockaddr *)&addr, sizeof(addr)) < 0) ||\n\t (listen(s,1) < 0)) {\n\t\tint tmperrno = errno; /* Don't clobber the real reason we failed */\n\n\t\tclose(s);\n\t\tsofree(so);\n\t\t/* Restore the real errno */\n#ifdef _WIN32\n\t\tWSASetLastError(tmperrno);\n#else\n\t\terrno = tmperrno;\n#endif\n\t\treturn NULL;\n\t}\n\tsetsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));\n\n\tgetsockname(s,(struct sockaddr *)&addr,&addrlen);\n\tso->so_fport = addr.sin_port;\n\tif (addr.sin_addr.s_addr == 0 || addr.sin_addr.s_addr == loopback_addr.s_addr)\n\t so->so_faddr = slirp->vhost_addr;\n\telse\n\t so->so_faddr = addr.sin_addr;\n\n\tso->s = s;\n\treturn so;\n}\n\n/*\n * Various session state calls\n * XXX Should be #define's\n * The socket state stuff needs work, these often get call 2 or 3\n * times each when only 1 was needed\n */\nvoid\nsoisfconnecting(struct socket *so)\n{\n\tso->so_state &= ~(SS_NOFDREF|SS_ISFCONNECTED|SS_FCANTRCVMORE|\n\t\t\t SS_FCANTSENDMORE|SS_FWDRAIN);\n\tso->so_state |= SS_ISFCONNECTING; /* Clobber other states */\n}\n\nvoid\nsoisfconnected(struct socket *so)\n{\n\tso->so_state &= ~(SS_ISFCONNECTING|SS_FWDRAIN|SS_NOFDREF);\n\tso->so_state |= SS_ISFCONNECTED; /* Clobber other states */\n}\n\nstatic void\nsofcantrcvmore(struct socket *so)\n{\n\tif ((so->so_state & SS_NOFDREF) == 0) {\n\t\tshutdown(so->s,0);\n\t\tif(global_writefds) {\n\t\t FD_CLR(so->s,global_writefds);\n\t\t}\n\t}\n\tso->so_state &= ~(SS_ISFCONNECTING);\n\tif (so->so_state & SS_FCANTSENDMORE) {\n\t so->so_state &= SS_PERSISTENT_MASK;\n\t so->so_state |= SS_NOFDREF; /* Don't select it */\n\t} else {\n\t so->so_state |= SS_FCANTRCVMORE;\n\t}\n}\n\nstatic void\nsofcantsendmore(struct socket *so)\n{\n\tif ((so->so_state & SS_NOFDREF) == 0) {\n shutdown(so->s,1); /* send FIN to fhost */\n if (global_readfds) {\n FD_CLR(so->s,global_readfds);\n }\n if (global_xfds) {\n FD_CLR(so->s,global_xfds);\n }\n\t}\n\tso->so_state &= ~(SS_ISFCONNECTING);\n\tif (so->so_state & SS_FCANTRCVMORE) {\n\t so->so_state &= SS_PERSISTENT_MASK;\n\t so->so_state |= SS_NOFDREF; /* as above */\n\t} else {\n\t so->so_state |= SS_FCANTSENDMORE;\n\t}\n}\n\n/*\n * Set write drain mode\n * Set CANTSENDMORE once all data has been write()n\n */\nvoid\nsofwdrain(struct socket *so)\n{\n\tif (so->so_rcv.sb_cc)\n\t\tso->so_state |= SS_FWDRAIN;\n\telse\n\t\tsofcantsendmore(so);\n}\n"], ["/linuxpdf/tinyemu/vga.c", "/*\n * Dummy VGA device\n * \n * Copyright (c) 2003-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n//#define DEBUG_VBE\n\n#define MSR_COLOR_EMULATION 0x01\n#define MSR_PAGE_SELECT 0x20\n\n#define ST01_V_RETRACE 0x08\n#define ST01_DISP_ENABLE 0x01\n\n#define VBE_DISPI_INDEX_ID 0x0\n#define VBE_DISPI_INDEX_XRES 0x1\n#define VBE_DISPI_INDEX_YRES 0x2\n#define VBE_DISPI_INDEX_BPP 0x3\n#define VBE_DISPI_INDEX_ENABLE 0x4\n#define VBE_DISPI_INDEX_BANK 0x5\n#define VBE_DISPI_INDEX_VIRT_WIDTH 0x6\n#define VBE_DISPI_INDEX_VIRT_HEIGHT 0x7\n#define VBE_DISPI_INDEX_X_OFFSET 0x8\n#define VBE_DISPI_INDEX_Y_OFFSET 0x9\n#define VBE_DISPI_INDEX_VIDEO_MEMORY_64K 0xa\n#define VBE_DISPI_INDEX_NB 0xb\n\n#define VBE_DISPI_ID0 0xB0C0\n#define VBE_DISPI_ID1 0xB0C1\n#define VBE_DISPI_ID2 0xB0C2\n#define VBE_DISPI_ID3 0xB0C3\n#define VBE_DISPI_ID4 0xB0C4\n#define VBE_DISPI_ID5 0xB0C5\n\n#define VBE_DISPI_DISABLED 0x00\n#define VBE_DISPI_ENABLED 0x01\n#define VBE_DISPI_GETCAPS 0x02\n#define VBE_DISPI_8BIT_DAC 0x20\n#define VBE_DISPI_LFB_ENABLED 0x40\n#define VBE_DISPI_NOCLEARMEM 0x80\n\n#define FB_ALLOC_ALIGN (1 << 20)\n\n#define MAX_TEXT_WIDTH 132\n#define MAX_TEXT_HEIGHT 60\n\nstruct VGAState {\n FBDevice *fb_dev;\n int fb_page_count;\n PhysMemoryRange *mem_range;\n PhysMemoryRange *mem_range2;\n PCIDevice *pci_dev;\n PhysMemoryRange *rom_range;\n\n uint8_t *vga_ram; /* 128K at 0xa0000 */\n \n uint8_t sr_index;\n uint8_t sr[8];\n uint8_t gr_index;\n uint8_t gr[16];\n uint8_t ar_index;\n uint8_t ar[21];\n int ar_flip_flop;\n uint8_t cr_index;\n uint8_t cr[256]; /* CRT registers */\n uint8_t msr; /* Misc Output Register */\n uint8_t fcr; /* Feature Control Register */\n uint8_t st00; /* status 0 */\n uint8_t st01; /* status 1 */\n uint8_t dac_state;\n uint8_t dac_sub_index;\n uint8_t dac_read_index;\n uint8_t dac_write_index;\n uint8_t dac_cache[3]; /* used when writing */\n uint8_t palette[768];\n \n /* text mode state */\n uint32_t last_palette[16];\n uint16_t last_ch_attr[MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT];\n uint32_t last_width;\n uint32_t last_height;\n uint16_t last_line_offset;\n uint16_t last_start_addr;\n uint16_t last_cursor_offset;\n uint8_t last_cursor_start;\n uint8_t last_cursor_end;\n \n /* VBE extension */\n uint16_t vbe_index;\n uint16_t vbe_regs[VBE_DISPI_INDEX_NB];\n};\n\nstatic void vga_draw_glyph8(uint8_t *d, int linesize,\n const uint8_t *font_ptr, int h,\n uint32_t fgcol, uint32_t bgcol)\n{\n uint32_t font_data, xorcol;\n\n xorcol = bgcol ^ fgcol;\n do {\n font_data = font_ptr[0];\n ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol;\n ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[7] = (-((font_data >> 0) & 1) & xorcol) ^ bgcol;\n font_ptr++;\n d += linesize;\n } while (--h);\n}\n\nstatic void vga_draw_glyph9(uint8_t *d, int linesize,\n const uint8_t *font_ptr, int h,\n uint32_t fgcol, uint32_t bgcol,\n int dup9)\n{\n uint32_t font_data, xorcol, v;\n\n xorcol = bgcol ^ fgcol;\n do {\n font_data = font_ptr[0];\n ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol;\n ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol;\n v = (-((font_data >> 0) & 1) & xorcol) ^ bgcol;\n ((uint32_t *)d)[7] = v;\n if (dup9)\n ((uint32_t *)d)[8] = v;\n else\n ((uint32_t *)d)[8] = bgcol;\n font_ptr++;\n d += linesize;\n } while (--h);\n}\n\nstatic const uint8_t cursor_glyph[32] = {\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n};\n\nstatic inline int c6_to_8(int v)\n{\n int b;\n v &= 0x3f;\n b = v & 1;\n return (v << 2) | (b << 1) | b;\n}\n\nstatic int update_palette16(VGAState *s, uint32_t *palette)\n{\n int full_update, i;\n uint32_t v, col;\n\n full_update = 0;\n for(i = 0; i < 16; i++) {\n v = s->ar[i];\n if (s->ar[0x10] & 0x80)\n v = ((s->ar[0x14] & 0xf) << 4) | (v & 0xf);\n else\n v = ((s->ar[0x14] & 0xc) << 4) | (v & 0x3f);\n v = v * 3;\n col = (c6_to_8(s->palette[v]) << 16) |\n (c6_to_8(s->palette[v + 1]) << 8) |\n c6_to_8(s->palette[v + 2]);\n if (col != palette[i]) {\n full_update = 1;\n palette[i] = col;\n }\n }\n return full_update;\n}\n\n/* the text refresh is just for debugging and initial boot message, so\n it is very incomplete */\nstatic void vga_text_refresh(VGAState *s,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n FBDevice *fb_dev = s->fb_dev;\n int width, height, cwidth, cheight, cy, cx, x1, y1, width1, height1;\n int cx_min, cx_max, dup9;\n uint32_t ch_attr, line_offset, start_addr, ch_addr, ch_addr1, ch, cattr;\n uint8_t *vga_ram, *font_ptr, *dst;\n uint32_t fgcol, bgcol, cursor_offset, cursor_start, cursor_end;\n BOOL full_update;\n\n full_update = update_palette16(s, s->last_palette);\n\n vga_ram = s->vga_ram;\n \n line_offset = s->cr[0x13];\n line_offset <<= 3;\n line_offset >>= 1;\n\n start_addr = s->cr[0x0d] | (s->cr[0x0c] << 8);\n \n cheight = (s->cr[9] & 0x1f) + 1;\n cwidth = 8;\n if (!(s->sr[1] & 0x01))\n cwidth++;\n \n width = (s->cr[0x01] + 1);\n height = s->cr[0x12] |\n ((s->cr[0x07] & 0x02) << 7) |\n ((s->cr[0x07] & 0x40) << 3);\n height = (height + 1) / cheight;\n \n width1 = width * cwidth;\n height1 = height * cheight;\n if (fb_dev->width < width1 || fb_dev->height < height1 ||\n width > MAX_TEXT_WIDTH || height > MAX_TEXT_HEIGHT)\n return; /* not enough space */\n if (s->last_line_offset != line_offset ||\n s->last_start_addr != start_addr ||\n s->last_width != width ||\n s->last_height != height) {\n s->last_line_offset = line_offset;\n s->last_start_addr = start_addr;\n s->last_width = width;\n s->last_height = height;\n full_update = TRUE;\n }\n \n /* update cursor position */\n cursor_offset = ((s->cr[0x0e] << 8) | s->cr[0x0f]) - start_addr;\n cursor_start = s->cr[0xa];\n cursor_end = s->cr[0xb];\n if (cursor_offset != s->last_cursor_offset ||\n cursor_start != s->last_cursor_start ||\n cursor_end != s->last_cursor_end) {\n /* force refresh of characters with the cursor */\n if (s->last_cursor_offset < MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT)\n s->last_ch_attr[s->last_cursor_offset] = -1;\n if (cursor_offset < MAX_TEXT_WIDTH * MAX_TEXT_HEIGHT)\n s->last_ch_attr[cursor_offset] = -1;\n s->last_cursor_offset = cursor_offset;\n s->last_cursor_start = cursor_start;\n s->last_cursor_end = cursor_end;\n }\n\n ch_addr1 = 0x18000 + (start_addr * 2);\n cursor_offset = 0x18000 + (start_addr + cursor_offset) * 2;\n \n x1 = (fb_dev->width - width1) / 2;\n y1 = (fb_dev->height - height1) / 2;\n#if 0\n printf(\"text refresh %dx%d font=%dx%d start_addr=0x%x line_offset=0x%x\\n\",\n width, height, cwidth, cheight, start_addr, line_offset);\n#endif\n for(cy = 0; cy < height; cy++) {\n ch_addr = ch_addr1;\n dst = fb_dev->fb_data + (y1 + cy * cheight) * fb_dev->stride + x1 * 4;\n cx_min = width;\n cx_max = -1;\n for(cx = 0; cx < width; cx++) {\n ch_attr = *(uint16_t *)(vga_ram + (ch_addr & 0x1fffe));\n if (full_update || ch_attr != s->last_ch_attr[cy * width + cx]) {\n s->last_ch_attr[cy * width + cx] = ch_attr;\n cx_min = min_int(cx_min, cx);\n cx_max = max_int(cx_max, cx);\n ch = ch_attr & 0xff;\n cattr = ch_attr >> 8;\n font_ptr = vga_ram + 32 * ch;\n bgcol = s->last_palette[cattr >> 4];\n fgcol = s->last_palette[cattr & 0x0f];\n if (cwidth == 8) {\n vga_draw_glyph8(dst, fb_dev->stride, font_ptr, cheight,\n fgcol, bgcol);\n } else {\n dup9 = 0;\n if (ch >= 0xb0 && ch <= 0xdf && (s->ar[0x10] & 0x04))\n dup9 = 1;\n vga_draw_glyph9(dst, fb_dev->stride, font_ptr, cheight,\n fgcol, bgcol, dup9);\n }\n /* cursor display */\n if (cursor_offset == ch_addr && !(cursor_start & 0x20)) {\n int line_start, line_last, h;\n uint8_t *dst1;\n line_start = cursor_start & 0x1f;\n line_last = min_int(cursor_end & 0x1f, cheight - 1);\n\n if (line_last >= line_start && line_start < cheight) {\n h = line_last - line_start + 1;\n dst1 = dst + fb_dev->stride * line_start;\n if (cwidth == 8) {\n vga_draw_glyph8(dst1, fb_dev->stride,\n cursor_glyph,\n h, fgcol, bgcol);\n } else {\n vga_draw_glyph9(dst1, fb_dev->stride,\n cursor_glyph,\n h, fgcol, bgcol, 1);\n }\n }\n }\n }\n ch_addr += 2;\n dst += 4 * cwidth;\n }\n if (cx_max >= cx_min) {\n // printf(\"redraw %d %d %d\\n\", cy, cx_min, cx_max);\n redraw_func(fb_dev, opaque,\n x1 + cx_min * cwidth, y1 + cy * cheight,\n (cx_max - cx_min + 1) * cwidth, cheight);\n }\n ch_addr1 += line_offset;\n }\n}\n\nstatic void vga_refresh(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n VGAState *s = fb_dev->device_opaque;\n\n if (!(s->ar_index & 0x20)) {\n /* blank */\n } else if (s->gr[0x06] & 1) {\n /* graphic mode (VBE) */\n simplefb_refresh(fb_dev, redraw_func, opaque, s->mem_range, s->fb_page_count);\n } else {\n /* text mode */\n vga_text_refresh(s, redraw_func, opaque);\n }\n}\n\n/* force some bits to zero */\nstatic const uint8_t sr_mask[8] = {\n (uint8_t)~0xfc,\n (uint8_t)~0xc2,\n (uint8_t)~0xf0,\n (uint8_t)~0xc0,\n (uint8_t)~0xf1,\n (uint8_t)~0xff,\n (uint8_t)~0xff,\n (uint8_t)~0x00,\n};\n\nstatic const uint8_t gr_mask[16] = {\n (uint8_t)~0xf0, /* 0x00 */\n (uint8_t)~0xf0, /* 0x01 */\n (uint8_t)~0xf0, /* 0x02 */\n (uint8_t)~0xe0, /* 0x03 */\n (uint8_t)~0xfc, /* 0x04 */\n (uint8_t)~0x84, /* 0x05 */\n (uint8_t)~0xf0, /* 0x06 */\n (uint8_t)~0xf0, /* 0x07 */\n (uint8_t)~0x00, /* 0x08 */\n (uint8_t)~0xff, /* 0x09 */\n (uint8_t)~0xff, /* 0x0a */\n (uint8_t)~0xff, /* 0x0b */\n (uint8_t)~0xff, /* 0x0c */\n (uint8_t)~0xff, /* 0x0d */\n (uint8_t)~0xff, /* 0x0e */\n (uint8_t)~0xff, /* 0x0f */\n};\n\nstatic uint32_t vga_ioport_read(VGAState *s, uint32_t addr)\n{\n int val, index;\n\n /* check port range access depending on color/monochrome mode */\n if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION)) ||\n (addr >= 0x3d0 && addr <= 0x3df && !(s->msr & MSR_COLOR_EMULATION))) {\n val = 0xff;\n } else {\n switch(addr) {\n case 0x3c0:\n if (s->ar_flip_flop == 0) {\n val = s->ar_index;\n } else {\n val = 0;\n }\n break;\n case 0x3c1:\n index = s->ar_index & 0x1f;\n if (index < 21)\n val = s->ar[index];\n else\n val = 0;\n break;\n case 0x3c2:\n val = s->st00;\n break;\n case 0x3c4:\n val = s->sr_index;\n break;\n case 0x3c5:\n val = s->sr[s->sr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n break;\n case 0x3c7:\n val = s->dac_state;\n break;\n\tcase 0x3c8:\n\t val = s->dac_write_index;\n\t break;\n case 0x3c9:\n val = s->palette[s->dac_read_index * 3 + s->dac_sub_index];\n if (++s->dac_sub_index == 3) {\n s->dac_sub_index = 0;\n s->dac_read_index++;\n }\n break;\n case 0x3ca:\n val = s->fcr;\n break;\n case 0x3cc:\n val = s->msr;\n break;\n case 0x3ce:\n val = s->gr_index;\n break;\n case 0x3cf:\n val = s->gr[s->gr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n break;\n case 0x3b4:\n case 0x3d4:\n val = s->cr_index;\n break;\n case 0x3b5:\n case 0x3d5:\n val = s->cr[s->cr_index];\n#ifdef DEBUG_VGA_REG\n printf(\"vga: read CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n break;\n case 0x3ba:\n case 0x3da:\n /* just toggle to fool polling */\n s->st01 ^= ST01_V_RETRACE | ST01_DISP_ENABLE;\n val = s->st01;\n s->ar_flip_flop = 0;\n break;\n default:\n val = 0x00;\n break;\n }\n }\n#if defined(DEBUG_VGA)\n printf(\"VGA: read addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n return val;\n}\n\nstatic void vga_ioport_write(VGAState *s, uint32_t addr, uint32_t val)\n{\n int index;\n\n /* check port range access depending on color/monochrome mode */\n if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION)) ||\n (addr >= 0x3d0 && addr <= 0x3df && !(s->msr & MSR_COLOR_EMULATION)))\n return;\n\n#ifdef DEBUG_VGA\n printf(\"VGA: write addr=0x%04x data=0x%02x\\n\", addr, val);\n#endif\n\n switch(addr) {\n case 0x3c0:\n if (s->ar_flip_flop == 0) {\n val &= 0x3f;\n s->ar_index = val;\n } else {\n index = s->ar_index & 0x1f;\n switch(index) {\n case 0x00 ... 0x0f:\n s->ar[index] = val & 0x3f;\n break;\n case 0x10:\n s->ar[index] = val & ~0x10;\n break;\n case 0x11:\n s->ar[index] = val;\n break;\n case 0x12:\n s->ar[index] = val & ~0xc0;\n break;\n case 0x13:\n s->ar[index] = val & ~0xf0;\n break;\n case 0x14:\n s->ar[index] = val & ~0xf0;\n break;\n default:\n break;\n }\n }\n s->ar_flip_flop ^= 1;\n break;\n case 0x3c2:\n s->msr = val & ~0x10;\n break;\n case 0x3c4:\n s->sr_index = val & 7;\n break;\n case 0x3c5:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write SR%x = 0x%02x\\n\", s->sr_index, val);\n#endif\n s->sr[s->sr_index] = val & sr_mask[s->sr_index];\n break;\n case 0x3c7:\n s->dac_read_index = val;\n s->dac_sub_index = 0;\n s->dac_state = 3;\n break;\n case 0x3c8:\n s->dac_write_index = val;\n s->dac_sub_index = 0;\n s->dac_state = 0;\n break;\n case 0x3c9:\n s->dac_cache[s->dac_sub_index] = val;\n if (++s->dac_sub_index == 3) {\n memcpy(&s->palette[s->dac_write_index * 3], s->dac_cache, 3);\n s->dac_sub_index = 0;\n s->dac_write_index++;\n }\n break;\n case 0x3ce:\n s->gr_index = val & 0x0f;\n break;\n case 0x3cf:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write GR%x = 0x%02x\\n\", s->gr_index, val);\n#endif\n s->gr[s->gr_index] = val & gr_mask[s->gr_index];\n break;\n case 0x3b4:\n case 0x3d4:\n s->cr_index = val;\n break;\n case 0x3b5:\n case 0x3d5:\n#ifdef DEBUG_VGA_REG\n printf(\"vga: write CR%x = 0x%02x\\n\", s->cr_index, val);\n#endif\n /* handle CR0-7 protection */\n if ((s->cr[0x11] & 0x80) && s->cr_index <= 7) {\n /* can always write bit 4 of CR7 */\n if (s->cr_index == 7)\n s->cr[7] = (s->cr[7] & ~0x10) | (val & 0x10);\n return;\n }\n switch(s->cr_index) {\n case 0x01: /* horizontal display end */\n case 0x07:\n case 0x09:\n case 0x0c:\n case 0x0d:\n case 0x12: /* vertical display end */\n s->cr[s->cr_index] = val;\n break;\n default:\n s->cr[s->cr_index] = val;\n break;\n }\n break;\n case 0x3ba:\n case 0x3da:\n s->fcr = val & 0x10;\n break;\n }\n}\n\n#define VGA_IO(base) \\\nstatic uint32_t vga_read_ ## base(void *opaque, uint32_t addr, int size_log2)\\\n{\\\n return vga_ioport_read(opaque, base + addr);\\\n}\\\nstatic void vga_write_ ## base(void *opaque, uint32_t addr, uint32_t val, int size_log2)\\\n{\\\n return vga_ioport_write(opaque, base + addr, val);\\\n}\n\nVGA_IO(0x3c0)\nVGA_IO(0x3b4)\nVGA_IO(0x3d4)\nVGA_IO(0x3ba)\nVGA_IO(0x3da)\n\nstatic void vbe_write(void *opaque, uint32_t offset,\n uint32_t val, int size_log2)\n{\n VGAState *s = opaque;\n FBDevice *fb_dev = s->fb_dev;\n \n if (offset == 0) {\n s->vbe_index = val;\n } else {\n#ifdef DEBUG_VBE\n printf(\"VBE write: index=0x%04x val=0x%04x\\n\", s->vbe_index, val);\n#endif\n switch(s->vbe_index) {\n case VBE_DISPI_INDEX_ID:\n if (val >= VBE_DISPI_ID0 && val <= VBE_DISPI_ID5)\n s->vbe_regs[s->vbe_index] = val;\n break;\n case VBE_DISPI_INDEX_ENABLE:\n if ((val & VBE_DISPI_ENABLED) &&\n !(s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED)) {\n /* set graphic mode */\n /* XXX: resolution change not really supported */\n if (s->vbe_regs[VBE_DISPI_INDEX_XRES] <= 4096 &&\n s->vbe_regs[VBE_DISPI_INDEX_YRES] <= 4096 &&\n (s->vbe_regs[VBE_DISPI_INDEX_XRES] * 4 *\n s->vbe_regs[VBE_DISPI_INDEX_YRES]) <= fb_dev->fb_size) {\n fb_dev->width = s->vbe_regs[VBE_DISPI_INDEX_XRES];\n fb_dev->height = s->vbe_regs[VBE_DISPI_INDEX_YRES];\n fb_dev->stride = fb_dev->width * 4;\n }\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] =\n s->vbe_regs[VBE_DISPI_INDEX_XRES];\n s->vbe_regs[VBE_DISPI_INDEX_VIRT_HEIGHT] =\n s->vbe_regs[VBE_DISPI_INDEX_YRES];\n s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET] = 0;\n s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET] = 0;\n }\n s->vbe_regs[s->vbe_index] = val;\n break;\n case VBE_DISPI_INDEX_XRES:\n case VBE_DISPI_INDEX_YRES:\n case VBE_DISPI_INDEX_BPP:\n case VBE_DISPI_INDEX_BANK:\n case VBE_DISPI_INDEX_VIRT_WIDTH:\n case VBE_DISPI_INDEX_VIRT_HEIGHT:\n case VBE_DISPI_INDEX_X_OFFSET:\n case VBE_DISPI_INDEX_Y_OFFSET:\n s->vbe_regs[s->vbe_index] = val;\n break;\n }\n }\n}\n\nstatic uint32_t vbe_read(void *opaque, uint32_t offset, int size_log2)\n{\n VGAState *s = opaque;\n uint32_t val;\n\n if (offset == 0) {\n val = s->vbe_index;\n } else {\n if (s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_GETCAPS) {\n switch(s->vbe_index) {\n case VBE_DISPI_INDEX_XRES:\n val = s->fb_dev->width;\n break;\n case VBE_DISPI_INDEX_YRES:\n val = s->fb_dev->height;\n break;\n case VBE_DISPI_INDEX_BPP:\n val = 32;\n break;\n default:\n goto read_reg;\n }\n } else {\n read_reg:\n if (s->vbe_index < VBE_DISPI_INDEX_NB)\n val = s->vbe_regs[s->vbe_index];\n else\n val = 0;\n }\n#ifdef DEBUG_VBE\n printf(\"VBE read: index=0x%04x val=0x%04x\\n\", s->vbe_index, val);\n#endif\n }\n return val;\n}\n\n\nstatic void simplefb_bar_set(void *opaque, int bar_num,\n uint32_t addr, BOOL enabled)\n{\n VGAState *s = opaque;\n if (bar_num == 0)\n phys_mem_set_addr(s->mem_range, addr, enabled);\n else\n phys_mem_set_addr(s->rom_range, addr, enabled);\n}\n\nVGAState *pci_vga_init(PCIBus *bus, FBDevice *fb_dev,\n int width, int height,\n const uint8_t *vga_rom_buf, int vga_rom_size)\n{\n VGAState *s;\n PCIDevice *d;\n uint32_t bar_size;\n PhysMemoryMap *mem_map, *port_map;\n \n d = pci_register_device(bus, \"VGA\", -1, 0x1234, 0x1111, 0x00, 0x0300);\n \n mem_map = pci_device_get_mem_map(d);\n port_map = pci_device_get_port_map(d);\n\n s = mallocz(sizeof(*s));\n s->fb_dev = fb_dev;\n \n fb_dev->width = width;\n fb_dev->height = height;\n fb_dev->stride = width * 4;\n\n fb_dev->fb_size = (height * fb_dev->stride + FB_ALLOC_ALIGN - 1) & ~(FB_ALLOC_ALIGN - 1);\n s->fb_page_count = fb_dev->fb_size >> DEVRAM_PAGE_SIZE_LOG2;\n\n s->mem_range =\n cpu_register_ram(mem_map, 0, fb_dev->fb_size,\n DEVRAM_FLAG_DIRTY_BITS | DEVRAM_FLAG_DISABLED);\n \n fb_dev->fb_data = s->mem_range->phys_mem;\n\n s->pci_dev = d;\n bar_size = 1;\n while (bar_size < fb_dev->fb_size)\n bar_size <<= 1;\n pci_register_bar(d, 0, bar_size, PCI_ADDRESS_SPACE_MEM, s,\n simplefb_bar_set);\n\n if (vga_rom_size > 0) {\n int rom_size;\n /* align to page size */\n rom_size = (vga_rom_size + DEVRAM_PAGE_SIZE - 1) & ~(DEVRAM_PAGE_SIZE - 1);\n s->rom_range = cpu_register_ram(mem_map, 0, rom_size,\n DEVRAM_FLAG_ROM | DEVRAM_FLAG_DISABLED);\n memcpy(s->rom_range->phys_mem, vga_rom_buf, vga_rom_size);\n\n bar_size = 1;\n while (bar_size < rom_size)\n bar_size <<= 1;\n pci_register_bar(d, PCI_ROM_SLOT, bar_size, PCI_ADDRESS_SPACE_MEM, s,\n simplefb_bar_set);\n }\n\n /* VGA memory (for simple text mode no need for callbacks) */\n s->mem_range2 = cpu_register_ram(mem_map, 0xa0000, 0x20000, 0);\n s->vga_ram = s->mem_range2->phys_mem;\n \n /* standard VGA ports */\n \n cpu_register_device(port_map, 0x3c0, 16, s, vga_read_0x3c0, vga_write_0x3c0,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3b4, 2, s, vga_read_0x3b4, vga_write_0x3b4,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3d4, 2, s, vga_read_0x3d4, vga_write_0x3d4,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3ba, 1, s, vga_read_0x3ba, vga_write_0x3ba,\n DEVIO_SIZE8);\n cpu_register_device(port_map, 0x3da, 1, s, vga_read_0x3da, vga_write_0x3da,\n DEVIO_SIZE8);\n \n /* VBE extension */\n cpu_register_device(port_map, 0x1ce, 2, s, vbe_read, vbe_write, \n DEVIO_SIZE16);\n \n s->vbe_regs[VBE_DISPI_INDEX_ID] = VBE_DISPI_ID5;\n s->vbe_regs[VBE_DISPI_INDEX_VIDEO_MEMORY_64K] = fb_dev->fb_size >> 16;\n\n fb_dev->device_opaque = s;\n fb_dev->refresh = vga_refresh;\n return s;\n}\n"], ["/linuxpdf/tinyemu/slirp/bootp.c", "/*\n * QEMU BOOTP/DHCP server\n *\n * Copyright (c) 2004 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \"slirp.h\"\n\n/* XXX: only DHCP is supported */\n\n#define LEASE_TIME (24 * 3600)\n\nstatic const uint8_t rfc1533_cookie[] = { RFC1533_COOKIE };\n\n#ifdef DEBUG\n#define DPRINTF(fmt, ...) \\\ndo if (slirp_debug & DBG_CALL) { fprintf(dfd, fmt, ## __VA_ARGS__); fflush(dfd); } while (0)\n#else\n#define DPRINTF(fmt, ...) do{}while(0)\n#endif\n\nstatic BOOTPClient *get_new_addr(Slirp *slirp, struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n BOOTPClient *bc;\n int i;\n\n for(i = 0; i < NB_BOOTP_CLIENTS; i++) {\n bc = &slirp->bootp_clients[i];\n if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6))\n goto found;\n }\n return NULL;\n found:\n bc = &slirp->bootp_clients[i];\n bc->allocated = 1;\n paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i);\n return bc;\n}\n\nstatic BOOTPClient *request_addr(Slirp *slirp, const struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n uint32_t req_addr = ntohl(paddr->s_addr);\n uint32_t dhcp_addr = ntohl(slirp->vdhcp_startaddr.s_addr);\n BOOTPClient *bc;\n\n if (req_addr >= dhcp_addr &&\n req_addr < (dhcp_addr + NB_BOOTP_CLIENTS)) {\n bc = &slirp->bootp_clients[req_addr - dhcp_addr];\n if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6)) {\n bc->allocated = 1;\n return bc;\n }\n }\n return NULL;\n}\n\nstatic BOOTPClient *find_addr(Slirp *slirp, struct in_addr *paddr,\n const uint8_t *macaddr)\n{\n BOOTPClient *bc;\n int i;\n\n for(i = 0; i < NB_BOOTP_CLIENTS; i++) {\n if (!memcmp(macaddr, slirp->bootp_clients[i].macaddr, 6))\n goto found;\n }\n return NULL;\n found:\n bc = &slirp->bootp_clients[i];\n bc->allocated = 1;\n paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i);\n return bc;\n}\n\nstatic void dhcp_decode(const struct bootp_t *bp, int *pmsg_type,\n struct in_addr *preq_addr)\n{\n const uint8_t *p, *p_end;\n int len, tag;\n\n *pmsg_type = 0;\n preq_addr->s_addr = htonl(0L);\n\n p = bp->bp_vend;\n p_end = p + DHCP_OPT_LEN;\n if (memcmp(p, rfc1533_cookie, 4) != 0)\n return;\n p += 4;\n while (p < p_end) {\n tag = p[0];\n if (tag == RFC1533_PAD) {\n p++;\n } else if (tag == RFC1533_END) {\n break;\n } else {\n p++;\n if (p >= p_end)\n break;\n len = *p++;\n DPRINTF(\"dhcp: tag=%d len=%d\\n\", tag, len);\n\n switch(tag) {\n case RFC2132_MSG_TYPE:\n if (len >= 1)\n *pmsg_type = p[0];\n break;\n case RFC2132_REQ_ADDR:\n if (len >= 4) {\n memcpy(&(preq_addr->s_addr), p, 4);\n }\n break;\n default:\n break;\n }\n p += len;\n }\n }\n if (*pmsg_type == DHCPREQUEST && preq_addr->s_addr == htonl(0L) &&\n bp->bp_ciaddr.s_addr) {\n memcpy(&(preq_addr->s_addr), &bp->bp_ciaddr, 4);\n }\n}\n\nstatic void bootp_reply(Slirp *slirp, const struct bootp_t *bp)\n{\n BOOTPClient *bc = NULL;\n struct mbuf *m;\n struct bootp_t *rbp;\n struct sockaddr_in saddr, daddr;\n struct in_addr preq_addr;\n int dhcp_msg_type, val;\n uint8_t *q;\n\n /* extract exact DHCP msg type */\n dhcp_decode(bp, &dhcp_msg_type, &preq_addr);\n DPRINTF(\"bootp packet op=%d msgtype=%d\", bp->bp_op, dhcp_msg_type);\n if (preq_addr.s_addr != htonl(0L))\n DPRINTF(\" req_addr=%08x\\n\", ntohl(preq_addr.s_addr));\n else\n DPRINTF(\"\\n\");\n\n if (dhcp_msg_type == 0)\n dhcp_msg_type = DHCPREQUEST; /* Force reply for old BOOTP clients */\n\n if (dhcp_msg_type != DHCPDISCOVER &&\n dhcp_msg_type != DHCPREQUEST)\n return;\n /* XXX: this is a hack to get the client mac address */\n memcpy(slirp->client_ethaddr, bp->bp_hwaddr, 6);\n\n m = m_get(slirp);\n if (!m) {\n return;\n }\n m->m_data += IF_MAXLINKHDR;\n rbp = (struct bootp_t *)m->m_data;\n m->m_data += sizeof(struct udpiphdr);\n memset(rbp, 0, sizeof(struct bootp_t));\n\n if (dhcp_msg_type == DHCPDISCOVER) {\n if (preq_addr.s_addr != htonl(0L)) {\n bc = request_addr(slirp, &preq_addr, slirp->client_ethaddr);\n if (bc) {\n daddr.sin_addr = preq_addr;\n }\n }\n if (!bc) {\n new_addr:\n bc = get_new_addr(slirp, &daddr.sin_addr, slirp->client_ethaddr);\n if (!bc) {\n DPRINTF(\"no address left\\n\");\n return;\n }\n }\n memcpy(bc->macaddr, slirp->client_ethaddr, 6);\n } else if (preq_addr.s_addr != htonl(0L)) {\n bc = request_addr(slirp, &preq_addr, slirp->client_ethaddr);\n if (bc) {\n daddr.sin_addr = preq_addr;\n memcpy(bc->macaddr, slirp->client_ethaddr, 6);\n } else {\n daddr.sin_addr.s_addr = 0;\n }\n } else {\n bc = find_addr(slirp, &daddr.sin_addr, bp->bp_hwaddr);\n if (!bc) {\n /* if never assigned, behaves as if it was already\n assigned (windows fix because it remembers its address) */\n goto new_addr;\n }\n }\n\n saddr.sin_addr = slirp->vhost_addr;\n saddr.sin_port = htons(BOOTP_SERVER);\n\n daddr.sin_port = htons(BOOTP_CLIENT);\n\n rbp->bp_op = BOOTP_REPLY;\n rbp->bp_xid = bp->bp_xid;\n rbp->bp_htype = 1;\n rbp->bp_hlen = 6;\n memcpy(rbp->bp_hwaddr, bp->bp_hwaddr, 6);\n\n rbp->bp_yiaddr = daddr.sin_addr; /* Client IP address */\n rbp->bp_siaddr = saddr.sin_addr; /* Server IP address */\n\n q = rbp->bp_vend;\n memcpy(q, rfc1533_cookie, 4);\n q += 4;\n\n if (bc) {\n DPRINTF(\"%s addr=%08x\\n\",\n (dhcp_msg_type == DHCPDISCOVER) ? \"offered\" : \"ack'ed\",\n ntohl(daddr.sin_addr.s_addr));\n\n if (dhcp_msg_type == DHCPDISCOVER) {\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPOFFER;\n } else /* DHCPREQUEST */ {\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPACK;\n }\n\n if (slirp->bootp_filename)\n snprintf((char *)rbp->bp_file, sizeof(rbp->bp_file), \"%s\",\n slirp->bootp_filename);\n\n *q++ = RFC2132_SRV_ID;\n *q++ = 4;\n memcpy(q, &saddr.sin_addr, 4);\n q += 4;\n\n *q++ = RFC1533_NETMASK;\n *q++ = 4;\n memcpy(q, &slirp->vnetwork_mask, 4);\n q += 4;\n\n if (!slirp->restricted) {\n *q++ = RFC1533_GATEWAY;\n *q++ = 4;\n memcpy(q, &saddr.sin_addr, 4);\n q += 4;\n\n *q++ = RFC1533_DNS;\n *q++ = 4;\n memcpy(q, &slirp->vnameserver_addr, 4);\n q += 4;\n }\n\n *q++ = RFC2132_LEASE_TIME;\n *q++ = 4;\n val = htonl(LEASE_TIME);\n memcpy(q, &val, 4);\n q += 4;\n\n if (*slirp->client_hostname) {\n val = strlen(slirp->client_hostname);\n *q++ = RFC1533_HOSTNAME;\n *q++ = val;\n memcpy(q, slirp->client_hostname, val);\n q += val;\n }\n } else {\n static const char nak_msg[] = \"requested address not available\";\n\n DPRINTF(\"nak'ed addr=%08x\\n\", ntohl(preq_addr->s_addr));\n\n *q++ = RFC2132_MSG_TYPE;\n *q++ = 1;\n *q++ = DHCPNAK;\n\n *q++ = RFC2132_MESSAGE;\n *q++ = sizeof(nak_msg) - 1;\n memcpy(q, nak_msg, sizeof(nak_msg) - 1);\n q += sizeof(nak_msg) - 1;\n }\n *q = RFC1533_END;\n\n daddr.sin_addr.s_addr = 0xffffffffu;\n\n m->m_len = sizeof(struct bootp_t) -\n sizeof(struct ip) - sizeof(struct udphdr);\n udp_output2(NULL, m, &saddr, &daddr, IPTOS_LOWDELAY);\n}\n\nvoid bootp_input(struct mbuf *m)\n{\n struct bootp_t *bp = mtod(m, struct bootp_t *);\n\n if (bp->bp_op == BOOTP_REQUEST) {\n bootp_reply(m->slirp, bp);\n }\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_icmp.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_icmp.c\t8.2 (Berkeley) 1/4/94\n * ip_icmp.c,v 1.7 1995/05/30 08:09:42 rgrimes Exp\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\n/* The message sent when emulating PING */\n/* Be nice and tell them it's just a pseudo-ping packet */\nstatic const char icmp_ping_msg[] = \"This is a pseudo-PING packet used by Slirp to emulate ICMP ECHO-REQUEST packets.\\n\";\n\n/* list of actions for icmp_error() on RX of an icmp message */\nstatic const int icmp_flush[19] = {\n/* ECHO REPLY (0) */ 0,\n\t\t 1,\n\t\t 1,\n/* DEST UNREACH (3) */ 1,\n/* SOURCE QUENCH (4)*/ 1,\n/* REDIRECT (5) */ 1,\n\t\t 1,\n\t\t 1,\n/* ECHO (8) */ 0,\n/* ROUTERADVERT (9) */ 1,\n/* ROUTERSOLICIT (10) */ 1,\n/* TIME EXCEEDED (11) */ 1,\n/* PARAMETER PROBLEM (12) */ 1,\n/* TIMESTAMP (13) */ 0,\n/* TIMESTAMP REPLY (14) */ 0,\n/* INFO (15) */ 0,\n/* INFO REPLY (16) */ 0,\n/* ADDR MASK (17) */ 0,\n/* ADDR MASK REPLY (18) */ 0\n};\n\n/*\n * Process a received ICMP message.\n */\nvoid\nicmp_input(struct mbuf *m, int hlen)\n{\n register struct icmp *icp;\n register struct ip *ip=mtod(m, struct ip *);\n int icmplen=ip->ip_len;\n Slirp *slirp = m->slirp;\n\n DEBUG_CALL(\"icmp_input\");\n DEBUG_ARG(\"m = %lx\", (long )m);\n DEBUG_ARG(\"m_len = %d\", m->m_len);\n\n /*\n * Locate icmp structure in mbuf, and check\n * that its not corrupted and of at least minimum length.\n */\n if (icmplen < ICMP_MINLEN) { /* min 8 bytes payload */\n freeit:\n m_freem(m);\n goto end_error;\n }\n\n m->m_len -= hlen;\n m->m_data += hlen;\n icp = mtod(m, struct icmp *);\n if (cksum(m, icmplen)) {\n goto freeit;\n }\n m->m_len += hlen;\n m->m_data -= hlen;\n\n DEBUG_ARG(\"icmp_type = %d\", icp->icmp_type);\n switch (icp->icmp_type) {\n case ICMP_ECHO:\n icp->icmp_type = ICMP_ECHOREPLY;\n ip->ip_len += hlen;\t /* since ip_input subtracts this */\n if (ip->ip_dst.s_addr == slirp->vhost_addr.s_addr) {\n icmp_reflect(m);\n } else {\n struct socket *so;\n struct sockaddr_in addr;\n if ((so = socreate(slirp)) == NULL) goto freeit;\n if(udp_attach(so) == -1) {\n\tDEBUG_MISC((dfd,\"icmp_input udp_attach errno = %d-%s\\n\",\n\t\t errno,strerror(errno)));\n\tsofree(so);\n\tm_free(m);\n\tgoto end_error;\n }\n so->so_m = m;\n so->so_faddr = ip->ip_dst;\n so->so_fport = htons(7);\n so->so_laddr = ip->ip_src;\n so->so_lport = htons(9);\n so->so_iptos = ip->ip_tos;\n so->so_type = IPPROTO_ICMP;\n so->so_state = SS_ISFCONNECTED;\n\n /* Send the packet */\n addr.sin_family = AF_INET;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n\t/* It's an alias */\n\tif (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {\n\t if (get_dns_addr(&addr.sin_addr) < 0)\n\t addr.sin_addr = loopback_addr;\n\t} else {\n\t addr.sin_addr = loopback_addr;\n\t}\n } else {\n\taddr.sin_addr = so->so_faddr;\n }\n addr.sin_port = so->so_fport;\n if(sendto(so->s, icmp_ping_msg, strlen(icmp_ping_msg), 0,\n\t\t(struct sockaddr *)&addr, sizeof(addr)) == -1) {\n\tDEBUG_MISC((dfd,\"icmp_input udp sendto tx errno = %d-%s\\n\",\n\t\t errno,strerror(errno)));\n\ticmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));\n\tudp_detach(so);\n }\n } /* if ip->ip_dst.s_addr == alias_addr.s_addr */\n break;\n case ICMP_UNREACH:\n /* XXX? report error? close socket? */\n case ICMP_TIMXCEED:\n case ICMP_PARAMPROB:\n case ICMP_SOURCEQUENCH:\n case ICMP_TSTAMP:\n case ICMP_MASKREQ:\n case ICMP_REDIRECT:\n m_freem(m);\n break;\n\n default:\n m_freem(m);\n } /* swith */\n\nend_error:\n /* m is m_free()'d xor put in a socket xor or given to ip_send */\n return;\n}\n\n\n/*\n *\tSend an ICMP message in response to a situation\n *\n *\tRFC 1122: 3.2.2\tMUST send at least the IP header and 8 bytes of header. MAY send more (we do).\n *\t\t\tMUST NOT change this header information.\n *\t\t\tMUST NOT reply to a multicast/broadcast IP address.\n *\t\t\tMUST NOT reply to a multicast/broadcast MAC address.\n *\t\t\tMUST reply to only the first fragment.\n */\n/*\n * Send ICMP_UNREACH back to the source regarding msrc.\n * mbuf *msrc is used as a template, but is NOT m_free()'d.\n * It is reported as the bad ip packet. The header should\n * be fully correct and in host byte order.\n * ICMP fragmentation is illegal. All machines must accept 576 bytes in one\n * packet. The maximum payload is 576-20(ip hdr)-8(icmp hdr)=548\n */\n\n#define ICMP_MAXDATALEN (IP_MSS-28)\nvoid\nicmp_error(struct mbuf *msrc, u_char type, u_char code, int minsize,\n const char *message)\n{\n unsigned hlen, shlen, s_ip_len;\n register struct ip *ip;\n register struct icmp *icp;\n register struct mbuf *m;\n\n DEBUG_CALL(\"icmp_error\");\n DEBUG_ARG(\"msrc = %lx\", (long )msrc);\n DEBUG_ARG(\"msrc_len = %d\", msrc->m_len);\n\n if(type!=ICMP_UNREACH && type!=ICMP_TIMXCEED) goto end_error;\n\n /* check msrc */\n if(!msrc) goto end_error;\n ip = mtod(msrc, struct ip *);\n#ifdef DEBUG\n { char bufa[20], bufb[20];\n strcpy(bufa, inet_ntoa(ip->ip_src));\n strcpy(bufb, inet_ntoa(ip->ip_dst));\n DEBUG_MISC((dfd, \" %.16s to %.16s\\n\", bufa, bufb));\n }\n#endif\n if(ip->ip_off & IP_OFFMASK) goto end_error; /* Only reply to fragment 0 */\n\n shlen=ip->ip_hl << 2;\n s_ip_len=ip->ip_len;\n if(ip->ip_p == IPPROTO_ICMP) {\n icp = (struct icmp *)((char *)ip + shlen);\n /*\n *\tAssume any unknown ICMP type is an error. This isn't\n *\tspecified by the RFC, but think about it..\n */\n if(icp->icmp_type>18 || icmp_flush[icp->icmp_type]) goto end_error;\n }\n\n /* make a copy */\n m = m_get(msrc->slirp);\n if (!m) {\n goto end_error;\n }\n\n { int new_m_size;\n new_m_size=sizeof(struct ip )+ICMP_MINLEN+msrc->m_len+ICMP_MAXDATALEN;\n if(new_m_size>m->m_size) m_inc(m, new_m_size);\n }\n memcpy(m->m_data, msrc->m_data, msrc->m_len);\n m->m_len = msrc->m_len; /* copy msrc to m */\n\n /* make the header of the reply packet */\n ip = mtod(m, struct ip *);\n hlen= sizeof(struct ip ); /* no options in reply */\n\n /* fill in icmp */\n m->m_data += hlen;\n m->m_len -= hlen;\n\n icp = mtod(m, struct icmp *);\n\n if(minsize) s_ip_len=shlen+ICMP_MINLEN; /* return header+8b only */\n else if(s_ip_len>ICMP_MAXDATALEN) /* maximum size */\n s_ip_len=ICMP_MAXDATALEN;\n\n m->m_len=ICMP_MINLEN+s_ip_len; /* 8 bytes ICMP header */\n\n /* min. size = 8+sizeof(struct ip)+8 */\n\n icp->icmp_type = type;\n icp->icmp_code = code;\n icp->icmp_id = 0;\n icp->icmp_seq = 0;\n\n memcpy(&icp->icmp_ip, msrc->m_data, s_ip_len); /* report the ip packet */\n HTONS(icp->icmp_ip.ip_len);\n HTONS(icp->icmp_ip.ip_id);\n HTONS(icp->icmp_ip.ip_off);\n\n#ifdef DEBUG\n if(message) { /* DEBUG : append message to ICMP packet */\n int message_len;\n char *cpnt;\n message_len=strlen(message);\n if(message_len>ICMP_MAXDATALEN) message_len=ICMP_MAXDATALEN;\n cpnt=(char *)m->m_data+m->m_len;\n memcpy(cpnt, message, message_len);\n m->m_len+=message_len;\n }\n#endif\n\n icp->icmp_cksum = 0;\n icp->icmp_cksum = cksum(m, m->m_len);\n\n m->m_data -= hlen;\n m->m_len += hlen;\n\n /* fill in ip */\n ip->ip_hl = hlen >> 2;\n ip->ip_len = m->m_len;\n\n ip->ip_tos=((ip->ip_tos & 0x1E) | 0xC0); /* high priority for errors */\n\n ip->ip_ttl = MAXTTL;\n ip->ip_p = IPPROTO_ICMP;\n ip->ip_dst = ip->ip_src; /* ip adresses */\n ip->ip_src = m->slirp->vhost_addr;\n\n (void ) ip_output((struct socket *)NULL, m);\n\nend_error:\n return;\n}\n#undef ICMP_MAXDATALEN\n\n/*\n * Reflect the ip packet back to the source\n */\nvoid\nicmp_reflect(struct mbuf *m)\n{\n register struct ip *ip = mtod(m, struct ip *);\n int hlen = ip->ip_hl << 2;\n int optlen = hlen - sizeof(struct ip );\n register struct icmp *icp;\n\n /*\n * Send an icmp packet back to the ip level,\n * after supplying a checksum.\n */\n m->m_data += hlen;\n m->m_len -= hlen;\n icp = mtod(m, struct icmp *);\n\n icp->icmp_cksum = 0;\n icp->icmp_cksum = cksum(m, ip->ip_len - hlen);\n\n m->m_data -= hlen;\n m->m_len += hlen;\n\n /* fill in ip */\n if (optlen > 0) {\n /*\n * Strip out original options by copying rest of first\n * mbuf's data back, and adjust the IP length.\n */\n memmove((caddr_t)(ip + 1), (caddr_t)ip + hlen,\n\t (unsigned )(m->m_len - hlen));\n hlen -= optlen;\n ip->ip_hl = hlen >> 2;\n ip->ip_len -= optlen;\n m->m_len -= optlen;\n }\n\n ip->ip_ttl = MAXTTL;\n { /* swap */\n struct in_addr icmp_dst;\n icmp_dst = ip->ip_dst;\n ip->ip_dst = ip->ip_src;\n ip->ip_src = icmp_dst;\n }\n\n (void ) ip_output((struct socket *)NULL, m);\n}\n"], ["/linuxpdf/tinyemu/iomem.c", "/*\n * IO memory handling\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n\nstatic PhysMemoryRange *default_register_ram(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags);\nstatic void default_free_ram(PhysMemoryMap *s, PhysMemoryRange *pr);\nstatic const uint32_t *default_get_dirty_bits(PhysMemoryMap *map, PhysMemoryRange *pr);\nstatic void default_set_addr(PhysMemoryMap *map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled);\n\nPhysMemoryMap *phys_mem_map_init(void)\n{\n PhysMemoryMap *s;\n s = mallocz(sizeof(*s));\n s->register_ram = default_register_ram;\n s->free_ram = default_free_ram;\n s->get_dirty_bits = default_get_dirty_bits;\n s->set_ram_addr = default_set_addr;\n return s;\n}\n\nvoid phys_mem_map_end(PhysMemoryMap *s)\n{\n int i;\n PhysMemoryRange *pr;\n\n for(i = 0; i < s->n_phys_mem_range; i++) {\n pr = &s->phys_mem_range[i];\n if (pr->is_ram) {\n s->free_ram(s, pr);\n }\n }\n free(s);\n}\n\n/* return NULL if not found */\n/* XXX: optimize */\nPhysMemoryRange *get_phys_mem_range(PhysMemoryMap *s, uint64_t paddr)\n{\n PhysMemoryRange *pr;\n int i;\n for(i = 0; i < s->n_phys_mem_range; i++) {\n pr = &s->phys_mem_range[i];\n if (paddr >= pr->addr && paddr < pr->addr + pr->size)\n return pr;\n }\n return NULL;\n}\n\nPhysMemoryRange *register_ram_entry(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n\n assert(s->n_phys_mem_range < PHYS_MEM_RANGE_MAX);\n assert((size & (DEVRAM_PAGE_SIZE - 1)) == 0 && size != 0);\n pr = &s->phys_mem_range[s->n_phys_mem_range++];\n pr->map = s;\n pr->is_ram = TRUE;\n pr->devram_flags = devram_flags & ~DEVRAM_FLAG_DISABLED;\n pr->addr = addr;\n pr->org_size = size;\n if (devram_flags & DEVRAM_FLAG_DISABLED)\n pr->size = 0;\n else\n pr->size = pr->org_size;\n pr->phys_mem = NULL;\n pr->dirty_bits = NULL;\n return pr;\n}\n\nstatic PhysMemoryRange *default_register_ram(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, int devram_flags)\n{\n PhysMemoryRange *pr;\n\n pr = register_ram_entry(s, addr, size, devram_flags);\n\n pr->phys_mem = mallocz(size);\n if (!pr->phys_mem) {\n fprintf(stderr, \"Could not allocate VM memory\\n\");\n exit(1);\n }\n\n if (devram_flags & DEVRAM_FLAG_DIRTY_BITS) {\n size_t nb_pages;\n int i;\n nb_pages = size >> DEVRAM_PAGE_SIZE_LOG2;\n pr->dirty_bits_size = ((nb_pages + 31) / 32) * sizeof(uint32_t);\n pr->dirty_bits_index = 0;\n for(i = 0; i < 2; i++) {\n pr->dirty_bits_tab[i] = mallocz(pr->dirty_bits_size);\n }\n pr->dirty_bits = pr->dirty_bits_tab[pr->dirty_bits_index];\n }\n return pr;\n}\n\n/* return a pointer to the bitmap of dirty bits and reset them */\nstatic const uint32_t *default_get_dirty_bits(PhysMemoryMap *map,\n PhysMemoryRange *pr)\n{\n uint32_t *dirty_bits;\n BOOL has_dirty_bits;\n size_t n, i;\n \n dirty_bits = pr->dirty_bits;\n\n has_dirty_bits = FALSE;\n n = pr->dirty_bits_size / sizeof(uint32_t);\n for(i = 0; i < n; i++) {\n if (dirty_bits[i] != 0) {\n has_dirty_bits = TRUE;\n break;\n }\n }\n if (has_dirty_bits && pr->size != 0) {\n /* invalidate the corresponding CPU write TLBs */\n map->flush_tlb_write_range(map->opaque, pr->phys_mem, pr->org_size);\n }\n \n pr->dirty_bits_index ^= 1;\n pr->dirty_bits = pr->dirty_bits_tab[pr->dirty_bits_index];\n memset(pr->dirty_bits, 0, pr->dirty_bits_size);\n return dirty_bits;\n}\n\n/* reset the dirty bit of one page at 'offset' inside 'pr' */\nvoid phys_mem_reset_dirty_bit(PhysMemoryRange *pr, size_t offset)\n{\n size_t page_index;\n uint32_t mask, *dirty_bits_ptr;\n PhysMemoryMap *map;\n if (pr->dirty_bits) {\n page_index = offset >> DEVRAM_PAGE_SIZE_LOG2;\n mask = 1 << (page_index & 0x1f);\n dirty_bits_ptr = pr->dirty_bits + (page_index >> 5);\n if (*dirty_bits_ptr & mask) {\n *dirty_bits_ptr &= ~mask;\n /* invalidate the corresponding CPU write TLBs */\n map = pr->map;\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem + (offset & ~(DEVRAM_PAGE_SIZE - 1)),\n DEVRAM_PAGE_SIZE);\n }\n }\n}\n\nstatic void default_free_ram(PhysMemoryMap *s, PhysMemoryRange *pr)\n{\n free(pr->phys_mem);\n}\n\nPhysMemoryRange *cpu_register_device(PhysMemoryMap *s, uint64_t addr,\n uint64_t size, void *opaque,\n DeviceReadFunc *read_func, DeviceWriteFunc *write_func,\n int devio_flags)\n{\n PhysMemoryRange *pr;\n assert(s->n_phys_mem_range < PHYS_MEM_RANGE_MAX);\n assert(size <= 0xffffffff);\n pr = &s->phys_mem_range[s->n_phys_mem_range++];\n pr->map = s;\n pr->addr = addr;\n pr->org_size = size;\n if (devio_flags & DEVIO_DISABLED)\n pr->size = 0;\n else\n pr->size = pr->org_size;\n pr->is_ram = FALSE;\n pr->opaque = opaque;\n pr->read_func = read_func;\n pr->write_func = write_func;\n pr->devio_flags = devio_flags;\n return pr;\n}\n\nstatic void default_set_addr(PhysMemoryMap *map,\n PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n if (enabled) {\n if (pr->size == 0 || pr->addr != addr) {\n /* enable or move mapping */\n if (pr->is_ram) {\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem, pr->org_size);\n }\n pr->addr = addr;\n pr->size = pr->org_size;\n }\n } else {\n if (pr->size != 0) {\n /* disable mapping */\n if (pr->is_ram) {\n map->flush_tlb_write_range(map->opaque,\n pr->phys_mem, pr->org_size);\n }\n pr->addr = 0;\n pr->size = 0;\n }\n }\n}\n\nvoid phys_mem_set_addr(PhysMemoryRange *pr, uint64_t addr, BOOL enabled)\n{\n PhysMemoryMap *map = pr->map;\n if (!pr->is_ram) {\n default_set_addr(map, pr, addr, enabled);\n } else {\n return map->set_ram_addr(map, pr, addr, enabled);\n }\n}\n\n/* return NULL if no valid RAM page. The access can only be done in the page */\nuint8_t *phys_mem_get_ram_ptr(PhysMemoryMap *map, uint64_t paddr, BOOL is_rw)\n{\n PhysMemoryRange *pr = get_phys_mem_range(map, paddr);\n uintptr_t offset;\n if (!pr || !pr->is_ram)\n return NULL;\n offset = paddr - pr->addr;\n if (is_rw)\n phys_mem_set_dirty_bit(pr, offset);\n return pr->phys_mem + (uintptr_t)offset;\n}\n\n/* IRQ support */\n\nvoid irq_init(IRQSignal *irq, SetIRQFunc *set_irq, void *opaque, int irq_num)\n{\n irq->set_irq = set_irq;\n irq->opaque = opaque;\n irq->irq_num = irq_num;\n}\n"], ["/linuxpdf/tinyemu/slirp/udp.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)udp_usrreq.c\t8.4 (Berkeley) 1/21/94\n * udp_usrreq.c,v 1.4 1994/10/02 17:48:45 phk Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n#include \"ip_icmp.h\"\n\nstatic uint8_t udp_tos(struct socket *so);\n\nvoid\nudp_init(Slirp *slirp)\n{\n slirp->udb.so_next = slirp->udb.so_prev = &slirp->udb;\n slirp->udp_last_so = &slirp->udb;\n}\n/* m->m_data points at ip packet header\n * m->m_len length ip packet\n * ip->ip_len length data (IPDU)\n */\nvoid\nudp_input(register struct mbuf *m, int iphlen)\n{\n\tSlirp *slirp = m->slirp;\n\tregister struct ip *ip;\n\tregister struct udphdr *uh;\n\tint len;\n\tstruct ip save_ip;\n\tstruct socket *so;\n\n\tDEBUG_CALL(\"udp_input\");\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"iphlen = %d\", iphlen);\n\n\t/*\n\t * Strip IP options, if any; should skip this,\n\t * make available to user, and use on returned packets,\n\t * but we don't yet have a way to check the checksum\n\t * with options still present.\n\t */\n\tif(iphlen > sizeof(struct ip)) {\n\t\tip_stripoptions(m, (struct mbuf *)0);\n\t\tiphlen = sizeof(struct ip);\n\t}\n\n\t/*\n\t * Get IP and UDP header together in first mbuf.\n\t */\n\tip = mtod(m, struct ip *);\n\tuh = (struct udphdr *)((caddr_t)ip + iphlen);\n\n\t/*\n\t * Make mbuf data length reflect UDP length.\n\t * If not enough data to reflect UDP length, drop.\n\t */\n\tlen = ntohs((uint16_t)uh->uh_ulen);\n\n\tif (ip->ip_len != len) {\n\t\tif (len > ip->ip_len) {\n\t\t\tgoto bad;\n\t\t}\n\t\tm_adj(m, len - ip->ip_len);\n\t\tip->ip_len = len;\n\t}\n\n\t/*\n\t * Save a copy of the IP header in case we want restore it\n\t * for sending an ICMP error message in response.\n\t */\n\tsave_ip = *ip;\n\tsave_ip.ip_len+= iphlen; /* tcp_input subtracts this */\n\n\t/*\n\t * Checksum extended UDP header and data.\n\t */\n\tif (uh->uh_sum) {\n memset(&((struct ipovly *)ip)->ih_mbuf, 0, sizeof(struct mbuf_ptr));\n\t ((struct ipovly *)ip)->ih_x1 = 0;\n\t ((struct ipovly *)ip)->ih_len = uh->uh_ulen;\n\t if(cksum(m, len + sizeof(struct ip))) {\n\t goto bad;\n\t }\n\t}\n\n /*\n * handle DHCP/BOOTP\n */\n if (ntohs(uh->uh_dport) == BOOTP_SERVER) {\n bootp_input(m);\n goto bad;\n }\n\n if (slirp->restricted) {\n goto bad;\n }\n\n#if 0\n /*\n * handle TFTP\n */\n if (ntohs(uh->uh_dport) == TFTP_SERVER) {\n tftp_input(m);\n goto bad;\n }\n#endif\n \n\t/*\n\t * Locate pcb for datagram.\n\t */\n\tso = slirp->udp_last_so;\n\tif (so->so_lport != uh->uh_sport ||\n\t so->so_laddr.s_addr != ip->ip_src.s_addr) {\n\t\tstruct socket *tmp;\n\n\t\tfor (tmp = slirp->udb.so_next; tmp != &slirp->udb;\n\t\t tmp = tmp->so_next) {\n\t\t\tif (tmp->so_lport == uh->uh_sport &&\n\t\t\t tmp->so_laddr.s_addr == ip->ip_src.s_addr) {\n\t\t\t\tso = tmp;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (tmp == &slirp->udb) {\n\t\t so = NULL;\n\t\t} else {\n\t\t slirp->udp_last_so = so;\n\t\t}\n\t}\n\n\tif (so == NULL) {\n\t /*\n\t * If there's no socket for this packet,\n\t * create one\n\t */\n\t so = socreate(slirp);\n\t if (!so) {\n\t goto bad;\n\t }\n\t if(udp_attach(so) == -1) {\n\t DEBUG_MISC((dfd,\" udp_attach errno = %d-%s\\n\",\n\t\t\terrno,strerror(errno)));\n\t sofree(so);\n\t goto bad;\n\t }\n\n\t /*\n\t * Setup fields\n\t */\n\t so->so_laddr = ip->ip_src;\n\t so->so_lport = uh->uh_sport;\n\n\t if ((so->so_iptos = udp_tos(so)) == 0)\n\t so->so_iptos = ip->ip_tos;\n\n\t /*\n\t * XXXXX Here, check if it's in udpexec_list,\n\t * and if it is, do the fork_exec() etc.\n\t */\n\t}\n\n so->so_faddr = ip->ip_dst; /* XXX */\n so->so_fport = uh->uh_dport; /* XXX */\n\n\tiphlen += sizeof(struct udphdr);\n\tm->m_len -= iphlen;\n\tm->m_data += iphlen;\n\n\t/*\n\t * Now we sendto() the packet.\n\t */\n\tif(sosendto(so,m) == -1) {\n\t m->m_len += iphlen;\n\t m->m_data -= iphlen;\n\t *ip=save_ip;\n\t DEBUG_MISC((dfd,\"udp tx errno = %d-%s\\n\",errno,strerror(errno)));\n\t icmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));\n\t}\n\n\tm_free(so->so_m); /* used for ICMP if error on sorecvfrom */\n\n\t/* restore the orig mbuf packet */\n\tm->m_len += iphlen;\n\tm->m_data -= iphlen;\n\t*ip=save_ip;\n\tso->so_m=m; /* ICMP backup */\n\n\treturn;\nbad:\n\tm_freem(m);\n\treturn;\n}\n\nint udp_output2(struct socket *so, struct mbuf *m,\n struct sockaddr_in *saddr, struct sockaddr_in *daddr,\n int iptos)\n{\n\tregister struct udpiphdr *ui;\n\tint error = 0;\n\n\tDEBUG_CALL(\"udp_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"saddr = %lx\", (long)saddr->sin_addr.s_addr);\n\tDEBUG_ARG(\"daddr = %lx\", (long)daddr->sin_addr.s_addr);\n\n\t/*\n\t * Adjust for header\n\t */\n\tm->m_data -= sizeof(struct udpiphdr);\n\tm->m_len += sizeof(struct udpiphdr);\n\n\t/*\n\t * Fill in mbuf with extended UDP header\n\t * and addresses and length put into network format.\n\t */\n\tui = mtod(m, struct udpiphdr *);\n memset(&ui->ui_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));\n\tui->ui_x1 = 0;\n\tui->ui_pr = IPPROTO_UDP;\n\tui->ui_len = htons(m->m_len - sizeof(struct ip));\n\t/* XXXXX Check for from-one-location sockets, or from-any-location sockets */\n ui->ui_src = saddr->sin_addr;\n\tui->ui_dst = daddr->sin_addr;\n\tui->ui_sport = saddr->sin_port;\n\tui->ui_dport = daddr->sin_port;\n\tui->ui_ulen = ui->ui_len;\n\n\t/*\n\t * Stuff checksum and output datagram.\n\t */\n\tui->ui_sum = 0;\n\tif ((ui->ui_sum = cksum(m, m->m_len)) == 0)\n\t\tui->ui_sum = 0xffff;\n\t((struct ip *)ui)->ip_len = m->m_len;\n\n\t((struct ip *)ui)->ip_ttl = IPDEFTTL;\n\t((struct ip *)ui)->ip_tos = iptos;\n\n\terror = ip_output(so, m);\n\n\treturn (error);\n}\n\nint udp_output(struct socket *so, struct mbuf *m,\n struct sockaddr_in *addr)\n\n{\n Slirp *slirp = so->slirp;\n struct sockaddr_in saddr, daddr;\n\n saddr = *addr;\n if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==\n slirp->vnetwork_addr.s_addr) {\n uint32_t inv_mask = ~slirp->vnetwork_mask.s_addr;\n\n if ((so->so_faddr.s_addr & inv_mask) == inv_mask) {\n saddr.sin_addr = slirp->vhost_addr;\n } else if (addr->sin_addr.s_addr == loopback_addr.s_addr ||\n so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {\n saddr.sin_addr = so->so_faddr;\n }\n }\n daddr.sin_addr = so->so_laddr;\n daddr.sin_port = so->so_lport;\n\n return udp_output2(so, m, &saddr, &daddr, so->so_iptos);\n}\n\nint\nudp_attach(struct socket *so)\n{\n if((so->s = os_socket(AF_INET,SOCK_DGRAM,0)) != -1) {\n so->so_expire = curtime + SO_EXPIRE;\n insque(so, &so->slirp->udb);\n }\n return(so->s);\n}\n\nvoid\nudp_detach(struct socket *so)\n{\n\tclosesocket(so->s);\n\tsofree(so);\n}\n\nstatic const struct tos_t udptos[] = {\n\t{0, 53, IPTOS_LOWDELAY, 0},\t\t\t/* DNS */\n\t{0, 0, 0, 0}\n};\n\nstatic uint8_t\nudp_tos(struct socket *so)\n{\n\tint i = 0;\n\n\twhile(udptos[i].tos) {\n\t\tif ((udptos[i].fport && ntohs(so->so_fport) == udptos[i].fport) ||\n\t\t (udptos[i].lport && ntohs(so->so_lport) == udptos[i].lport)) {\n\t\t \tso->so_emu = udptos[i].emu;\n\t\t\treturn udptos[i].tos;\n\t\t}\n\t\ti++;\n\t}\n\n\treturn 0;\n}\n\nstruct socket *\nudp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,\n u_int lport, int flags)\n{\n\tstruct sockaddr_in addr;\n\tstruct socket *so;\n\tsocklen_t addrlen = sizeof(struct sockaddr_in), opt = 1;\n\n\tso = socreate(slirp);\n\tif (!so) {\n\t return NULL;\n\t}\n\tso->s = os_socket(AF_INET,SOCK_DGRAM,0);\n\tso->so_expire = curtime + SO_EXPIRE;\n\tinsque(so, &slirp->udb);\n\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = haddr;\n\taddr.sin_port = hport;\n\n\tif (bind(so->s,(struct sockaddr *)&addr, addrlen) < 0) {\n\t\tudp_detach(so);\n\t\treturn NULL;\n\t}\n\tsetsockopt(so->s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));\n\n\tgetsockname(so->s,(struct sockaddr *)&addr,&addrlen);\n\tso->so_fport = addr.sin_port;\n\tif (addr.sin_addr.s_addr == 0 ||\n\t addr.sin_addr.s_addr == loopback_addr.s_addr) {\n\t so->so_faddr = slirp->vhost_addr;\n\t} else {\n\t so->so_faddr = addr.sin_addr;\n\t}\n\tso->so_lport = lport;\n\tso->so_laddr.s_addr = laddr;\n\tif (flags != SS_FACCEPTONCE)\n\t so->so_expire = 0;\n\n\tso->so_state &= SS_PERSISTENT_MASK;\n\tso->so_state |= SS_ISFCONNECTED | flags;\n\n\treturn so;\n}\n"], ["/linuxpdf/tinyemu/slirp/mbuf.c", "/*\n * Copyright (c) 1995 Danny Gasparovski\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n/*\n * mbuf's in SLiRP are much simpler than the real mbufs in\n * FreeBSD. They are fixed size, determined by the MTU,\n * so that one whole packet can fit. Mbuf's cannot be\n * chained together. If there's more data than the mbuf\n * could hold, an external malloced buffer is pointed to\n * by m_ext (and the data pointers) and M_EXT is set in\n * the flags\n */\n\n#include \"slirp.h\"\n\n#define MBUF_THRESH 30\n\n/*\n * Find a nice value for msize\n * XXX if_maxlinkhdr already in mtu\n */\n#define SLIRP_MSIZE (IF_MTU + IF_MAXLINKHDR + offsetof(struct mbuf, m_dat) + 6)\n\nvoid\nm_init(Slirp *slirp)\n{\n slirp->m_freelist.m_next = slirp->m_freelist.m_prev = &slirp->m_freelist;\n slirp->m_usedlist.m_next = slirp->m_usedlist.m_prev = &slirp->m_usedlist;\n}\n\n/*\n * Get an mbuf from the free list, if there are none\n * malloc one\n *\n * Because fragmentation can occur if we alloc new mbufs and\n * free old mbufs, we mark all mbufs above mbuf_thresh as M_DOFREE,\n * which tells m_free to actually free() it\n */\nstruct mbuf *\nm_get(Slirp *slirp)\n{\n\tregister struct mbuf *m;\n\tint flags = 0;\n\n\tDEBUG_CALL(\"m_get\");\n\n\tif (slirp->m_freelist.m_next == &slirp->m_freelist) {\n\t\tm = (struct mbuf *)malloc(SLIRP_MSIZE);\n\t\tif (m == NULL) goto end_error;\n\t\tslirp->mbuf_alloced++;\n\t\tif (slirp->mbuf_alloced > MBUF_THRESH)\n\t\t\tflags = M_DOFREE;\n\t\tm->slirp = slirp;\n\t} else {\n\t\tm = slirp->m_freelist.m_next;\n\t\tremque(m);\n\t}\n\n\t/* Insert it in the used list */\n\tinsque(m,&slirp->m_usedlist);\n\tm->m_flags = (flags | M_USEDLIST);\n\n\t/* Initialise it */\n\tm->m_size = SLIRP_MSIZE - offsetof(struct mbuf, m_dat);\n\tm->m_data = m->m_dat;\n\tm->m_len = 0;\n m->m_nextpkt = NULL;\n m->m_prevpkt = NULL;\nend_error:\n\tDEBUG_ARG(\"m = %lx\", (long )m);\n\treturn m;\n}\n\nvoid\nm_free(struct mbuf *m)\n{\n\n DEBUG_CALL(\"m_free\");\n DEBUG_ARG(\"m = %lx\", (long )m);\n\n if(m) {\n\t/* Remove from m_usedlist */\n\tif (m->m_flags & M_USEDLIST)\n\t remque(m);\n\n\t/* If it's M_EXT, free() it */\n\tif (m->m_flags & M_EXT)\n\t free(m->m_ext);\n\n\t/*\n\t * Either free() it or put it on the free list\n\t */\n\tif (m->m_flags & M_DOFREE) {\n\t\tm->slirp->mbuf_alloced--;\n\t\tfree(m);\n\t} else if ((m->m_flags & M_FREELIST) == 0) {\n\t\tinsque(m,&m->slirp->m_freelist);\n\t\tm->m_flags = M_FREELIST; /* Clobber other flags */\n\t}\n } /* if(m) */\n}\n\n/*\n * Copy data from one mbuf to the end of\n * the other.. if result is too big for one mbuf, malloc()\n * an M_EXT data segment\n */\nvoid\nm_cat(struct mbuf *m, struct mbuf *n)\n{\n\t/*\n\t * If there's no room, realloc\n\t */\n\tif (M_FREEROOM(m) < n->m_len)\n\t\tm_inc(m,m->m_size+MINCSIZE);\n\n\tmemcpy(m->m_data+m->m_len, n->m_data, n->m_len);\n\tm->m_len += n->m_len;\n\n\tm_free(n);\n}\n\n\n/* make m size bytes large */\nvoid\nm_inc(struct mbuf *m, int size)\n{\n\tint datasize;\n\n\t/* some compiles throw up on gotos. This one we can fake. */\n if(m->m_size>size) return;\n\n if (m->m_flags & M_EXT) {\n\t datasize = m->m_data - m->m_ext;\n\t m->m_ext = (char *)realloc(m->m_ext,size);\n\t m->m_data = m->m_ext + datasize;\n } else {\n\t char *dat;\n\t datasize = m->m_data - m->m_dat;\n\t dat = (char *)malloc(size);\n\t memcpy(dat, m->m_dat, m->m_size);\n\n\t m->m_ext = dat;\n\t m->m_data = m->m_ext + datasize;\n\t m->m_flags |= M_EXT;\n }\n\n m->m_size = size;\n\n}\n\n\n\nvoid\nm_adj(struct mbuf *m, int len)\n{\n\tif (m == NULL)\n\t\treturn;\n\tif (len >= 0) {\n\t\t/* Trim from head */\n\t\tm->m_data += len;\n\t\tm->m_len -= len;\n\t} else {\n\t\t/* Trim from tail */\n\t\tlen = -len;\n\t\tm->m_len -= len;\n\t}\n}\n\n\n/*\n * Copy len bytes from m, starting off bytes into n\n */\nint\nm_copy(struct mbuf *n, struct mbuf *m, int off, int len)\n{\n\tif (len > M_FREEROOM(n))\n\t\treturn -1;\n\n\tmemcpy((n->m_data + n->m_len), (m->m_data + off), len);\n\tn->m_len += len;\n\treturn 0;\n}\n\n\n/*\n * Given a pointer into an mbuf, return the mbuf\n * XXX This is a kludge, I should eliminate the need for it\n * Fortunately, it's not used often\n */\nstruct mbuf *\ndtom(Slirp *slirp, void *dat)\n{\n\tstruct mbuf *m;\n\n\tDEBUG_CALL(\"dtom\");\n\tDEBUG_ARG(\"dat = %lx\", (long )dat);\n\n\t/* bug corrected for M_EXT buffers */\n\tfor (m = slirp->m_usedlist.m_next; m != &slirp->m_usedlist;\n\t m = m->m_next) {\n\t if (m->m_flags & M_EXT) {\n\t if( (char *)dat>=m->m_ext && (char *)dat<(m->m_ext + m->m_size) )\n\t return m;\n\t } else {\n\t if( (char *)dat >= m->m_dat && (char *)dat<(m->m_dat + m->m_size) )\n\t return m;\n\t }\n\t}\n\n\tDEBUG_ERROR((dfd, \"dtom failed\"));\n\n\treturn (struct mbuf *)0;\n}\n"], ["/linuxpdf/tinyemu/ps2.c", "/*\n * QEMU PS/2 keyboard/mouse emulation\n *\n * Copyright (c) 2003 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n\n/* debug PC keyboard */\n//#define DEBUG_KBD\n\n/* debug PC keyboard : only mouse */\n//#define DEBUG_MOUSE\n\n/* Keyboard Commands */\n#define KBD_CMD_SET_LEDS\t0xED\t/* Set keyboard leds */\n#define KBD_CMD_ECHO \t0xEE\n#define KBD_CMD_GET_ID \t 0xF2\t/* get keyboard ID */\n#define KBD_CMD_SET_RATE\t0xF3\t/* Set typematic rate */\n#define KBD_CMD_ENABLE\t\t0xF4\t/* Enable scanning */\n#define KBD_CMD_RESET_DISABLE\t0xF5\t/* reset and disable scanning */\n#define KBD_CMD_RESET_ENABLE \t0xF6 /* reset and enable scanning */\n#define KBD_CMD_RESET\t\t0xFF\t/* Reset */\n\n/* Keyboard Replies */\n#define KBD_REPLY_POR\t\t0xAA\t/* Power on reset */\n#define KBD_REPLY_ACK\t\t0xFA\t/* Command ACK */\n#define KBD_REPLY_RESEND\t0xFE\t/* Command NACK, send the cmd again */\n\n/* Mouse Commands */\n#define AUX_SET_SCALE11\t\t0xE6\t/* Set 1:1 scaling */\n#define AUX_SET_SCALE21\t\t0xE7\t/* Set 2:1 scaling */\n#define AUX_SET_RES\t\t0xE8\t/* Set resolution */\n#define AUX_GET_SCALE\t\t0xE9\t/* Get scaling factor */\n#define AUX_SET_STREAM\t\t0xEA\t/* Set stream mode */\n#define AUX_POLL\t\t0xEB\t/* Poll */\n#define AUX_RESET_WRAP\t\t0xEC\t/* Reset wrap mode */\n#define AUX_SET_WRAP\t\t0xEE\t/* Set wrap mode */\n#define AUX_SET_REMOTE\t\t0xF0\t/* Set remote mode */\n#define AUX_GET_TYPE\t\t0xF2\t/* Get type */\n#define AUX_SET_SAMPLE\t\t0xF3\t/* Set sample rate */\n#define AUX_ENABLE_DEV\t\t0xF4\t/* Enable aux device */\n#define AUX_DISABLE_DEV\t\t0xF5\t/* Disable aux device */\n#define AUX_SET_DEFAULT\t\t0xF6\n#define AUX_RESET\t\t0xFF\t/* Reset aux device */\n#define AUX_ACK\t\t\t0xFA\t/* Command byte ACK. */\n\n#define MOUSE_STATUS_REMOTE 0x40\n#define MOUSE_STATUS_ENABLED 0x20\n#define MOUSE_STATUS_SCALE21 0x10\n\n#define PS2_QUEUE_SIZE 256\n\ntypedef struct {\n uint8_t data[PS2_QUEUE_SIZE];\n int rptr, wptr, count;\n} PS2Queue;\n\ntypedef struct {\n PS2Queue queue;\n int32_t write_cmd;\n void (*update_irq)(void *, int);\n void *update_arg;\n} PS2State;\n\nstruct PS2KbdState {\n PS2State common;\n int scan_enabled;\n /* Qemu uses translated PC scancodes internally. To avoid multiple\n conversions we do the translation (if any) in the PS/2 emulation\n not the keyboard controller. */\n int translate;\n};\n\nstruct PS2MouseState {\n PS2State common;\n uint8_t mouse_status;\n uint8_t mouse_resolution;\n uint8_t mouse_sample_rate;\n uint8_t mouse_wrap;\n uint8_t mouse_type; /* 0 = PS2, 3 = IMPS/2, 4 = IMEX */\n uint8_t mouse_detect_state;\n int mouse_dx; /* current values, needed for 'poll' mode */\n int mouse_dy;\n int mouse_dz;\n uint8_t mouse_buttons;\n};\n\nvoid ps2_queue(void *opaque, int b)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q = &s->queue;\n\n if (q->count >= PS2_QUEUE_SIZE)\n return;\n q->data[q->wptr] = b;\n if (++q->wptr == PS2_QUEUE_SIZE)\n q->wptr = 0;\n q->count++;\n s->update_irq(s->update_arg, 1);\n}\n\n#define INPUT_MAKE_KEY_MIN 96\n#define INPUT_MAKE_KEY_MAX 127\n\nstatic const uint8_t linux_input_to_keycode_set1[INPUT_MAKE_KEY_MAX - INPUT_MAKE_KEY_MIN + 1] = {\n 0x1c, 0x1d, 0x35, 0x00, 0x38, 0x00, 0x47, 0x48, \n 0x49, 0x4b, 0x4d, 0x4f, 0x50, 0x51, 0x52, 0x53, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x5b, 0x5c, 0x5d, \n};\n\n/* keycode is a Linux input layer keycode. We only support the PS/2\n keycode set 1 */\nvoid ps2_put_keycode(PS2KbdState *s, BOOL is_down, int keycode)\n{\n if (keycode >= INPUT_MAKE_KEY_MIN) {\n if (keycode > INPUT_MAKE_KEY_MAX)\n return;\n keycode = linux_input_to_keycode_set1[keycode - INPUT_MAKE_KEY_MIN];\n if (keycode == 0)\n return;\n ps2_queue(&s->common, 0xe0);\n }\n ps2_queue(&s->common, keycode | ((!is_down) << 7));\n}\n\nuint32_t ps2_read_data(void *opaque)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q;\n int val, index;\n\n q = &s->queue;\n if (q->count == 0) {\n /* NOTE: if no data left, we return the last keyboard one\n (needed for EMM386) */\n /* XXX: need a timer to do things correctly */\n index = q->rptr - 1;\n if (index < 0)\n index = PS2_QUEUE_SIZE - 1;\n val = q->data[index];\n } else {\n val = q->data[q->rptr];\n if (++q->rptr == PS2_QUEUE_SIZE)\n q->rptr = 0;\n q->count--;\n /* reading deasserts IRQ */\n s->update_irq(s->update_arg, 0);\n /* reassert IRQs if data left */\n s->update_irq(s->update_arg, q->count != 0);\n }\n return val;\n}\n\nstatic void ps2_reset_keyboard(PS2KbdState *s)\n{\n s->scan_enabled = 1;\n}\n\nvoid ps2_write_keyboard(void *opaque, int val)\n{\n PS2KbdState *s = (PS2KbdState *)opaque;\n\n switch(s->common.write_cmd) {\n default:\n case -1:\n switch(val) {\n case 0x00:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case 0x05:\n ps2_queue(&s->common, KBD_REPLY_RESEND);\n break;\n case KBD_CMD_GET_ID:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n ps2_queue(&s->common, 0xab);\n ps2_queue(&s->common, 0x83);\n break;\n case KBD_CMD_ECHO:\n ps2_queue(&s->common, KBD_CMD_ECHO);\n break;\n case KBD_CMD_ENABLE:\n s->scan_enabled = 1;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_SET_LEDS:\n case KBD_CMD_SET_RATE:\n s->common.write_cmd = val;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET_DISABLE:\n ps2_reset_keyboard(s);\n s->scan_enabled = 0;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET_ENABLE:\n ps2_reset_keyboard(s);\n s->scan_enabled = 1;\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n case KBD_CMD_RESET:\n ps2_reset_keyboard(s);\n ps2_queue(&s->common, KBD_REPLY_ACK);\n ps2_queue(&s->common, KBD_REPLY_POR);\n break;\n default:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n break;\n }\n break;\n case KBD_CMD_SET_LEDS:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n s->common.write_cmd = -1;\n break;\n case KBD_CMD_SET_RATE:\n ps2_queue(&s->common, KBD_REPLY_ACK);\n s->common.write_cmd = -1;\n break;\n }\n}\n\n/* Set the scancode translation mode.\n 0 = raw scancodes.\n 1 = translated scancodes (used by qemu internally). */\n\nvoid ps2_keyboard_set_translation(void *opaque, int mode)\n{\n PS2KbdState *s = (PS2KbdState *)opaque;\n s->translate = mode;\n}\n\nstatic void ps2_mouse_send_packet(PS2MouseState *s)\n{\n unsigned int b;\n int dx1, dy1, dz1;\n\n dx1 = s->mouse_dx;\n dy1 = s->mouse_dy;\n dz1 = s->mouse_dz;\n /* XXX: increase range to 8 bits ? */\n if (dx1 > 127)\n dx1 = 127;\n else if (dx1 < -127)\n dx1 = -127;\n if (dy1 > 127)\n dy1 = 127;\n else if (dy1 < -127)\n dy1 = -127;\n b = 0x08 | ((dx1 < 0) << 4) | ((dy1 < 0) << 5) | (s->mouse_buttons & 0x07);\n ps2_queue(&s->common, b);\n ps2_queue(&s->common, dx1 & 0xff);\n ps2_queue(&s->common, dy1 & 0xff);\n /* extra byte for IMPS/2 or IMEX */\n switch(s->mouse_type) {\n default:\n break;\n case 3:\n if (dz1 > 127)\n dz1 = 127;\n else if (dz1 < -127)\n dz1 = -127;\n ps2_queue(&s->common, dz1 & 0xff);\n break;\n case 4:\n if (dz1 > 7)\n dz1 = 7;\n else if (dz1 < -7)\n dz1 = -7;\n b = (dz1 & 0x0f) | ((s->mouse_buttons & 0x18) << 1);\n ps2_queue(&s->common, b);\n break;\n }\n\n /* update deltas */\n s->mouse_dx -= dx1;\n s->mouse_dy -= dy1;\n s->mouse_dz -= dz1;\n}\n\nvoid ps2_mouse_event(PS2MouseState *s,\n int dx, int dy, int dz, int buttons_state)\n{\n /* check if deltas are recorded when disabled */\n if (!(s->mouse_status & MOUSE_STATUS_ENABLED))\n return;\n\n s->mouse_dx += dx;\n s->mouse_dy -= dy;\n s->mouse_dz += dz;\n /* XXX: SDL sometimes generates nul events: we delete them */\n if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0 &&\n s->mouse_buttons == buttons_state)\n\treturn;\n s->mouse_buttons = buttons_state;\n\n if (!(s->mouse_status & MOUSE_STATUS_REMOTE) &&\n (s->common.queue.count < (PS2_QUEUE_SIZE - 16))) {\n for(;;) {\n /* if not remote, send event. Multiple events are sent if\n too big deltas */\n ps2_mouse_send_packet(s);\n if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0)\n break;\n }\n }\n}\n\nvoid ps2_write_mouse(void *opaque, int val)\n{\n PS2MouseState *s = (PS2MouseState *)opaque;\n#ifdef DEBUG_MOUSE\n printf(\"kbd: write mouse 0x%02x\\n\", val);\n#endif\n switch(s->common.write_cmd) {\n default:\n case -1:\n /* mouse command */\n if (s->mouse_wrap) {\n if (val == AUX_RESET_WRAP) {\n s->mouse_wrap = 0;\n ps2_queue(&s->common, AUX_ACK);\n return;\n } else if (val != AUX_RESET) {\n ps2_queue(&s->common, val);\n return;\n }\n }\n switch(val) {\n case AUX_SET_SCALE11:\n s->mouse_status &= ~MOUSE_STATUS_SCALE21;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_SCALE21:\n s->mouse_status |= MOUSE_STATUS_SCALE21;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_STREAM:\n s->mouse_status &= ~MOUSE_STATUS_REMOTE;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_WRAP:\n s->mouse_wrap = 1;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_REMOTE:\n s->mouse_status |= MOUSE_STATUS_REMOTE;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_GET_TYPE:\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, s->mouse_type);\n break;\n case AUX_SET_RES:\n case AUX_SET_SAMPLE:\n s->common.write_cmd = val;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_GET_SCALE:\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, s->mouse_status);\n ps2_queue(&s->common, s->mouse_resolution);\n ps2_queue(&s->common, s->mouse_sample_rate);\n break;\n case AUX_POLL:\n ps2_queue(&s->common, AUX_ACK);\n ps2_mouse_send_packet(s);\n break;\n case AUX_ENABLE_DEV:\n s->mouse_status |= MOUSE_STATUS_ENABLED;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_DISABLE_DEV:\n s->mouse_status &= ~MOUSE_STATUS_ENABLED;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_SET_DEFAULT:\n s->mouse_sample_rate = 100;\n s->mouse_resolution = 2;\n s->mouse_status = 0;\n ps2_queue(&s->common, AUX_ACK);\n break;\n case AUX_RESET:\n s->mouse_sample_rate = 100;\n s->mouse_resolution = 2;\n s->mouse_status = 0;\n s->mouse_type = 0;\n ps2_queue(&s->common, AUX_ACK);\n ps2_queue(&s->common, 0xaa);\n ps2_queue(&s->common, s->mouse_type);\n break;\n default:\n break;\n }\n break;\n case AUX_SET_SAMPLE:\n s->mouse_sample_rate = val;\n /* detect IMPS/2 or IMEX */\n switch(s->mouse_detect_state) {\n default:\n case 0:\n if (val == 200)\n s->mouse_detect_state = 1;\n break;\n case 1:\n if (val == 100)\n s->mouse_detect_state = 2;\n else if (val == 200)\n s->mouse_detect_state = 3;\n else\n s->mouse_detect_state = 0;\n break;\n case 2:\n if (val == 80)\n s->mouse_type = 3; /* IMPS/2 */\n s->mouse_detect_state = 0;\n break;\n case 3:\n if (val == 80)\n s->mouse_type = 4; /* IMEX */\n s->mouse_detect_state = 0;\n break;\n }\n ps2_queue(&s->common, AUX_ACK);\n s->common.write_cmd = -1;\n break;\n case AUX_SET_RES:\n s->mouse_resolution = val;\n ps2_queue(&s->common, AUX_ACK);\n s->common.write_cmd = -1;\n break;\n }\n}\n\nstatic void ps2_reset(void *opaque)\n{\n PS2State *s = (PS2State *)opaque;\n PS2Queue *q;\n s->write_cmd = -1;\n q = &s->queue;\n q->rptr = 0;\n q->wptr = 0;\n q->count = 0;\n}\n\nPS2KbdState *ps2_kbd_init(void (*update_irq)(void *, int), void *update_arg)\n{\n PS2KbdState *s = (PS2KbdState *)mallocz(sizeof(PS2KbdState));\n\n s->common.update_irq = update_irq;\n s->common.update_arg = update_arg;\n ps2_reset(&s->common);\n return s;\n}\n\nPS2MouseState *ps2_mouse_init(void (*update_irq)(void *, int), void *update_arg)\n{\n PS2MouseState *s = (PS2MouseState *)mallocz(sizeof(PS2MouseState));\n\n s->common.update_irq = update_irq;\n s->common.update_arg = update_arg;\n ps2_reset(&s->common);\n return s;\n}\n"], ["/linuxpdf/tinyemu/sdl.c", "/*\n * SDL display driver\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"cutils.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n#define KEYCODE_MAX 127\n\nstatic SDL_Surface *screen;\nstatic SDL_Surface *fb_surface;\nstatic int screen_width, screen_height, fb_width, fb_height, fb_stride;\nstatic SDL_Cursor *sdl_cursor_hidden;\nstatic uint8_t key_pressed[KEYCODE_MAX + 1];\n\nstatic void sdl_update_fb_surface(FBDevice *fb_dev)\n{\n if (!fb_surface)\n goto force_alloc;\n if (fb_width != fb_dev->width ||\n fb_height != fb_dev->height ||\n fb_stride != fb_dev->stride) {\n force_alloc:\n if (fb_surface != NULL)\n SDL_FreeSurface(fb_surface);\n fb_width = fb_dev->width;\n fb_height = fb_dev->height;\n fb_stride = fb_dev->stride;\n fb_surface = SDL_CreateRGBSurfaceFrom(fb_dev->fb_data,\n fb_dev->width, fb_dev->height,\n 32, fb_dev->stride,\n 0x00ff0000,\n 0x0000ff00,\n 0x000000ff,\n 0x00000000);\n if (!fb_surface) {\n fprintf(stderr, \"Could not create SDL framebuffer surface\\n\");\n exit(1);\n }\n }\n}\n\nstatic void sdl_update(FBDevice *fb_dev, void *opaque,\n int x, int y, int w, int h)\n{\n SDL_Rect r;\n // printf(\"sdl_update: %d %d %d %d\\n\", x, y, w, h);\n r.x = x;\n r.y = y;\n r.w = w;\n r.h = h;\n SDL_BlitSurface(fb_surface, &r, screen, &r);\n SDL_UpdateRect(screen, r.x, r.y, r.w, r.h);\n}\n\n#if defined(_WIN32)\n\nstatic int sdl_get_keycode(const SDL_KeyboardEvent *ev)\n{\n return ev->keysym.scancode;\n}\n\n#else\n\n/* we assume Xorg is used with a PC keyboard. Return 0 if no keycode found. */\nstatic int sdl_get_keycode(const SDL_KeyboardEvent *ev)\n{\n int keycode;\n keycode = ev->keysym.scancode;\n if (keycode < 9) {\n keycode = 0;\n } else if (keycode < 127 + 8) {\n keycode -= 8;\n } else {\n keycode = 0;\n }\n return keycode;\n}\n\n#endif\n\n/* release all pressed keys */\nstatic void sdl_reset_keys(VirtMachine *m)\n{\n int i;\n \n for(i = 1; i <= KEYCODE_MAX; i++) {\n if (key_pressed[i]) {\n vm_send_key_event(m, FALSE, i);\n key_pressed[i] = FALSE;\n }\n }\n}\n\nstatic void sdl_handle_key_event(const SDL_KeyboardEvent *ev, VirtMachine *m)\n{\n int keycode, keypress;\n\n keycode = sdl_get_keycode(ev);\n if (keycode) {\n if (keycode == 0x3a || keycode ==0x45) {\n /* SDL does not generate key up for numlock & caps lock */\n vm_send_key_event(m, TRUE, keycode);\n vm_send_key_event(m, FALSE, keycode);\n } else {\n keypress = (ev->type == SDL_KEYDOWN);\n if (keycode <= KEYCODE_MAX)\n key_pressed[keycode] = keypress;\n vm_send_key_event(m, keypress, keycode);\n }\n } else if (ev->type == SDL_KEYUP) {\n /* workaround to reset the keyboard state (used when changing\n desktop with ctrl-alt-x on Linux) */\n sdl_reset_keys(m);\n }\n}\n\nstatic void sdl_send_mouse_event(VirtMachine *m, int x1, int y1,\n int dz, int state, BOOL is_absolute)\n{\n int buttons, x, y;\n\n buttons = 0;\n if (state & SDL_BUTTON(SDL_BUTTON_LEFT))\n buttons |= (1 << 0);\n if (state & SDL_BUTTON(SDL_BUTTON_RIGHT))\n buttons |= (1 << 1);\n if (state & SDL_BUTTON(SDL_BUTTON_MIDDLE))\n buttons |= (1 << 2);\n if (is_absolute) {\n x = (x1 * 32768) / screen_width;\n y = (y1 * 32768) / screen_height;\n } else {\n x = x1;\n y = y1;\n }\n vm_send_mouse_event(m, x, y, dz, buttons);\n}\n\nstatic void sdl_handle_mouse_motion_event(const SDL_Event *ev, VirtMachine *m)\n{\n BOOL is_absolute = vm_mouse_is_absolute(m);\n int x, y;\n if (is_absolute) {\n x = ev->motion.x;\n y = ev->motion.y;\n } else {\n x = ev->motion.xrel;\n y = ev->motion.yrel;\n }\n sdl_send_mouse_event(m, x, y, 0, ev->motion.state, is_absolute);\n}\n\nstatic void sdl_handle_mouse_button_event(const SDL_Event *ev, VirtMachine *m)\n{\n BOOL is_absolute = vm_mouse_is_absolute(m);\n int state, dz;\n\n dz = 0;\n if (ev->type == SDL_MOUSEBUTTONDOWN) {\n if (ev->button.button == SDL_BUTTON_WHEELUP) {\n dz = 1;\n } else if (ev->button.button == SDL_BUTTON_WHEELDOWN) {\n dz = -1;\n }\n }\n \n state = SDL_GetMouseState(NULL, NULL);\n /* just in case */\n if (ev->type == SDL_MOUSEBUTTONDOWN)\n state |= SDL_BUTTON(ev->button.button);\n else\n state &= ~SDL_BUTTON(ev->button.button);\n\n if (is_absolute) {\n sdl_send_mouse_event(m, ev->button.x, ev->button.y,\n dz, state, is_absolute);\n } else {\n sdl_send_mouse_event(m, 0, 0, dz, state, is_absolute);\n }\n}\n\nvoid sdl_refresh(VirtMachine *m)\n{\n SDL_Event ev_s, *ev = &ev_s;\n\n if (!m->fb_dev)\n return;\n \n sdl_update_fb_surface(m->fb_dev);\n\n m->fb_dev->refresh(m->fb_dev, sdl_update, NULL);\n \n while (SDL_PollEvent(ev)) {\n switch (ev->type) {\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n sdl_handle_key_event(&ev->key, m);\n break;\n case SDL_MOUSEMOTION:\n sdl_handle_mouse_motion_event(ev, m);\n break;\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n sdl_handle_mouse_button_event(ev, m);\n break;\n case SDL_QUIT:\n exit(0);\n }\n }\n}\n\nstatic void sdl_hide_cursor(void)\n{\n uint8_t data = 0;\n sdl_cursor_hidden = SDL_CreateCursor(&data, &data, 8, 1, 0, 0);\n SDL_ShowCursor(1);\n SDL_SetCursor(sdl_cursor_hidden);\n}\n\nvoid sdl_init(int width, int height)\n{\n int flags;\n \n screen_width = width;\n screen_height = height;\n\n if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE)) {\n fprintf(stderr, \"Could not initialize SDL - exiting\\n\");\n exit(1);\n }\n\n flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;\n screen = SDL_SetVideoMode(width, height, 0, flags);\n if (!screen || !screen->pixels) {\n fprintf(stderr, \"Could not open SDL display\\n\");\n exit(1);\n }\n\n SDL_WM_SetCaption(\"TinyEMU\", \"TinyEMU\");\n\n sdl_hide_cursor();\n}\n\n"], ["/linuxpdf/tinyemu/sha256.c", "/* LibTomCrypt, modular cryptographic library -- Tom St Denis\n *\n * LibTomCrypt is a library that provides various cryptographic\n * algorithms in a highly modular and flexible manner.\n *\n * The library is free for all purposes without any express\n * guarantee it works.\n *\n * Tom St Denis, tomstdenis@gmail.com, http://libtom.org\n */\n#include \n#include \n#include \"cutils.h\"\n#include \"sha256.h\"\n\n#define LOAD32H(a, b) a = get_be32(b)\n#define STORE32H(a, b) put_be32(b, a)\n#define STORE64H(a, b) put_be64(b, a)\n#define RORc(x, y) ( ((((uint32_t)(x)&0xFFFFFFFFUL)>>(uint32_t)((y)&31)) | ((uint32_t)(x)<<(uint32_t)(32-((y)&31)))) & 0xFFFFFFFFUL)\n\n#if defined(CONFIG_EMBUE)\n#define LTC_SMALL_CODE\n#endif\n\n/**\n @file sha256.c\n LTC_SHA256 by Tom St Denis\n*/\n\n#ifdef LTC_SMALL_CODE\n/* the K array */\nstatic const uint32_t K[64] = {\n 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,\n 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,\n 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,\n 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,\n 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,\n 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,\n 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,\n 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,\n 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,\n 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,\n 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,\n 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,\n 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL\n};\n#endif\n\n/* Various logical functions */\n#define Ch(x,y,z) (z ^ (x & (y ^ z)))\n#define Maj(x,y,z) (((x | y) & z) | (x & y))\n#define S(x, n) RORc((x),(n))\n#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))\n#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))\n#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25))\n#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3))\n#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10))\n\n/* compress 512-bits */\nstatic void sha256_compress(SHA256_CTX *s, unsigned char *buf)\n{\n uint32_t S[8], W[64], t0, t1;\n#ifdef LTC_SMALL_CODE\n uint32_t t;\n#endif\n int i;\n\n /* copy state into S */\n for (i = 0; i < 8; i++) {\n S[i] = s->state[i];\n }\n\n /* copy the state into 512-bits into W[0..15] */\n for (i = 0; i < 16; i++) {\n LOAD32H(W[i], buf + (4*i));\n }\n\n /* fill W[16..63] */\n for (i = 16; i < 64; i++) {\n W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];\n }\n\n /* Compress */\n#ifdef LTC_SMALL_CODE\n#define RND(a,b,c,d,e,f,g,h,i) \\\n t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \\\n t1 = Sigma0(a) + Maj(a, b, c); \\\n d += t0; \\\n h = t0 + t1;\n\n for (i = 0; i < 64; ++i) {\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i);\n t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4];\n S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;\n }\n#else\n#define RND(a,b,c,d,e,f,g,h,i,ki) \\\n t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i]; \\\n t1 = Sigma0(a) + Maj(a, b, c); \\\n d += t0; \\\n h = t0 + t1;\n\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,0x428a2f98);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,0x71374491);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,0xb5c0fbcf);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,0xe9b5dba5);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,0x3956c25b);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],5,0x59f111f1);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],6,0x923f82a4);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],7,0xab1c5ed5);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],8,0xd807aa98);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],9,0x12835b01);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],10,0x243185be);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],11,0x550c7dc3);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],12,0x72be5d74);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],13,0x80deb1fe);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],14,0x9bdc06a7);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],15,0xc19bf174);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],16,0xe49b69c1);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],17,0xefbe4786);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],18,0x0fc19dc6);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],19,0x240ca1cc);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],20,0x2de92c6f);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],21,0x4a7484aa);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],22,0x5cb0a9dc);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],23,0x76f988da);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],24,0x983e5152);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],25,0xa831c66d);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],26,0xb00327c8);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],27,0xbf597fc7);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],28,0xc6e00bf3);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],29,0xd5a79147);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],30,0x06ca6351);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],31,0x14292967);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],32,0x27b70a85);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],33,0x2e1b2138);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],34,0x4d2c6dfc);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],35,0x53380d13);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],36,0x650a7354);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],37,0x766a0abb);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],38,0x81c2c92e);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],39,0x92722c85);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],40,0xa2bfe8a1);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],41,0xa81a664b);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],42,0xc24b8b70);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],43,0xc76c51a3);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],44,0xd192e819);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],45,0xd6990624);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],46,0xf40e3585);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],47,0x106aa070);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],48,0x19a4c116);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],49,0x1e376c08);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],50,0x2748774c);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],51,0x34b0bcb5);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],52,0x391c0cb3);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],53,0x4ed8aa4a);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],54,0x5b9cca4f);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],55,0x682e6ff3);\n RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],56,0x748f82ee);\n RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],57,0x78a5636f);\n RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],58,0x84c87814);\n RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],59,0x8cc70208);\n RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],60,0x90befffa);\n RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],61,0xa4506ceb);\n RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);\n RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);\n\n#undef RND\n\n#endif\n\n /* feedback */\n for (i = 0; i < 8; i++) {\n s->state[i] = s->state[i] + S[i];\n }\n}\n\n#ifdef LTC_CLEAN_STACK\nstatic int sha256_compress(hash_state * md, unsigned char *buf)\n{\n int err;\n err = _sha256_compress(md, buf);\n burn_stack(sizeof(uint32_t) * 74);\n return err;\n}\n#endif\n\n/**\n Initialize the hash state\n @param md The hash state you wish to initialize\n @return CRYPT_OK if successful\n*/\nvoid SHA256_Init(SHA256_CTX *s)\n{\n s->curlen = 0;\n s->length = 0;\n s->state[0] = 0x6A09E667UL;\n s->state[1] = 0xBB67AE85UL;\n s->state[2] = 0x3C6EF372UL;\n s->state[3] = 0xA54FF53AUL;\n s->state[4] = 0x510E527FUL;\n s->state[5] = 0x9B05688CUL;\n s->state[6] = 0x1F83D9ABUL;\n s->state[7] = 0x5BE0CD19UL;\n}\n\nvoid SHA256_Update(SHA256_CTX *s, const uint8_t *in, unsigned long inlen)\n{\n unsigned long n;\n\n if (s->curlen > sizeof(s->buf)) {\n abort();\n }\n if ((s->length + inlen) < s->length) {\n abort();\n }\n while (inlen > 0) {\n if (s->curlen == 0 && inlen >= 64) {\n sha256_compress(s, (unsigned char *)in);\n s->length += 64 * 8;\n in += 64;\n inlen -= 64;\n } else {\n n = min_int(inlen, 64 - s->curlen);\n memcpy(s->buf + s->curlen, in, (size_t)n);\n s->curlen += n;\n in += n;\n inlen -= n;\n if (s->curlen == 64) {\n sha256_compress(s, s->buf);\n s->length += 8*64;\n s->curlen = 0;\n }\n }\n } }\n\n/**\n Terminate the hash to get the digest\n @param md The hash state\n @param out [out] The destination of the hash (32 bytes)\n @return CRYPT_OK if successful\n*/\nvoid SHA256_Final(uint8_t *out, SHA256_CTX *s)\n{\n int i;\n\n if (s->curlen >= sizeof(s->buf)) {\n abort();\n }\n\n\n /* increase the length of the message */\n s->length += s->curlen * 8;\n\n /* append the '1' bit */\n s->buf[s->curlen++] = (unsigned char)0x80;\n\n /* if the length is currently above 56 bytes we append zeros\n * then compress. Then we can fall back to padding zeros and length\n * encoding like normal.\n */\n if (s->curlen > 56) {\n while (s->curlen < 64) {\n s->buf[s->curlen++] = (unsigned char)0;\n }\n sha256_compress(s, s->buf);\n s->curlen = 0;\n }\n\n /* pad upto 56 bytes of zeroes */\n while (s->curlen < 56) {\n s->buf[s->curlen++] = (unsigned char)0;\n }\n\n /* store length */\n STORE64H(s->length, s->buf+56);\n sha256_compress(s, s->buf);\n\n /* copy output */\n for (i = 0; i < 8; i++) {\n STORE32H(s->state[i], out+(4*i));\n }\n#ifdef LTC_CLEAN_STACK\n zeromem(md, sizeof(hash_state));\n#endif\n}\n\nvoid SHA256(const uint8_t *buf, int buf_len, uint8_t *out)\n{\n SHA256_CTX ctx;\n\n SHA256_Init(&ctx);\n SHA256_Update(&ctx, buf, buf_len);\n SHA256_Final(out, &ctx);\n}\n\n#if 0\n/**\n Self-test the hash\n @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled\n*/\nint sha256_test(void)\n{\n #ifndef LTC_TEST\n return CRYPT_NOP;\n #else\n static const struct {\n char *msg;\n unsigned char hash[32];\n } tests[] = {\n { \"abc\",\n { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,\n 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,\n 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,\n 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }\n },\n { \"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\",\n { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,\n 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,\n 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,\n 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }\n },\n };\n\n int i;\n unsigned char tmp[32];\n hash_state md;\n\n for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {\n sha256_init(&md);\n sha256_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));\n sha256_done(&md, tmp);\n if (XMEMCMP(tmp, tests[i].hash, 32) != 0) {\n return CRYPT_FAIL_TESTVECTOR;\n }\n }\n return CRYPT_OK;\n #endif\n}\n\n#endif\n"], ["/linuxpdf/tinyemu/splitimg.c", "/*\n * Disk image splitter\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n int blocksize, ret, i;\n const char *infilename, *outpath;\n FILE *f, *fo;\n char buf1[1024];\n uint8_t *buf;\n\n if ((optind + 1) >= argc) {\n printf(\"splitimg version \" CONFIG_VERSION \", Copyright (c) 2011-2016 Fabrice Bellard\\n\"\n \"usage: splitimg infile outpath [blocksize]\\n\"\n \"Create a multi-file disk image for the RISCVEMU HTTP block device\\n\"\n \"\\n\"\n \"outpath must be a directory\\n\"\n \"blocksize is the block size in KB\\n\");\n exit(1);\n }\n\n infilename = argv[optind++];\n outpath = argv[optind++];\n blocksize = 256;\n if (optind < argc)\n blocksize = strtol(argv[optind++], NULL, 0);\n\n blocksize *= 1024;\n \n buf = malloc(blocksize);\n\n f = fopen(infilename, \"rb\");\n if (!f) {\n perror(infilename);\n exit(1);\n }\n i = 0;\n for(;;) {\n ret = fread(buf, 1, blocksize, f);\n if (ret < 0) {\n perror(\"fread\");\n exit(1);\n }\n if (ret == 0)\n break;\n if (ret < blocksize) {\n printf(\"warning: last block is not full\\n\");\n memset(buf + ret, 0, blocksize - ret);\n }\n snprintf(buf1, sizeof(buf1), \"%s/blk%09u.bin\", outpath, i);\n fo = fopen(buf1, \"wb\");\n if (!fo) {\n perror(buf1);\n exit(1);\n }\n fwrite(buf, 1, blocksize, fo);\n fclose(fo);\n i++;\n }\n fclose(f);\n printf(\"%d blocks\\n\", i);\n\n snprintf(buf1, sizeof(buf1), \"%s/blk.txt\", outpath);\n fo = fopen(buf1, \"wb\");\n if (!fo) {\n perror(buf1);\n exit(1);\n }\n fprintf(fo, \"{\\n\");\n fprintf(fo, \" block_size: %d,\\n\", blocksize / 1024);\n fprintf(fo, \" n_block: %d,\\n\", i);\n fprintf(fo, \"}\\n\");\n fclose(fo);\n return 0;\n}\n"], ["/linuxpdf/tinyemu/pckbd.c", "/*\n * QEMU PC keyboard emulation\n *\n * Copyright (c) 2003 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n/* debug PC keyboard */\n//#define DEBUG_KBD\n\n/* debug PC keyboard : only mouse */\n//#define DEBUG_MOUSE\n\n/*\tKeyboard Controller Commands */\n#define KBD_CCMD_READ_MODE\t0x20\t/* Read mode bits */\n#define KBD_CCMD_WRITE_MODE\t0x60\t/* Write mode bits */\n#define KBD_CCMD_GET_VERSION\t0xA1\t/* Get controller version */\n#define KBD_CCMD_MOUSE_DISABLE\t0xA7\t/* Disable mouse interface */\n#define KBD_CCMD_MOUSE_ENABLE\t0xA8\t/* Enable mouse interface */\n#define KBD_CCMD_TEST_MOUSE\t0xA9\t/* Mouse interface test */\n#define KBD_CCMD_SELF_TEST\t0xAA\t/* Controller self test */\n#define KBD_CCMD_KBD_TEST\t0xAB\t/* Keyboard interface test */\n#define KBD_CCMD_KBD_DISABLE\t0xAD\t/* Keyboard interface disable */\n#define KBD_CCMD_KBD_ENABLE\t0xAE\t/* Keyboard interface enable */\n#define KBD_CCMD_READ_INPORT 0xC0 /* read input port */\n#define KBD_CCMD_READ_OUTPORT\t0xD0 /* read output port */\n#define KBD_CCMD_WRITE_OUTPORT\t0xD1 /* write output port */\n#define KBD_CCMD_WRITE_OBUF\t0xD2\n#define KBD_CCMD_WRITE_AUX_OBUF\t0xD3 /* Write to output buffer as if\n\t\t\t\t\t initiated by the auxiliary device */\n#define KBD_CCMD_WRITE_MOUSE\t0xD4\t/* Write the following byte to the mouse */\n#define KBD_CCMD_DISABLE_A20 0xDD /* HP vectra only ? */\n#define KBD_CCMD_ENABLE_A20 0xDF /* HP vectra only ? */\n#define KBD_CCMD_RESET\t 0xFE\n\n/* Status Register Bits */\n#define KBD_STAT_OBF \t\t0x01\t/* Keyboard output buffer full */\n#define KBD_STAT_IBF \t\t0x02\t/* Keyboard input buffer full */\n#define KBD_STAT_SELFTEST\t0x04\t/* Self test successful */\n#define KBD_STAT_CMD\t\t0x08\t/* Last write was a command write (0=data) */\n#define KBD_STAT_UNLOCKED\t0x10\t/* Zero if keyboard locked */\n#define KBD_STAT_MOUSE_OBF\t0x20\t/* Mouse output buffer full */\n#define KBD_STAT_GTO \t\t0x40\t/* General receive/xmit timeout */\n#define KBD_STAT_PERR \t\t0x80\t/* Parity error */\n\n/* Controller Mode Register Bits */\n#define KBD_MODE_KBD_INT\t0x01\t/* Keyboard data generate IRQ1 */\n#define KBD_MODE_MOUSE_INT\t0x02\t/* Mouse data generate IRQ12 */\n#define KBD_MODE_SYS \t\t0x04\t/* The system flag (?) */\n#define KBD_MODE_NO_KEYLOCK\t0x08\t/* The keylock doesn't affect the keyboard if set */\n#define KBD_MODE_DISABLE_KBD\t0x10\t/* Disable keyboard interface */\n#define KBD_MODE_DISABLE_MOUSE\t0x20\t/* Disable mouse interface */\n#define KBD_MODE_KCC \t\t0x40\t/* Scan code conversion to PC format */\n#define KBD_MODE_RFU\t\t0x80\n\n#define KBD_PENDING_KBD 1\n#define KBD_PENDING_AUX 2\n\nstruct KBDState {\n uint8_t write_cmd; /* if non zero, write data to port 60 is expected */\n uint8_t status;\n uint8_t mode;\n /* Bitmask of devices with data available. */\n uint8_t pending;\n PS2KbdState *kbd;\n PS2MouseState *mouse;\n\n IRQSignal *irq_kbd;\n IRQSignal *irq_mouse;\n};\n\nstatic void qemu_system_reset_request(void)\n{\n printf(\"system_reset_request\\n\");\n exit(1);\n /* XXX */\n}\n\nstatic void ioport_set_a20(int val)\n{\n}\n\nstatic int ioport_get_a20(void)\n{\n return 1;\n}\n\n/* update irq and KBD_STAT_[MOUSE_]OBF */\n/* XXX: not generating the irqs if KBD_MODE_DISABLE_KBD is set may be\n incorrect, but it avoids having to simulate exact delays */\nstatic void kbd_update_irq(KBDState *s)\n{\n int irq_kbd_level, irq_mouse_level;\n\n irq_kbd_level = 0;\n irq_mouse_level = 0;\n s->status &= ~(KBD_STAT_OBF | KBD_STAT_MOUSE_OBF);\n if (s->pending) {\n s->status |= KBD_STAT_OBF;\n /* kbd data takes priority over aux data. */\n if (s->pending == KBD_PENDING_AUX) {\n s->status |= KBD_STAT_MOUSE_OBF;\n if (s->mode & KBD_MODE_MOUSE_INT)\n irq_mouse_level = 1;\n } else {\n if ((s->mode & KBD_MODE_KBD_INT) &&\n !(s->mode & KBD_MODE_DISABLE_KBD))\n irq_kbd_level = 1;\n }\n }\n set_irq(s->irq_kbd, irq_kbd_level);\n set_irq(s->irq_mouse, irq_mouse_level);\n}\n\nstatic void kbd_update_kbd_irq(void *opaque, int level)\n{\n KBDState *s = (KBDState *)opaque;\n\n if (level)\n s->pending |= KBD_PENDING_KBD;\n else\n s->pending &= ~KBD_PENDING_KBD;\n kbd_update_irq(s);\n}\n\nstatic void kbd_update_aux_irq(void *opaque, int level)\n{\n KBDState *s = (KBDState *)opaque;\n\n if (level)\n s->pending |= KBD_PENDING_AUX;\n else\n s->pending &= ~KBD_PENDING_AUX;\n kbd_update_irq(s);\n}\n\nstatic uint32_t kbd_read_status(void *opaque, uint32_t addr, int size_log2)\n{\n KBDState *s = opaque;\n int val;\n val = s->status;\n#if defined(DEBUG_KBD)\n printf(\"kbd: read status=0x%02x\\n\", val);\n#endif\n return val;\n}\n\nstatic void kbd_queue(KBDState *s, int b, int aux)\n{\n if (aux)\n ps2_queue(s->mouse, b);\n else\n ps2_queue(s->kbd, b);\n}\n\nstatic void kbd_write_command(void *opaque, uint32_t addr, uint32_t val,\n int size_log2)\n{\n KBDState *s = opaque;\n\n#if defined(DEBUG_KBD)\n printf(\"kbd: write cmd=0x%02x\\n\", val);\n#endif\n switch(val) {\n case KBD_CCMD_READ_MODE:\n kbd_queue(s, s->mode, 1);\n break;\n case KBD_CCMD_WRITE_MODE:\n case KBD_CCMD_WRITE_OBUF:\n case KBD_CCMD_WRITE_AUX_OBUF:\n case KBD_CCMD_WRITE_MOUSE:\n case KBD_CCMD_WRITE_OUTPORT:\n s->write_cmd = val;\n break;\n case KBD_CCMD_MOUSE_DISABLE:\n s->mode |= KBD_MODE_DISABLE_MOUSE;\n break;\n case KBD_CCMD_MOUSE_ENABLE:\n s->mode &= ~KBD_MODE_DISABLE_MOUSE;\n break;\n case KBD_CCMD_TEST_MOUSE:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_SELF_TEST:\n s->status |= KBD_STAT_SELFTEST;\n kbd_queue(s, 0x55, 0);\n break;\n case KBD_CCMD_KBD_TEST:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_KBD_DISABLE:\n s->mode |= KBD_MODE_DISABLE_KBD;\n kbd_update_irq(s);\n break;\n case KBD_CCMD_KBD_ENABLE:\n s->mode &= ~KBD_MODE_DISABLE_KBD;\n kbd_update_irq(s);\n break;\n case KBD_CCMD_READ_INPORT:\n kbd_queue(s, 0x00, 0);\n break;\n case KBD_CCMD_READ_OUTPORT:\n /* XXX: check that */\n val = 0x01 | (ioport_get_a20() << 1);\n if (s->status & KBD_STAT_OBF)\n val |= 0x10;\n if (s->status & KBD_STAT_MOUSE_OBF)\n val |= 0x20;\n kbd_queue(s, val, 0);\n break;\n case KBD_CCMD_ENABLE_A20:\n ioport_set_a20(1);\n break;\n case KBD_CCMD_DISABLE_A20:\n ioport_set_a20(0);\n break;\n case KBD_CCMD_RESET:\n qemu_system_reset_request();\n break;\n case 0xff:\n /* ignore that - I don't know what is its use */\n break;\n default:\n fprintf(stderr, \"qemu: unsupported keyboard cmd=0x%02x\\n\", val);\n break;\n }\n}\n\nstatic uint32_t kbd_read_data(void *opaque, uint32_t addr, int size_log2)\n{\n KBDState *s = opaque;\n uint32_t val;\n if (s->pending == KBD_PENDING_AUX)\n val = ps2_read_data(s->mouse);\n else\n val = ps2_read_data(s->kbd);\n#ifdef DEBUG_KBD\n printf(\"kbd: read data=0x%02x\\n\", val);\n#endif\n return val;\n}\n\nstatic void kbd_write_data(void *opaque, uint32_t addr, uint32_t val, int size_log2)\n{\n KBDState *s = opaque;\n\n#ifdef DEBUG_KBD\n printf(\"kbd: write data=0x%02x\\n\", val);\n#endif\n\n switch(s->write_cmd) {\n case 0:\n ps2_write_keyboard(s->kbd, val);\n break;\n case KBD_CCMD_WRITE_MODE:\n s->mode = val;\n ps2_keyboard_set_translation(s->kbd, (s->mode & KBD_MODE_KCC) != 0);\n /* ??? */\n kbd_update_irq(s);\n break;\n case KBD_CCMD_WRITE_OBUF:\n kbd_queue(s, val, 0);\n break;\n case KBD_CCMD_WRITE_AUX_OBUF:\n kbd_queue(s, val, 1);\n break;\n case KBD_CCMD_WRITE_OUTPORT:\n ioport_set_a20((val >> 1) & 1);\n if (!(val & 1)) {\n qemu_system_reset_request();\n }\n break;\n case KBD_CCMD_WRITE_MOUSE:\n ps2_write_mouse(s->mouse, val);\n break;\n default:\n break;\n }\n s->write_cmd = 0;\n}\n\nstatic void kbd_reset(void *opaque)\n{\n KBDState *s = opaque;\n\n s->mode = KBD_MODE_KBD_INT | KBD_MODE_MOUSE_INT;\n s->status = KBD_STAT_CMD | KBD_STAT_UNLOCKED;\n}\n\nKBDState *i8042_init(PS2KbdState **pkbd,\n PS2MouseState **pmouse,\n PhysMemoryMap *port_map,\n IRQSignal *kbd_irq, IRQSignal *mouse_irq, uint32_t io_base)\n{\n KBDState *s;\n \n s = mallocz(sizeof(*s));\n \n s->irq_kbd = kbd_irq;\n s->irq_mouse = mouse_irq;\n\n kbd_reset(s);\n cpu_register_device(port_map, io_base, 1, s, kbd_read_data, kbd_write_data, \n DEVIO_SIZE8);\n cpu_register_device(port_map, io_base + 4, 1, s, kbd_read_status, kbd_write_command, \n DEVIO_SIZE8);\n\n s->kbd = ps2_kbd_init(kbd_update_kbd_irq, s);\n s->mouse = ps2_mouse_init(kbd_update_aux_irq, s);\n\n *pkbd = s->kbd;\n *pmouse = s->mouse;\n return s;\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_timer.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_timer.c\t8.1 (Berkeley) 6/10/93\n * tcp_timer.c,v 1.2 1994/08/02 07:49:10 davidg Exp\n */\n\n#include \"slirp.h\"\n\nstatic struct tcpcb *tcp_timers(register struct tcpcb *tp, int timer);\n\n/*\n * Fast timeout routine for processing delayed acks\n */\nvoid\ntcp_fasttimo(Slirp *slirp)\n{\n\tregister struct socket *so;\n\tregister struct tcpcb *tp;\n\n\tDEBUG_CALL(\"tcp_fasttimo\");\n\n\tso = slirp->tcb.so_next;\n\tif (so)\n\tfor (; so != &slirp->tcb; so = so->so_next)\n\t\tif ((tp = (struct tcpcb *)so->so_tcpcb) &&\n\t\t (tp->t_flags & TF_DELACK)) {\n\t\t\ttp->t_flags &= ~TF_DELACK;\n\t\t\ttp->t_flags |= TF_ACKNOW;\n\t\t\t(void) tcp_output(tp);\n\t\t}\n}\n\n/*\n * Tcp protocol timeout routine called every 500 ms.\n * Updates the timers in all active tcb's and\n * causes finite state machine actions if timers expire.\n */\nvoid\ntcp_slowtimo(Slirp *slirp)\n{\n\tregister struct socket *ip, *ipnxt;\n\tregister struct tcpcb *tp;\n\tregister int i;\n\n\tDEBUG_CALL(\"tcp_slowtimo\");\n\n\t/*\n\t * Search through tcb's and update active timers.\n\t */\n\tip = slirp->tcb.so_next;\n if (ip == NULL) {\n return;\n }\n\tfor (; ip != &slirp->tcb; ip = ipnxt) {\n\t\tipnxt = ip->so_next;\n\t\ttp = sototcpcb(ip);\n if (tp == NULL) {\n continue;\n }\n\t\tfor (i = 0; i < TCPT_NTIMERS; i++) {\n\t\t\tif (tp->t_timer[i] && --tp->t_timer[i] == 0) {\n\t\t\t\ttcp_timers(tp,i);\n\t\t\t\tif (ipnxt->so_prev != ip)\n\t\t\t\t\tgoto tpgone;\n\t\t\t}\n\t\t}\n\t\ttp->t_idle++;\n\t\tif (tp->t_rtt)\n\t\t tp->t_rtt++;\ntpgone:\n\t\t;\n\t}\n\tslirp->tcp_iss += TCP_ISSINCR/PR_SLOWHZ;\t/* increment iss */\n\tslirp->tcp_now++;\t\t\t\t/* for timestamps */\n}\n\n/*\n * Cancel all timers for TCP tp.\n */\nvoid\ntcp_canceltimers(struct tcpcb *tp)\n{\n\tregister int i;\n\n\tfor (i = 0; i < TCPT_NTIMERS; i++)\n\t\ttp->t_timer[i] = 0;\n}\n\nconst int tcp_backoff[TCP_MAXRXTSHIFT + 1] =\n { 1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64 };\n\n/*\n * TCP timer processing.\n */\nstatic struct tcpcb *\ntcp_timers(register struct tcpcb *tp, int timer)\n{\n\tregister int rexmt;\n\n\tDEBUG_CALL(\"tcp_timers\");\n\n\tswitch (timer) {\n\n\t/*\n\t * 2 MSL timeout in shutdown went off. If we're closed but\n\t * still waiting for peer to close and connection has been idle\n\t * too long, or if 2MSL time is up from TIME_WAIT, delete connection\n\t * control block. Otherwise, check again in a bit.\n\t */\n\tcase TCPT_2MSL:\n\t\tif (tp->t_state != TCPS_TIME_WAIT &&\n\t\t tp->t_idle <= TCP_MAXIDLE)\n\t\t\ttp->t_timer[TCPT_2MSL] = TCPTV_KEEPINTVL;\n\t\telse\n\t\t\ttp = tcp_close(tp);\n\t\tbreak;\n\n\t/*\n\t * Retransmission timer went off. Message has not\n\t * been acked within retransmit interval. Back off\n\t * to a longer retransmit interval and retransmit one segment.\n\t */\n\tcase TCPT_REXMT:\n\n\t\t/*\n\t\t * XXXXX If a packet has timed out, then remove all the queued\n\t\t * packets for that session.\n\t\t */\n\n\t\tif (++tp->t_rxtshift > TCP_MAXRXTSHIFT) {\n\t\t\t/*\n\t\t\t * This is a hack to suit our terminal server here at the uni of canberra\n\t\t\t * since they have trouble with zeroes... It usually lets them through\n\t\t\t * unharmed, but under some conditions, it'll eat the zeros. If we\n\t\t\t * keep retransmitting it, it'll keep eating the zeroes, so we keep\n\t\t\t * retransmitting, and eventually the connection dies...\n\t\t\t * (this only happens on incoming data)\n\t\t\t *\n\t\t\t * So, if we were gonna drop the connection from too many retransmits,\n\t\t\t * don't... instead halve the t_maxseg, which might break up the NULLs and\n\t\t\t * let them through\n\t\t\t *\n\t\t\t * *sigh*\n\t\t\t */\n\n\t\t\ttp->t_maxseg >>= 1;\n\t\t\tif (tp->t_maxseg < 32) {\n\t\t\t\t/*\n\t\t\t\t * We tried our best, now the connection must die!\n\t\t\t\t */\n\t\t\t\ttp->t_rxtshift = TCP_MAXRXTSHIFT;\n\t\t\t\ttp = tcp_drop(tp, tp->t_softerror);\n\t\t\t\t/* tp->t_softerror : ETIMEDOUT); */ /* XXX */\n\t\t\t\treturn (tp); /* XXX */\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Set rxtshift to 6, which is still at the maximum\n\t\t\t * backoff time\n\t\t\t */\n\t\t\ttp->t_rxtshift = 6;\n\t\t}\n\t\trexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];\n\t\tTCPT_RANGESET(tp->t_rxtcur, rexmt,\n\t\t (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */\n\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t/*\n\t\t * If losing, let the lower level know and try for\n\t\t * a better route. Also, if we backed off this far,\n\t\t * our srtt estimate is probably bogus. Clobber it\n\t\t * so we'll take the next rtt measurement as our srtt;\n\t\t * move the current srtt into rttvar to keep the current\n\t\t * retransmit times until then.\n\t\t */\n\t\tif (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {\n\t\t\ttp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);\n\t\t\ttp->t_srtt = 0;\n\t\t}\n\t\ttp->snd_nxt = tp->snd_una;\n\t\t/*\n\t\t * If timing a segment in this window, stop the timer.\n\t\t */\n\t\ttp->t_rtt = 0;\n\t\t/*\n\t\t * Close the congestion window down to one segment\n\t\t * (we'll open it by one segment for each ack we get).\n\t\t * Since we probably have a window's worth of unacked\n\t\t * data accumulated, this \"slow start\" keeps us from\n\t\t * dumping all that data as back-to-back packets (which\n\t\t * might overwhelm an intermediate gateway).\n\t\t *\n\t\t * There are two phases to the opening: Initially we\n\t\t * open by one mss on each ack. This makes the window\n\t\t * size increase exponentially with time. If the\n\t\t * window is larger than the path can handle, this\n\t\t * exponential growth results in dropped packet(s)\n\t\t * almost immediately. To get more time between\n\t\t * drops but still \"push\" the network to take advantage\n\t\t * of improving conditions, we switch from exponential\n\t\t * to linear window opening at some threshold size.\n\t\t * For a threshold, we use half the current window\n\t\t * size, truncated to a multiple of the mss.\n\t\t *\n\t\t * (the minimum cwnd that will give us exponential\n\t\t * growth is 2 mss. We don't allow the threshold\n\t\t * to go below this.)\n\t\t */\n\t\t{\n\t\tu_int win = min(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg;\n\t\tif (win < 2)\n\t\t\twin = 2;\n\t\ttp->snd_cwnd = tp->t_maxseg;\n\t\ttp->snd_ssthresh = win * tp->t_maxseg;\n\t\ttp->t_dupacks = 0;\n\t\t}\n\t\t(void) tcp_output(tp);\n\t\tbreak;\n\n\t/*\n\t * Persistence timer into zero window.\n\t * Force a byte to be output, if possible.\n\t */\n\tcase TCPT_PERSIST:\n\t\ttcp_setpersist(tp);\n\t\ttp->t_force = 1;\n\t\t(void) tcp_output(tp);\n\t\ttp->t_force = 0;\n\t\tbreak;\n\n\t/*\n\t * Keep-alive timer went off; send something\n\t * or drop connection if idle for too long.\n\t */\n\tcase TCPT_KEEP:\n\t\tif (tp->t_state < TCPS_ESTABLISHED)\n\t\t\tgoto dropit;\n\n\t\tif ((SO_OPTIONS) && tp->t_state <= TCPS_CLOSE_WAIT) {\n\t\t \tif (tp->t_idle >= TCPTV_KEEP_IDLE + TCP_MAXIDLE)\n\t\t\t\tgoto dropit;\n\t\t\t/*\n\t\t\t * Send a packet designed to force a response\n\t\t\t * if the peer is up and reachable:\n\t\t\t * either an ACK if the connection is still alive,\n\t\t\t * or an RST if the peer has closed the connection\n\t\t\t * due to timeout or reboot.\n\t\t\t * Using sequence number tp->snd_una-1\n\t\t\t * causes the transmitted zero-length segment\n\t\t\t * to lie outside the receive window;\n\t\t\t * by the protocol spec, this requires the\n\t\t\t * correspondent TCP to respond.\n\t\t\t */\n\t\t\ttcp_respond(tp, &tp->t_template, (struct mbuf *)NULL,\n\t\t\t tp->rcv_nxt, tp->snd_una - 1, 0);\n\t\t\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;\n\t\t} else\n\t\t\ttp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;\n\t\tbreak;\n\n\tdropit:\n\t\ttp = tcp_drop(tp, 0);\n\t\tbreak;\n\t}\n\n\treturn (tp);\n}\n"], ["/linuxpdf/tinyemu/simplefb.c", "/*\n * Simple frame buffer\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"virtio.h\"\n#include \"machine.h\"\n\n//#define DEBUG_VBE\n\n#define FB_ALLOC_ALIGN 65536\n\nstruct SimpleFBState {\n FBDevice *fb_dev;\n int fb_page_count;\n PhysMemoryRange *mem_range;\n};\n\n#define MAX_MERGE_DISTANCE 3\n\nvoid simplefb_refresh(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque,\n PhysMemoryRange *mem_range,\n int fb_page_count)\n{\n const uint32_t *dirty_bits;\n uint32_t dirty_val;\n int y0, y1, page_y0, page_y1, byte_pos, page_index, bit_pos;\n\n dirty_bits = phys_mem_get_dirty_bits(mem_range);\n \n page_index = 0;\n y0 = y1 = 0;\n while (page_index < fb_page_count) {\n dirty_val = dirty_bits[page_index >> 5];\n if (dirty_val != 0) {\n bit_pos = 0;\n while (dirty_val != 0) {\n while (((dirty_val >> bit_pos) & 1) == 0)\n bit_pos++;\n dirty_val &= ~(1 << bit_pos);\n\n byte_pos = (page_index + bit_pos) * DEVRAM_PAGE_SIZE;\n page_y0 = byte_pos / fb_dev->stride;\n page_y1 = ((byte_pos + DEVRAM_PAGE_SIZE - 1) / fb_dev->stride) + 1;\n page_y1 = min_int(page_y1, fb_dev->height);\n if (y0 == y1) {\n y0 = page_y0;\n y1 = page_y1;\n } else if (page_y0 <= (y1 + MAX_MERGE_DISTANCE)) {\n /* union with current region */\n y1 = page_y1;\n } else {\n /* flush */\n redraw_func(fb_dev, opaque,\n 0, y0, fb_dev->width, y1 - y0);\n y0 = page_y0;\n y1 = page_y1;\n }\n }\n }\n page_index += 32;\n }\n\n if (y0 != y1) {\n redraw_func(fb_dev, opaque,\n 0, y0, fb_dev->width, y1 - y0);\n }\n}\n\nstatic void simplefb_refresh1(FBDevice *fb_dev,\n SimpleFBDrawFunc *redraw_func, void *opaque)\n{\n SimpleFBState *s = fb_dev->device_opaque;\n simplefb_refresh(fb_dev, redraw_func, opaque, s->mem_range,\n s->fb_page_count);\n}\n\nSimpleFBState *simplefb_init(PhysMemoryMap *map, uint64_t phys_addr,\n FBDevice *fb_dev, int width, int height)\n{\n SimpleFBState *s;\n \n s = mallocz(sizeof(*s));\n s->fb_dev = fb_dev;\n\n fb_dev->width = width;\n fb_dev->height = height;\n fb_dev->stride = width * 4;\n fb_dev->fb_size = (height * fb_dev->stride + FB_ALLOC_ALIGN - 1) & ~(FB_ALLOC_ALIGN - 1);\n s->fb_page_count = fb_dev->fb_size >> DEVRAM_PAGE_SIZE_LOG2;\n\n s->mem_range = cpu_register_ram(map, phys_addr, fb_dev->fb_size,\n DEVRAM_FLAG_DIRTY_BITS);\n \n fb_dev->fb_data = s->mem_range->phys_mem;\n fb_dev->device_opaque = s;\n fb_dev->refresh = simplefb_refresh1;\n return s;\n}\n"], ["/linuxpdf/tinyemu/vmmouse.c", "/*\n * VM mouse emulation\n * \n * Copyright (c) 2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"iomem.h\"\n#include \"ps2.h\"\n\n#define VMPORT_MAGIC 0x564D5868\n\n#define REG_EAX 0\n#define REG_EBX 1\n#define REG_ECX 2\n#define REG_EDX 3\n#define REG_ESI 4\n#define REG_EDI 5\n\n#define FIFO_SIZE (4 * 16)\n\nstruct VMMouseState {\n PS2MouseState *ps2_mouse;\n int fifo_count, fifo_rindex, fifo_windex;\n BOOL enabled;\n BOOL absolute;\n uint32_t fifo_buf[FIFO_SIZE];\n};\n\nstatic void put_queue(VMMouseState *s, uint32_t val)\n{\n if (s->fifo_count >= FIFO_SIZE)\n return;\n s->fifo_buf[s->fifo_windex] = val;\n if (++s->fifo_windex == FIFO_SIZE)\n s->fifo_windex = 0;\n s->fifo_count++;\n}\n\nstatic void read_data(VMMouseState *s, uint32_t *regs, int size)\n{\n int i;\n if (size > 6 || size > s->fifo_count) {\n // printf(\"vmmouse: read error req=%d count=%d\\n\", size, s->fifo_count);\n s->enabled = FALSE;\n return;\n }\n for(i = 0; i < size; i++) {\n regs[i] = s->fifo_buf[s->fifo_rindex];\n if (++s->fifo_rindex == FIFO_SIZE)\n s->fifo_rindex = 0;\n }\n s->fifo_count -= size;\n}\n\nvoid vmmouse_send_mouse_event(VMMouseState *s, int x, int y, int dz,\n int buttons)\n{\n int state;\n\n if (!s->enabled) {\n ps2_mouse_event(s->ps2_mouse, x, y, dz, buttons);\n return;\n }\n\n if ((s->fifo_count + 4) > FIFO_SIZE)\n return;\n\n state = 0;\n if (buttons & 1)\n state |= 0x20;\n if (buttons & 2)\n state |= 0x10;\n if (buttons & 4)\n state |= 0x08;\n if (s->absolute) {\n /* range = 0 ... 65535 */\n x *= 2; \n y *= 2;\n }\n\n put_queue(s, state);\n put_queue(s, x);\n put_queue(s, y);\n put_queue(s, -dz);\n\n /* send PS/2 mouse event */\n ps2_mouse_event(s->ps2_mouse, 1, 0, 0, 0);\n}\n\nvoid vmmouse_handler(VMMouseState *s, uint32_t *regs)\n{\n uint32_t cmd;\n \n cmd = regs[REG_ECX] & 0xff;\n switch(cmd) {\n case 10: /* get version */\n regs[REG_EBX] = VMPORT_MAGIC;\n break;\n case 39: /* VMMOUSE_DATA */\n read_data(s, regs, regs[REG_EBX]);\n break;\n case 40: /* VMMOUSE_STATUS */\n regs[REG_EAX] = ((s->enabled ? 0 : 0xffff) << 16) | s->fifo_count;\n break;\n case 41: /* VMMOUSE_COMMAND */\n switch(regs[REG_EBX]) {\n case 0x45414552: /* read id */\n if (s->fifo_count < FIFO_SIZE) {\n put_queue(s, 0x3442554a);\n s->enabled = TRUE;\n }\n break;\n case 0x000000f5: /* disable */\n s->enabled = FALSE;\n break;\n case 0x4c455252: /* set relative */\n s->absolute = 0;\n break;\n case 0x53424152: /* set absolute */\n s->absolute = 1;\n break;\n }\n break;\n }\n}\n\nBOOL vmmouse_is_absolute(VMMouseState *s)\n{\n return s->absolute;\n}\n\nVMMouseState *vmmouse_init(PS2MouseState *ps2_mouse)\n{\n VMMouseState *s;\n s = mallocz(sizeof(*s));\n s->ps2_mouse = ps2_mouse;\n return s;\n}\n"], ["/linuxpdf/tinyemu/slirp/tcp_output.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)tcp_output.c\t8.3 (Berkeley) 12/30/93\n * tcp_output.c,v 1.3 1994/09/15 10:36:55 davidg Exp\n */\n\n/*\n * Changes and additions relating to SLiRP\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\nstatic const u_char tcp_outflags[TCP_NSTATES] = {\n\tTH_RST|TH_ACK, 0, TH_SYN, TH_SYN|TH_ACK,\n\tTH_ACK, TH_ACK, TH_FIN|TH_ACK, TH_FIN|TH_ACK,\n\tTH_FIN|TH_ACK, TH_ACK, TH_ACK,\n};\n\n\n#define MAX_TCPOPTLEN\t32\t/* max # bytes that go in options */\n\n/*\n * Tcp output routine: figure out what should be sent and send it.\n */\nint\ntcp_output(struct tcpcb *tp)\n{\n\tregister struct socket *so = tp->t_socket;\n\tregister long len, win;\n\tint off, flags, error;\n\tregister struct mbuf *m;\n\tregister struct tcpiphdr *ti;\n\tu_char opt[MAX_TCPOPTLEN];\n\tunsigned optlen, hdrlen;\n\tint idle, sendalot;\n\n\tDEBUG_CALL(\"tcp_output\");\n\tDEBUG_ARG(\"tp = %lx\", (long )tp);\n\n\t/*\n\t * Determine length of data that should be transmitted,\n\t * and flags that will be used.\n\t * If there is some data or critical controls (SYN, RST)\n\t * to send, then transmit; otherwise, investigate further.\n\t */\n\tidle = (tp->snd_max == tp->snd_una);\n\tif (idle && tp->t_idle >= tp->t_rxtcur)\n\t\t/*\n\t\t * We have been idle for \"a while\" and no acks are\n\t\t * expected to clock out any data we send --\n\t\t * slow start to get ack \"clock\" running again.\n\t\t */\n\t\ttp->snd_cwnd = tp->t_maxseg;\nagain:\n\tsendalot = 0;\n\toff = tp->snd_nxt - tp->snd_una;\n\twin = min(tp->snd_wnd, tp->snd_cwnd);\n\n\tflags = tcp_outflags[tp->t_state];\n\n\tDEBUG_MISC((dfd, \" --- tcp_output flags = 0x%x\\n\",flags));\n\n\t/*\n\t * If in persist timeout with window of 0, send 1 byte.\n\t * Otherwise, if window is small but nonzero\n\t * and timer expired, we will send what we can\n\t * and go to transmit state.\n\t */\n\tif (tp->t_force) {\n\t\tif (win == 0) {\n\t\t\t/*\n\t\t\t * If we still have some data to send, then\n\t\t\t * clear the FIN bit. Usually this would\n\t\t\t * happen below when it realizes that we\n\t\t\t * aren't sending all the data. However,\n\t\t\t * if we have exactly 1 byte of unset data,\n\t\t\t * then it won't clear the FIN bit below,\n\t\t\t * and if we are in persist state, we wind\n\t\t\t * up sending the packet without recording\n\t\t\t * that we sent the FIN bit.\n\t\t\t *\n\t\t\t * We can't just blindly clear the FIN bit,\n\t\t\t * because if we don't have any more data\n\t\t\t * to send then the probe will be the FIN\n\t\t\t * itself.\n\t\t\t */\n\t\t\tif (off < so->so_snd.sb_cc)\n\t\t\t\tflags &= ~TH_FIN;\n\t\t\twin = 1;\n\t\t} else {\n\t\t\ttp->t_timer[TCPT_PERSIST] = 0;\n\t\t\ttp->t_rxtshift = 0;\n\t\t}\n\t}\n\n\tlen = min(so->so_snd.sb_cc, win) - off;\n\n\tif (len < 0) {\n\t\t/*\n\t\t * If FIN has been sent but not acked,\n\t\t * but we haven't been called to retransmit,\n\t\t * len will be -1. Otherwise, window shrank\n\t\t * after we sent into it. If window shrank to 0,\n\t\t * cancel pending retransmit and pull snd_nxt\n\t\t * back to (closed) window. We will enter persist\n\t\t * state below. If the window didn't close completely,\n\t\t * just wait for an ACK.\n\t\t */\n\t\tlen = 0;\n\t\tif (win == 0) {\n\t\t\ttp->t_timer[TCPT_REXMT] = 0;\n\t\t\ttp->snd_nxt = tp->snd_una;\n\t\t}\n\t}\n\n\tif (len > tp->t_maxseg) {\n\t\tlen = tp->t_maxseg;\n\t\tsendalot = 1;\n\t}\n\tif (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc))\n\t\tflags &= ~TH_FIN;\n\n\twin = sbspace(&so->so_rcv);\n\n\t/*\n\t * Sender silly window avoidance. If connection is idle\n\t * and can send all data, a maximum segment,\n\t * at least a maximum default-size segment do it,\n\t * or are forced, do it; otherwise don't bother.\n\t * If peer's buffer is tiny, then send\n\t * when window is at least half open.\n\t * If retransmitting (possibly after persist timer forced us\n\t * to send into a small window), then must resend.\n\t */\n\tif (len) {\n\t\tif (len == tp->t_maxseg)\n\t\t\tgoto send;\n\t\tif ((1 || idle || tp->t_flags & TF_NODELAY) &&\n\t\t len + off >= so->so_snd.sb_cc)\n\t\t\tgoto send;\n\t\tif (tp->t_force)\n\t\t\tgoto send;\n\t\tif (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)\n\t\t\tgoto send;\n\t\tif (SEQ_LT(tp->snd_nxt, tp->snd_max))\n\t\t\tgoto send;\n\t}\n\n\t/*\n\t * Compare available window to amount of window\n\t * known to peer (as advertised window less\n\t * next expected input). If the difference is at least two\n\t * max size segments, or at least 50% of the maximum possible\n\t * window, then want to send a window update to peer.\n\t */\n\tif (win > 0) {\n\t\t/*\n\t\t * \"adv\" is the amount we can increase the window,\n\t\t * taking into account that we are limited by\n\t\t * TCP_MAXWIN << tp->rcv_scale.\n\t\t */\n\t\tlong adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -\n\t\t\t(tp->rcv_adv - tp->rcv_nxt);\n\n\t\tif (adv >= (long) (2 * tp->t_maxseg))\n\t\t\tgoto send;\n\t\tif (2 * adv >= (long) so->so_rcv.sb_datalen)\n\t\t\tgoto send;\n\t}\n\n\t/*\n\t * Send if we owe peer an ACK.\n\t */\n\tif (tp->t_flags & TF_ACKNOW)\n\t\tgoto send;\n\tif (flags & (TH_SYN|TH_RST))\n\t\tgoto send;\n\tif (SEQ_GT(tp->snd_up, tp->snd_una))\n\t\tgoto send;\n\t/*\n\t * If our state indicates that FIN should be sent\n\t * and we have not yet done so, or we're retransmitting the FIN,\n\t * then we need to send.\n\t */\n\tif (flags & TH_FIN &&\n\t ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))\n\t\tgoto send;\n\n\t/*\n\t * TCP window updates are not reliable, rather a polling protocol\n\t * using ``persist'' packets is used to insure receipt of window\n\t * updates. The three ``states'' for the output side are:\n\t *\tidle\t\t\tnot doing retransmits or persists\n\t *\tpersisting\t\tto move a small or zero window\n\t *\t(re)transmitting\tand thereby not persisting\n\t *\n\t * tp->t_timer[TCPT_PERSIST]\n\t *\tis set when we are in persist state.\n\t * tp->t_force\n\t *\tis set when we are called to send a persist packet.\n\t * tp->t_timer[TCPT_REXMT]\n\t *\tis set when we are retransmitting\n\t * The output side is idle when both timers are zero.\n\t *\n\t * If send window is too small, there is data to transmit, and no\n\t * retransmit or persist is pending, then go to persist state.\n\t * If nothing happens soon, send when timer expires:\n\t * if window is nonzero, transmit what we can,\n\t * otherwise force out a byte.\n\t */\n\tif (so->so_snd.sb_cc && tp->t_timer[TCPT_REXMT] == 0 &&\n\t tp->t_timer[TCPT_PERSIST] == 0) {\n\t\ttp->t_rxtshift = 0;\n\t\ttcp_setpersist(tp);\n\t}\n\n\t/*\n\t * No reason to send a segment, just return.\n\t */\n\treturn (0);\n\nsend:\n\t/*\n\t * Before ESTABLISHED, force sending of initial options\n\t * unless TCP set not to do any options.\n\t * NOTE: we assume that the IP/TCP header plus TCP options\n\t * always fit in a single mbuf, leaving room for a maximum\n\t * link header, i.e.\n\t *\tmax_linkhdr + sizeof (struct tcpiphdr) + optlen <= MHLEN\n\t */\n\toptlen = 0;\n\thdrlen = sizeof (struct tcpiphdr);\n\tif (flags & TH_SYN) {\n\t\ttp->snd_nxt = tp->iss;\n\t\tif ((tp->t_flags & TF_NOOPT) == 0) {\n\t\t\tuint16_t mss;\n\n\t\t\topt[0] = TCPOPT_MAXSEG;\n\t\t\topt[1] = 4;\n\t\t\tmss = htons((uint16_t) tcp_mss(tp, 0));\n\t\t\tmemcpy((caddr_t)(opt + 2), (caddr_t)&mss, sizeof(mss));\n\t\t\toptlen = 4;\n\t\t}\n \t}\n\n \thdrlen += optlen;\n\n\t/*\n\t * Adjust data length if insertion of options will\n\t * bump the packet length beyond the t_maxseg length.\n\t */\n\t if (len > tp->t_maxseg - optlen) {\n\t\tlen = tp->t_maxseg - optlen;\n\t\tsendalot = 1;\n\t }\n\n\t/*\n\t * Grab a header mbuf, attaching a copy of data to\n\t * be transmitted, and initialize the header from\n\t * the template for sends on this connection.\n\t */\n\tif (len) {\n\t\tm = m_get(so->slirp);\n\t\tif (m == NULL) {\n\t\t\terror = 1;\n\t\t\tgoto out;\n\t\t}\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\tm->m_len = hdrlen;\n\n\t\tsbcopy(&so->so_snd, off, (int) len, mtod(m, caddr_t) + hdrlen);\n\t\tm->m_len += len;\n\n\t\t/*\n\t\t * If we're sending everything we've got, set PUSH.\n\t\t * (This will keep happy those implementations which only\n\t\t * give data to the user when a buffer fills or\n\t\t * a PUSH comes in.)\n\t\t */\n\t\tif (off + len == so->so_snd.sb_cc)\n\t\t\tflags |= TH_PUSH;\n\t} else {\n\t\tm = m_get(so->slirp);\n\t\tif (m == NULL) {\n\t\t\terror = 1;\n\t\t\tgoto out;\n\t\t}\n\t\tm->m_data += IF_MAXLINKHDR;\n\t\tm->m_len = hdrlen;\n\t}\n\n\tti = mtod(m, struct tcpiphdr *);\n\n\tmemcpy((caddr_t)ti, &tp->t_template, sizeof (struct tcpiphdr));\n\n\t/*\n\t * Fill in fields, remembering maximum advertised\n\t * window for use in delaying messages about window sizes.\n\t * If resending a FIN, be sure not to use a new sequence number.\n\t */\n\tif (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&\n\t tp->snd_nxt == tp->snd_max)\n\t\ttp->snd_nxt--;\n\t/*\n\t * If we are doing retransmissions, then snd_nxt will\n\t * not reflect the first unsent octet. For ACK only\n\t * packets, we do not want the sequence number of the\n\t * retransmitted packet, we want the sequence number\n\t * of the next unsent octet. So, if there is no data\n\t * (and no SYN or FIN), use snd_max instead of snd_nxt\n\t * when filling in ti_seq. But if we are in persist\n\t * state, snd_max might reflect one byte beyond the\n\t * right edge of the window, so use snd_nxt in that\n\t * case, since we know we aren't doing a retransmission.\n\t * (retransmit and persist are mutually exclusive...)\n\t */\n\tif (len || (flags & (TH_SYN|TH_FIN)) || tp->t_timer[TCPT_PERSIST])\n\t\tti->ti_seq = htonl(tp->snd_nxt);\n\telse\n\t\tti->ti_seq = htonl(tp->snd_max);\n\tti->ti_ack = htonl(tp->rcv_nxt);\n\tif (optlen) {\n\t\tmemcpy((caddr_t)(ti + 1), (caddr_t)opt, optlen);\n\t\tti->ti_off = (sizeof (struct tcphdr) + optlen) >> 2;\n\t}\n\tti->ti_flags = flags;\n\t/*\n\t * Calculate receive window. Don't shrink window,\n\t * but avoid silly window syndrome.\n\t */\n\tif (win < (long)(so->so_rcv.sb_datalen / 4) && win < (long)tp->t_maxseg)\n\t\twin = 0;\n\tif (win > (long)TCP_MAXWIN << tp->rcv_scale)\n\t\twin = (long)TCP_MAXWIN << tp->rcv_scale;\n\tif (win < (long)(tp->rcv_adv - tp->rcv_nxt))\n\t\twin = (long)(tp->rcv_adv - tp->rcv_nxt);\n\tti->ti_win = htons((uint16_t) (win>>tp->rcv_scale));\n\n\tif (SEQ_GT(tp->snd_up, tp->snd_una)) {\n\t\tti->ti_urp = htons((uint16_t)(tp->snd_up - ntohl(ti->ti_seq)));\n\t\tti->ti_flags |= TH_URG;\n\t} else\n\t\t/*\n\t\t * If no urgent pointer to send, then we pull\n\t\t * the urgent pointer to the left edge of the send window\n\t\t * so that it doesn't drift into the send window on sequence\n\t\t * number wraparound.\n\t\t */\n\t\ttp->snd_up = tp->snd_una;\t\t/* drag it along */\n\n\t/*\n\t * Put TCP length in extended header, and then\n\t * checksum extended header and data.\n\t */\n\tif (len + optlen)\n\t\tti->ti_len = htons((uint16_t)(sizeof (struct tcphdr) +\n\t\t optlen + len));\n\tti->ti_sum = cksum(m, (int)(hdrlen + len));\n\n\t/*\n\t * In transmit state, time the transmission and arrange for\n\t * the retransmit. In persist state, just set snd_max.\n\t */\n\tif (tp->t_force == 0 || tp->t_timer[TCPT_PERSIST] == 0) {\n\t\ttcp_seq startseq = tp->snd_nxt;\n\n\t\t/*\n\t\t * Advance snd_nxt over sequence space of this segment.\n\t\t */\n\t\tif (flags & (TH_SYN|TH_FIN)) {\n\t\t\tif (flags & TH_SYN)\n\t\t\t\ttp->snd_nxt++;\n\t\t\tif (flags & TH_FIN) {\n\t\t\t\ttp->snd_nxt++;\n\t\t\t\ttp->t_flags |= TF_SENTFIN;\n\t\t\t}\n\t\t}\n\t\ttp->snd_nxt += len;\n\t\tif (SEQ_GT(tp->snd_nxt, tp->snd_max)) {\n\t\t\ttp->snd_max = tp->snd_nxt;\n\t\t\t/*\n\t\t\t * Time this transmission if not a retransmission and\n\t\t\t * not currently timing anything.\n\t\t\t */\n\t\t\tif (tp->t_rtt == 0) {\n\t\t\t\ttp->t_rtt = 1;\n\t\t\t\ttp->t_rtseq = startseq;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Set retransmit timer if not currently set,\n\t\t * and not doing an ack or a keep-alive probe.\n\t\t * Initial value for retransmit timer is smoothed\n\t\t * round-trip time + 2 * round-trip time variance.\n\t\t * Initialize shift counter which is used for backoff\n\t\t * of retransmit time.\n\t\t */\n\t\tif (tp->t_timer[TCPT_REXMT] == 0 &&\n\t\t tp->snd_nxt != tp->snd_una) {\n\t\t\ttp->t_timer[TCPT_REXMT] = tp->t_rxtcur;\n\t\t\tif (tp->t_timer[TCPT_PERSIST]) {\n\t\t\t\ttp->t_timer[TCPT_PERSIST] = 0;\n\t\t\t\ttp->t_rxtshift = 0;\n\t\t\t}\n\t\t}\n\t} else\n\t\tif (SEQ_GT(tp->snd_nxt + len, tp->snd_max))\n\t\t\ttp->snd_max = tp->snd_nxt + len;\n\n\t/*\n\t * Fill in IP length and desired time to live and\n\t * send to IP level. There should be a better way\n\t * to handle ttl and tos; we could keep them in\n\t * the template, but need a way to checksum without them.\n\t */\n\tm->m_len = hdrlen + len; /* XXX Needed? m_len should be correct */\n\n {\n\n\t((struct ip *)ti)->ip_len = m->m_len;\n\n\t((struct ip *)ti)->ip_ttl = IPDEFTTL;\n\t((struct ip *)ti)->ip_tos = so->so_iptos;\n\n\terror = ip_output(so, m);\n }\n\tif (error) {\nout:\n\t\treturn (error);\n\t}\n\n\t/*\n\t * Data sent (as far as we can tell).\n\t * If this advertises a larger window than any other segment,\n\t * then remember the size of the advertised window.\n\t * Any pending ACK has now been sent.\n\t */\n\tif (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))\n\t\ttp->rcv_adv = tp->rcv_nxt + win;\n\ttp->last_ack_sent = tp->rcv_nxt;\n\ttp->t_flags &= ~(TF_ACKNOW|TF_DELACK);\n\tif (sendalot)\n\t\tgoto again;\n\n\treturn (0);\n}\n\nvoid\ntcp_setpersist(struct tcpcb *tp)\n{\n int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;\n\n\t/*\n\t * Start/restart persistence timer.\n\t */\n\tTCPT_RANGESET(tp->t_timer[TCPT_PERSIST],\n\t t * tcp_backoff[tp->t_rxtshift],\n\t TCPTV_PERSMIN, TCPTV_PERSMAX);\n\tif (tp->t_rxtshift < TCP_MAXRXTSHIFT)\n\t\ttp->t_rxtshift++;\n}\n"], ["/linuxpdf/tinyemu/slirp/if.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n#define ifs_init(ifm) ((ifm)->ifs_next = (ifm)->ifs_prev = (ifm))\n\nstatic void\nifs_insque(struct mbuf *ifm, struct mbuf *ifmhead)\n{\n\tifm->ifs_next = ifmhead->ifs_next;\n\tifmhead->ifs_next = ifm;\n\tifm->ifs_prev = ifmhead;\n\tifm->ifs_next->ifs_prev = ifm;\n}\n\nstatic void\nifs_remque(struct mbuf *ifm)\n{\n\tifm->ifs_prev->ifs_next = ifm->ifs_next;\n\tifm->ifs_next->ifs_prev = ifm->ifs_prev;\n}\n\nvoid\nif_init(Slirp *slirp)\n{\n slirp->if_fastq.ifq_next = slirp->if_fastq.ifq_prev = &slirp->if_fastq;\n slirp->if_batchq.ifq_next = slirp->if_batchq.ifq_prev = &slirp->if_batchq;\n slirp->next_m = &slirp->if_batchq;\n}\n\n/*\n * if_output: Queue packet into an output queue.\n * There are 2 output queue's, if_fastq and if_batchq.\n * Each output queue is a doubly linked list of double linked lists\n * of mbufs, each list belonging to one \"session\" (socket). This\n * way, we can output packets fairly by sending one packet from each\n * session, instead of all the packets from one session, then all packets\n * from the next session, etc. Packets on the if_fastq get absolute\n * priority, but if one session hogs the link, it gets \"downgraded\"\n * to the batchq until it runs out of packets, then it'll return\n * to the fastq (eg. if the user does an ls -alR in a telnet session,\n * it'll temporarily get downgraded to the batchq)\n */\nvoid\nif_output(struct socket *so, struct mbuf *ifm)\n{\n\tSlirp *slirp = ifm->slirp;\n\tstruct mbuf *ifq;\n\tint on_fastq = 1;\n\n\tDEBUG_CALL(\"if_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"ifm = %lx\", (long)ifm);\n\n\t/*\n\t * First remove the mbuf from m_usedlist,\n\t * since we're gonna use m_next and m_prev ourselves\n\t * XXX Shouldn't need this, gotta change dtom() etc.\n\t */\n\tif (ifm->m_flags & M_USEDLIST) {\n\t\tremque(ifm);\n\t\tifm->m_flags &= ~M_USEDLIST;\n\t}\n\n\t/*\n\t * See if there's already a batchq list for this session.\n\t * This can include an interactive session, which should go on fastq,\n\t * but gets too greedy... hence it'll be downgraded from fastq to batchq.\n\t * We mustn't put this packet back on the fastq (or we'll send it out of order)\n\t * XXX add cache here?\n\t */\n\tfor (ifq = slirp->if_batchq.ifq_prev; ifq != &slirp->if_batchq;\n\t ifq = ifq->ifq_prev) {\n\t\tif (so == ifq->ifq_so) {\n\t\t\t/* A match! */\n\t\t\tifm->ifq_so = so;\n\t\t\tifs_insque(ifm, ifq->ifs_prev);\n\t\t\tgoto diddit;\n\t\t}\n\t}\n\n\t/* No match, check which queue to put it on */\n\tif (so && (so->so_iptos & IPTOS_LOWDELAY)) {\n\t\tifq = slirp->if_fastq.ifq_prev;\n\t\ton_fastq = 1;\n\t\t/*\n\t\t * Check if this packet is a part of the last\n\t\t * packet's session\n\t\t */\n\t\tif (ifq->ifq_so == so) {\n\t\t\tifm->ifq_so = so;\n\t\t\tifs_insque(ifm, ifq->ifs_prev);\n\t\t\tgoto diddit;\n\t\t}\n\t} else\n\t\tifq = slirp->if_batchq.ifq_prev;\n\n\t/* Create a new doubly linked list for this session */\n\tifm->ifq_so = so;\n\tifs_init(ifm);\n\tinsque(ifm, ifq);\n\ndiddit:\n\tslirp->if_queued++;\n\n\tif (so) {\n\t\t/* Update *_queued */\n\t\tso->so_queued++;\n\t\tso->so_nqueued++;\n\t\t/*\n\t\t * Check if the interactive session should be downgraded to\n\t\t * the batchq. A session is downgraded if it has queued 6\n\t\t * packets without pausing, and at least 3 of those packets\n\t\t * have been sent over the link\n\t\t * (XXX These are arbitrary numbers, probably not optimal..)\n\t\t */\n\t\tif (on_fastq && ((so->so_nqueued >= 6) &&\n\t\t\t\t (so->so_nqueued - so->so_queued) >= 3)) {\n\n\t\t\t/* Remove from current queue... */\n\t\t\tremque(ifm->ifs_next);\n\n\t\t\t/* ...And insert in the new. That'll teach ya! */\n\t\t\tinsque(ifm->ifs_next, &slirp->if_batchq);\n\t\t}\n\t}\n\n#ifndef FULL_BOLT\n\t/*\n\t * This prevents us from malloc()ing too many mbufs\n\t */\n\tif_start(ifm->slirp);\n#endif\n}\n\n/*\n * Send a packet\n * We choose a packet based on it's position in the output queues;\n * If there are packets on the fastq, they are sent FIFO, before\n * everything else. Otherwise we choose the first packet from the\n * batchq and send it. the next packet chosen will be from the session\n * after this one, then the session after that one, and so on.. So,\n * for example, if there are 3 ftp session's fighting for bandwidth,\n * one packet will be sent from the first session, then one packet\n * from the second session, then one packet from the third, then back\n * to the first, etc. etc.\n */\nvoid\nif_start(Slirp *slirp)\n{\n\tstruct mbuf *ifm, *ifqt;\n\n\tDEBUG_CALL(\"if_start\");\n\n\tif (slirp->if_queued == 0)\n\t return; /* Nothing to do */\n\n again:\n /* check if we can really output */\n if (!slirp_can_output(slirp->opaque))\n return;\n\n\t/*\n\t * See which queue to get next packet from\n\t * If there's something in the fastq, select it immediately\n\t */\n\tif (slirp->if_fastq.ifq_next != &slirp->if_fastq) {\n\t\tifm = slirp->if_fastq.ifq_next;\n\t} else {\n\t\t/* Nothing on fastq, see if next_m is valid */\n\t\tif (slirp->next_m != &slirp->if_batchq)\n\t\t ifm = slirp->next_m;\n\t\telse\n\t\t ifm = slirp->if_batchq.ifq_next;\n\n\t\t/* Set which packet to send on next iteration */\n\t\tslirp->next_m = ifm->ifq_next;\n\t}\n\t/* Remove it from the queue */\n\tifqt = ifm->ifq_prev;\n\tremque(ifm);\n\tslirp->if_queued--;\n\n\t/* If there are more packets for this session, re-queue them */\n\tif (ifm->ifs_next != /* ifm->ifs_prev != */ ifm) {\n\t\tinsque(ifm->ifs_next, ifqt);\n\t\tifs_remque(ifm);\n\t}\n\n\t/* Update so_queued */\n\tif (ifm->ifq_so) {\n\t\tif (--ifm->ifq_so->so_queued == 0)\n\t\t /* If there's no more queued, reset nqueued */\n\t\t ifm->ifq_so->so_nqueued = 0;\n\t}\n\n\t/* Encapsulate the packet for sending */\n if_encap(slirp, (uint8_t *)ifm->m_data, ifm->m_len);\n\n m_free(ifm);\n\n\tif (slirp->if_queued)\n\t goto again;\n}\n"], ["/linuxpdf/tinyemu/cutils.c", "/*\n * Misc C utilities\n * \n * Copyright (c) 2016-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n\nvoid *mallocz(size_t size)\n{\n void *ptr;\n ptr = malloc(size);\n if (!ptr)\n return NULL;\n memset(ptr, 0, size);\n return ptr;\n}\n\nvoid pstrcpy(char *buf, int buf_size, const char *str)\n{\n int c;\n char *q = buf;\n\n if (buf_size <= 0)\n return;\n\n for(;;) {\n c = *str++;\n if (c == 0 || q >= buf + buf_size - 1)\n break;\n *q++ = c;\n }\n *q = '\\0';\n}\n\nchar *pstrcat(char *buf, int buf_size, const char *s)\n{\n int len;\n len = strlen(buf);\n if (len < buf_size)\n pstrcpy(buf + len, buf_size - len, s);\n return buf;\n}\n\nint strstart(const char *str, const char *val, const char **ptr)\n{\n const char *p, *q;\n p = str;\n q = val;\n while (*q != '\\0') {\n if (*p != *q)\n return 0;\n p++;\n q++;\n }\n if (ptr)\n *ptr = p;\n return 1;\n}\n\nvoid dbuf_init(DynBuf *s)\n{\n memset(s, 0, sizeof(*s));\n}\n\nvoid dbuf_write(DynBuf *s, size_t offset, const uint8_t *data, size_t len)\n{\n size_t end, new_size;\n new_size = end = offset + len;\n if (new_size > s->allocated_size) {\n new_size = max_int(new_size, s->allocated_size * 3 / 2);\n s->buf = realloc(s->buf, new_size);\n s->allocated_size = new_size;\n }\n memcpy(s->buf + offset, data, len);\n if (end > s->size)\n s->size = end;\n}\n\nvoid dbuf_putc(DynBuf *s, uint8_t c)\n{\n dbuf_write(s, s->size, &c, 1);\n}\n\nvoid dbuf_putstr(DynBuf *s, const char *str)\n{\n dbuf_write(s, s->size, (const uint8_t *)str, strlen(str));\n}\n\nvoid dbuf_free(DynBuf *s)\n{\n free(s->buf);\n memset(s, 0, sizeof(*s));\n}\n"], ["/linuxpdf/tinyemu/aes.c", "/**\n *\n * aes.c - integrated in QEMU by Fabrice Bellard from the OpenSSL project.\n */\n/*\n * rijndael-alg-fst.c\n *\n * @version 3.0 (December 2000)\n *\n * Optimised ANSI C code for the Rijndael cipher (now AES)\n *\n * @author Vincent Rijmen \n * @author Antoon Bosselaers \n * @author Paulo Barreto \n *\n * This code is hereby placed in the public domain.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS\n * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n#include \n#include \n#include \"aes.h\"\n\n#ifndef NDEBUG\n#define NDEBUG\n#endif\n\n#include \n\ntypedef uint32_t u32;\ntypedef uint16_t u16;\ntypedef uint8_t u8;\n\n#define MAXKC (256/32)\n#define MAXKB (256/8)\n#define MAXNR 14\n\n/* This controls loop-unrolling in aes_core.c */\n#undef FULL_UNROLL\n# define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3]))\n# define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); }\n\n/*\nTe0[x] = S [x].[02, 01, 01, 03];\nTe1[x] = S [x].[03, 02, 01, 01];\nTe2[x] = S [x].[01, 03, 02, 01];\nTe3[x] = S [x].[01, 01, 03, 02];\nTe4[x] = S [x].[01, 01, 01, 01];\n\nTd0[x] = Si[x].[0e, 09, 0d, 0b];\nTd1[x] = Si[x].[0b, 0e, 09, 0d];\nTd2[x] = Si[x].[0d, 0b, 0e, 09];\nTd3[x] = Si[x].[09, 0d, 0b, 0e];\nTd4[x] = Si[x].[01, 01, 01, 01];\n*/\n\nstatic const u32 Te0[256] = {\n 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU,\n 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U,\n 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU,\n 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU,\n 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U,\n 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU,\n 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU,\n 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU,\n 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU,\n 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU,\n 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U,\n 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU,\n 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU,\n 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U,\n 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU,\n 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU,\n 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU,\n 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU,\n 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU,\n 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U,\n 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU,\n 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU,\n 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU,\n 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU,\n 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U,\n 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U,\n 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U,\n 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U,\n 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU,\n 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U,\n 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U,\n 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU,\n 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU,\n 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U,\n 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U,\n 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U,\n 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU,\n 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U,\n 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU,\n 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U,\n 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU,\n 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U,\n 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U,\n 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU,\n 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U,\n 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U,\n 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U,\n 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U,\n 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U,\n 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U,\n 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U,\n 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U,\n 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU,\n 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U,\n 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U,\n 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U,\n 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U,\n 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U,\n 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U,\n 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU,\n 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U,\n 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U,\n 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U,\n 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU,\n};\nstatic const u32 Te1[256] = {\n 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU,\n 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U,\n 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU,\n 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U,\n 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU,\n 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U,\n 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU,\n 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U,\n 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U,\n 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU,\n 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U,\n 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U,\n 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U,\n 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU,\n 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U,\n 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U,\n 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU,\n 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U,\n 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U,\n 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U,\n 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU,\n 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU,\n 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U,\n 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU,\n 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU,\n 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U,\n 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU,\n 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U,\n 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU,\n 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U,\n 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U,\n 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U,\n 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU,\n 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U,\n 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU,\n 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U,\n 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU,\n 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U,\n 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U,\n 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU,\n 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU,\n 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU,\n 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U,\n 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U,\n 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU,\n 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U,\n 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU,\n 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U,\n 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU,\n 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U,\n 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU,\n 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU,\n 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U,\n 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU,\n 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U,\n 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU,\n 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U,\n 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U,\n 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U,\n 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU,\n 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU,\n 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U,\n 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU,\n 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U,\n};\nstatic const u32 Te2[256] = {\n 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU,\n 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U,\n 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU,\n 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U,\n 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU,\n 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U,\n 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU,\n 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U,\n 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U,\n 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU,\n 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U,\n 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U,\n 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U,\n 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU,\n 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U,\n 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U,\n 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU,\n 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U,\n 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U,\n 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U,\n 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU,\n 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU,\n 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U,\n 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU,\n 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU,\n 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U,\n 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU,\n 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U,\n 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU,\n 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U,\n 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U,\n 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U,\n 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU,\n 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U,\n 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU,\n 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U,\n 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU,\n 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U,\n 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U,\n 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU,\n 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU,\n 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU,\n 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U,\n 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U,\n 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU,\n 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U,\n 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU,\n 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U,\n 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU,\n 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U,\n 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU,\n 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU,\n 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U,\n 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU,\n 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U,\n 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU,\n 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U,\n 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U,\n 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U,\n 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU,\n 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU,\n 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U,\n 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU,\n 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U,\n};\nstatic const u32 Te3[256] = {\n\n 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U,\n 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U,\n 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U,\n 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU,\n 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU,\n 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU,\n 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U,\n 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU,\n 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU,\n 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U,\n 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U,\n 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU,\n 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU,\n 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU,\n 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU,\n 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU,\n 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U,\n 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU,\n 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU,\n 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U,\n 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U,\n 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U,\n 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U,\n 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U,\n 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU,\n 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U,\n 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU,\n 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU,\n 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U,\n 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U,\n 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U,\n 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU,\n 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U,\n 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU,\n 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU,\n 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U,\n 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U,\n 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU,\n 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U,\n 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU,\n 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U,\n 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U,\n 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U,\n 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U,\n 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU,\n 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U,\n 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU,\n 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U,\n 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU,\n 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U,\n 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU,\n 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU,\n 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU,\n 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU,\n 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U,\n 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U,\n 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U,\n 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U,\n 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U,\n 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U,\n 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU,\n 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U,\n 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU,\n 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU,\n};\nstatic const u32 Te4[256] = {\n 0x63636363U, 0x7c7c7c7cU, 0x77777777U, 0x7b7b7b7bU,\n 0xf2f2f2f2U, 0x6b6b6b6bU, 0x6f6f6f6fU, 0xc5c5c5c5U,\n 0x30303030U, 0x01010101U, 0x67676767U, 0x2b2b2b2bU,\n 0xfefefefeU, 0xd7d7d7d7U, 0xababababU, 0x76767676U,\n 0xcacacacaU, 0x82828282U, 0xc9c9c9c9U, 0x7d7d7d7dU,\n 0xfafafafaU, 0x59595959U, 0x47474747U, 0xf0f0f0f0U,\n 0xadadadadU, 0xd4d4d4d4U, 0xa2a2a2a2U, 0xafafafafU,\n 0x9c9c9c9cU, 0xa4a4a4a4U, 0x72727272U, 0xc0c0c0c0U,\n 0xb7b7b7b7U, 0xfdfdfdfdU, 0x93939393U, 0x26262626U,\n 0x36363636U, 0x3f3f3f3fU, 0xf7f7f7f7U, 0xccccccccU,\n 0x34343434U, 0xa5a5a5a5U, 0xe5e5e5e5U, 0xf1f1f1f1U,\n 0x71717171U, 0xd8d8d8d8U, 0x31313131U, 0x15151515U,\n 0x04040404U, 0xc7c7c7c7U, 0x23232323U, 0xc3c3c3c3U,\n 0x18181818U, 0x96969696U, 0x05050505U, 0x9a9a9a9aU,\n 0x07070707U, 0x12121212U, 0x80808080U, 0xe2e2e2e2U,\n 0xebebebebU, 0x27272727U, 0xb2b2b2b2U, 0x75757575U,\n 0x09090909U, 0x83838383U, 0x2c2c2c2cU, 0x1a1a1a1aU,\n 0x1b1b1b1bU, 0x6e6e6e6eU, 0x5a5a5a5aU, 0xa0a0a0a0U,\n 0x52525252U, 0x3b3b3b3bU, 0xd6d6d6d6U, 0xb3b3b3b3U,\n 0x29292929U, 0xe3e3e3e3U, 0x2f2f2f2fU, 0x84848484U,\n 0x53535353U, 0xd1d1d1d1U, 0x00000000U, 0xededededU,\n 0x20202020U, 0xfcfcfcfcU, 0xb1b1b1b1U, 0x5b5b5b5bU,\n 0x6a6a6a6aU, 0xcbcbcbcbU, 0xbebebebeU, 0x39393939U,\n 0x4a4a4a4aU, 0x4c4c4c4cU, 0x58585858U, 0xcfcfcfcfU,\n 0xd0d0d0d0U, 0xefefefefU, 0xaaaaaaaaU, 0xfbfbfbfbU,\n 0x43434343U, 0x4d4d4d4dU, 0x33333333U, 0x85858585U,\n 0x45454545U, 0xf9f9f9f9U, 0x02020202U, 0x7f7f7f7fU,\n 0x50505050U, 0x3c3c3c3cU, 0x9f9f9f9fU, 0xa8a8a8a8U,\n 0x51515151U, 0xa3a3a3a3U, 0x40404040U, 0x8f8f8f8fU,\n 0x92929292U, 0x9d9d9d9dU, 0x38383838U, 0xf5f5f5f5U,\n 0xbcbcbcbcU, 0xb6b6b6b6U, 0xdadadadaU, 0x21212121U,\n 0x10101010U, 0xffffffffU, 0xf3f3f3f3U, 0xd2d2d2d2U,\n 0xcdcdcdcdU, 0x0c0c0c0cU, 0x13131313U, 0xececececU,\n 0x5f5f5f5fU, 0x97979797U, 0x44444444U, 0x17171717U,\n 0xc4c4c4c4U, 0xa7a7a7a7U, 0x7e7e7e7eU, 0x3d3d3d3dU,\n 0x64646464U, 0x5d5d5d5dU, 0x19191919U, 0x73737373U,\n 0x60606060U, 0x81818181U, 0x4f4f4f4fU, 0xdcdcdcdcU,\n 0x22222222U, 0x2a2a2a2aU, 0x90909090U, 0x88888888U,\n 0x46464646U, 0xeeeeeeeeU, 0xb8b8b8b8U, 0x14141414U,\n 0xdedededeU, 0x5e5e5e5eU, 0x0b0b0b0bU, 0xdbdbdbdbU,\n 0xe0e0e0e0U, 0x32323232U, 0x3a3a3a3aU, 0x0a0a0a0aU,\n 0x49494949U, 0x06060606U, 0x24242424U, 0x5c5c5c5cU,\n 0xc2c2c2c2U, 0xd3d3d3d3U, 0xacacacacU, 0x62626262U,\n 0x91919191U, 0x95959595U, 0xe4e4e4e4U, 0x79797979U,\n 0xe7e7e7e7U, 0xc8c8c8c8U, 0x37373737U, 0x6d6d6d6dU,\n 0x8d8d8d8dU, 0xd5d5d5d5U, 0x4e4e4e4eU, 0xa9a9a9a9U,\n 0x6c6c6c6cU, 0x56565656U, 0xf4f4f4f4U, 0xeaeaeaeaU,\n 0x65656565U, 0x7a7a7a7aU, 0xaeaeaeaeU, 0x08080808U,\n 0xbabababaU, 0x78787878U, 0x25252525U, 0x2e2e2e2eU,\n 0x1c1c1c1cU, 0xa6a6a6a6U, 0xb4b4b4b4U, 0xc6c6c6c6U,\n 0xe8e8e8e8U, 0xddddddddU, 0x74747474U, 0x1f1f1f1fU,\n 0x4b4b4b4bU, 0xbdbdbdbdU, 0x8b8b8b8bU, 0x8a8a8a8aU,\n 0x70707070U, 0x3e3e3e3eU, 0xb5b5b5b5U, 0x66666666U,\n 0x48484848U, 0x03030303U, 0xf6f6f6f6U, 0x0e0e0e0eU,\n 0x61616161U, 0x35353535U, 0x57575757U, 0xb9b9b9b9U,\n 0x86868686U, 0xc1c1c1c1U, 0x1d1d1d1dU, 0x9e9e9e9eU,\n 0xe1e1e1e1U, 0xf8f8f8f8U, 0x98989898U, 0x11111111U,\n 0x69696969U, 0xd9d9d9d9U, 0x8e8e8e8eU, 0x94949494U,\n 0x9b9b9b9bU, 0x1e1e1e1eU, 0x87878787U, 0xe9e9e9e9U,\n 0xcecececeU, 0x55555555U, 0x28282828U, 0xdfdfdfdfU,\n 0x8c8c8c8cU, 0xa1a1a1a1U, 0x89898989U, 0x0d0d0d0dU,\n 0xbfbfbfbfU, 0xe6e6e6e6U, 0x42424242U, 0x68686868U,\n 0x41414141U, 0x99999999U, 0x2d2d2d2dU, 0x0f0f0f0fU,\n 0xb0b0b0b0U, 0x54545454U, 0xbbbbbbbbU, 0x16161616U,\n};\nstatic const u32 Td0[256] = {\n 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U,\n 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U,\n 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U,\n 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU,\n 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U,\n 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U,\n 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU,\n 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U,\n 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU,\n 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U,\n 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U,\n 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U,\n 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U,\n 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU,\n 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U,\n 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU,\n 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U,\n 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU,\n 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U,\n 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U,\n 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U,\n 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU,\n 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U,\n 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU,\n 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U,\n 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU,\n 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U,\n 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU,\n 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU,\n 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U,\n 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU,\n 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U,\n 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU,\n 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U,\n 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U,\n 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U,\n 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU,\n 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U,\n 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U,\n 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU,\n 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U,\n 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U,\n 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U,\n 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U,\n 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U,\n 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU,\n 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U,\n 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U,\n 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U,\n 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U,\n 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U,\n 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU,\n 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU,\n 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU,\n 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU,\n 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U,\n 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U,\n 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU,\n 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU,\n 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U,\n 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU,\n 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U,\n 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U,\n 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U,\n};\nstatic const u32 Td1[256] = {\n 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU,\n 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U,\n 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU,\n 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U,\n 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U,\n 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U,\n 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U,\n 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U,\n 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U,\n 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU,\n 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU,\n 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU,\n 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U,\n 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU,\n 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U,\n 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U,\n 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U,\n 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU,\n 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU,\n 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U,\n 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU,\n 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U,\n 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU,\n 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU,\n 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U,\n 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U,\n 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U,\n 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU,\n 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U,\n 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU,\n 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U,\n 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U,\n 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U,\n 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU,\n 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U,\n 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U,\n 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U,\n 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U,\n 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U,\n 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U,\n 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU,\n 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU,\n 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U,\n 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU,\n 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U,\n 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU,\n 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU,\n 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U,\n 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU,\n 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U,\n 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U,\n 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U,\n 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U,\n 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U,\n 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U,\n 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U,\n 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU,\n 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U,\n 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U,\n 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU,\n 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U,\n 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U,\n 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U,\n 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U,\n};\nstatic const u32 Td2[256] = {\n 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U,\n 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U,\n 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U,\n 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U,\n 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU,\n 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U,\n 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U,\n 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U,\n 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U,\n 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU,\n 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U,\n 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U,\n 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU,\n 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U,\n 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U,\n 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U,\n 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U,\n 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U,\n 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U,\n 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU,\n\n 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U,\n 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U,\n 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U,\n 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U,\n 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U,\n 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU,\n 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU,\n 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U,\n 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU,\n 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U,\n 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU,\n 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU,\n 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU,\n 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU,\n 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U,\n 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U,\n 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U,\n 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U,\n 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U,\n 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U,\n 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U,\n 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU,\n 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU,\n 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U,\n 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U,\n 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU,\n 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU,\n 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U,\n 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U,\n 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U,\n 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U,\n 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U,\n 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U,\n 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U,\n 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU,\n 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U,\n 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U,\n 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U,\n 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U,\n 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U,\n 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U,\n 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU,\n 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U,\n 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U,\n};\nstatic const u32 Td3[256] = {\n 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU,\n 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU,\n 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U,\n 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U,\n 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU,\n 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU,\n 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U,\n 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU,\n 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U,\n 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU,\n 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U,\n 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U,\n 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U,\n 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U,\n 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U,\n 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU,\n 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU,\n 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U,\n 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U,\n 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU,\n 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU,\n 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U,\n 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U,\n 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U,\n 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U,\n 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU,\n 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U,\n 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U,\n 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU,\n 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU,\n 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U,\n 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U,\n 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U,\n 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU,\n 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U,\n 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U,\n 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U,\n 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U,\n 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U,\n 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U,\n 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U,\n 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU,\n 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U,\n 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U,\n 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU,\n 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU,\n 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U,\n 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU,\n 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U,\n 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U,\n 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U,\n 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U,\n 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U,\n 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U,\n 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU,\n 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU,\n 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU,\n 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU,\n 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U,\n 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U,\n 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U,\n 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU,\n 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U,\n 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U,\n};\nstatic const u32 Td4[256] = {\n 0x52525252U, 0x09090909U, 0x6a6a6a6aU, 0xd5d5d5d5U,\n 0x30303030U, 0x36363636U, 0xa5a5a5a5U, 0x38383838U,\n 0xbfbfbfbfU, 0x40404040U, 0xa3a3a3a3U, 0x9e9e9e9eU,\n 0x81818181U, 0xf3f3f3f3U, 0xd7d7d7d7U, 0xfbfbfbfbU,\n 0x7c7c7c7cU, 0xe3e3e3e3U, 0x39393939U, 0x82828282U,\n 0x9b9b9b9bU, 0x2f2f2f2fU, 0xffffffffU, 0x87878787U,\n 0x34343434U, 0x8e8e8e8eU, 0x43434343U, 0x44444444U,\n 0xc4c4c4c4U, 0xdedededeU, 0xe9e9e9e9U, 0xcbcbcbcbU,\n 0x54545454U, 0x7b7b7b7bU, 0x94949494U, 0x32323232U,\n 0xa6a6a6a6U, 0xc2c2c2c2U, 0x23232323U, 0x3d3d3d3dU,\n 0xeeeeeeeeU, 0x4c4c4c4cU, 0x95959595U, 0x0b0b0b0bU,\n 0x42424242U, 0xfafafafaU, 0xc3c3c3c3U, 0x4e4e4e4eU,\n 0x08080808U, 0x2e2e2e2eU, 0xa1a1a1a1U, 0x66666666U,\n 0x28282828U, 0xd9d9d9d9U, 0x24242424U, 0xb2b2b2b2U,\n 0x76767676U, 0x5b5b5b5bU, 0xa2a2a2a2U, 0x49494949U,\n 0x6d6d6d6dU, 0x8b8b8b8bU, 0xd1d1d1d1U, 0x25252525U,\n 0x72727272U, 0xf8f8f8f8U, 0xf6f6f6f6U, 0x64646464U,\n 0x86868686U, 0x68686868U, 0x98989898U, 0x16161616U,\n 0xd4d4d4d4U, 0xa4a4a4a4U, 0x5c5c5c5cU, 0xccccccccU,\n 0x5d5d5d5dU, 0x65656565U, 0xb6b6b6b6U, 0x92929292U,\n 0x6c6c6c6cU, 0x70707070U, 0x48484848U, 0x50505050U,\n 0xfdfdfdfdU, 0xededededU, 0xb9b9b9b9U, 0xdadadadaU,\n 0x5e5e5e5eU, 0x15151515U, 0x46464646U, 0x57575757U,\n 0xa7a7a7a7U, 0x8d8d8d8dU, 0x9d9d9d9dU, 0x84848484U,\n 0x90909090U, 0xd8d8d8d8U, 0xababababU, 0x00000000U,\n 0x8c8c8c8cU, 0xbcbcbcbcU, 0xd3d3d3d3U, 0x0a0a0a0aU,\n 0xf7f7f7f7U, 0xe4e4e4e4U, 0x58585858U, 0x05050505U,\n 0xb8b8b8b8U, 0xb3b3b3b3U, 0x45454545U, 0x06060606U,\n 0xd0d0d0d0U, 0x2c2c2c2cU, 0x1e1e1e1eU, 0x8f8f8f8fU,\n 0xcacacacaU, 0x3f3f3f3fU, 0x0f0f0f0fU, 0x02020202U,\n 0xc1c1c1c1U, 0xafafafafU, 0xbdbdbdbdU, 0x03030303U,\n 0x01010101U, 0x13131313U, 0x8a8a8a8aU, 0x6b6b6b6bU,\n 0x3a3a3a3aU, 0x91919191U, 0x11111111U, 0x41414141U,\n 0x4f4f4f4fU, 0x67676767U, 0xdcdcdcdcU, 0xeaeaeaeaU,\n 0x97979797U, 0xf2f2f2f2U, 0xcfcfcfcfU, 0xcecececeU,\n 0xf0f0f0f0U, 0xb4b4b4b4U, 0xe6e6e6e6U, 0x73737373U,\n 0x96969696U, 0xacacacacU, 0x74747474U, 0x22222222U,\n 0xe7e7e7e7U, 0xadadadadU, 0x35353535U, 0x85858585U,\n 0xe2e2e2e2U, 0xf9f9f9f9U, 0x37373737U, 0xe8e8e8e8U,\n 0x1c1c1c1cU, 0x75757575U, 0xdfdfdfdfU, 0x6e6e6e6eU,\n 0x47474747U, 0xf1f1f1f1U, 0x1a1a1a1aU, 0x71717171U,\n 0x1d1d1d1dU, 0x29292929U, 0xc5c5c5c5U, 0x89898989U,\n 0x6f6f6f6fU, 0xb7b7b7b7U, 0x62626262U, 0x0e0e0e0eU,\n 0xaaaaaaaaU, 0x18181818U, 0xbebebebeU, 0x1b1b1b1bU,\n 0xfcfcfcfcU, 0x56565656U, 0x3e3e3e3eU, 0x4b4b4b4bU,\n 0xc6c6c6c6U, 0xd2d2d2d2U, 0x79797979U, 0x20202020U,\n 0x9a9a9a9aU, 0xdbdbdbdbU, 0xc0c0c0c0U, 0xfefefefeU,\n 0x78787878U, 0xcdcdcdcdU, 0x5a5a5a5aU, 0xf4f4f4f4U,\n 0x1f1f1f1fU, 0xddddddddU, 0xa8a8a8a8U, 0x33333333U,\n 0x88888888U, 0x07070707U, 0xc7c7c7c7U, 0x31313131U,\n 0xb1b1b1b1U, 0x12121212U, 0x10101010U, 0x59595959U,\n 0x27272727U, 0x80808080U, 0xececececU, 0x5f5f5f5fU,\n 0x60606060U, 0x51515151U, 0x7f7f7f7fU, 0xa9a9a9a9U,\n 0x19191919U, 0xb5b5b5b5U, 0x4a4a4a4aU, 0x0d0d0d0dU,\n 0x2d2d2d2dU, 0xe5e5e5e5U, 0x7a7a7a7aU, 0x9f9f9f9fU,\n 0x93939393U, 0xc9c9c9c9U, 0x9c9c9c9cU, 0xefefefefU,\n 0xa0a0a0a0U, 0xe0e0e0e0U, 0x3b3b3b3bU, 0x4d4d4d4dU,\n 0xaeaeaeaeU, 0x2a2a2a2aU, 0xf5f5f5f5U, 0xb0b0b0b0U,\n 0xc8c8c8c8U, 0xebebebebU, 0xbbbbbbbbU, 0x3c3c3c3cU,\n 0x83838383U, 0x53535353U, 0x99999999U, 0x61616161U,\n 0x17171717U, 0x2b2b2b2bU, 0x04040404U, 0x7e7e7e7eU,\n 0xbabababaU, 0x77777777U, 0xd6d6d6d6U, 0x26262626U,\n 0xe1e1e1e1U, 0x69696969U, 0x14141414U, 0x63636363U,\n 0x55555555U, 0x21212121U, 0x0c0c0c0cU, 0x7d7d7d7dU,\n};\nstatic const u32 rcon[] = {\n\t0x01000000, 0x02000000, 0x04000000, 0x08000000,\n\t0x10000000, 0x20000000, 0x40000000, 0x80000000,\n\t0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */\n};\n\n/**\n * Expand the cipher key into the encryption key schedule.\n */\nint AES_set_encrypt_key(const unsigned char *userKey, const int bits,\n\t\t\tAES_KEY *key) {\n\n\tu32 *rk;\n \tint i = 0;\n\tu32 temp;\n\n\tif (!userKey || !key)\n\t\treturn -1;\n\tif (bits != 128 && bits != 192 && bits != 256)\n\t\treturn -2;\n\n\trk = key->rd_key;\n\n\tif (bits==128)\n\t\tkey->rounds = 10;\n\telse if (bits==192)\n\t\tkey->rounds = 12;\n\telse\n\t\tkey->rounds = 14;\n\n\trk[0] = GETU32(userKey );\n\trk[1] = GETU32(userKey + 4);\n\trk[2] = GETU32(userKey + 8);\n\trk[3] = GETU32(userKey + 12);\n\tif (bits == 128) {\n\t\twhile (1) {\n\t\t\ttemp = rk[3];\n\t\t\trk[4] = rk[0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[5] = rk[1] ^ rk[4];\n\t\t\trk[6] = rk[2] ^ rk[5];\n\t\t\trk[7] = rk[3] ^ rk[6];\n\t\t\tif (++i == 10) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\trk += 4;\n\t\t}\n\t}\n\trk[4] = GETU32(userKey + 16);\n\trk[5] = GETU32(userKey + 20);\n\tif (bits == 192) {\n\t\twhile (1) {\n\t\t\ttemp = rk[ 5];\n\t\t\trk[ 6] = rk[ 0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[ 7] = rk[ 1] ^ rk[ 6];\n\t\t\trk[ 8] = rk[ 2] ^ rk[ 7];\n\t\t\trk[ 9] = rk[ 3] ^ rk[ 8];\n\t\t\tif (++i == 8) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\trk[10] = rk[ 4] ^ rk[ 9];\n\t\t\trk[11] = rk[ 5] ^ rk[10];\n\t\t\trk += 6;\n\t\t}\n\t}\n\trk[6] = GETU32(userKey + 24);\n\trk[7] = GETU32(userKey + 28);\n\tif (bits == 256) {\n\t\twhile (1) {\n\t\t\ttemp = rk[ 7];\n\t\t\trk[ 8] = rk[ 0] ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0x000000ff) ^\n\t\t\t\trcon[i];\n\t\t\trk[ 9] = rk[ 1] ^ rk[ 8];\n\t\t\trk[10] = rk[ 2] ^ rk[ 9];\n\t\t\trk[11] = rk[ 3] ^ rk[10];\n\t\t\tif (++i == 7) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\ttemp = rk[11];\n\t\t\trk[12] = rk[ 4] ^\n\t\t\t\t(Te4[(temp >> 24) ] & 0xff000000) ^\n\t\t\t\t(Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^\n\t\t\t\t(Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^\n\t\t\t\t(Te4[(temp ) & 0xff] & 0x000000ff);\n\t\t\trk[13] = rk[ 5] ^ rk[12];\n\t\t\trk[14] = rk[ 6] ^ rk[13];\n\t\t\trk[15] = rk[ 7] ^ rk[14];\n\n\t\t\trk += 8;\n \t}\n\t}\n\treturn 0;\n}\n\n/**\n * Expand the cipher key into the decryption key schedule.\n */\nint AES_set_decrypt_key(const unsigned char *userKey, const int bits,\n\t\t\t AES_KEY *key) {\n\n u32 *rk;\n\tint i, j, status;\n\tu32 temp;\n\n\t/* first, start with an encryption schedule */\n\tstatus = AES_set_encrypt_key(userKey, bits, key);\n\tif (status < 0)\n\t\treturn status;\n\n\trk = key->rd_key;\n\n\t/* invert the order of the round keys: */\n\tfor (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) {\n\t\ttemp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp;\n\t\ttemp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;\n\t\ttemp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;\n\t\ttemp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;\n\t}\n\t/* apply the inverse MixColumn transform to all round keys but the first and the last: */\n\tfor (i = 1; i < (key->rounds); i++) {\n\t\trk += 4;\n\t\trk[0] =\n\t\t\tTd0[Te4[(rk[0] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[0] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[0] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[0] ) & 0xff] & 0xff];\n\t\trk[1] =\n\t\t\tTd0[Te4[(rk[1] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[1] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[1] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[1] ) & 0xff] & 0xff];\n\t\trk[2] =\n\t\t\tTd0[Te4[(rk[2] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[2] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[2] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[2] ) & 0xff] & 0xff];\n\t\trk[3] =\n\t\t\tTd0[Te4[(rk[3] >> 24) ] & 0xff] ^\n\t\t\tTd1[Te4[(rk[3] >> 16) & 0xff] & 0xff] ^\n\t\t\tTd2[Te4[(rk[3] >> 8) & 0xff] & 0xff] ^\n\t\t\tTd3[Te4[(rk[3] ) & 0xff] & 0xff];\n\t}\n\treturn 0;\n}\n\n#ifndef AES_ASM\n/*\n * Encrypt a single block\n * in and out can overlap\n */\nvoid AES_encrypt(const unsigned char *in, unsigned char *out,\n\t\t const AES_KEY *key) {\n\n\tconst u32 *rk;\n\tu32 s0, s1, s2, s3, t0, t1, t2, t3;\n#ifndef FULL_UNROLL\n\tint r;\n#endif /* ?FULL_UNROLL */\n\n\tassert(in && out && key);\n\trk = key->rd_key;\n\n\t/*\n\t * map byte array block to cipher state\n\t * and add initial round key:\n\t */\n\ts0 = GETU32(in ) ^ rk[0];\n\ts1 = GETU32(in + 4) ^ rk[1];\n\ts2 = GETU32(in + 8) ^ rk[2];\n\ts3 = GETU32(in + 12) ^ rk[3];\n#ifdef FULL_UNROLL\n\t/* round 1: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7];\n \t/* round 2: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11];\n\t/* round 3: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15];\n \t/* round 4: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19];\n\t/* round 5: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23];\n \t/* round 6: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27];\n\t/* round 7: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31];\n \t/* round 8: */\n \ts0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32];\n \ts1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33];\n \ts2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34];\n \ts3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35];\n\t/* round 9: */\n \tt0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36];\n \tt1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37];\n \tt2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38];\n \tt3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39];\n if (key->rounds > 10) {\n /* round 10: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43];\n /* round 11: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47];\n if (key->rounds > 12) {\n /* round 12: */\n s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48];\n s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49];\n s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50];\n s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51];\n /* round 13: */\n t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52];\n t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53];\n t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54];\n t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55];\n }\n }\n rk += key->rounds << 2;\n#else /* !FULL_UNROLL */\n /*\n * Nr - 1 full rounds:\n */\n r = key->rounds >> 1;\n for (;;) {\n t0 =\n Te0[(s0 >> 24) ] ^\n Te1[(s1 >> 16) & 0xff] ^\n Te2[(s2 >> 8) & 0xff] ^\n Te3[(s3 ) & 0xff] ^\n rk[4];\n t1 =\n Te0[(s1 >> 24) ] ^\n Te1[(s2 >> 16) & 0xff] ^\n Te2[(s3 >> 8) & 0xff] ^\n Te3[(s0 ) & 0xff] ^\n rk[5];\n t2 =\n Te0[(s2 >> 24) ] ^\n Te1[(s3 >> 16) & 0xff] ^\n Te2[(s0 >> 8) & 0xff] ^\n Te3[(s1 ) & 0xff] ^\n rk[6];\n t3 =\n Te0[(s3 >> 24) ] ^\n Te1[(s0 >> 16) & 0xff] ^\n Te2[(s1 >> 8) & 0xff] ^\n Te3[(s2 ) & 0xff] ^\n rk[7];\n\n rk += 8;\n if (--r == 0) {\n break;\n }\n\n s0 =\n Te0[(t0 >> 24) ] ^\n Te1[(t1 >> 16) & 0xff] ^\n Te2[(t2 >> 8) & 0xff] ^\n Te3[(t3 ) & 0xff] ^\n rk[0];\n s1 =\n Te0[(t1 >> 24) ] ^\n Te1[(t2 >> 16) & 0xff] ^\n Te2[(t3 >> 8) & 0xff] ^\n Te3[(t0 ) & 0xff] ^\n rk[1];\n s2 =\n Te0[(t2 >> 24) ] ^\n Te1[(t3 >> 16) & 0xff] ^\n Te2[(t0 >> 8) & 0xff] ^\n Te3[(t1 ) & 0xff] ^\n rk[2];\n s3 =\n Te0[(t3 >> 24) ] ^\n Te1[(t0 >> 16) & 0xff] ^\n Te2[(t1 >> 8) & 0xff] ^\n Te3[(t2 ) & 0xff] ^\n rk[3];\n }\n#endif /* ?FULL_UNROLL */\n /*\n\t * apply last round and\n\t * map cipher state to byte array block:\n\t */\n\ts0 =\n\t\t(Te4[(t0 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t3 ) & 0xff] & 0x000000ff) ^\n\t\trk[0];\n\tPUTU32(out , s0);\n\ts1 =\n\t\t(Te4[(t1 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t0 ) & 0xff] & 0x000000ff) ^\n\t\trk[1];\n\tPUTU32(out + 4, s1);\n\ts2 =\n\t\t(Te4[(t2 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t1 ) & 0xff] & 0x000000ff) ^\n\t\trk[2];\n\tPUTU32(out + 8, s2);\n\ts3 =\n\t\t(Te4[(t3 >> 24) ] & 0xff000000) ^\n\t\t(Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^\n\t\t(Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^\n\t\t(Te4[(t2 ) & 0xff] & 0x000000ff) ^\n\t\trk[3];\n\tPUTU32(out + 12, s3);\n}\n\n/*\n * Decrypt a single block\n * in and out can overlap\n */\nvoid AES_decrypt(const unsigned char *in, unsigned char *out,\n\t\t const AES_KEY *key) {\n\n\tconst u32 *rk;\n\tu32 s0, s1, s2, s3, t0, t1, t2, t3;\n#ifndef FULL_UNROLL\n\tint r;\n#endif /* ?FULL_UNROLL */\n\n\tassert(in && out && key);\n\trk = key->rd_key;\n\n\t/*\n\t * map byte array block to cipher state\n\t * and add initial round key:\n\t */\n s0 = GETU32(in ) ^ rk[0];\n s1 = GETU32(in + 4) ^ rk[1];\n s2 = GETU32(in + 8) ^ rk[2];\n s3 = GETU32(in + 12) ^ rk[3];\n#ifdef FULL_UNROLL\n /* round 1: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[ 4];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[ 5];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[ 6];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[ 7];\n /* round 2: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[ 8];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[ 9];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11];\n /* round 3: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15];\n /* round 4: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19];\n /* round 5: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23];\n /* round 6: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27];\n /* round 7: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31];\n /* round 8: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35];\n /* round 9: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39];\n if (key->rounds > 10) {\n /* round 10: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43];\n /* round 11: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47];\n if (key->rounds > 12) {\n /* round 12: */\n s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48];\n s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49];\n s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50];\n s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51];\n /* round 13: */\n t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52];\n t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53];\n t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54];\n t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55];\n }\n }\n\trk += key->rounds << 2;\n#else /* !FULL_UNROLL */\n /*\n * Nr - 1 full rounds:\n */\n r = key->rounds >> 1;\n for (;;) {\n t0 =\n Td0[(s0 >> 24) ] ^\n Td1[(s3 >> 16) & 0xff] ^\n Td2[(s2 >> 8) & 0xff] ^\n Td3[(s1 ) & 0xff] ^\n rk[4];\n t1 =\n Td0[(s1 >> 24) ] ^\n Td1[(s0 >> 16) & 0xff] ^\n Td2[(s3 >> 8) & 0xff] ^\n Td3[(s2 ) & 0xff] ^\n rk[5];\n t2 =\n Td0[(s2 >> 24) ] ^\n Td1[(s1 >> 16) & 0xff] ^\n Td2[(s0 >> 8) & 0xff] ^\n Td3[(s3 ) & 0xff] ^\n rk[6];\n t3 =\n Td0[(s3 >> 24) ] ^\n Td1[(s2 >> 16) & 0xff] ^\n Td2[(s1 >> 8) & 0xff] ^\n Td3[(s0 ) & 0xff] ^\n rk[7];\n\n rk += 8;\n if (--r == 0) {\n break;\n }\n\n s0 =\n Td0[(t0 >> 24) ] ^\n Td1[(t3 >> 16) & 0xff] ^\n Td2[(t2 >> 8) & 0xff] ^\n Td3[(t1 ) & 0xff] ^\n rk[0];\n s1 =\n Td0[(t1 >> 24) ] ^\n Td1[(t0 >> 16) & 0xff] ^\n Td2[(t3 >> 8) & 0xff] ^\n Td3[(t2 ) & 0xff] ^\n rk[1];\n s2 =\n Td0[(t2 >> 24) ] ^\n Td1[(t1 >> 16) & 0xff] ^\n Td2[(t0 >> 8) & 0xff] ^\n Td3[(t3 ) & 0xff] ^\n rk[2];\n s3 =\n Td0[(t3 >> 24) ] ^\n Td1[(t2 >> 16) & 0xff] ^\n Td2[(t1 >> 8) & 0xff] ^\n Td3[(t0 ) & 0xff] ^\n rk[3];\n }\n#endif /* ?FULL_UNROLL */\n /*\n\t * apply last round and\n\t * map cipher state to byte array block:\n\t */\n \ts0 =\n \t\t(Td4[(t0 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t3 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t2 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t1 ) & 0xff] & 0x000000ff) ^\n \t\trk[0];\n\tPUTU32(out , s0);\n \ts1 =\n \t\t(Td4[(t1 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t0 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t3 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t2 ) & 0xff] & 0x000000ff) ^\n \t\trk[1];\n\tPUTU32(out + 4, s1);\n \ts2 =\n \t\t(Td4[(t2 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t1 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t0 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t3 ) & 0xff] & 0x000000ff) ^\n \t\trk[2];\n\tPUTU32(out + 8, s2);\n \ts3 =\n \t\t(Td4[(t3 >> 24) ] & 0xff000000) ^\n \t\t(Td4[(t2 >> 16) & 0xff] & 0x00ff0000) ^\n \t\t(Td4[(t1 >> 8) & 0xff] & 0x0000ff00) ^\n \t\t(Td4[(t0 ) & 0xff] & 0x000000ff) ^\n \t\trk[3];\n\tPUTU32(out + 12, s3);\n}\n\n#endif /* AES_ASM */\n\nvoid AES_cbc_encrypt(const unsigned char *in, unsigned char *out,\n\t\t const unsigned long length, const AES_KEY *key,\n\t\t unsigned char *ivec, const int enc)\n{\n\n\tunsigned long n;\n\tunsigned long len = length;\n\tunsigned char tmp[AES_BLOCK_SIZE];\n\n\tassert(in && out && key && ivec);\n\n\tif (enc) {\n\t\twhile (len >= AES_BLOCK_SIZE) {\n\t\t\tfor(n=0; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\ttmp[n] = in[n] ^ ivec[n];\n\t\t\tAES_encrypt(tmp, out, key);\n\t\t\tmemcpy(ivec, out, AES_BLOCK_SIZE);\n\t\t\tlen -= AES_BLOCK_SIZE;\n\t\t\tin += AES_BLOCK_SIZE;\n\t\t\tout += AES_BLOCK_SIZE;\n\t\t}\n\t\tif (len) {\n\t\t\tfor(n=0; n < len; ++n)\n\t\t\t\ttmp[n] = in[n] ^ ivec[n];\n\t\t\tfor(n=len; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\ttmp[n] = ivec[n];\n\t\t\tAES_encrypt(tmp, tmp, key);\n\t\t\tmemcpy(out, tmp, AES_BLOCK_SIZE);\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t}\n\t} else {\n\t\twhile (len >= AES_BLOCK_SIZE) {\n\t\t\tmemcpy(tmp, in, AES_BLOCK_SIZE);\n\t\t\tAES_decrypt(in, out, key);\n\t\t\tfor(n=0; n < AES_BLOCK_SIZE; ++n)\n\t\t\t\tout[n] ^= ivec[n];\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t\tlen -= AES_BLOCK_SIZE;\n\t\t\tin += AES_BLOCK_SIZE;\n\t\t\tout += AES_BLOCK_SIZE;\n\t\t}\n\t\tif (len) {\n\t\t\tmemcpy(tmp, in, AES_BLOCK_SIZE);\n\t\t\tAES_decrypt(tmp, tmp, key);\n\t\t\tfor(n=0; n < len; ++n)\n\t\t\t\tout[n] = tmp[n] ^ ivec[n];\n\t\t\tmemcpy(ivec, tmp, AES_BLOCK_SIZE);\n\t\t}\n\t}\n}\n"], ["/linuxpdf/tinyemu/slirp/ip_output.c", "/*\n * Copyright (c) 1982, 1986, 1988, 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)ip_output.c\t8.3 (Berkeley) 1/21/94\n * ip_output.c,v 1.9 1994/11/16 10:17:10 jkh Exp\n */\n\n/*\n * Changes and additions relating to SLiRP are\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\n/* Number of packets queued before we start sending\n * (to prevent allocing too many mbufs) */\n#define IF_THRESH 10\n\n/*\n * IP output. The packet in mbuf chain m contains a skeletal IP\n * header (with len, off, ttl, proto, tos, src, dst).\n * The mbuf chain containing the packet will be freed.\n * The mbuf opt, if present, will not be freed.\n */\nint\nip_output(struct socket *so, struct mbuf *m0)\n{\n\tSlirp *slirp = m0->slirp;\n\tregister struct ip *ip;\n\tregister struct mbuf *m = m0;\n\tregister int hlen = sizeof(struct ip );\n\tint len, off, error = 0;\n\n\tDEBUG_CALL(\"ip_output\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m0 = %lx\", (long)m0);\n\n\tip = mtod(m, struct ip *);\n\t/*\n\t * Fill in IP header.\n\t */\n\tip->ip_v = IPVERSION;\n\tip->ip_off &= IP_DF;\n\tip->ip_id = htons(slirp->ip_id++);\n\tip->ip_hl = hlen >> 2;\n\n\t/*\n\t * If small enough for interface, can just send directly.\n\t */\n\tif ((uint16_t)ip->ip_len <= IF_MTU) {\n\t\tip->ip_len = htons((uint16_t)ip->ip_len);\n\t\tip->ip_off = htons((uint16_t)ip->ip_off);\n\t\tip->ip_sum = 0;\n\t\tip->ip_sum = cksum(m, hlen);\n\n\t\tif_output(so, m);\n\t\tgoto done;\n\t}\n\n\t/*\n\t * Too large for interface; fragment if possible.\n\t * Must be able to put at least 8 bytes per fragment.\n\t */\n\tif (ip->ip_off & IP_DF) {\n\t\terror = -1;\n\t\tgoto bad;\n\t}\n\n\tlen = (IF_MTU - hlen) &~ 7; /* ip databytes per packet */\n\tif (len < 8) {\n\t\terror = -1;\n\t\tgoto bad;\n\t}\n\n {\n\tint mhlen, firstlen = len;\n\tstruct mbuf **mnext = &m->m_nextpkt;\n\n\t/*\n\t * Loop through length of segment after first fragment,\n\t * make new header and copy data of each part and link onto chain.\n\t */\n\tm0 = m;\n\tmhlen = sizeof (struct ip);\n\tfor (off = hlen + len; off < (uint16_t)ip->ip_len; off += len) {\n\t register struct ip *mhip;\n\t m = m_get(slirp);\n if (m == NULL) {\n\t error = -1;\n\t goto sendorfree;\n\t }\n\t m->m_data += IF_MAXLINKHDR;\n\t mhip = mtod(m, struct ip *);\n\t *mhip = *ip;\n\n\t m->m_len = mhlen;\n\t mhip->ip_off = ((off - hlen) >> 3) + (ip->ip_off & ~IP_MF);\n\t if (ip->ip_off & IP_MF)\n\t mhip->ip_off |= IP_MF;\n\t if (off + len >= (uint16_t)ip->ip_len)\n\t len = (uint16_t)ip->ip_len - off;\n\t else\n\t mhip->ip_off |= IP_MF;\n\t mhip->ip_len = htons((uint16_t)(len + mhlen));\n\n\t if (m_copy(m, m0, off, len) < 0) {\n\t error = -1;\n\t goto sendorfree;\n\t }\n\n\t mhip->ip_off = htons((uint16_t)mhip->ip_off);\n\t mhip->ip_sum = 0;\n\t mhip->ip_sum = cksum(m, mhlen);\n\t *mnext = m;\n\t mnext = &m->m_nextpkt;\n\t}\n\t/*\n\t * Update first fragment by trimming what's been copied out\n\t * and updating header, then send each fragment (in order).\n\t */\n\tm = m0;\n\tm_adj(m, hlen + firstlen - (uint16_t)ip->ip_len);\n\tip->ip_len = htons((uint16_t)m->m_len);\n\tip->ip_off = htons((uint16_t)(ip->ip_off | IP_MF));\n\tip->ip_sum = 0;\n\tip->ip_sum = cksum(m, hlen);\nsendorfree:\n\tfor (m = m0; m; m = m0) {\n\t\tm0 = m->m_nextpkt;\n m->m_nextpkt = NULL;\n\t\tif (error == 0)\n\t\t\tif_output(so, m);\n\t\telse\n\t\t\tm_freem(m);\n\t}\n }\n\ndone:\n\treturn (error);\n\nbad:\n\tm_freem(m0);\n\tgoto done;\n}\n"], ["/linuxpdf/tinyemu/slirp/sbuf.c", "/*\n * Copyright (c) 1995 Danny Gasparovski.\n *\n * Please read the file COPYRIGHT for the\n * terms and conditions of the copyright.\n */\n\n#include \"slirp.h\"\n\nstatic void sbappendsb(struct sbuf *sb, struct mbuf *m);\n\nvoid\nsbfree(struct sbuf *sb)\n{\n\tfree(sb->sb_data);\n}\n\nvoid\nsbdrop(struct sbuf *sb, int num)\n{\n\t/*\n\t * We can only drop how much we have\n\t * This should never succeed\n\t */\n\tif(num > sb->sb_cc)\n\t\tnum = sb->sb_cc;\n\tsb->sb_cc -= num;\n\tsb->sb_rptr += num;\n\tif(sb->sb_rptr >= sb->sb_data + sb->sb_datalen)\n\t\tsb->sb_rptr -= sb->sb_datalen;\n\n}\n\nvoid\nsbreserve(struct sbuf *sb, int size)\n{\n\tif (sb->sb_data) {\n\t\t/* Already alloced, realloc if necessary */\n\t\tif (sb->sb_datalen != size) {\n\t\t\tsb->sb_wptr = sb->sb_rptr = sb->sb_data = (char *)realloc(sb->sb_data, size);\n\t\t\tsb->sb_cc = 0;\n\t\t\tif (sb->sb_wptr)\n\t\t\t sb->sb_datalen = size;\n\t\t\telse\n\t\t\t sb->sb_datalen = 0;\n\t\t}\n\t} else {\n\t\tsb->sb_wptr = sb->sb_rptr = sb->sb_data = (char *)malloc(size);\n\t\tsb->sb_cc = 0;\n\t\tif (sb->sb_wptr)\n\t\t sb->sb_datalen = size;\n\t\telse\n\t\t sb->sb_datalen = 0;\n\t}\n}\n\n/*\n * Try and write() to the socket, whatever doesn't get written\n * append to the buffer... for a host with a fast net connection,\n * this prevents an unnecessary copy of the data\n * (the socket is non-blocking, so we won't hang)\n */\nvoid\nsbappend(struct socket *so, struct mbuf *m)\n{\n\tint ret = 0;\n\n\tDEBUG_CALL(\"sbappend\");\n\tDEBUG_ARG(\"so = %lx\", (long)so);\n\tDEBUG_ARG(\"m = %lx\", (long)m);\n\tDEBUG_ARG(\"m->m_len = %d\", m->m_len);\n\n\t/* Shouldn't happen, but... e.g. foreign host closes connection */\n\tif (m->m_len <= 0) {\n\t\tm_free(m);\n\t\treturn;\n\t}\n\n\t/*\n\t * If there is urgent data, call sosendoob\n\t * if not all was sent, sowrite will take care of the rest\n\t * (The rest of this function is just an optimisation)\n\t */\n\tif (so->so_urgc) {\n\t\tsbappendsb(&so->so_rcv, m);\n\t\tm_free(m);\n\t\tsosendoob(so);\n\t\treturn;\n\t}\n\n\t/*\n\t * We only write if there's nothing in the buffer,\n\t * ottherwise it'll arrive out of order, and hence corrupt\n\t */\n\tif (!so->so_rcv.sb_cc)\n\t ret = slirp_send(so, m->m_data, m->m_len, 0);\n\n\tif (ret <= 0) {\n\t\t/*\n\t\t * Nothing was written\n\t\t * It's possible that the socket has closed, but\n\t\t * we don't need to check because if it has closed,\n\t\t * it will be detected in the normal way by soread()\n\t\t */\n\t\tsbappendsb(&so->so_rcv, m);\n\t} else if (ret != m->m_len) {\n\t\t/*\n\t\t * Something was written, but not everything..\n\t\t * sbappendsb the rest\n\t\t */\n\t\tm->m_len -= ret;\n\t\tm->m_data += ret;\n\t\tsbappendsb(&so->so_rcv, m);\n\t} /* else */\n\t/* Whatever happened, we free the mbuf */\n\tm_free(m);\n}\n\n/*\n * Copy the data from m into sb\n * The caller is responsible to make sure there's enough room\n */\nstatic void\nsbappendsb(struct sbuf *sb, struct mbuf *m)\n{\n\tint len, n, nn;\n\n\tlen = m->m_len;\n\n\tif (sb->sb_wptr < sb->sb_rptr) {\n\t\tn = sb->sb_rptr - sb->sb_wptr;\n\t\tif (n > len) n = len;\n\t\tmemcpy(sb->sb_wptr, m->m_data, n);\n\t} else {\n\t\t/* Do the right edge first */\n\t\tn = sb->sb_data + sb->sb_datalen - sb->sb_wptr;\n\t\tif (n > len) n = len;\n\t\tmemcpy(sb->sb_wptr, m->m_data, n);\n\t\tlen -= n;\n\t\tif (len) {\n\t\t\t/* Now the left edge */\n\t\t\tnn = sb->sb_rptr - sb->sb_data;\n\t\t\tif (nn > len) nn = len;\n\t\t\tmemcpy(sb->sb_data,m->m_data+n,nn);\n\t\t\tn += nn;\n\t\t}\n\t}\n\n\tsb->sb_cc += n;\n\tsb->sb_wptr += n;\n\tif (sb->sb_wptr >= sb->sb_data + sb->sb_datalen)\n\t\tsb->sb_wptr -= sb->sb_datalen;\n}\n\n/*\n * Copy data from sbuf to a normal, straight buffer\n * Don't update the sbuf rptr, this will be\n * done in sbdrop when the data is acked\n */\nvoid\nsbcopy(struct sbuf *sb, int off, int len, char *to)\n{\n\tchar *from;\n\n\tfrom = sb->sb_rptr + off;\n\tif (from >= sb->sb_data + sb->sb_datalen)\n\t\tfrom -= sb->sb_datalen;\n\n\tif (from < sb->sb_wptr) {\n\t\tif (len > sb->sb_cc) len = sb->sb_cc;\n\t\tmemcpy(to,from,len);\n\t} else {\n\t\t/* re-use off */\n\t\toff = (sb->sb_data + sb->sb_datalen) - from;\n\t\tif (off > len) off = len;\n\t\tmemcpy(to,from,off);\n\t\tlen -= off;\n\t\tif (len)\n\t\t memcpy(to+off,sb->sb_data,len);\n\t}\n}\n"], ["/linuxpdf/tinyemu/slirp/cksum.c", "/*\n * Copyright (c) 1988, 1992, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)in_cksum.c\t8.1 (Berkeley) 6/10/93\n * in_cksum.c,v 1.2 1994/08/02 07:48:16 davidg Exp\n */\n\n#include \"slirp.h\"\n\n/*\n * Checksum routine for Internet Protocol family headers (Portable Version).\n *\n * This routine is very heavily used in the network\n * code and should be modified for each CPU to be as fast as possible.\n *\n * XXX Since we will never span more than 1 mbuf, we can optimise this\n */\n\n#define ADDCARRY(x) (x > 65535 ? x -= 65535 : x)\n#define REDUCE {l_util.l = sum; sum = l_util.s[0] + l_util.s[1]; \\\n (void)ADDCARRY(sum);}\n\nint cksum(struct mbuf *m, int len)\n{\n\tregister uint16_t *w;\n\tregister int sum = 0;\n\tregister int mlen = 0;\n\tint byte_swapped = 0;\n\n\tunion {\n\t\tuint8_t c[2];\n\t\tuint16_t s;\n\t} s_util;\n\tunion {\n\t\tuint16_t s[2];\n\t\tuint32_t l;\n\t} l_util;\n\n\tif (m->m_len == 0)\n\t goto cont;\n\tw = mtod(m, uint16_t *);\n\n\tmlen = m->m_len;\n\n\tif (len < mlen)\n\t mlen = len;\n#ifdef DEBUG\n\tlen -= mlen;\n#endif\n\t/*\n\t * Force to even boundary.\n\t */\n\tif ((1 & (long) w) && (mlen > 0)) {\n\t\tREDUCE;\n\t\tsum <<= 8;\n\t\ts_util.c[0] = *(uint8_t *)w;\n\t\tw = (uint16_t *)((int8_t *)w + 1);\n\t\tmlen--;\n\t\tbyte_swapped = 1;\n\t}\n\t/*\n\t * Unroll the loop to make overhead from\n\t * branches &c small.\n\t */\n\twhile ((mlen -= 32) >= 0) {\n\t\tsum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];\n\t\tsum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];\n\t\tsum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];\n\t\tsum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];\n\t\tw += 16;\n\t}\n\tmlen += 32;\n\twhile ((mlen -= 8) >= 0) {\n\t\tsum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];\n\t\tw += 4;\n\t}\n\tmlen += 8;\n\tif (mlen == 0 && byte_swapped == 0)\n\t goto cont;\n\tREDUCE;\n\twhile ((mlen -= 2) >= 0) {\n\t\tsum += *w++;\n\t}\n\n\tif (byte_swapped) {\n\t\tREDUCE;\n\t\tsum <<= 8;\n\t\tif (mlen == -1) {\n\t\t\ts_util.c[1] = *(uint8_t *)w;\n\t\t\tsum += s_util.s;\n\t\t\tmlen = 0;\n\t\t} else\n\n\t\t mlen = -1;\n\t} else if (mlen == -1)\n\t s_util.c[0] = *(uint8_t *)w;\n\ncont:\n#ifdef DEBUG\n\tif (len) {\n\t\tDEBUG_ERROR((dfd, \"cksum: out of data\\n\"));\n\t\tDEBUG_ERROR((dfd, \" len = %d\\n\", len));\n\t}\n#endif\n\tif (mlen == -1) {\n\t\t/* The last mbuf has odd # of bytes. Follow the\n\t\t standard (the odd byte may be shifted left by 8 bits\n\t\t\t or not as determined by endian-ness of the machine) */\n\t\ts_util.c[1] = 0;\n\t\tsum += s_util.s;\n\t}\n\tREDUCE;\n\treturn (~sum & 0xffff);\n}\n"], ["/linuxpdf/tinyemu/x86_cpu.c", "/*\n * x86 CPU emulator stub\n * \n * Copyright (c) 2011-2017 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"x86_cpu.h\"\n\nX86CPUState *x86_cpu_init(PhysMemoryMap *mem_map)\n{\n fprintf(stderr, \"x86 emulator is not supported\\n\");\n exit(1);\n}\n\nvoid x86_cpu_end(X86CPUState *s)\n{\n}\n\nvoid x86_cpu_interp(X86CPUState *s, int max_cycles1)\n{\n}\n\nvoid x86_cpu_set_irq(X86CPUState *s, BOOL set)\n{\n}\n\nvoid x86_cpu_set_reg(X86CPUState *s, int reg, uint32_t val)\n{\n}\n\nuint32_t x86_cpu_get_reg(X86CPUState *s, int reg)\n{\n return 0;\n}\n\nvoid x86_cpu_set_seg(X86CPUState *s, int seg, const X86CPUSeg *sd)\n{\n}\n\nvoid x86_cpu_set_get_hard_intno(X86CPUState *s,\n int (*get_hard_intno)(void *opaque),\n void *opaque)\n{\n}\n\nvoid x86_cpu_set_get_tsc(X86CPUState *s,\n uint64_t (*get_tsc)(void *opaque),\n void *opaque)\n{\n}\n\nvoid x86_cpu_set_port_io(X86CPUState *s, \n DeviceReadFunc *port_read, DeviceWriteFunc *port_write,\n void *opaque)\n{\n}\n\nint64_t x86_cpu_get_cycles(X86CPUState *s)\n{\n return 0;\n}\n\nBOOL x86_cpu_get_power_down(X86CPUState *s)\n{\n return FALSE;\n}\n\nvoid x86_cpu_flush_tlb_write_range_ram(X86CPUState *s,\n uint8_t *ram_ptr, size_t ram_size)\n{\n}\n"], ["/linuxpdf/tinyemu/softfp.c", "/*\n * SoftFP Library\n * \n * Copyright (c) 2016 Fabrice Bellard\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include \n#include \n#include \n#include \n\n#include \"cutils.h\"\n#include \"softfp.h\"\n\nstatic inline int clz32(uint32_t a)\n{\n int r;\n if (a == 0) {\n r = 32;\n } else {\n r = __builtin_clz(a);\n }\n return r;\n}\n\nstatic inline int clz64(uint64_t a)\n{\n int r;\n if (a == 0) {\n r = 64;\n } else \n {\n r = __builtin_clzll(a);\n }\n return r;\n}\n\n#ifdef HAVE_INT128\nstatic inline int clz128(uint128_t a)\n{\n int r;\n if (a == 0) {\n r = 128;\n } else \n {\n uint64_t ah, al;\n ah = a >> 64;\n al = a;\n if (ah != 0)\n r = __builtin_clzll(ah);\n else\n r = __builtin_clzll(al) + 64;\n }\n return r;\n}\n#endif\n\n#define F_SIZE 32\n#include \"softfp_template.h\"\n\n#define F_SIZE 64\n#include \"softfp_template.h\"\n\n#ifdef HAVE_INT128\n\n#define F_SIZE 128\n#include \"softfp_template.h\"\n\n#endif\n\n"]], "task_instance_info": {"created_time": "2025-08-20 17:59:23", "created_task_model": "DeepSeek-R1", "function_skeleton": "static int preload_parse(FSDevice *fs, const char *fname, BOOL is_new) {}", "code_description": "This code segment functions to: Parse a configuration file to determine which resources should be loaded into memory in advance, selecting between different parsing strategies based on format version flags."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c\n[TASK_BEGIN]\nstatic int preload_parse(FSDevice *fs, const char *fname, BOOL is_new) {\n FSFile *root_fd = NULL, *fd = NULL;\n FSQID qid;\n uint8_t *buf = NULL;\n int ret = -1;\n int err;\n\n err = fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\");\n if (err < 0)\n return -1;\n\n fd = fs_walk_path(fs, root_fd, fname);\n if (!fd)\n goto fail;\n\n err = fs->fs_open(fs, &qid, fd, P9_O_RDONLY, NULL, NULL);\n if (err < 0)\n goto fail;\n\n FSINode *n = fd->inode;\n if (n->type != FT_REG || n->u.reg.size == 0)\n goto fail;\n\n uint64_t size = n->u.reg.size;\n buf = malloc(size + 1);\n if (!buf)\n goto fail;\n\n int read_size = fs->fs_read(fs, fd, 0, buf, size);\n if (read_size != size)\n goto fail;\n buf[size] = '\\0';\n\n if (is_new)\n preload_parse_str(fs, (const char *)buf);\n else\n preload_parse_str_old(fs, (const char *)buf);\n\n ret = 0;\n\nfail:\n free(buf);\n if (fd)\n fs->fs_delete(fs, fd);\n if (root_fd)\n fs->fs_delete(fs, root_fd);\n return ret;\n}\n[TASK_END]", "inference_time": "2025-08-20 18-00-51"}, "editdistance_info": {"edit_distance": 33.7278, "calculate_time": "2025-08-20 18:00:51", "true_code_clean": "static int preload_parse(FSDevice *fs, const char *fname, BOOL is_new)\n{\n FSINode *n;\n char *buf;\n size_t size;\n n = inode_search_path(fs, fname);\n if (!n || n->type != FT_REG || n->u.reg.state != REG_STATE_LOADED)\n return -1;\n size = n->u.reg.size;\n buf = malloc(size + 1);\n file_buffer_read(&n->u.reg.fbuf, 0, (uint8_t *)buf, size);\n buf[size] = '\\0';\n if (is_new)\n preload_parse_str(fs, buf);\n else\n preload_parse_str_old(fs, buf);\n free(buf);\n return 0;\n}", "predict_code_clean": "static int preload_parse(FSDevice *fs, const char *fname, BOOL is_new) {\n FSFile *root_fd = NULL, *fd = NULL;\n FSQID qid;\n uint8_t *buf = NULL;\n int ret = -1;\n int err;\n err = fs->fs_attach(fs, &root_fd, &qid, 0, \"\", \"\");\n if (err < 0)\n return -1;\n fd = fs_walk_path(fs, root_fd, fname);\n if (!fd)\n goto fail;\n err = fs->fs_open(fs, &qid, fd, P9_O_RDONLY, NULL, NULL);\n if (err < 0)\n goto fail;\n FSINode *n = fd->inode;\n if (n->type != FT_REG || n->u.reg.size == 0)\n goto fail;\n uint64_t size = n->u.reg.size;\n buf = malloc(size + 1);\n if (!buf)\n goto fail;\n int read_size = fs->fs_read(fs, fd, 0, buf, size);\n if (read_size != size)\n goto fail;\n buf[size] = '\\0';\n if (is_new)\n preload_parse_str(fs, (const char *)buf);\n else\n preload_parse_str_old(fs, (const char *)buf);\n ret = 0;\nfail:\n free(buf);\n if (fd)\n fs->fs_delete(fs, fd);\n if (root_fd)\n fs->fs_delete(fs, root_fd);\n return ret;\n}"}}