File: iucode_tool.c

package info (click to toggle)
iucode-tool 0.8.3-2
  • links: PTS, VCS
  • area: contrib
  • in suites: wheezy
  • size: 1,092 kB
  • sloc: ansic: 15,028; sh: 3,926; makefile: 87
file content (2143 lines) | stat: -rw-r--r-- 49,681 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
/*
 * uicode_tool - Manipulates Intel(R) IA32/x86_64 processor microcode bundles
 *
 * Copyright (c) 2010-2012 Henrique de Moraes Holschuh <hmh@hmh.eng.br>
 *               2000 Simon Trimmer, Tigran Aivazian
 *
 * Some code copied from microcode.ctl v1.17.
 * Some code based on the Linux kernel microcode_intel driver.
 *
 * 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.
 *
 */

#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <argp.h>
#include <dirent.h>

#include "intel_microcode.h"
#include "iucode_tool_config.h"

#define PROGNAME "iucode_tool"

/*
 * For micro-optimization on the hotter paths
 */
#define likely(x)       __builtin_expect(!!(x), 1)
#define unlikely(x)     __builtin_expect(!!(x), 0)

/* Command-line processing and UI */

enum {
	EXIT_USAGE = 1,		/* Exit due to command line errors */
	EXIT_SWFAILURE = 2,	/* Exit due to software failure (ENOMEM, etc) */
};

enum { /* actions */
	IUCODE_DO_UPLOADUC = 0x0001,
	IUCODE_DO_WRITEUC  = 0x0002,
	IUCODE_DO_WRITEFW  = 0x0004,
	IUCODE_DO_SELPROC  = 0x0008,
	IUCODE_DO_LOADFILE = 0x0010,
	IUCODE_DO_WRITEFWN = 0x0020,

	IUCODE_F_UCSELECT  = 0x1000,

	IUCODE_DOMASK_NEEDSUC = IUCODE_DO_UPLOADUC
				| IUCODE_DO_WRITEUC
				| IUCODE_DO_WRITEFW
				| IUCODE_DO_WRITEFWN,
} command_line_actions;

static char *progname;
static int verbosity = 1; /* 0 = errors, 1 = normal... */
static int strict_checks = 1;
static int ignore_bad_ucode = 0;
static int allow_downgrade = 0;
static int list_all_microcodes = 0;
static int list_sel_microcodes = 0;
static int unlink_files = 0;
static char *upload_microcode = NULL;
static char *write_microcode = NULL;
static char *write_firmware = NULL;
static char *write_named = NULL;

typedef enum { /* File type */
	INTEL_UC_FT_UNKNOWN = 0,
	INTEL_UC_FT_DAT,
	INTEL_UC_FT_BIN,
} intel_ucode_file_type_t;
static intel_ucode_file_type_t ucfiletype = INTEL_UC_FT_UNKNOWN;

/* linked list of filenames */
struct filename_list {
	intel_ucode_file_type_t type;
	struct filename_list *next;
	char path[];
};
static struct filename_list *input_files = NULL;

/* Intel Microcode data structures */

struct microcode_bundle {
	struct microcode_bundle *next;
	const char *filename;	/* source file name */
	unsigned long int id;   /* bundle id */
	unsigned long int size; /* bytes */
	const void *data;       /* binary file data */
};
static struct microcode_bundle *microcode_bundles = NULL;
static unsigned long int last_bundle_id = 0;

/* signature single-linked list */
struct intel_uclist_entry {
	unsigned long int id;	/* microcode id within group */
	unsigned long int gid;	/* microcode group id */
	uint32_t cpuid;		/* sorting key */
	uint32_t pf_mask;
	int32_t  uc_rev;	/* duplicated from header */
	const void *uc;
	uint32_t uc_size;
	struct intel_uclist_entry *next;
};
static struct intel_uclist_entry *microcodes = NULL;

/* UI helpers */
#define UCODE_ID_MAX_LEN 20
struct microcode_interator_data {
	const struct microcode_bundle *current_bundle;
	unsigned long int total_signature_count;
	unsigned long int total_entry_count;
	unsigned long int current_uc;
	char current_uc_id_str[UCODE_ID_MAX_LEN];
};
static struct microcode_interator_data microcode_interator_data;

/* Filter masks */
struct microcode_filter_entry {
	uint32_t cpuid;		/* exact match */
	uint32_t pf_mask;	/* common bits set match */
	int invert;
	struct microcode_filter_entry *next;
};
static struct microcode_filter_entry *uc_filter_list = NULL;
static int filter_list_allow = 1;

static uint32_t datefilter_max = 0xffffffffU;  /* select dates before this */
static uint32_t datefilter_min = 0;	       /* select dates after this */

static int inline filter_list_active(void)
{
	return !!uc_filter_list ||
		!!(command_line_actions & IUCODE_F_UCSELECT);
}

/* Helpers */

#define print_msg_u(format, arg...) \
	do { fprintf(stderr, "%s: " format "\n", progname, ## arg); } while (0)

#define print_msg(level, format, arg...) \
	do { if (verbosity >= level) \
		fprintf(stderr, "%s: " format "\n", progname, ## arg); \
	} while (0)

#define print_err(format, arg...) \
	do { fprintf(stderr, "%s: " format "\n", progname, ## arg); } while (0)

static inline int is_dash(const char * const fn)
{
	return fn && *fn == '-' && !*(fn+1);
}

/* UI microcode id */

static void str_append_ucode_id(unsigned long int id,
				unsigned long int gid,
				char *str, unsigned int len)
{
	snprintf(str, len, "%02lu/%03lu", gid, id);
}

/* Signature linked list */

/**
 * free_uclist() - frees chain of struct intel_uclist_entry
 * @p:		pointer to the first struct intel_uclist_entry
 *
 * If p != NULL, frees all members of the struct intel_uclist_entry
 * linked list.
 */
void free_uclist(struct intel_uclist_entry *p)
{
	struct intel_uclist_entry *e;

	while (p) {
		e = p;
		p = e->next;
		free(e);
	}
}

/*
 * remove entries that were superseeded
 */
static void __uclist_remove_shadowed(const unsigned long int gid,
				     const uint32_t cpuid,
				     const uint32_t pf_mask,
				     const int32_t uc_rev,
				     const int downgrade,
				     struct intel_uclist_entry **pnext)
{
	while (*pnext && (*pnext)->cpuid == cpuid) {
		struct intel_uclist_entry * const e = *pnext;

		if (((pf_mask & e->pf_mask) == e->pf_mask) &&
		    (uc_rev >= e->uc_rev || (downgrade && gid != e->gid))) {
			/* entry is a subset of the one we just added */
			/* delete entry */
			*pnext = e->next;
			free(e);
		} else {
			pnext = &(e->next);
		}
	}
}

/**
 * uclist_add_signature() - adds signature to ucode sig list
 * @id:		microcode id
 * @gid:	microcode group id
 * @cpuid:	signature of the signature entry being added
 * @pf_mask:	pf_mask of the signature entry being added
 * @uc_rev:	revision of the microcode entry being added
 * @uc:		microcode data (including headers)
 * @uc_size:	microcode data size (total, including headers)
 * @downgrade:	version downgrades betwen groups allowed if NZ
 * @uclist:	pointer to the first entry on the list
 *
 * Adds a microcode signature entry to the list.  When @downgrade
 * is zero, it will replace any suitable entry that has a lesser
 * revision.  When @downgrade is non-zero, it will replace any
 * suitable entry that has a lesser revision or which is from
 * a different microcode group.
 *
 * "suitable" means microcodes with the same cpuid and with a
 * pf_mask that is either equal or a strict subset of the one from
 * the new microcode.
 *
 * Note that it IS still possible that two signatures in the list
 * could apply to the same processor, if they have different revisions
 * and different pf masks, and the cpu is present in both pf masks.
 *
 * returns: ENOMEM: could not allocate memory,
 *          EEXIST: entry already in list (but may have been
 *                  inserted if @downgrade is non-zero)
 *          EINVAL: bad @cpuid, @uc pointer or @uclist pointer
 */
int uclist_add_signature(const unsigned long int id,
			const unsigned long int gid,
			const uint32_t cpuid,
			const uint32_t pf_mask,
			const int32_t uc_rev,
			const void * const uc,
			const uint32_t uc_size,
			const int downgrade,
			struct intel_uclist_entry ** const uclist)
{
	struct intel_uclist_entry **pnext, *n;

	if (unlikely(!cpuid || !uc || !uclist))
		return EINVAL;

	pnext = uclist;

	/* note: pf_mask *can* be zero on old processors */

	/* search linked list for matching CPUID */
	while (*pnext && (*pnext)->cpuid < cpuid)
		pnext = &((*pnext)->next);

	while (*pnext && (*pnext)->cpuid == cpuid) {
		struct intel_uclist_entry * const e = *pnext;

		if (likely(pf_mask && (e->pf_mask & pf_mask) == 0)) {
			/* disjoint sets, continue search */
			pnext = &(e->next);
		} else if (!downgrade || gid == e->gid) { /* do not downgrade */
			if ((e->pf_mask & pf_mask) == pf_mask) {
				/* new set same or contained in the old set */
				if (e->uc_rev >= uc_rev) {
					/* old set as good, or newer */
					return EEXIST;
				} else if (pf_mask == e->pf_mask) {
					/* the sets are identical, and the new
					 * one is newer microcode: replace */
					e->id = id;
					e->gid = gid;
					/* e->cpuid = cpuid; */
					e->pf_mask = pf_mask;
					e->uc_rev = uc_rev;
					e->uc = uc;
					e->uc_size = uc_size;
					return 0;
				}
				pnext = &(e->next);
			} else if ((pf_mask & e->pf_mask) == e->pf_mask) {
				/* new entry a superset of the old */
				if (uc_rev >= e->uc_rev) {
					/* we can replace the old entry */
					e->id = id;
					e->gid = gid;
					/* e->cpuid = cpuid; */
					e->pf_mask = pf_mask;
					e->uc_rev = uc_rev;
					e->uc = uc;
					e->uc_size = uc_size;

					__uclist_remove_shadowed(gid, cpuid,
						     pf_mask, uc_rev,
						     downgrade, &(e->next));
					return 0;
				}
				pnext = &(e->next);
			}
		} else { /* downgrade */
			if (e->pf_mask == pf_mask) {
				int rc = (e->uc_rev == uc_rev) ? EEXIST : 0;
				/* same set, replace */
				e->id = id;
				e->gid = gid;
				/* e->cpuid = cpuid; */
				e->pf_mask = pf_mask;
				e->uc_rev = uc_rev;
				e->uc = uc;
				e->uc_size = uc_size;
				return rc;
			} else {
				/* sets are not disjoint: we have to insert it here */
				break;
			}
		}
	}

	n = malloc(sizeof(struct intel_uclist_entry));
	if (unlikely(!n))
		return ENOMEM;

	memset(n, 0, sizeof(struct intel_uclist_entry));
	n->id = id;
	n->gid = gid;
	n->cpuid = cpuid;
	n->pf_mask = pf_mask;
	n->uc_rev = uc_rev;
	n->uc = uc;
	n->uc_size = uc_size;

	/* prepend */
	n->next = *pnext;
	*pnext = n;

	__uclist_remove_shadowed(gid, cpuid, pf_mask, uc_rev, downgrade, &(n->next));

	return 0;
}

/* Microcode bundle handling */

/**
 * add_intel_microcode_bundle() - add a microcode bundle to set
 * @mcb_filename:	filename (metadata)
 * @mcb_id:		bundle id (metadata)
 * @mcb:		pointer to the microcode bundle data
 * @mcb_size:		size of the microcode bundle data
 *
 * Note: the memory pointed to by @mcb will be freed when
 * the bundles are freed by free_intel_microcode_bundles().
 *
 * Returns 0 if the bundled was added, or ENOMEM
 */
static int add_intel_microcode_bundle(const char * const mcb_filename,
				      unsigned long int mcb_id,
				      const void * const mcb,
				      const size_t mcb_size)
{
	struct microcode_bundle *b, **p;

	assert(mcb && mcb_size >= 1024);
	assert(mcb_filename);

	b = malloc(sizeof(struct microcode_bundle) + mcb_size);
	if (!b)
		return ENOMEM;

	memset(b, 0, sizeof(struct microcode_bundle));
	b->id = mcb_id;
	b->filename = strdup(mcb_filename);
	b->size = mcb_size;
	b->data = mcb;

	/* add to end of list */
	p = &microcode_bundles;
	while (*p)
		p = &((*p)->next);
	*p = b;

	return 0;
}

static void free_intel_microcode_bundles(void)
{
	struct microcode_bundle *p, *t;

	p = microcode_bundles;
	while (p) {
		t = p;
		p = t->next;
		free((void *)(t->filename));
		free((void *)(t->data));
		free(t);
	}

	microcode_bundles = NULL;
}

static int __load_intel_microcode_dat(FILE *fp, void **mcb, size_t *mcb_length)
{
	const size_t line_buffer_size = 2048;
	const size_t buffer_size_granularity = 256*1024; /* 1MiB, dwords */
	char *line_buffer = NULL;
	char *lp;
	size_t mcb_buflen;
	uint32_t *mcb_buffer = NULL;
	uint32_t *rp;
	size_t length;
	size_t pos = 0;
	int err;

	assert(mcb);
	assert(mcb_length);

	mcb_buflen = buffer_size_granularity;
	mcb_buffer = malloc(buffer_size_granularity * sizeof(uint32_t));
	line_buffer = malloc(line_buffer_size);
	if (!mcb_buffer || !line_buffer) {
		err = ENOMEM;
		goto err_out;
	}

	err = EINVAL;
	while (likely(fgets(line_buffer, line_buffer_size, fp) != NULL)) {
		/*
		 * Data lines are of the form "%x, %x, %x, %x,"
		 *
		 * other valid lines start with / (comments), and we also
		 * accept empty lines, and ignore whitespace.
		 */
		lp = line_buffer;
		while (isspace(*lp))
			lp++;

		if (!*lp || *lp == '/')
			continue;

		while (*lp) {
			char *ep;

			errno = 0;
			mcb_buffer[pos] = strtoul(lp, &ep, 0);
			if (unlikely(errno))
				goto err_out;
			if (lp == ep) {
				while (isspace(*lp))
					lp++;
				/* last value might have a , after it and
				 * we will hit it here */
				if (*lp == ',')
					lp++;
				while (isspace(*lp))
					lp++;
				if (unlikely(*lp))
					goto err_out;
				break; /* EOL */
			}

			/* we did read a value */
			pos++;
			if (unlikely(mcb_buflen <= pos)) {
				/* expand buffer */
				mcb_buflen += buffer_size_granularity;
				rp = realloc(mcb_buffer,
					     mcb_buflen * sizeof(uint32_t));
				if (unlikely(!rp)) {
					err = ENOMEM;
					goto err_out;
				}
				mcb_buffer = rp;
			}

			lp = ep;
			/* next value */
			while (isspace(*lp))
				lp++;
			if (*lp == ',') {
				lp++;
				continue;
			} else if (unlikely(*lp)) {
				goto err_out;
			}
		}
	}

	length = pos * sizeof(uint32_t);
	if (length < 1024) {
		err = EINVAL;
		goto err_out;
	}

	/* truncate buffer if too large */
	rp = realloc(mcb_buffer, length);
	if (!rp) {
		err = ENOMEM;
		goto err_out;
	}

	*mcb = rp;
	*mcb_length = length;

	err = 0;

err_out:
	if (err) {
		free(mcb_buffer);
		*mcb = NULL;
		*mcb_length = 0;
	}

	free(line_buffer);
	return err;
}

static int __load_intel_microcode_bin(int fd, void **mcb, size_t *mcb_length)
{
	const size_t buffer_size_granularity = 1024*1024;

	int file_size_known;
	struct stat stat;

	size_t mcb_size;
	size_t mcb_space_left;
	uint8_t *mcb_buffer = NULL;
	uint8_t *rp;

	size_t pos;
	int err;

	assert(mcb);
	assert(mcb_length);

	/* Try to get file size beforehand */
	if (!fstat(fd, &stat) && S_ISREG(stat.st_mode) && stat.st_size > 0) {
		mcb_size = stat.st_size;
		file_size_known = 1;
	} else {
		mcb_size = buffer_size_granularity;
		file_size_known = 0;
	}

	/* sanity check size */
	if (mcb_size < 1024) {
		err = EINVAL;
		goto err_out;
	}

	mcb_buffer = malloc(mcb_size);
	if (!mcb_buffer) {
		err = ENOMEM;
		goto err_out;
	}

	err = 0;
	pos = 0;
	mcb_space_left = mcb_size;
	do {
		ssize_t rc;

		rc = read(fd, mcb_buffer + pos, mcb_space_left);
		if (rc == -1) {
			if (errno == EINTR)
				continue;
			err = -errno; /* negative! */
			goto err_out;
		}

		pos += rc;
		mcb_space_left -= rc;

		if (rc == 0)
			break; /* EOF */
		if (file_size_known && !mcb_space_left)
			break; /* Read entire file */

		if (!mcb_space_left) {
			mcb_size += buffer_size_granularity;
			mcb_space_left += buffer_size_granularity;
			rp = realloc(mcb_buffer, mcb_size);
			if (!rp) {
				err = ENOMEM;
				goto err_out;
			}
			mcb_buffer = rp;
		}
	} while (1);

	mcb_size = pos;
	if (mcb_size < 1024) {
		err = EINVAL;
		goto err_out;
	}

	rp = realloc(mcb_buffer, mcb_size);
	if (!rp) {
		err = ENOMEM;
		goto err_out;
	}

	*mcb = rp;
	*mcb_length = mcb_size;

	return 0;

err_out:
	free(mcb_buffer);
	*mcb = NULL;
	*mcb_length = 0;

	return err;
}

static int __load_intel_microcode_file(int fd,
				       FILE *fp,
				       const char * const fn,
				       const intel_ucode_file_type_t ftype)
{
	int err = 0;

	void *mcb = NULL;
	size_t mcb_length = 0;

	switch (ftype) {
	case INTEL_UC_FT_BIN:
		err = __load_intel_microcode_bin(fd, &mcb, &mcb_length);
		break;

	case INTEL_UC_FT_DAT:
		if (!fp)
			fp = fdopen(fd, "r");

		if (fp) {
			err = __load_intel_microcode_dat(fp, &mcb, &mcb_length);
		} else {
			err = -errno;
		}
		break;

	default:
		err = ENOTSUP;
	}

	if (err < 0) { /* error from read() or stdio */
		print_err("%s: could not read: %s", fn, strerror(-err));
		goto err_out;
	}

	if (!err && mcb) {
		last_bundle_id++;
		err = add_intel_microcode_bundle(fn, last_bundle_id,
						 mcb, mcb_length);
		if (!err)
			mcb = NULL; /* someone else will free it */
	}

	switch (err) {
	case 0:
		print_msg(2, "microcode bundle %lu: %s (%zu bytes)",
			  last_bundle_id, fn, mcb_length);
		break;
	case ENOMEM:
		print_err("%s: could not allocate memory while loading", fn);
		break;
	case EINVAL:
		print_err("%s: invalid file format", fn);
		break;
	}

err_out:
	if (fp)
		fclose(fp); /* also closes fd */
	else if (fd != -1)
		close(fd);

	free(mcb);

	return err;
}

static int load_intel_microcode(const char *path,
				const intel_ucode_file_type_t baseftype)
{
	int fd = -1;

	DIR *dir;
	int err;

	char fnbuf[PATH_MAX];
	const char *fn;
	intel_ucode_file_type_t ftype;

	assert(path);

	/* Should we read from stdin ? */
	if (is_dash(path)) {
		ftype = baseftype;

		/* default to .dat mode for stdin */
		if (ftype == INTEL_UC_FT_UNKNOWN)
			ftype = INTEL_UC_FT_DAT;

		return __load_intel_microcode_file(0, stdin, "(stdin)", ftype);
	}

	dir = NULL;
	fn = path;

	do {
		struct stat st;
		struct dirent *dentry;

		err = 0;

		if (fd != -1) {
			close(fd);
			fd = -1;
		}

		if (dir) {
			errno = 0;
			dentry = readdir(dir);
			if (dentry) {
				int s;

				if (dentry->d_name[0] == '.')
					continue;

				s = snprintf(fnbuf, sizeof(fnbuf), "%s/%s",
					     path, dentry->d_name);
				if (unlikely(s < 1 || s >= sizeof(fnbuf))) {
					print_err("%s/%s: path too long",
						  path, dentry->d_name);
					err = -ENAMETOOLONG;
					continue;
				}
				fn = fnbuf;
			} else {
				err = errno;
				if (unlikely(err)) {
					print_err("%s: cannot walk directory: %s",
						  path, strerror(err));
					err = -err;
				}
				break; /* finish/abort walk */
			}
		}

		fd = open(fn, O_RDONLY);
		if (unlikely(fd == -1)) {
			err = errno;
			print_err("%s: cannot open: %s", fn, strerror(err));
			err = -err;
			continue;
		}
		if (unlikely(fstat(fd, &st) == -1)) {
			err = errno;
			print_err("%s: cannot stat inode: %s", fn,
				  strerror(err));
			err = -err;
			continue;
		}
		if (S_ISDIR(st.st_mode)) {
			if (!dir) {
				dir = fdopendir(fd);
				if (!dir) {
					err = errno;
					print_err("%s: cannot open directory: %s",
						  path, strerror(err));
					err = -err;
					continue;
				}
				fd = -1;
			} else {
				print_msg(1, "%s: skipping nested directory: %s",
					  path, fn);
			}
			continue;
		}

		ftype = baseftype;
		if (ftype == INTEL_UC_FT_UNKNOWN && S_ISREG(st.st_mode)) {
			char *p;

			/* try to guess based on extension */
			p = strrchr(fn, '.');
			if (p) {
				if (!strcasecmp(p + 1, "dat"))
					ftype = INTEL_UC_FT_DAT;
				/*
				 * Unneeded due to default to bin mode
				 *
				else if (!strcasecmp(p + 1, "bin"))
					ftype = INTEL_UC_FT_BIN;
				else if (!strcasecmp(p + 1, "fw"))
					ftype = INTEL_UC_FT_BIN;
				*/
			}
		}

		/* default to bin mode */
		if (ftype == INTEL_UC_FT_UNKNOWN)
			ftype = INTEL_UC_FT_BIN;

		err = __load_intel_microcode_file(fd, NULL, fn, ftype);
	} while (dir && (!err || ignore_bad_ucode));

	if (dir)
		closedir(dir);
	if (fd != -1)
		close(fd);
	return err;
}

/* Microcode write (binary format) and kernel upload */

static ssize_t __write_intel_microcode_entry(const int fd,
						const void * const uc,
						const uint32_t uc_size)
{
	const void *p;
	ssize_t len, s;

	len = uc_size;
	if (len < 0)
		return -EINVAL;

	p = uc;
	while (len > 0) {
		s = write(fd, p, len);
		if (s == -1) {
			if (errno != EINTR)
				return -errno;
		} else {
			p += s;
			len -= s;
		}
	}

	return uc_size;
}

static void log_microcode_action(const char * const action,
				const char * const devname,
				const struct intel_uclist_entry * const uce)
{
	char id_str[UCODE_ID_MAX_LEN];

	str_append_ucode_id(uce->id, uce->gid, id_str, sizeof(id_str));
	print_msg_u("%s: %s microcode %s (sig 0x%08x, pf_mask 0x%02x, rev 0x%04x)",
		    devname, action, id_str,
		    uce->cpuid, uce->pf_mask, uce->uc_rev);
}

/**
 * upload_intel_microcodes() - uploads microcodes to kernel device
 * @devname:		device path
 * @uc_write_list:	uclist with the microcodes to write
 *
 * returns 0 if successful, or errno() if a problem happens
 */
static int upload_intel_microcodes(const char * const devname,
				  struct intel_uclist_entry *uc_write_list)
{
	int fd;
	struct stat stat;
	int err = 0;
	size_t total_written = 0;
	unsigned int entries_written = 0;
	ssize_t rc;

	assert(uc_write_list);
	assert(devname);

	fd = open(devname, O_WRONLY);
	if (fd == -1) {
		err = errno;
		print_err("%s: cannot open for writing: %s",
			  devname, strerror(err));
		return err;
	}
	/* Is it a char device? */
	if (fstat(fd, &stat) == -1) {
		err = errno;
		print_err("%s: cannot stat: %s", devname, strerror(err));
		return err;
	}
	if (!S_ISCHR(stat.st_mode)) {
		print_err("%s: not a character device", devname);
		return EINVAL;
	}

	while (uc_write_list && uc_write_list->uc) {
		if (verbosity >= 3)
			log_microcode_action("uploading",
					     devname, uc_write_list);

		rc = __write_intel_microcode_entry(fd,
					uc_write_list->uc,
					uc_write_list->uc_size);
		if (rc < 0) {
			err = -rc;
			print_err("%s: write error: %s",
				  devname, strerror(err));
			break;
		} else {
			total_written += rc;
			uc_write_list = uc_write_list->next;
			entries_written++;
		}
	}

	if (close(fd)) {
		err = errno;
		print_err("%s: error while closing device: %s",
			  devname, strerror(err));
	}

	if (!err)
		print_msg(2, "%s: %u microcode entries uploaded, %zu bytes",
			  devname, entries_written, total_written);

	return err;
}

/**
 * write_intel_microcodes() - writes microcodes to bin file
 * @filename:		file to write to
 * @uc_write_list:	uclist with the microcodes to write
 *
 * returns 0 if successful, or errno() if a problem happens
 */
static int write_intel_microcodes(const char * const filename,
				  struct intel_uclist_entry *uc_write_list)
{
	int fd;
	int err = 0;
	size_t total_written = 0;
	unsigned int entries_written = 0;
	ssize_t rc;

	assert(uc_write_list);
	assert(filename);

	/* Unlink first */
	if (unlink_files) {
		if (unlink(filename) == -1) {
			if (errno != ENOENT) {
				err = errno;
				print_err("%s: cannot unlink: %s", filename,
					  strerror(err));
				return err;
			}
		} else {
			print_msg(3, "unlinked %s", filename);
		}
	}
	fd = open(filename, O_CREAT | O_WRONLY | O_EXCL,
			    S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
	if (fd == -1) {
		err = errno;
		print_err("%s: cannot write to, or create file: %s",
			  filename, strerror(err));
		return err;
	}

	while (uc_write_list && uc_write_list->uc) {
		if (verbosity >= 3)
			log_microcode_action("writing",
					     filename, uc_write_list);

		rc = __write_intel_microcode_entry(fd,
					uc_write_list->uc,
					uc_write_list->uc_size);
		if (rc < 0) {
			err = -rc;
			print_err("%s: write error: %s",
				  filename, strerror(err));
			break;
		} else {
			total_written += rc;
			uc_write_list = uc_write_list->next;
			entries_written++;
		}
	}

	if (close(fd)) {
		err = errno;
		print_err("%s: error while closing file: %s",
			  filename, strerror(err));
	}

	if (!err)
		print_msg(2, "%s: %u microcode entries written, %zu bytes",
			  filename, entries_written, total_written);

	return err;
}

/* Microcode filtering */

#define PFMASK_MATCH_ANY 0xffffffffU

static int is_in_date_range(const struct intel_ucode_metadata * const m)
{
	const uint32_t d = (m->date_year << 16) | (m->date_month << 8) |
			   (m->date_day);
	return !!((d > datefilter_min) && (d < datefilter_max));
}

static void free_filter_list(struct microcode_filter_entry *f)
{
	static struct microcode_filter_entry *p;

	while (f) {
		p = f;
		f = f->next;
		free(p);
	}
}

static void __merge_filter(struct microcode_filter_entry * const f,
			 const uint32_t pf_mask, const int invert)
{
	if (f->invert == invert) {
		f->pf_mask |= pf_mask;
	} else if (!(f->invert)) {
		f->pf_mask &= ~pf_mask;
	} else {
		f->invert = 0;
		f->pf_mask = pf_mask;
	}
}

static int add_filter_to_list(uint32_t cpuid, uint32_t pf_mask, int invert,
				struct microcode_filter_entry ** const base)
{
	struct microcode_filter_entry **pnext, *n;

	assert(base);

	if (!pf_mask)
		pf_mask = PFMASK_MATCH_ANY;

	pnext = base;
	/* search for matching cpuid */
	while (*pnext && (*pnext)->cpuid < cpuid)
		pnext = &((*pnext)->next);

	if (*pnext && (*pnext)->cpuid == cpuid) {
		if (((pf_mask & (*pnext)->pf_mask) == pf_mask) &&
		     ((*pnext)->invert == invert)) {
			/* found equivalent, report it */
			return EEXIST;
		}

		__merge_filter(*pnext, pf_mask, invert);
		return 0;
	}

	/* insert before */
	n = malloc(sizeof(struct microcode_filter_entry));
	if (!n)
		return ENOMEM;
	n->cpuid = cpuid;
	n->pf_mask = pf_mask;
	n->invert = invert;
	n->next = *pnext;
	*pnext = n;

	return 0;
}

/* After calling this, "entries" becomes invalid */
static void add_filter_list_to_list(
			struct microcode_filter_entry ** const base,
			struct microcode_filter_entry *entries)
{
	struct microcode_filter_entry **pp;

	assert(base);

	/* both lists are sorted, no need to rescan from the
	 * beginning at every iteration */
	pp = base;
	while (entries) {
		struct microcode_filter_entry *e;

		e = entries;
		entries = entries->next;

		while (*pp && (*pp)->cpuid < e->cpuid)
			pp = &((*pp)->next);

		if (*pp && (*pp)->cpuid == e->cpuid) {
			__merge_filter(*pp, e->pf_mask, e->invert);
		} else {
			/* insert before */
			e->next = *pp;
			*pp = e;
			e = NULL;
		}
		if (e)
			free(e);
	}
}

/* returns non-zero if selected */
static int is_selected(uint32_t cpuid, uint32_t pf_mask,
			const struct microcode_filter_entry *f)
{
	while (f && f->cpuid < cpuid)
		f = f->next;
	while (f && f->cpuid == cpuid) {
		if ((pf_mask & f->pf_mask) != 0 ||
		    f->pf_mask == PFMASK_MATCH_ANY)
			return !(f->invert);
		f = f->next;
	}

	return filter_list_allow;
}

/* Microcode processing */

static int __uclist_add_print_errors(int status)
{
	switch (status) {
	case EEXIST:
	case 0:
		return 0;
	case ENOMEM:
		print_err("Cannot add index entry: out of memory");
		return 1;
	case EINVAL:
		print_err("Internal error uclist_add_signature() returned EINVAL");
		return 1;
	default:
		return 1;
	}
}

static int __process_ucode_signature(void *userdata,
				unsigned int const sig_count,
				uint32_t const cpuid,
				uint32_t const pf_mask,
				const void * const uc_data,
				unsigned int const uc_data_size,
				const void * const uc,
				unsigned int const uc_size)
{
	struct microcode_interator_data * const ctx = userdata;
	struct intel_ucode_metadata m;
	intel_ucode_status_t s;
	int add_status = ENOENT;

	assert(ctx);

	ctx->total_signature_count++;

	s = intel_ucode_getmetadata(uc, &m);
	if (s != INTEL_UCODE_NOERROR) {
		print_err("Microcode entry %s: %s",
			  ctx->current_uc_id_str, intel_ucode_errstr(s));
		return 1;
	}

	if (is_in_date_range(&m) &&
	    is_selected(cpuid, pf_mask, uc_filter_list)) {
		add_status = uclist_add_signature(ctx->current_uc,
					ctx->current_bundle->id,
					cpuid, pf_mask, m.revision,
					uc, uc_size, allow_downgrade,
					&microcodes);
		if (add_status && add_status != EEXIST) {
			print_err("Failed to select microcode entry %s: %s",
				  ctx->current_uc_id_str, strerror(add_status));
			return 1;
		}
	}

	if (list_all_microcodes) {
		if (!sig_count)
			printf("  %6s: sig 0x%08x, pf mask 0x%02x, "
				"%04x-%02x-%02x, rev 0x%04x, size %u\n",
				ctx->current_uc_id_str, cpuid, pf_mask,
				m.date_year, m.date_month, m.date_day,
				m.revision, uc_size);
		else
			printf("          sig 0x%08x, pf mask 0x%02x, "
				"%04x-%02x-%02x, rev 0x%04x\n",
				cpuid, pf_mask,
				m.date_year, m.date_month, m.date_day,
				m.revision);
	}

	switch (add_status) {
	case 0:
	case ENOENT:
	case EEXIST:
		break;
	default:
		return __uclist_add_print_errors(add_status);
	}

	return 0;
}

static int __process_ucode_entry(void *userdata,
			         unsigned int const uc_count,
			         const void * const uc)
{
	struct microcode_interator_data * const ctx = userdata;
	intel_ucode_status_t s;

	assert(ctx);

	ctx->current_uc = uc_count;
	str_append_ucode_id(ctx->current_uc, ctx->current_bundle->id,
			    ctx->current_uc_id_str,
			    sizeof(ctx->current_uc_id_str));

	s = intel_ucode_check_microcode(uc, strict_checks);
	if (s != INTEL_UCODE_NOERROR) {
		print_err("microcode %s: %s", ctx->current_uc_id_str,
			  intel_ucode_errstr(s));
		return (ignore_bad_ucode) ? 0 : 1;
	}

	ctx->total_entry_count++;

	s = intel_ucode_foreach_signature(uc, __process_ucode_signature,
					  userdata);
	if (s != INTEL_UCODE_NOERROR && !ignore_bad_ucode) {
		print_err("aborting microcode processing...");
		return 1;
	}

	return 0;
}

static int __show_ucode_signature_and_count(void *userdata,
				unsigned int const sig_count,
				uint32_t const cpuid,
				uint32_t const pf_mask,
				const void * const uc_data,
				unsigned int const uc_data_size,
				const void * const uc,
				unsigned int const uc_size)
{
	unsigned long int * const counter = userdata;

	assert(counter);

	(*counter)++;

	if (list_sel_microcodes) {
		struct intel_ucode_metadata m;

		intel_ucode_getmetadata(uc, &m);
		if (!sig_count)
			printf("%03lu: sig 0x%08x, pf mask 0x%02x, "
				"%04x-%02x-%02x, rev 0x%04x, size %u\n",
				*counter, cpuid, pf_mask,
				m.date_year, m.date_month, m.date_day,
				m.revision, uc_size);
		else
			printf("     sig 0x%08x, pf mask 0x%02x, "
				"%04x-%02x-%02x, rev 0x%04x\n",
				cpuid, pf_mask,
				m.date_year, m.date_month, m.date_day,
				m.revision);
	}

	return 0;
}

static int do_process_microcodes(void)
{
	intel_ucode_status_t s;
	struct microcode_bundle *mcb;

	memset(&microcode_interator_data, 0, sizeof(microcode_interator_data));
	mcb = microcode_bundles;

	while (mcb) {
		if (list_all_microcodes) {
			if (mcb->filename) {
				printf("microcode bundle %lu: %s\n",
					mcb->id, mcb->filename);
			} else {
				printf("microcode bundle %lu:\n",
					mcb->id);
			}
		}
		microcode_interator_data.current_bundle = mcb;
		s = intel_ucode_foreach_microcode(mcb->data, mcb->size,
						__process_ucode_entry,
						&microcode_interator_data);
		if (s != INTEL_UCODE_NOERROR) {
			if (s != INTEL_UCODE_CALLBACK_ERROR)
				print_err("microcode bundle %s: %s",
					mcb->filename ? mcb->filename : "(no filename)",
					intel_ucode_errstr(s));

			if (!ignore_bad_ucode)
				return 1;
		}

		mcb = mcb->next;
	}

	print_msg(2, "processed %lu valid microcode(s), %lu signature(s)",
		  microcode_interator_data.total_entry_count,
		  microcode_interator_data.total_signature_count);

	/*
	 * we iterate over all selected microcodes only once, either
	 * to list selected microcodes, or to gather some stats when
	 * the verbosity is high
	 */
	if (list_sel_microcodes || verbosity >= 2) {
		struct intel_uclist_entry *uce;
		unsigned long uccount = 0;
		unsigned long sigcount = 0;

		if (list_sel_microcodes)
			printf("selected microcodes:\n");

		uce = microcodes;
		s = INTEL_UCODE_NOERROR;
		while (uce && s == INTEL_UCODE_NOERROR) {
			uccount++;
			s = intel_ucode_foreach_signature(uce->uc,
					__show_ucode_signature_and_count, &sigcount);
			uce = uce->next;
		}
		if (s == INTEL_UCODE_NOERROR) {
			print_msg(2, "selected %lu microcode(s), %lu signature(s)",
				  uccount, sigcount);
		}
	}

	return 0;
}

static int do_write_microcode(const char * const filename)
{
	if (!microcodes)
		return 0;

	print_msg(1, "Writing selected microcodes to: %s", filename);
	return write_intel_microcodes(filename, microcodes);
}

static int do_upload_microcode(const char * const filename)
{
	if (!microcodes)
		return 0;

	print_msg(1, "Uploading selected microcodes to: %s", filename);
	return upload_intel_microcodes(filename, microcodes);
}

static int do_write_named(const char * const dirname)
{
	char fn[PATH_MAX];
	struct stat st;

	struct intel_uclist_entry e, *p;
	unsigned long int count;
	int rc;

	if (!microcodes)
		return 0;

	/* were we given a directory ? */
	if (stat(dirname, &st) == -1) {
		int err = errno;
		print_err("%s: cannot stat inode: %s", dirname,
			  strerror(err));
		return err;
	}
	if (!S_ISDIR(st.st_mode)) {
		print_err("%s: is not a directory", dirname);
		return EINVAL;
	}

	print_msg(1, "Writing microcode file(s) into %s", dirname);

	p = microcodes;
	count = 0;
	rc = 0;

	while (p && !rc) {
		/* write to file in dirname/ */
		rc = snprintf(fn, sizeof(fn), "%s/s%08X_m%08X_r%08X.fw", dirname,
			     p->cpuid, p->pf_mask, p->uc_rev);
		if (rc < 1 || rc >= sizeof(fn)) {
			print_err("%s: directory name too long, cannot create files inside",
				  dirname);
			return EINVAL;
		}

		memcpy(&e, p, sizeof(e));
		e.next = NULL;
		rc = write_intel_microcodes(fn, &e);
		if (!rc)
			count++;

		p = p->next;
	}
	if (count)
		print_msg(2, "%lu file(s) were written into %s", count, dirname);
	else
		print_msg(1, "no files were written into %s", dirname);

	return rc;
}

static int do_write_firmware(const char * const dirname)
{
	char fn[PATH_MAX];
	struct stat st;

	struct intel_uclist_entry *samecpuid_list, *p;
	unsigned long int count;
	int rc;

	if (!microcodes)
		return 0;

	/* were we given a directory ? */
	if (stat(dirname, &st) == -1) {
		int err = errno;
		print_err("%s: cannot stat inode: %s", dirname,
			  strerror(err));
		return err;
	}
	if (!S_ISDIR(st.st_mode)) {
		print_err("%s: is not a directory", dirname);
		return EINVAL;
	}

	print_msg(1, "Writing microcode firmware file(s) into %s", dirname);

	p = microcodes;
	samecpuid_list = NULL;
	count = 0;
	rc = 0;

	/* the lists are already ordered by cpuid */
	while (p && !rc) {
		uint32_t cpuid;
		unsigned int x86_family, x86_model, x86_mask;
		int add_status;

		/* select all that share the same cpuid */
		cpuid = p->cpuid;
		while (p && p->cpuid == cpuid) {
			add_status = uclist_add_signature(p->id, p->gid,
						p->cpuid, p->pf_mask,
						p->uc_rev, p->uc, p->uc_size,
						0, &samecpuid_list);
			if (__uclist_add_print_errors(add_status))
				return add_status;

			p = p->next;
		}

		/* write to file in dirname/ as expected by the kernel */

		x86_family = (cpuid >> 8) & 0x0f;
		x86_model  = (cpuid >> 4) & 0x0f;
		x86_mask   = cpuid & 0x0f;
		if (x86_family == 0x0f)
			x86_family += (cpuid >> 20) & 0xff;
		if (x86_family >= 0x06)
			x86_model += ((cpuid >> 16) & 0x0f) << 4;

		rc = snprintf(fn, sizeof(fn), "%s/%02x-%02x-%02x", dirname,
			     x86_family, x86_model, x86_mask);
		if (rc < 1 || rc >= sizeof(fn)) {
			print_err("%s: directory name too long, cannot create files inside",
				  dirname);
			return EINVAL;
		}

		rc = write_intel_microcodes(fn, samecpuid_list);

		free_uclist(samecpuid_list);
		samecpuid_list = NULL;

		if (!rc)
			count++;
	}
	if (count)
		print_msg(2, "%lu file(s) were written into %s", count, dirname);
	else
		print_msg(1, "no files were written into %s", dirname);

	return rc;
}

static int scan_system_processors(void)
{
	char cpuid_device[PATH_MAX];
	uint32_t cpuid_buf[8];
	struct microcode_filter_entry *uc_cpu = NULL;

	int cpuid_fd;
	unsigned int i = 0;
	unsigned int ncpu = 0;
	int rc = 0;

	while (1) {
		snprintf(cpuid_device, sizeof(cpuid_device),
			 CPUID_DEVICE_BASE, i);
		cpuid_fd = open(cpuid_device, O_RDONLY);
		if (cpuid_fd == -1) {
			if (errno == EINTR)
				continue; /* try again */
			else if (errno == ENOENT)
				break; /* EOL */

			/* skip this processor */
			print_msg(2, "skipping processor %u (not online?): %d",
				  i, errno);
			i++;
			continue;
		}
		print_msg(3, "trying to get CPUID information from %s",
			  cpuid_device);
		if (read(cpuid_fd, &cpuid_buf, sizeof(cpuid_buf)) == -1) {
			print_err("%s: access to CPUID(0) and CPUID(1) failed",
				  cpuid_device);
			/* this is in the should not happen list, so abort */
			close(cpuid_fd);
			rc = 1;
			goto err_out;
		}
		close(cpuid_fd);

		ncpu++;

		/* Is it a supported Intel processor ? */
		if (cpuid_buf[0] > 0 && /* we need cpuid(1) to exist */
		    cpuid_buf[1] == 0x756e6547 && /* "Genu" */
		    cpuid_buf[3] == 0x49656e69 && /* "ineI" */
		    cpuid_buf[2] == 0x6c65746e) { /* "ntel" */
			/*
			 * Get main processor signature from cpuid(1) EAX
			 * and add it as a filter.
			 */
			switch (add_filter_to_list(cpuid_buf[4], 0, 0, &uc_cpu)) {
			case ENOMEM:
				print_err("out of memory");
				rc = 1;
				goto err_out;
			case EEXIST:
				break;
			default:
				print_msg(1, "system has processor(s) with signature 0x%08x",
					  cpuid_buf[4]);
			}
		} else {
			if (!uc_cpu) {
				/* shortcut search, assume none will be found */
				print_msg(2, "non-Intel processor found, skipping scan");
				break;
			}
		}

		i++;
	};

	/*
	 * Be helpful: tell user why we're not doing what he explicitly
	 * requested if we cannot get any cpuids at all.
	 *
	 * fail-safe: we only switch away from "select all microcodes by default"
	 * if we managed to scan, so we will include all microcodes if cpuid is not
	 * available, and no other microcode selection option was used
	 */
	if (i == 0 && ncpu == 0) {
		print_err("cpuid kernel driver unavailable, cannot scan system processor signatures");
		rc = 0;
		goto err_out;
	}

	/* we managed to scan, do not select every microcode by default */
	filter_list_allow = 0;

	if (uc_cpu) {
		/* tie linked lists */
		add_filter_list_to_list(&uc_filter_list, uc_cpu);
		uc_cpu = NULL;
	}
	print_msg(2, "checked the signature of %u processor(s)", ncpu);

err_out:
	if (uc_cpu)
		free_filter_list(uc_cpu);

	return rc;
}

/* Command line processing */

const char program_version[] =
	PROGNAME " " VERSION "\n"
	"Copyright (c) 2010-2012 by Henrique de Moraes Holschuh\n\n"

	"Based on code from the Linux microcode_intel driver and from\n"
	"the microcode.ctl package, copyright (c) 2000 by Simon Trimmer\n"
	"and Tigran Aivazian.\n\n"

	"This is free software; see the source for copying conditions.\n"
	"There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR\n"
	"A PARTICULAR PURPOSE.";
const char program_bug_address[] = PACKAGE_BUGREPORT;

static char cmdline_doc[] =
	PROGNAME " - Tool to manipulate Intel IA32/X86_64 microcode bundles\n"

	"\v"

	"The microcode bundle files should be specified as arguments.  "
	"The bundle type is determined by the file name suffix.  It "
	"defaults to the binary format.\n\n"

	"Should the filename end with \".bin\", binary mode will be "
	"used.  Should the filename end with \".dat\", text mode will be "
	"used.  The -t option can be used to set the type of the "
	"microcode bundle files that come after it, e.g. "
	"-td /tmp/dat-file -tb /tmp/binary /tmp/binary2.\n\n"

	"To load microcode data from stdin, use \"-\" as the filename.  "
	"File type will be assumed to be text (\".dat\"), use option -tb "
	"to load binary data from stdin.";

enum {
	IUCODE_ARGP_STRICTCHK = 0x81,
	IUCODE_ARGP_NOSTRICTCHK,
	IUCODE_ARGP_IGNOREBROKEN,
	IUCODE_ARGP_NOIGNOREBROKEN,
	IUCODE_ARGP_UNLINK,
	IUCODE_ARGP_NOUNLINK,
	IUCODE_ARGP_DOWNGRADE,
	IUCODE_ARGP_NODOWNGRADE,
	IUCODE_ARGP_DATEBEFORE,
	IUCODE_ARGP_DATEAFTER,
};

static struct argp_option cmdline_options[] = {
	{ NULL, 'h', NULL, 0, "Give this help list", -1 },

	{ "quiet",   'q', NULL, 0, "Quiet operation",                1 },
	{ "verbose", 'v', NULL, 0, "Verbose operation (cumulative)", 1 },

	{ NULL, 't', "type", 0,
	   "Sets input file type for the next microcode files. The type is "
	   "a single character: \"b\" (binary), \"d\" (Intel .dat), or \"a\" "
	   "(type will be selected by filename suffix)",
	  10 },

	{ NULL, 's', "[!]signature[,pf_mask]", 0,
	   "Select microcodes by the specificed signature and processor "
	   "flags mask.  Specify more than once to select/unselect more "
	   "microcodes.  Prefix with ! to unselect microcodes",
	  20 },
	{ "scan-system", 'S', NULL, 0,
	   "Select microcodes by scanning all online processors on "
	   "this system for their signatures.  Can be combined with the -s "
	   "option.  Note: this option has precedence over the -s option, "
	   "microcodes selected by --scan-system cannot be unselected by -s",
	  20 },

	{ "downgrade", IUCODE_ARGP_DOWNGRADE, NULL, 0,
	  "Instead of discarding microcodes based on revision level, "
	  "keep the one from the file loaded last.  Files are loaded "
	  "in the order they were specified in the command line",
	  25 },
	{ "no-downgrade", IUCODE_ARGP_NODOWNGRADE, NULL, 0,
	  "Keep the microcode with the highest revision level, regardless "
	  "of the file load order (default)",
	  25 },

	{ "date-before", IUCODE_ARGP_DATEBEFORE, "YYYY-MM-DD", 0,
	  "Select only microcodes older than the specified date",
	  27 },
	{ "date-after", IUCODE_ARGP_DATEAFTER, "YYYY-MM-DD", 0,
	  "Select only microcodes newer than the specified date",
	  27 },

	{ "list",     'l', NULL, 0, "List selected microcode signatures", 30 },
	{ "list-all", 'L', NULL, 0, "List all microcode signatures",      30 },

	{ "kernel", 'k', "device", OPTION_ARG_OPTIONAL,
	   "Upload selected microcodes to the kernel.  Optionally, the "
	   "device path can be specified (default: " MICROCODE_DEVICE_DEFAULT
	   ")",
	  40 },
	{ "write-firmware", 'K', "directory", OPTION_ARG_OPTIONAL,
	   "Write selected microcodes with the filenames expected by the "
	   "Linux kernel firmware loader.  Optionally, the destination "
	   "directory can be specified (default: " MICROCODE_DIR_DEFAULT ")",
	  40 },
	{ "write-to", 'w', "file", 0,
	   "Write selected microcodes to a file in binary format.  "
	   "The binary format is suitable to be uploaded to the kernel",
	  40 },
	{ "write-named-to", 'W', "directory", 0,
	  "Write selected microcodes to files in the specified directory, "
	  "in binary format.  The file name will reflect the microcode "
	  "signature, mask and revision",
	  40 },

	{ "overwrite", IUCODE_ARGP_UNLINK, NULL, 0,
	   "Unlink (remove) destination files before writing",
	  45 },
	{ "no-overwrite", IUCODE_ARGP_NOUNLINK, NULL, 0,
	   "Do not remove existing files (default)",
	  45 },

	{ "strict-checks", IUCODE_ARGP_STRICTCHK, NULL, 0,
	   "Perform strict checks on the microcode data (default)",
	  50 },
	{ "no-strict-checks", IUCODE_ARGP_NOSTRICTCHK, NULL, 0,
	   "Perform less strict checks on the microcode data",
	  51 },

	{ "ignore-broken", IUCODE_ARGP_IGNOREBROKEN, NULL, 0,
	  "Skip broken microcode entries instead of aborting",
	  55 },
	{ "no-ignore-broken", IUCODE_ARGP_NOIGNOREBROKEN, NULL, 0,
	  "Abort on broken microcode entries (default)",
	  56 },

	{ NULL, 0 },
};
static char cmdline_nonarg_doc[] = "[[-t<type>] filename] ...";

static int new_filename(const char * const fn,
			intel_ucode_file_type_t ftype)
{
	struct filename_list **p, *n;
	size_t s, l;

	l = strlen(fn);
	if (l > 1 && fn[l-1] == '/')
		l--;

	if (!l)
		return EINVAL;

	s = sizeof(struct filename_list) + l + 1;
	n = malloc(s);
	if (!n)
		return ENOMEM;

	memset(n, 0, s);
	memcpy(n->path, fn, l);
	n->type = ftype;

	/* tail-add */
	p = &input_files;
	while (*p)
		p = &((*p)->next);
	*p = n;

	return 0;
}

static void free_filename_list(void)
{
	struct filename_list *p, *q;

	p = input_files;

	while (p) {
		q = p;
		p = p->next;
		free(q);
	}
	input_files = NULL;
}

/* -s [!]cpuid[,pf_mask] */
static int add_ucode_filter(const char *arg)
{
	char *p;
	uint32_t acpuid, amask;
	int invert;

	amask = 0;
	invert = 0;

	while (isspace(*arg))
		arg++;
	if (*arg == '!') {
		invert = 1;
		arg++;
	}

	errno = 0;
	acpuid = strtoul(arg, &p, 0);
	if (errno || p == arg || !*arg)
		return EINVAL;
	while (isspace(*p))
		p++;

	if (*p == ',') {
		p++;
		arg = p;
		errno = 0;
		amask = strtoul(arg, &p, 0);
		if (errno || p == arg || !*arg)
			return EINVAL;
		while (isspace(*p))
			p++;
		if (*p)
			return EINVAL;
	} else if (*p) {
		return EINVAL;
	}

	if (!invert)
		filter_list_allow = 0;

	return add_filter_to_list(acpuid, amask, invert, &uc_filter_list);
}

/* YYYY-MM-DD */
static int cmdline_get_date(const char *arg, uint32_t *d)
{
	unsigned long int year, month, day;
	char *p;

	while (isspace(*arg))
		arg++;

	errno = 0;
	year = strtoul(arg, &p, 10);
	if (errno || p == arg || *p != '-')
		return EINVAL;
	arg = ++p;
	month = strtoul(arg, &p, 10);
	if (errno || p == arg || *p != '-')
		return EINVAL;
	arg = ++p;
	day = strtoul(arg, &p, 10);
	if (errno || p == arg)
		return EINVAL;
	while (isspace(*p))
		p++;
	if (*p)
		return EINVAL;

	if (year > 9999 || month > 99 || day > 99)
		return EINVAL;

	/* Encode in BCD: YYYYMMDD */
	*d = (year / 1000)     << 28 |
	     (year / 100 % 10) << 24 |
	     (year / 10 % 10)  << 20 |
	     (year % 10)       << 16 |
	     (month / 10)      << 12 |
	     (month % 10)      << 8 |
	     (day / 10)        << 4 |
	     (day % 10);

	return 0;
}

static error_t cmdline_do_parse_arg(int key, char *arg,
				    struct argp_state *state)
{
	int rc;

	switch (key) {
	case 'h':
		argp_state_help(state, stdout, ARGP_HELP_STD_HELP);
		break; /* usually not reached */

	case 'q':
		verbosity = 0;
		break;
	case 'v':
		verbosity++;
		break;

	case 'L':
		list_all_microcodes = 1;
		break;
	case 'l':
		list_sel_microcodes = 1;
		break;

	case 't':
		if (strlen(arg) > 1)
			argp_error(state, "unknown file type: %s\n", arg);
		switch (*arg) {
		case 'd': /* .dat */
			ucfiletype = INTEL_UC_FT_DAT;
			break;
		case 'b': /* .bin */
			ucfiletype = INTEL_UC_FT_BIN;
			break;
		case 'a': /* any (detect) */
			ucfiletype = INTEL_UC_FT_UNKNOWN;
			break;
		default:
			argp_error(state, "unknown file type: %c\n", *arg);
		}
		break;

	case 'k':
		if (command_line_actions & IUCODE_DO_UPLOADUC)
			argp_error(state,
				   "-k option can be specified only once\n");

		if (arg)
			upload_microcode = strdup(arg);
		else
			upload_microcode = strdup(MICROCODE_DEVICE_DEFAULT);

		command_line_actions |= IUCODE_DO_UPLOADUC;
		break;
	case 'K':
		if (command_line_actions & IUCODE_DO_WRITEFW)
			argp_error(state,
				   "-K option can be specified only once\n");

		if (arg)
			write_firmware = strdup(arg);
		else
			write_firmware = strdup(MICROCODE_DIR_DEFAULT);

		command_line_actions |= IUCODE_DO_WRITEFW;
		break;
	case 'w':
		if (command_line_actions & IUCODE_DO_WRITEUC)
			argp_error(state,
				   "-w option can be specified only once\n");

		write_microcode = strdup(arg);
		command_line_actions |= IUCODE_DO_WRITEUC;
		break;
	case 'W':
		if (command_line_actions & IUCODE_DO_WRITEFWN)
			argp_error(state,
				   "-W option can be specified only once\n");

		write_named = strdup(arg);

		command_line_actions |= IUCODE_DO_WRITEFWN;
		break;

	case IUCODE_ARGP_UNLINK:
		unlink_files = 1;
		break;
	case IUCODE_ARGP_NOUNLINK:
		unlink_files = 0;
		break;

	case 's':
		rc = add_ucode_filter(arg);
		switch (rc) {
		case 0:
		case EEXIST:
			break; /* success */
		case EINVAL:
			argp_error(state, "invalid filter: %s", arg);
			break; /* not reached */
		default:
			argp_failure(state, EXIT_SWFAILURE, rc,
				     "could not add filter '%s'", arg);
		}
		command_line_actions |= IUCODE_F_UCSELECT;
		break;
	case 'S':
		command_line_actions |= IUCODE_DO_SELPROC | IUCODE_F_UCSELECT;
		break;

	case IUCODE_ARGP_DATEBEFORE:
	case IUCODE_ARGP_DATEAFTER:
		if (cmdline_get_date(arg, (key == IUCODE_ARGP_DATEBEFORE) ?
					   &datefilter_max : &datefilter_min))
			argp_error(state, "invalid date: %s", arg);
		command_line_actions |= IUCODE_F_UCSELECT;
		break;

	case IUCODE_ARGP_STRICTCHK:
		strict_checks = 1;
		break;
	case IUCODE_ARGP_NOSTRICTCHK:
		strict_checks = 0;
		break;
	case IUCODE_ARGP_IGNOREBROKEN:
		ignore_bad_ucode = 1;
		break;
	case IUCODE_ARGP_NOIGNOREBROKEN:
		ignore_bad_ucode = 0;
		break;
	case IUCODE_ARGP_DOWNGRADE:
		allow_downgrade = 1;
		break;
	case IUCODE_ARGP_NODOWNGRADE:
		allow_downgrade = 0;
		break;

	case ARGP_KEY_ARG: /* NON-OPTION ARGUMENTS */
		rc = new_filename(arg, ucfiletype);
		if (rc)
			argp_failure(state, EXIT_SWFAILURE, rc,
				     "could not add path '%s'", arg);
		command_line_actions |= IUCODE_DO_LOADFILE;
		break;

	default:
		return ARGP_ERR_UNKNOWN;
	}

	return 0;
}

static struct argp cmdline_argp = {
	.options  = cmdline_options,
	.parser   = cmdline_do_parse_arg,
	.args_doc = cmdline_nonarg_doc,
	.doc      = cmdline_doc };

int main(int argc, char *argv[])
{
	int rc;

	progname = argv[0];

	argp_err_exit_status = EXIT_USAGE;
	argp_program_version = program_version;
	argp_program_bug_address = NULL; /* FIXME */
	argp_parse(&cmdline_argp, argc, argv, ARGP_IN_ORDER, 0, NULL);

	if (!command_line_actions) {
		print_msg(1, "nothing to do...");
		goto do_nothing;
	}

	if ((command_line_actions & IUCODE_DO_SELPROC) &&
	    scan_system_processors()) {
		rc = EXIT_SWFAILURE;
		goto err_exit;
	}

	if (command_line_actions & IUCODE_DO_LOADFILE) {
		struct filename_list *fn = input_files;
		while (fn) {
			switch (load_intel_microcode(fn->path, fn->type)) {
			case 0:
				break;
			case ENOTSUP:
				rc = EXIT_USAGE;
				goto err_exit;
			default:
				if (!ignore_bad_ucode) {
					rc = EXIT_SWFAILURE;
					goto err_exit;
				}
			}
			fn = fn->next;
		}

		if (do_process_microcodes()) {
			rc = EXIT_SWFAILURE;
			goto err_exit;
		}
	}

	if (command_line_actions & IUCODE_DOMASK_NEEDSUC) {
		if (microcodes) {
			rc = 0;
			if (upload_microcode)
				rc = do_upload_microcode(upload_microcode);
			if (!rc && write_microcode)
				rc = do_write_microcode(write_microcode);
			if (!rc && write_firmware)
				rc = do_write_firmware(write_firmware);
			if (!rc && write_named)
				rc = do_write_named(write_named);

			if (rc) {
				rc = EXIT_SWFAILURE;
				goto err_exit;
			}
		} else {
			if (filter_list_active()) {
				print_msg(1, "No valid microcodes were selected, nothing to do...");
			} else {
				print_msg(1, "No valid microcodes were loaded, nothing to do...");
			}
		}
	}

do_nothing:
	rc = 0;
err_exit:

	/* Disable all of this cleanup for some speedup... */
#ifdef VALGRIND_BUILD
	free(write_microcode);
	free(upload_microcode);
	free(write_firmware);
	free(write_named);

	free_filter_list(uc_filter_list);
	uc_filter_list = NULL;
	free_uclist(microcodes);
	microcodes = NULL;
	free_intel_microcode_bundles();
	free_filename_list();
#endif /* VALGRIND_BUILD */

	return rc;
}