/* * Intel CPU Microcode Update Driver for Linux * * Copyright (C) 2000-2004 Tigran Aivazian * * This driver allows to upgrade microcode on Intel processors * belonging to IA-32 family - PentiumPro, Pentium II, * Pentium III, Xeon, Pentium 4, etc. * * Reference: Section 8.10 of Volume III, Intel Pentium 4 Manual, * Order Number 245472 or free download from: * * http://developer.intel.com/design/pentium4/manuals/245472.htm * * For more information, go to http://www.urbanmyth.org/microcode * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * 1.0 16 Feb 2000, Tigran Aivazian * Initial release. * 1.01 18 Feb 2000, Tigran Aivazian * Added read() support + cleanups. * 1.02 21 Feb 2000, Tigran Aivazian * Added 'device trimming' support. open(O_WRONLY) zeroes * and frees the saved copy of applied microcode. * 1.03 29 Feb 2000, Tigran Aivazian * Made to use devfs (/dev/cpu/microcode) + cleanups. * 1.04 06 Jun 2000, Simon Trimmer * Added misc device support (now uses both devfs and misc). * Added MICROCODE_IOCFREE ioctl to clear memory. * 1.05 09 Jun 2000, Simon Trimmer * Messages for error cases (non Intel & no suitable microcode). * 1.06 03 Aug 2000, Tigran Aivazian * Removed ->release(). Removed exclusive open and status bitmap. * Added microcode_rwsem to serialize read()/write()/ioctl(). * Removed global kernel lock usage. * 1.07 07 Sep 2000, Tigran Aivazian * Write 0 to 0x8B msr and then cpuid before reading revision, * so that it works even if there were no update done by the * BIOS. Otherwise, reading from 0x8B gives junk (which happened * to be 0 on my machine which is why it worked even when I * disabled update by the BIOS) * Thanks to Eric W. Biederman for the fix. * 1.08 11 Dec 2000, Richard Schaal and * Tigran Aivazian * Intel Pentium 4 processor support and bugfixes. * 1.09 30 Oct 2001, Tigran Aivazian * Bugfix for HT (Hyper-Threading) enabled processors * whereby processor resources are shared by all logical processors * in a single CPU package. * 1.10 28 Feb 2002 Asit K Mallick and * Tigran Aivazian , * Serialize updates as required on HT processors due to speculative * nature of implementation. * 1.11 22 Mar 2002 Tigran Aivazian * Fix the panic when writing zero-length microcode chunk. * 1.12 29 Sep 2003 Nitin Kamble , * Jun Nakajima * Support for the microcode updates in the new format. * 1.13 10 Oct 2003 Tigran Aivazian * Removed ->read() method and obsoleted MICROCODE_IOCFREE ioctl * because we no longer hold a copy of applied microcode * in kernel memory. * 1.14 25 Jun 2004 Tigran Aivazian * Fix sigmatch() macro to handle old CPUs with pf == 0. * Thanks to Stuart Swales for pointing out this bug. */ #include #include #include #include #include #include #include #include #include #include #include #define pr_debug(x...) ((void)0) #define DEFINE_MUTEX(_m) DEFINE_SPINLOCK(_m) #define mutex_lock(_m) spin_lock(_m) #define mutex_unlock(_m) spin_unlock(_m) #define vmalloc(_s) xmalloc_bytes(_s) #define vfree(_p) xfree(_p) #if 0 MODULE_DESCRIPTION("Intel CPU (IA-32) Microcode Update Driver"); MODULE_AUTHOR("Tigran Aivazian "); MODULE_LICENSE("GPL"); #endif static int verbose; boolean_param("microcode.verbose", verbose); #define MICROCODE_VERSION "1.14a" #define DEFAULT_UCODE_DATASIZE (2000) /* 2000 bytes */ #define MC_HEADER_SIZE (sizeof (microcode_header_t)) /* 48 bytes */ #define DEFAULT_UCODE_TOTALSIZE (DEFAULT_UCODE_DATASIZE + MC_HEADER_SIZE) /* 2048 bytes */ #define EXT_HEADER_SIZE (sizeof (struct extended_sigtable)) /* 20 bytes */ #define EXT_SIGNATURE_SIZE (sizeof (struct extended_signature)) /* 12 bytes */ #define DWSIZE (sizeof (u32)) #define get_totalsize(mc) \ (((microcode_t *)mc)->hdr.totalsize ? \ ((microcode_t *)mc)->hdr.totalsize : DEFAULT_UCODE_TOTALSIZE) #define get_datasize(mc) \ (((microcode_t *)mc)->hdr.datasize ? \ ((microcode_t *)mc)->hdr.datasize : DEFAULT_UCODE_DATASIZE) #define sigmatch(s1, s2, p1, p2) \ (((s1) == (s2)) && (((p1) & (p2)) || (((p1) == 0) && ((p2) == 0)))) #define exttable_size(et) ((et)->count * EXT_SIGNATURE_SIZE + EXT_HEADER_SIZE) /* serialize access to the physical write to MSR 0x79 */ static DEFINE_SPINLOCK(microcode_update_lock); /* no concurrent ->write()s are allowed on /dev/cpu/microcode */ static DEFINE_MUTEX(microcode_mutex); static void __user *user_buffer; /* user area microcode data buffer */ static unsigned int user_buffer_size; /* it's size */ typedef enum mc_error_code { MC_SUCCESS = 0, MC_IGNORED = 1, MC_NOTFOUND = 2, MC_MARKED = 3, MC_ALLOCATED = 4, } mc_error_code_t; static struct ucode_cpu_info { unsigned int sig; unsigned int pf, orig_pf; unsigned int rev; unsigned int cksum; mc_error_code_t err; microcode_t *mc; } ucode_cpu_info[NR_CPUS]; static void collect_cpu_info (void *unused) { int cpu_num = smp_processor_id(); struct cpuinfo_x86 *c = cpu_data + cpu_num; struct ucode_cpu_info *uci = ucode_cpu_info + cpu_num; unsigned int val[2]; uci->sig = uci->pf = uci->rev = uci->cksum = 0; uci->err = MC_NOTFOUND; uci->mc = NULL; if (c->x86_vendor != X86_VENDOR_INTEL || c->x86 < 6 || cpu_has(c, X86_FEATURE_IA64)) { printk(KERN_ERR "microcode: CPU%d not a capable Intel processor\n", cpu_num); return; } else { uci->sig = cpuid_eax(0x00000001); if ((c->x86_model >= 5) || (c->x86 > 6)) { /* get processor flags from MSR 0x17 */ rdmsr(MSR_IA32_PLATFORM_ID, val[0], val[1]); uci->pf = 1 << ((val[1] >> 18) & 7); } uci->orig_pf = uci->pf; } wrmsr(MSR_IA32_UCODE_REV, 0, 0); /* see notes above for revision 1.07. Apparent chip bug */ sync_core(); /* get the current revision from MSR 0x8B */ rdmsr(MSR_IA32_UCODE_REV, val[0], uci->rev); pr_debug("microcode: collect_cpu_info : sig=0x%x, pf=0x%x, rev=0x%x\n", uci->sig, uci->pf, uci->rev); } static inline void mark_microcode_update (int cpu_num, microcode_header_t *mc_header, int sig, int pf, int cksum) { struct ucode_cpu_info *uci = ucode_cpu_info + cpu_num; pr_debug("Microcode Found.\n"); pr_debug(" Header Revision 0x%x\n", mc_header->hdrver); pr_debug(" Loader Revision 0x%x\n", mc_header->ldrver); pr_debug(" Revision 0x%x \n", mc_header->rev); pr_debug(" Date %x/%x/%x\n", ((mc_header->date >> 24 ) & 0xff), ((mc_header->date >> 16 ) & 0xff), (mc_header->date & 0xFFFF)); pr_debug(" Signature 0x%x\n", sig); pr_debug(" Type 0x%x Family 0x%x Model 0x%x Stepping 0x%x\n", ((sig >> 12) & 0x3), ((sig >> 8) & 0xf), ((sig >> 4) & 0xf), ((sig & 0xf))); pr_debug(" Processor Flags 0x%x\n", pf); pr_debug(" Checksum 0x%x\n", cksum); if (mc_header->rev < uci->rev) { if (uci->err == MC_NOTFOUND) { uci->err = MC_IGNORED; uci->cksum = mc_header->rev; } else if (uci->err == MC_IGNORED && uci->cksum < mc_header->rev) uci->cksum = mc_header->rev; } else if (mc_header->rev == uci->rev) { if (uci->err < MC_MARKED) { /* notify the caller of success on this cpu */ uci->err = MC_SUCCESS; } } else if (uci->err != MC_ALLOCATED || mc_header->rev > uci->mc->hdr.rev) { pr_debug("microcode: CPU%d found a matching microcode update with " " revision 0x%x (current=0x%x)\n", cpu_num, mc_header->rev, uci->rev); uci->cksum = cksum; uci->pf = pf; /* keep the original mc pf for cksum calculation */ uci->err = MC_MARKED; /* found the match */ for_each_online_cpu(cpu_num) { if (ucode_cpu_info + cpu_num != uci && ucode_cpu_info[cpu_num].mc == uci->mc) { uci->mc = NULL; break; } } if (uci->mc != NULL) { vfree(uci->mc); uci->mc = NULL; } } return; } static int find_matching_ucodes (void) { int cursor = 0; int error = 0; while (cursor + MC_HEADER_SIZE < user_buffer_size) { microcode_header_t mc_header; void *newmc = NULL; int i, sum, cpu_num, allocated_flag, total_size, data_size, ext_table_size; if (copy_from_user(&mc_header, user_buffer + cursor, MC_HEADER_SIZE)) { printk(KERN_ERR "microcode: error! Can not read user data\n"); error = -EFAULT; goto out; } total_size = get_totalsize(&mc_header); if (cursor + total_size > user_buffer_size) { printk(KERN_ERR "microcode: error! Bad data in microcode data file\n"); error = -EINVAL; goto out; } data_size = get_datasize(&mc_header); if (data_size + MC_HEADER_SIZE > total_size) { printk(KERN_ERR "microcode: error! Bad data in microcode data file\n"); error = -EINVAL; goto out; } if (mc_header.ldrver != 1 || mc_header.hdrver != 1) { printk(KERN_ERR "microcode: error! Unknown microcode update format\n"); error = -EINVAL; goto out; } for_each_online_cpu(cpu_num) { struct ucode_cpu_info *uci = ucode_cpu_info + cpu_num; if (sigmatch(mc_header.sig, uci->sig, mc_header.pf, uci->orig_pf)) mark_microcode_update(cpu_num, &mc_header, mc_header.sig, mc_header.pf, mc_header.cksum); } ext_table_size = total_size - (MC_HEADER_SIZE + data_size); if (ext_table_size) { struct extended_sigtable ext_header; struct extended_signature ext_sig; int ext_sigcount; if ((ext_table_size < EXT_HEADER_SIZE) || ((ext_table_size - EXT_HEADER_SIZE) % EXT_SIGNATURE_SIZE)) { printk(KERN_ERR "microcode: error! Bad data in microcode data file\n"); error = -EINVAL; goto out; } if (copy_from_user(&ext_header, user_buffer + cursor + MC_HEADER_SIZE + data_size, EXT_HEADER_SIZE)) { printk(KERN_ERR "microcode: error! Can not read user data\n"); error = -EFAULT; goto out; } if (ext_table_size != exttable_size(&ext_header)) { printk(KERN_ERR "microcode: error! Bad data in microcode data file\n"); error = -EFAULT; goto out; } ext_sigcount = ext_header.count; for (i = 0; i < ext_sigcount; i++) { if (copy_from_user(&ext_sig, user_buffer + cursor + MC_HEADER_SIZE + data_size + EXT_HEADER_SIZE + EXT_SIGNATURE_SIZE * i, EXT_SIGNATURE_SIZE)) { printk(KERN_ERR "microcode: error! Can not read user data\n"); error = -EFAULT; goto out; } for_each_online_cpu(cpu_num) { struct ucode_cpu_info *uci = ucode_cpu_info + cpu_num; if (sigmatch(ext_sig.sig, uci->sig, ext_sig.pf, uci->orig_pf)) { mark_microcode_update(cpu_num, &mc_header, ext_sig.sig, ext_sig.pf, ext_sig.cksum); } } } } /* now check if any cpu has matched */ allocated_flag = 0; sum = 0; for_each_online_cpu(cpu_num) { if (ucode_cpu_info[cpu_num].err == MC_MARKED) { struct ucode_cpu_info *uci = ucode_cpu_info + cpu_num; if (!allocated_flag) { allocated_flag = 1; newmc = vmalloc(total_size); if (!newmc) { printk(KERN_ERR "microcode: error! Can not allocate memory\n"); error = -ENOMEM; goto out; } if (copy_from_user(newmc + MC_HEADER_SIZE, user_buffer + cursor + MC_HEADER_SIZE, total_size - MC_HEADER_SIZE)) { printk(KERN_ERR "microcode: error! Can not read user data\n"); vfree(newmc); error = -EFAULT; goto out; } memcpy(newmc, &mc_header, MC_HEADER_SIZE); /* check extended table checksum */ if (ext_table_size) { int ext_table_sum = 0; int * ext_tablep = (((void *) newmc) + MC_HEADER_SIZE + data_size); i = ext_table_size / DWSIZE; while (i--) ext_table_sum += ext_tablep[i]; if (ext_table_sum) { printk(KERN_WARNING "microcode: aborting, bad extended signature table checksum\n"); vfree(newmc); error = -EINVAL; goto out; } } /* calculate the checksum */ i = (MC_HEADER_SIZE + data_size) / DWSIZE; while (i--) sum += ((int *)newmc)[i]; sum -= (mc_header.sig + mc_header.pf + mc_header.cksum); } ucode_cpu_info[cpu_num].mc = newmc; ucode_cpu_info[cpu_num].err = MC_ALLOCATED; /* mc updated */ if (sum + uci->sig + uci->pf + uci->cksum != 0) { printk(KERN_ERR "microcode: CPU%d aborting, bad checksum\n", cpu_num); error = -EINVAL; goto out; } } } cursor += total_size; /* goto the next update patch */ } /* end of while */ out: return error; } static void do_update_one (void * unused) { unsigned long flags; unsigned int val[2]; int cpu_num = smp_processor_id(); struct ucode_cpu_info *uci = ucode_cpu_info + cpu_num; if (uci->mc == NULL) { if (verbose) { if (uci->err == MC_SUCCESS) printk(KERN_INFO "microcode: CPU%d already at revision 0x%x\n", cpu_num, uci->rev); else printk(KERN_INFO "microcode: No new microcode data for CPU%d\n", cpu_num); } return; } /* serialize access to the physical write to MSR 0x79 */ spin_lock_irqsave(µcode_update_lock, flags); /* write microcode via MSR 0x79 */ wrmsr(MSR_IA32_UCODE_WRITE, (unsigned long) uci->mc->bits, (unsigned long) uci->mc->bits >> 16 >> 16); wrmsr(MSR_IA32_UCODE_REV, 0, 0); /* see notes above for revision 1.07. Apparent chip bug */ sync_core(); /* get the current revision from MSR 0x8B */ rdmsr(MSR_IA32_UCODE_REV, val[0], val[1]); /* notify the caller of success on this cpu */ uci->err = MC_SUCCESS; spin_unlock_irqrestore(µcode_update_lock, flags); printk(KERN_INFO "microcode: CPU%d updated from revision " "0x%x to 0x%x, date = %08x \n", cpu_num, uci->rev, val[1], uci->mc->hdr.date); return; } static int do_microcode_update (void) { int i, error; if (on_each_cpu(collect_cpu_info, NULL, 1, 1) != 0) { printk(KERN_ERR "microcode: Error! Could not run on all processors\n"); error = -EIO; goto out; } if ((error = find_matching_ucodes())) { printk(KERN_ERR "microcode: Error in the microcode data\n"); goto out_free; } if (on_each_cpu(do_update_one, NULL, 1, 1) != 0) { printk(KERN_ERR "microcode: Error! Could not run on all processors\n"); error = -EIO; } out_free: for_each_online_cpu(i) { if (ucode_cpu_info[i].mc) { int j; void *tmp = ucode_cpu_info[i].mc; vfree(tmp); for_each_online_cpu(j) { if (ucode_cpu_info[j].mc == tmp) ucode_cpu_info[j].mc = NULL; } } if (ucode_cpu_info[i].err == MC_IGNORED && verbose) printk(KERN_WARNING "microcode: CPU%d not 'upgrading' to earlier revision" " 0x%x (current=0x%x)\n", i, ucode_cpu_info[i].cksum, ucode_cpu_info[i].rev); } out: return error; } int microcode_update(XEN_GUEST_HANDLE(void) buf, unsigned long len) { int ret; if (len != (typeof(user_buffer_size))len) { printk(KERN_ERR "microcode: too much data\n"); return -E2BIG; } mutex_lock(µcode_mutex); user_buffer = buf.p; user_buffer_size = len; ret = do_microcode_update(); mutex_unlock(µcode_mutex); return ret; } ment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
/*
 * Copyright (C) 2004  Manuel Novoa III  <mjn3@codepoet.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

/* July 29, 2004
 *
 * This is a hacked replacement for the 'addpattern' utility used to
 * create wrt54g .bin firmware files.  It isn't pretty, but it does
 * the job for me.
 *
 * Extensions:
 *  -v allows setting the version string on the command line.
 *  -{0|1} sets the (currently ignored) hw_ver flag in the header
 *      to 0 or 1 respectively.
 */

/* January 12, 2005
 *
 * Modified by rodent at rodent dot za dot net
 * Support added for the new WRT54G v2.2 and WRT54GS v1.1 "flags"
 * Without the flags set to 0x7, the above units will refuse to flash.
 *
 * Extensions:
 *  -{0|1|2} sets {0|1} sets hw_ver flag to 0/1. {2} sets hw_ver to 1
 *     and adds the new hardware "flags" for the v2.2/v1.1 units
*/

/* January 1, 2007
 *
 * Modified by juan.i.gonzalez at subdown dot net
 * Support added for the AG241v2  and similar
 *
 * Extensions:
 *  -r #.# adds revision hardware flags. AG241v2 and similar.
 *
 * AG241V2 firmware sets the hw_ver to 0x44.
 *
 * Example: -r 2.0
 *
 * Convert 2.0 to 20 to be an integer, and add 0x30 to skip special ASCII
 * #define HW_Version ((HW_REV * 10) + 0x30)  -> from cyutils.h
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/stat.h>

/**********************************************************************/

#define CODE_ID		"U2ND"		/* from code_pattern.h */
#define CODE_PATTERN   "W54S"	/* from code_pattern.h */
#define PBOT_PATTERN   "PBOT"

#define CYBERTAN_VERSION	"v3.37.2" /* from cyutils.h */

/* WRT54G v2.2 and WRT54GS v1.1 "flags" (from 3.37.32 firmware cyutils.h) */
#define SUPPORT_4712_CHIP      0x0001
#define SUPPORT_INTEL_FLASH    0x0002
#define SUPPORT_5325E_SWITCH   0x0004
/* (from 3.00.24 firmware cyutils.h) */
#define SUPPORT_4704_CHIP      0x0008
#define SUPPORT_5352E_CHIP     0x0010
/* (from WD My Net Wi-Fi Range Extender's cyutils.s) */
#define SUPPORT_4703_CHIP      0x0020

struct code_header {			/* from cyutils.h */
	char magic[8];
	char fwdate[3];
	char fwvern[3];
	char id[4];					/* U2ND */
	char hw_ver;    			/* 0: for 4702, 1: for 4712 -- new in 2.04.3 */

	unsigned char  sn;		// Serial Number
	unsigned char  flags[2];	/* SUPPORT_ flags new for 3.37.2 (WRT54G v2.2 and WRT54GS v1.1) */
	unsigned char  stable[2];	// The image is stable (for dual image)
	unsigned char  try1[2];		// Try to boot image first time (for dual image)
	unsigned char  try2[2];		// Try to boot image second time (for dual image)
	unsigned char  try3[2];		// Try to boot image third time (for dual_image)
	unsigned char  res3[2];
} ;

struct board_info {
	char	*id;
	char	*pattern;
	char	hw_ver;
	char	sn;
	char	flags[2];
};

struct board_info boards[] = {
	{
		.id		= "WRT160NL",
		.pattern	= "NL16",
		.hw_ver		= 0x00,
		.sn		= 0x0f,
		.flags		= {0x3f, 0x00},
	},
	{
		.id		= "mynet-rext",
		.pattern	= "WDHNSTFH",
		.hw_ver		= 0x00,
		.sn		= 0x00,
		.flags		= {0x3f, 0x00},
	}, {
		/* Terminating entry */
		.id	= NULL,
	}
};

/**********************************************************************/

void usage(void) __attribute__ (( __noreturn__ ));

void usage(void)
{
	fprintf(stderr, "Usage: addpattern [-i trxfile] [-o binfile] [-B board_id] [-p pattern] [-s serial] [-g] [-b] [-v v#.#.#] [-r #.#] [-{0|1|2|4|5}] -h\n");
	exit(EXIT_FAILURE);
}

struct board_info *find_board(char *id)
{
	struct board_info *board;

	for (board = boards; board->id != NULL; board++)
		if (strcasecmp(id, board->id) == 0)
			return board;

	return NULL;
}

int main(int argc, char **argv)
{
	char buf[1024];	/* keep this at 1k or adjust garbage calc below */
	struct code_header *hdr;
	FILE *in = stdin;
	FILE *out = stdout;
	char *ifn = NULL;
	char *ofn = NULL;
	char *pattern = CODE_PATTERN;
	char *pbotpat = PBOT_PATTERN;
	char *version = CYBERTAN_VERSION;
	char *board_id = NULL;
	struct board_info *board = NULL;
	int gflag = 0;
	int pbotflag = 0;
	int c;
	int v0, v1, v2;
	size_t off, n;
	time_t t;
	struct tm *ptm;

	fprintf(stderr, "mjn3's addpattern replacement - v0.81\n");

	hdr = (struct code_header *) buf;
	memset(hdr, 0, sizeof(struct code_header));

	while ((c = getopt(argc, argv, "i:o:p:s:gbv:01245hr:B:")) != -1) {
		switch (c) {
			case 'i':
				ifn = optarg;
				break;
			case 'o':
				ofn = optarg;
				break;
			case 'p':
				pattern = optarg;
				break;
			case 's':
				hdr->sn = (unsigned char) atoi (optarg);
				break;
			case 'g':
				gflag = 1;
				break;
			case 'b':
				pbotflag = 1;
				break;
			case 'v':			/* extension to allow setting version */
				version = optarg;
				break;
			case '0':
				hdr->hw_ver = 0;
				break;
			case '1':
				hdr->hw_ver = 1;
				break;
			case '2': 			/* new 54G v2.2 and 54GS v1.1 flags */
				hdr->hw_ver = 1;
				hdr->flags[0] |= SUPPORT_4712_CHIP;
				hdr->flags[0] |= SUPPORT_INTEL_FLASH;
				hdr->flags[0] |= SUPPORT_5325E_SWITCH;
				break;
			case '4':
				/* V4 firmware sets the flags to 0x1f */
				hdr->hw_ver = 0;
				hdr->flags[0] = 0x1f;
				break;
			case '5':
				/* V5 is appended to trxV2 image */
				hdr->stable[0] = 0x73; // force image to be stable
				hdr->stable[1] = 0x00;
				hdr->try1[0]   = 0x74; // force try1 to be set
				hdr->try1[1]   = 0x00;
				hdr->try2[0]   = hdr->try2[1]   = 0xFF;
				hdr->try3[0]   = hdr->try3[1]   = 0xFF;
				break;
                        case 'r':
                                hdr->hw_ver = (char)(atof(optarg)*10)+0x30;
                                break;
                        case 'B':
                                board_id = optarg;
                                break;

                        case 'h':
			default:
				usage();
		}
	}

    	if (optind != argc || optind == 1) {
		fprintf(stderr, "illegal arg \"%s\"\n", argv[optind]);
		usage();
	}

	if (board_id) {
		board = find_board(board_id);
		if (board == NULL) {
			fprintf(stderr, "unknown board \"%s\"\n", board_id);
			usage();
		}
		pattern = board->pattern;
		hdr->hw_ver = board->hw_ver;
		hdr->sn = board->sn;
		hdr->flags[0] = board->flags[0];
		hdr->flags[1] = board->flags[1];
	}

	if (strlen(pattern) > 8) {
		fprintf(stderr, "illegal pattern \"%s\"\n", pattern);
		usage();
	}

	if (ifn && !(in = fopen(ifn, "r"))) {
		fprintf(stderr, "can not open \"%s\" for reading\n", ifn);
		usage();
	}

	if (ofn && !(out = fopen(ofn, "w"))) {
		fprintf(stderr, "can not open \"%s\" for writing\n", ofn);
		usage();
	}

	if (time(&t) == (time_t)(-1)) {
		fprintf(stderr, "time call failed\n");
		return EXIT_FAILURE;
	}

	ptm = localtime(&t);

	if (3 != sscanf(version, "v%d.%d.%d", &v0, &v1, &v2)) {
		fprintf(stderr, "bad version string \"%s\"\n", version);
		return EXIT_FAILURE;
	}

	memcpy(hdr->magic, pattern, strlen(pattern));
	if (pbotflag)
		memcpy(&hdr->magic[4], pbotpat, 4);
	hdr->fwdate[0] = ptm->tm_year % 100;
	hdr->fwdate[1] = ptm->tm_mon + 1;
	hdr->fwdate[2] = ptm->tm_mday;
	hdr->fwvern[0] = v0;
	hdr->fwvern[1] = v1;
	hdr->fwvern[2] = v2;
	memcpy(hdr->id, CODE_ID, strlen(CODE_ID));

	off = sizeof(struct code_header);

	fprintf(stderr, "writing firmware v%d.%d.%d on %d/%d/%d (y/m/d)\n",
			v0, v1, v2,
			hdr->fwdate[0], hdr->fwdate[1], hdr->fwdate[2]);


	while ((n = fread(buf + off, 1, sizeof(buf)-off, in) + off) > 0) {
		off = 0;
		if (n < sizeof(buf)) {
			if (ferror(in)) {
			FREAD_ERROR:
				fprintf(stderr, "fread error\n");
				return EXIT_FAILURE;
			}
			if (gflag) {
				gflag = sizeof(buf) - n;
				memset(buf + n, 0xff, gflag);
				fprintf(stderr, "adding %d bytes of garbage\n", gflag);
				n = sizeof(buf);
			}
		}
		if (!fwrite(buf, n, 1, out)) {
		FWRITE_ERROR:
			fprintf(stderr, "fwrite error\n");
			return EXIT_FAILURE;
		}
	}

	if (ferror(in)) {
		goto FREAD_ERROR;
	}

	if (fflush(out)) {
		goto FWRITE_ERROR;
	}

	fclose(in);
	fclose(out);

	return EXIT_SUCCESS;
}