xref: /freebsd/sys/dev/jedec_dimm/jedec_dimm.c (revision 389e4940069316fe667ffa263fa7d6390d0a960f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Authors: Ravi Pokala (rpokala@freebsd.org), Andriy Gapon (avg@FreeBSD.org)
5  *
6  * Copyright (c) 2016 Andriy Gapon <avg@FreeBSD.org>
7  * Copyright (c) 2018 Panasas
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * $FreeBSD$
32  */
33 
34 /*
35  * This driver is a super-set of jedec_ts(4), and most of the code for reading
36  * and reporting the temperature is either based on that driver, or copied
37  * from it verbatim.
38  */
39 
40 #include <sys/param.h>
41 #include <sys/kernel.h>
42 #include <sys/bus.h>
43 #include <sys/endian.h>
44 #include <sys/malloc.h>
45 #include <sys/module.h>
46 #include <sys/sysctl.h>
47 #include <sys/systm.h>
48 
49 #include <dev/jedec_dimm/jedec_dimm.h>
50 #include <dev/smbus/smbconf.h>
51 #include <dev/smbus/smbus.h>
52 
53 #include "smbus_if.h"
54 
55 struct jedec_dimm_softc {
56 	device_t dev;
57 	device_t smbus;
58 	uint8_t spd_addr;	/* SMBus address of the SPD EEPROM. */
59 	uint8_t tsod_addr;	/* Address of the Thermal Sensor On DIMM */
60 	uint32_t capacity_mb;
61 	char type_str[5];
62 	char part_str[21]; /* 18 (DDR3) or 20 (DDR4) chars, plus terminator */
63 	char serial_str[9]; /* 4 bytes = 8 nybble characters, plus terminator */
64 	char *slotid_str; /* Optional DIMM slot identifier (silkscreen) */
65 };
66 
67 /* General Thermal Sensor on DIMM (TSOD) identification notes.
68  *
69  * The JEDEC TSE2004av specification defines the device ID that all compliant
70  * devices should use, but very few do in practice. Maybe that's because the
71  * earlier TSE2002av specification was rather vague about that.
72  * Rare examples are IDT TSE2004GB2B0 and Atmel AT30TSE004A, not sure if
73  * they are TSE2004av compliant by design or by accident.
74  * Also, the specification mandates that PCI SIG manufacturer IDs are to be
75  * used, but in practice the JEDEC manufacturer IDs are often used.
76  */
77 const struct jedec_dimm_tsod_dev {
78 	uint16_t	vendor_id;
79 	uint8_t		device_id;
80 	const char	*description;
81 } known_tsod_devices[] = {
82 	/* Analog Devices ADT7408.
83 	 * http://www.analog.com/media/en/technical-documentation/data-sheets/ADT7408.pdf
84 	 */
85 	{ 0x11d4, 0x08, "Analog Devices TSOD" },
86 
87 	/* Atmel AT30TSE002B, AT30TSE004A.
88 	 * http://www.atmel.com/images/doc8711.pdf
89 	 * http://www.atmel.com/images/atmel-8868-dts-at30tse004a-datasheet.pdf
90 	 * Note how one chip uses the JEDEC Manufacturer ID while the other
91 	 * uses the PCI SIG one.
92 	 */
93 	{ 0x001f, 0x82, "Atmel TSOD" },
94 	{ 0x1114, 0x22, "Atmel TSOD" },
95 
96 	/* Integrated Device Technology (IDT) TS3000B3A, TSE2002B3C,
97 	 * TSE2004GB2B0 chips and their variants.
98 	 * http://www.idt.com/sites/default/files/documents/IDT_TSE2002B3C_DST_20100512_120303152056.pdf
99 	 * http://www.idt.com/sites/default/files/documents/IDT_TS3000B3A_DST_20101129_120303152013.pdf
100 	 * https://www.idt.com/document/dst/tse2004gb2b0-datasheet
101 	 */
102 	{ 0x00b3, 0x29, "IDT TSOD" },
103 	{ 0x00b3, 0x22, "IDT TSOD" },
104 
105 	/* Maxim Integrated MAX6604.
106 	 * Different document revisions specify different Device IDs.
107 	 * Document 19-3837; Rev 0; 10/05 has 0x3e00 while
108 	 * 19-3837; Rev 3; 10/11 has 0x5400.
109 	 * http://datasheets.maximintegrated.com/en/ds/MAX6604.pdf
110 	 */
111 	{ 0x004d, 0x3e, "Maxim Integrated TSOD" },
112 	{ 0x004d, 0x54, "Maxim Integrated TSOD" },
113 
114 	/* Microchip Technology MCP9805, MCP9843, MCP98242, MCP98243
115 	 * and their variants.
116 	 * http://ww1.microchip.com/downloads/en/DeviceDoc/21977b.pdf
117 	 * Microchip Technology EMC1501.
118 	 * http://ww1.microchip.com/downloads/en/DeviceDoc/00001605A.pdf
119 	 */
120 	{ 0x0054, 0x00, "Microchip TSOD" },
121 	{ 0x0054, 0x20, "Microchip TSOD" },
122 	{ 0x0054, 0x21, "Microchip TSOD" },
123 	{ 0x1055, 0x08, "Microchip TSOD" },
124 
125 	/* NXP Semiconductors SE97 and SE98.
126 	 * http://www.nxp.com/docs/en/data-sheet/SE97B.pdf
127 	 */
128 	{ 0x1131, 0xa1, "NXP TSOD" },
129 	{ 0x1131, 0xa2, "NXP TSOD" },
130 
131 	/* ON Semiconductor CAT34TS02 revisions B and C, CAT6095 and compatible.
132 	 * https://www.onsemi.com/pub/Collateral/CAT34TS02-D.PDF
133 	 * http://www.onsemi.com/pub/Collateral/CAT6095-D.PDF
134 	 */
135 	{ 0x1b09, 0x08, "ON Semiconductor TSOD" },
136 	{ 0x1b09, 0x0a, "ON Semiconductor TSOD" },
137 
138 	/* ST[Microelectronics] STTS424E02, STTS2002 and others.
139 	 * http://www.st.com/resource/en/datasheet/cd00157558.pdf
140 	 * http://www.st.com/resource/en/datasheet/stts2002.pdf
141 	 */
142 	{ 0x104a, 0x00, "ST Microelectronics TSOD" },
143 	{ 0x104a, 0x03, "ST Microelectronics TSOD" },
144 };
145 
146 static int jedec_dimm_attach(device_t dev);
147 
148 static int jedec_dimm_capacity(struct jedec_dimm_softc *sc, enum dram_type type,
149     uint32_t *capacity_mb);
150 
151 static int jedec_dimm_detach(device_t dev);
152 
153 static int jedec_dimm_dump(struct jedec_dimm_softc *sc, enum dram_type type);
154 
155 static int jedec_dimm_field_to_str(struct jedec_dimm_softc *sc, char *dst,
156     size_t dstsz, uint16_t offset, uint16_t len, bool ascii);
157 
158 static int jedec_dimm_probe(device_t dev);
159 
160 static int jedec_dimm_readw_be(struct jedec_dimm_softc *sc, uint8_t reg,
161     uint16_t *val);
162 
163 static int jedec_dimm_temp_sysctl(SYSCTL_HANDLER_ARGS);
164 
165 static const char *jedec_dimm_tsod_match(uint16_t vid, uint16_t did);
166 
167 
168 /**
169  * device_attach() method. Read the DRAM type, use that to determine the offsets
170  * and lengths of the asset string fields. Calculate the capacity. If a TSOD is
171  * present, figure out exactly what it is, and update the device description.
172  * If all of that was successful, create the sysctls for the DIMM. If an
173  * optional slotid has been hinted, create a sysctl for that too.
174  *
175  * @author rpokala
176  *
177  * @param[in,out] dev
178  *      Device being attached.
179  */
180 static int
181 jedec_dimm_attach(device_t dev)
182 {
183 	uint8_t byte;
184 	uint16_t devid;
185 	uint16_t partnum_len;
186 	uint16_t partnum_offset;
187 	uint16_t serial_len;
188 	uint16_t serial_offset;
189 	uint16_t tsod_present_offset;
190 	uint16_t vendorid;
191 	bool tsod_present;
192 	int rc;
193 	int new_desc_len;
194 	enum dram_type type;
195 	struct jedec_dimm_softc *sc;
196 	struct sysctl_ctx_list *ctx;
197 	struct sysctl_oid *oid;
198 	struct sysctl_oid_list *children;
199 	const char *tsod_match;
200 	const char *slotid_str;
201 	char *new_desc;
202 
203 	sc = device_get_softc(dev);
204 	ctx = device_get_sysctl_ctx(dev);
205 	oid = device_get_sysctl_tree(dev);
206 	children = SYSCTL_CHILDREN(oid);
207 
208 	bzero(sc, sizeof(*sc));
209 	sc->dev = dev;
210 	sc->smbus = device_get_parent(dev);
211 	sc->spd_addr = smbus_get_addr(dev);
212 
213 	/* The TSOD address has a different DTI from the SPD address, but shares
214 	 * the LSA bits.
215 	 */
216 	sc->tsod_addr = JEDEC_DTI_TSOD | (sc->spd_addr & 0x0f);
217 
218 	/* Read the DRAM type, and set the various offsets and lengths. */
219 	rc = smbus_readb(sc->smbus, sc->spd_addr, SPD_OFFSET_DRAM_TYPE, &byte);
220 	if (rc != 0) {
221 		device_printf(dev, "failed to read dram_type: %d\n", rc);
222 		goto out;
223 	}
224 	type = (enum dram_type) byte;
225 	switch (type) {
226 	case DRAM_TYPE_DDR3_SDRAM:
227 		(void) snprintf(sc->type_str, sizeof(sc->type_str), "DDR3");
228 		partnum_len = SPD_LEN_DDR3_PARTNUM;
229 		partnum_offset = SPD_OFFSET_DDR3_PARTNUM;
230 		serial_len = SPD_LEN_DDR3_SERIAL;
231 		serial_offset = SPD_OFFSET_DDR3_SERIAL;
232 		tsod_present_offset = SPD_OFFSET_DDR3_TSOD_PRESENT;
233 		break;
234 	case DRAM_TYPE_DDR4_SDRAM:
235 		(void) snprintf(sc->type_str, sizeof(sc->type_str), "DDR4");
236 		partnum_len = SPD_LEN_DDR4_PARTNUM;
237 		partnum_offset = SPD_OFFSET_DDR4_PARTNUM;
238 		serial_len = SPD_LEN_DDR4_SERIAL;
239 		serial_offset = SPD_OFFSET_DDR4_SERIAL;
240 		tsod_present_offset = SPD_OFFSET_DDR4_TSOD_PRESENT;
241 		break;
242 	default:
243 		device_printf(dev, "unsupported dram_type 0x%02x\n", type);
244 		rc = EINVAL;
245 		goto out;
246 	}
247 
248 	if (bootverbose) {
249 		/* bootverbose debuggery is best-effort, so ignore the rc. */
250 		(void) jedec_dimm_dump(sc, type);
251 	}
252 
253 	/* Read all the required info from the SPD. If any of it fails, error
254 	 * out without creating the sysctls.
255 	 */
256 	rc = jedec_dimm_capacity(sc, type, &sc->capacity_mb);
257 	if (rc != 0) {
258 		goto out;
259 	}
260 
261 	rc = jedec_dimm_field_to_str(sc, sc->part_str, sizeof(sc->part_str),
262 	    partnum_offset, partnum_len, true);
263 	if (rc != 0) {
264 		goto out;
265 	}
266 
267 	rc = jedec_dimm_field_to_str(sc, sc->serial_str, sizeof(sc->serial_str),
268 	    serial_offset, serial_len, false);
269 	if (rc != 0) {
270 		goto out;
271 	}
272 
273 	/* The MSBit of the TSOD-presence byte reports whether or not the TSOD
274 	 * is in fact present. If it is, read manufacturer and device info from
275 	 * it to confirm that it's a valid TSOD device. It's an error if any of
276 	 * those bytes are unreadable; it's not an error if the device is simply
277 	 * not known to us (tsod_match == NULL).
278 	 * While DDR3 and DDR4 don't explicitly require a TSOD, essentially all
279 	 * DDR3 and DDR4 DIMMs include one.
280 	 */
281 	rc = smbus_readb(sc->smbus, sc->spd_addr, tsod_present_offset, &byte);
282 	if (rc != 0) {
283 		device_printf(dev, "failed to read TSOD-present byte: %d\n",
284 		    rc);
285 		goto out;
286 	}
287 	if (byte & 0x80) {
288 		tsod_present = true;
289 		rc = jedec_dimm_readw_be(sc, TSOD_REG_MANUFACTURER, &vendorid);
290 		if (rc != 0) {
291 			device_printf(dev,
292 			    "failed to read TSOD Manufacturer ID\n");
293 			goto out;
294 		}
295 		rc = jedec_dimm_readw_be(sc, TSOD_REG_DEV_REV, &devid);
296 		if (rc != 0) {
297 			device_printf(dev, "failed to read TSOD Device ID\n");
298 			goto out;
299 		}
300 
301 		tsod_match = jedec_dimm_tsod_match(vendorid, devid);
302 		if (bootverbose) {
303 			if (tsod_match == NULL) {
304 				device_printf(dev,
305 				    "Unknown TSOD Manufacturer and Device IDs,"
306 				    " 0x%x and 0x%x\n", vendorid, devid);
307 			} else {
308 				device_printf(dev,
309 				    "TSOD: %s\n", tsod_match);
310 			}
311 		}
312 	} else {
313 		tsod_match = NULL;
314 		tsod_present = false;
315 	}
316 
317 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "type",
318 	    CTLFLAG_RD | CTLFLAG_MPSAFE, sc->type_str, 0,
319 	    "DIMM type");
320 
321 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "capacity",
322 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, sc->capacity_mb,
323 	    "DIMM capacity (MB)");
324 
325 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "part",
326 	    CTLFLAG_RD | CTLFLAG_MPSAFE, sc->part_str, 0,
327 	    "DIMM Part Number");
328 
329 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "serial",
330 	    CTLFLAG_RD | CTLFLAG_MPSAFE, sc->serial_str, 0,
331 	    "DIMM Serial Number");
332 
333 	/* Create the temperature sysctl IFF the TSOD is present and valid */
334 	if (tsod_present && (tsod_match != NULL)) {
335 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temp",
336 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, dev, 0,
337 		    jedec_dimm_temp_sysctl, "IK", "DIMM temperature (deg C)");
338 	}
339 
340 	/* If a "slotid" was hinted, add the sysctl for it. */
341 	if (resource_string_value(device_get_name(dev), device_get_unit(dev),
342 	    "slotid", &slotid_str) == 0) {
343 		if (slotid_str != NULL) {
344 			sc->slotid_str = strdup(slotid_str, M_DEVBUF);
345 			SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "slotid",
346 			    CTLFLAG_RD | CTLFLAG_MPSAFE, sc->slotid_str, 0,
347 			    "DIMM Slot Identifier");
348 		}
349 	}
350 
351 	/* If a TSOD type string or a slotid are present, add them to the
352 	 * device description.
353 	 */
354 	if ((tsod_match != NULL) || (sc->slotid_str != NULL)) {
355 		new_desc_len = strlen(device_get_desc(dev));
356 		if (tsod_match != NULL) {
357 			new_desc_len += strlen(tsod_match);
358 			new_desc_len += 4; /* " w/ " */
359 		}
360 		if (sc->slotid_str != NULL) {
361 			new_desc_len += strlen(sc->slotid_str);
362 			new_desc_len += 3; /* space + parens */
363 		}
364 		new_desc_len++; /* terminator */
365 		new_desc = malloc(new_desc_len, M_TEMP, (M_WAITOK | M_ZERO));
366 		(void) snprintf(new_desc, new_desc_len, "%s%s%s%s%s%s",
367 		    device_get_desc(dev),
368 		    (tsod_match ? " w/ " : ""),
369 		    (tsod_match ? tsod_match : ""),
370 		    (sc->slotid_str ? " (" : ""),
371 		    (sc->slotid_str ? sc->slotid_str : ""),
372 		    (sc->slotid_str ? ")" : ""));
373 		device_set_desc_copy(dev, new_desc);
374 		free(new_desc, M_TEMP);
375 	}
376 
377 out:
378 	return (rc);
379 }
380 
381 /**
382  * Calculate the capacity of a DIMM. Both DDR3 and DDR4 encode "geometry"
383  * information in various SPD bytes. The standards documents codify everything
384  * in look-up tables, but it's trivial to reverse-engineer the the formulas for
385  * most of them. Unless otherwise noted, the same formulas apply for both DDR3
386  * and DDR4. The SPD offsets of where the data comes from are different between
387  * the two types, because having them be the same would be too easy.
388  *
389  * @author rpokala
390  *
391  * @param[in] sc
392  *      Instance-specific context data
393  *
394  * @param[in] dram_type
395  *      The locations of the data used to calculate the capacity depends on the
396  *      type of the DIMM.
397  *
398  * @param[out] capacity_mb
399  *      The calculated capacity, in MB
400  */
401 static int
402 jedec_dimm_capacity(struct jedec_dimm_softc *sc, enum dram_type type,
403     uint32_t *capacity_mb)
404 {
405 	uint8_t bus_width_byte;
406 	uint8_t bus_width_offset;
407 	uint8_t dimm_ranks_byte;
408 	uint8_t dimm_ranks_offset;
409 	uint8_t sdram_capacity_byte;
410 	uint8_t sdram_capacity_offset;
411 	uint8_t sdram_pkg_type_byte;
412 	uint8_t sdram_pkg_type_offset;
413 	uint8_t sdram_width_byte;
414 	uint8_t sdram_width_offset;
415 	uint32_t bus_width;
416 	uint32_t dimm_ranks;
417 	uint32_t sdram_capacity;
418 	uint32_t sdram_pkg_type;
419 	uint32_t sdram_width;
420 	int rc;
421 
422 	switch (type) {
423 	case DRAM_TYPE_DDR3_SDRAM:
424 		bus_width_offset = SPD_OFFSET_DDR3_BUS_WIDTH;
425 		dimm_ranks_offset = SPD_OFFSET_DDR3_DIMM_RANKS;
426 		sdram_capacity_offset = SPD_OFFSET_DDR3_SDRAM_CAPACITY;
427 		sdram_width_offset = SPD_OFFSET_DDR3_SDRAM_WIDTH;
428 		break;
429 	case DRAM_TYPE_DDR4_SDRAM:
430 		bus_width_offset = SPD_OFFSET_DDR4_BUS_WIDTH;
431 		dimm_ranks_offset = SPD_OFFSET_DDR4_DIMM_RANKS;
432 		sdram_capacity_offset = SPD_OFFSET_DDR4_SDRAM_CAPACITY;
433 		sdram_pkg_type_offset = SPD_OFFSET_DDR4_SDRAM_PKG_TYPE;
434 		sdram_width_offset = SPD_OFFSET_DDR4_SDRAM_WIDTH;
435 		break;
436 	default:
437 		device_printf(sc->dev, "unsupported dram_type 0x%02x\n", type);
438 		rc = EINVAL;
439 		goto out;
440 	}
441 
442 	rc = smbus_readb(sc->smbus, sc->spd_addr, bus_width_offset,
443 	    &bus_width_byte);
444 	if (rc != 0) {
445 		device_printf(sc->dev, "failed to read bus_width: %d\n", rc);
446 		goto out;
447 	}
448 
449 	rc = smbus_readb(sc->smbus, sc->spd_addr, dimm_ranks_offset,
450 	    &dimm_ranks_byte);
451 	if (rc != 0) {
452 		device_printf(sc->dev, "failed to read dimm_ranks: %d\n", rc);
453 		goto out;
454 	}
455 
456 	rc = smbus_readb(sc->smbus, sc->spd_addr, sdram_capacity_offset,
457 	    &sdram_capacity_byte);
458 	if (rc != 0) {
459 		device_printf(sc->dev, "failed to read sdram_capacity: %d\n",
460 		    rc);
461 		goto out;
462 	}
463 
464 	rc = smbus_readb(sc->smbus, sc->spd_addr, sdram_width_offset,
465 	    &sdram_width_byte);
466 	if (rc != 0) {
467 		device_printf(sc->dev, "failed to read sdram_width: %d\n", rc);
468 		goto out;
469 	}
470 
471 	/* The "SDRAM Package Type" is only needed for DDR4 DIMMs. */
472 	if (type == DRAM_TYPE_DDR4_SDRAM) {
473 		rc = smbus_readb(sc->smbus, sc->spd_addr, sdram_pkg_type_offset,
474 		    &sdram_pkg_type_byte);
475 		if (rc != 0) {
476 			device_printf(sc->dev,
477 			    "failed to read sdram_pkg_type: %d\n", rc);
478 			goto out;
479 		}
480 	}
481 
482 	/* "Primary bus width, in bits" is in bits [2:0]. */
483 	bus_width_byte &= 0x07;
484 	if (bus_width_byte <= 3) {
485 		bus_width = 1 << bus_width_byte;
486 		bus_width *= 8;
487 	} else {
488 		device_printf(sc->dev, "invalid bus width info\n");
489 		rc = EINVAL;
490 		goto out;
491 	}
492 
493 	/* "Number of ranks per DIMM" is in bits [5:3]. Values 4-7 are only
494 	 * valid for DDR4.
495 	 */
496 	dimm_ranks_byte >>= 3;
497 	dimm_ranks_byte &= 0x07;
498 	if (dimm_ranks_byte <= 7) {
499 		dimm_ranks = dimm_ranks_byte + 1;
500 	} else {
501 		device_printf(sc->dev, "invalid DIMM Rank info\n");
502 		rc = EINVAL;
503 		goto out;
504 	}
505 	if ((dimm_ranks_byte >= 4) && (type != DRAM_TYPE_DDR4_SDRAM)) {
506 		device_printf(sc->dev, "invalid DIMM Rank info\n");
507 		rc = EINVAL;
508 		goto out;
509 	}
510 
511 	/* "Total SDRAM capacity per die, in Mb" is in bits [3:0]. There are two
512 	 * different formulas, for values 0-7 and for values 8-9. Also, values
513 	 * 7-9 are only valid for DDR4.
514 	 */
515 	sdram_capacity_byte &= 0x0f;
516 	if (sdram_capacity_byte <= 7) {
517 		sdram_capacity = 1 << sdram_capacity_byte;
518 		sdram_capacity *= 256;
519 	} else if (sdram_capacity_byte <= 9) {
520 		sdram_capacity = 12 << (sdram_capacity_byte - 8);
521 		sdram_capacity *= 1024;
522 	} else {
523 		device_printf(sc->dev, "invalid SDRAM capacity info\n");
524 		rc = EINVAL;
525 		goto out;
526 	}
527 	if ((sdram_capacity_byte >= 7) && (type != DRAM_TYPE_DDR4_SDRAM)) {
528 		device_printf(sc->dev, "invalid SDRAM capacity info\n");
529 		rc = EINVAL;
530 		goto out;
531 	}
532 
533 	/* "SDRAM device width" is in bits [2:0]. */
534 	sdram_width_byte &= 0x7;
535 	if (sdram_width_byte <= 3) {
536 		sdram_width = 1 << sdram_width_byte;
537 		sdram_width *= 4;
538 	} else {
539 		device_printf(sc->dev, "invalid SDRAM width info\n");
540 		rc = EINVAL;
541 		goto out;
542 	}
543 
544 	/* DDR4 has something called "3DS", which is indicated by [1:0] = 2;
545 	 * when that is the case, the die count is encoded in [6:4], and
546 	 * dimm_ranks is multiplied by it.
547 	 */
548 	if ((type == DRAM_TYPE_DDR4_SDRAM) &&
549 	    ((sdram_pkg_type_byte & 0x3) == 2)) {
550 		sdram_pkg_type_byte >>= 4;
551 		sdram_pkg_type_byte &= 0x07;
552 		sdram_pkg_type = sdram_pkg_type_byte + 1;
553 		dimm_ranks *= sdram_pkg_type;
554 	}
555 
556 	/* Finally, assemble the actual capacity. The formula is the same for
557 	 * both DDR3 and DDR4.
558 	 */
559 	*capacity_mb = sdram_capacity / 8 * bus_width / sdram_width *
560 	    dimm_ranks;
561 
562 out:
563 	return (rc);
564 }
565 
566 /**
567  * device_detach() method. If we allocated sc->slotid_str, free it. Even if we
568  *      didn't allocate, free it anyway; free(NULL) is safe.
569  *
570  * @author rpokala
571  *
572  * @param[in,out] dev
573  *      Device being detached.
574  */
575 static int
576 jedec_dimm_detach(device_t dev)
577 {
578 	struct jedec_dimm_softc *sc;
579 
580 	sc = device_get_softc(dev);
581 	free(sc->slotid_str, M_DEVBUF);
582 
583 	return (0);
584 }
585 
586 /**
587  * Read and dump the entire SPD contents.
588  *
589  * @author rpokala
590  *
591  * @param[in] sc
592  *      Instance-specific context data
593  *
594  * @param[in] dram_type
595  *      The length of data which needs to be read and dumped differs based on
596  *      the type of the DIMM.
597  */
598 static int
599 jedec_dimm_dump(struct jedec_dimm_softc *sc, enum dram_type type)
600 {
601 	int i;
602 	int rc;
603 	bool page_changed;
604 	uint8_t bytes[512];
605 
606 	page_changed = false;
607 
608 	for (i = 0; i < 256; i++) {
609 		rc = smbus_readb(sc->smbus, sc->spd_addr, i, &bytes[i]);
610 		if (rc != 0) {
611 			device_printf(sc->dev,
612 			    "unable to read page0:0x%02x: %d\n", i, rc);
613 			goto out;
614 		}
615 	}
616 
617 	/* The DDR4 SPD is 512 bytes, but SMBus only allows for 8-bit offsets.
618 	 * JEDEC gets around this by defining the "PAGE" DTI and LSAs.
619 	 */
620 	if (type == DRAM_TYPE_DDR4_SDRAM) {
621 		page_changed = true;
622 		rc = smbus_writeb(sc->smbus,
623 		    (JEDEC_DTI_PAGE | JEDEC_LSA_PAGE_SET1), 0, 0);
624 		if (rc != 0) {
625 			device_printf(sc->dev, "unable to change page: %d\n",
626 			    rc);
627 			goto out;
628 		}
629 		/* Add 256 to the store location, because we're in the second
630 		 * page.
631 		 */
632 		for (i = 0; i < 256; i++) {
633 			rc = smbus_readb(sc->smbus, sc->spd_addr, i,
634 			    &bytes[256 + i]);
635 			if (rc != 0) {
636 				device_printf(sc->dev,
637 				    "unable to read page1:0x%02x: %d\n", i, rc);
638 				goto out;
639 			}
640 		}
641 	}
642 
643 	/* Display the data in a nice hexdump format, with byte offsets. */
644 	hexdump(bytes, (page_changed ? 512 : 256), NULL, 0);
645 
646 out:
647 	if (page_changed) {
648 		int rc2;
649 		/* Switch back to page0 before returning. */
650 		rc2 = smbus_writeb(sc->smbus,
651 		    (JEDEC_DTI_PAGE | JEDEC_LSA_PAGE_SET0), 0, 0);
652 		if (rc2 != 0) {
653 			device_printf(sc->dev, "unable to restore page: %d\n",
654 			    rc2);
655 		}
656 	}
657 	return (rc);
658 }
659 
660 /**
661  * Read a specified range of bytes from the SPD, convert them to a string, and
662  * store them in the provided buffer. Some SPD fields are space-padded ASCII,
663  * and some are just a string of bits that we want to convert to a hex string.
664  *
665  * @author rpokala
666  *
667  * @param[in] sc
668  *      Instance-specific context data
669  *
670  * @param[out] dst
671  *      The output buffer to populate
672  *
673  * @param[in] dstsz
674  *      The size of the output buffer
675  *
676  * @param[in] offset
677  *      The starting offset of the field within the SPD
678  *
679  * @param[in] len
680  *      The length in bytes of the field within the SPD
681  *
682  * @param[in] ascii
683  *      Is the field a sequence of ASCII characters? If not, it is binary data
684  *      which should be converted to characters.
685  */
686 static int
687 jedec_dimm_field_to_str(struct jedec_dimm_softc *sc, char *dst, size_t dstsz,
688     uint16_t offset, uint16_t len, bool ascii)
689 {
690 	uint8_t byte;
691 	int i;
692 	int rc;
693 	bool page_changed;
694 
695 	/* Change to the proper page. Offsets [0, 255] are in page0; offsets
696 	 * [256, 512] are in page1.
697 	 *
698 	 * *The page must be reset to page0 before returning.*
699 	 *
700 	 * For the page-change operation, only the DTI and LSA matter; the
701 	 * offset and write-value are ignored, so use just 0.
702 	 *
703 	 * Mercifully, JEDEC defined the fields such that none of them cross
704 	 * pages, so we don't need to worry about that complication.
705 	 */
706 	if (offset < JEDEC_SPD_PAGE_SIZE) {
707 		page_changed = false;
708 	} else if (offset < (2 * JEDEC_SPD_PAGE_SIZE)) {
709 		page_changed = true;
710 		rc = smbus_writeb(sc->smbus,
711 		    (JEDEC_DTI_PAGE | JEDEC_LSA_PAGE_SET1), 0, 0);
712 		if (rc != 0) {
713 			device_printf(sc->dev,
714 			    "unable to change page for offset 0x%04x: %d\n",
715 			    offset, rc);
716 		}
717 		/* Adjust the offset to account for the page change. */
718 		offset -= JEDEC_SPD_PAGE_SIZE;
719 	} else {
720 		page_changed = false;
721 		rc = EINVAL;
722 		device_printf(sc->dev, "invalid offset 0x%04x\n", offset);
723 		goto out;
724 	}
725 
726 	/* Sanity-check (adjusted) offset and length; everything must be within
727 	 * the same page.
728 	 */
729 	if (offset >= JEDEC_SPD_PAGE_SIZE) {
730 		rc = EINVAL;
731 		device_printf(sc->dev, "invalid offset 0x%04x\n", offset);
732 		goto out;
733 	}
734 	if ((offset + len) >= JEDEC_SPD_PAGE_SIZE) {
735 		rc = EINVAL;
736 		device_printf(sc->dev,
737 		    "(offset + len) would cross page (0x%04x + 0x%04x)\n",
738 		    offset, len);
739 		goto out;
740 	}
741 
742 	/* Sanity-check the destination string length. If we're dealing with
743 	 * ASCII chars, then the destination must be at least the same length;
744 	 * otherwise, it must be *twice* the length, because each byte must
745 	 * be converted into two nybble characters.
746 	 *
747 	 * And, of course, there needs to be an extra byte for the terminator.
748 	 */
749 	if (ascii) {
750 		if (dstsz < (len + 1)) {
751 			rc = EINVAL;
752 			device_printf(sc->dev,
753 			    "destination too short (%u < %u)\n",
754 			    (uint16_t) dstsz, (len + 1));
755 			goto out;
756 		}
757 	} else {
758 		if (dstsz < ((2 * len) + 1)) {
759 			rc = EINVAL;
760 			device_printf(sc->dev,
761 			    "destination too short (%u < %u)\n",
762 			    (uint16_t) dstsz, ((2 * len) + 1));
763 			goto out;
764 		}
765 	}
766 
767 	/* Read a byte at a time. */
768 	for (i = 0; i < len; i++) {
769 		rc = smbus_readb(sc->smbus, sc->spd_addr, (offset + i), &byte);
770 		if (rc != 0) {
771 			device_printf(sc->dev,
772 			    "failed to read byte at 0x%02x: %d\n",
773 			    (offset + i), rc);
774 			goto out;
775 		}
776 		if (ascii) {
777 			/* chars can be copied directly. */
778 			dst[i] = byte;
779 		} else {
780 			/* Raw bytes need to be converted to a two-byte hex
781 			 * string, plus the terminator.
782 			 */
783 			(void) snprintf(&dst[(2 * i)], 3, "%02x", byte);
784 		}
785 	}
786 
787 	/* If we're dealing with ASCII, convert trailing spaces to NULs. */
788 	if (ascii) {
789 		for (i = dstsz; i > 0; i--) {
790 			if (dst[i] == ' ') {
791 				dst[i] = 0;
792 			} else if (dst[i] == 0) {
793 				continue;
794 			} else {
795 				break;
796 			}
797 		}
798 	}
799 
800 out:
801 	if (page_changed) {
802 		int rc2;
803 		/* Switch back to page0 before returning. */
804 		rc2 = smbus_writeb(sc->smbus,
805 		    (JEDEC_DTI_PAGE | JEDEC_LSA_PAGE_SET0), 0, 0);
806 		if (rc2 != 0) {
807 			device_printf(sc->dev,
808 			    "unable to restore page for offset 0x%04x: %d\n",
809 			    offset, rc2);
810 		}
811 	}
812 
813 	return (rc);
814 }
815 
816 /**
817  * device_probe() method. Validate the address that was given as a hint, and
818  * display an error if it's bogus. Make sure that we're dealing with one of the
819  * SPD versions that we can handle.
820  *
821  * @author rpokala
822  *
823  * @param[in] dev
824  *      Device being probed.
825  */
826 static int
827 jedec_dimm_probe(device_t dev)
828 {
829 	uint8_t addr;
830 	uint8_t byte;
831 	int rc;
832 	enum dram_type type;
833 	device_t smbus;
834 
835 	smbus = device_get_parent(dev);
836 	addr = smbus_get_addr(dev);
837 
838 	/* Don't bother if this isn't an SPD address, or if the LSBit is set. */
839 	if (((addr & 0xf0) != JEDEC_DTI_SPD) ||
840 	    ((addr & 0x01) != 0)) {
841 		device_printf(dev,
842 		    "invalid \"addr\" hint; address must start with \"0x%x\","
843 		    " and the least-significant bit must be 0\n",
844 		    JEDEC_DTI_SPD);
845 		rc = ENXIO;
846 		goto out;
847 	}
848 
849 	/* Try to read the DRAM_TYPE from the SPD. */
850 	rc = smbus_readb(smbus, addr, SPD_OFFSET_DRAM_TYPE, &byte);
851 	if (rc != 0) {
852 		device_printf(dev, "failed to read dram_type\n");
853 		goto out;
854 	}
855 
856 	/* This driver currently only supports DDR3 and DDR4 SPDs. */
857 	type = (enum dram_type) byte;
858 	switch (type) {
859 	case DRAM_TYPE_DDR3_SDRAM:
860 		rc = BUS_PROBE_DEFAULT;
861 		device_set_desc(dev, "DDR3 DIMM");
862 		break;
863 	case DRAM_TYPE_DDR4_SDRAM:
864 		rc = BUS_PROBE_DEFAULT;
865 		device_set_desc(dev, "DDR4 DIMM");
866 		break;
867 	default:
868 		rc = ENXIO;
869 		break;
870 	}
871 
872 out:
873 	return (rc);
874 }
875 
876 /**
877  * SMBus specifies little-endian byte order, but it looks like the TSODs use
878  * big-endian. Read and convert.
879  *
880  * @author avg
881  *
882  * @param[in] sc
883  *      Instance-specific context data
884  *
885  * @param[in] reg
886  *      The register number to read.
887  *
888  * @param[out] val
889  *      Pointer to populate with the value read.
890  */
891 static int
892 jedec_dimm_readw_be(struct jedec_dimm_softc *sc, uint8_t reg, uint16_t *val)
893 {
894 	int rc;
895 
896 	rc = smbus_readw(sc->smbus, sc->tsod_addr, reg, val);
897 	if (rc != 0) {
898 		goto out;
899 	}
900 	*val = be16toh(*val);
901 
902 out:
903 	return (rc);
904 }
905 
906 /**
907  * Read the temperature data from the TSOD and convert it to the deciKelvin
908  * value that the sysctl expects.
909  *
910  * @author avg
911  */
912 static int
913 jedec_dimm_temp_sysctl(SYSCTL_HANDLER_ARGS)
914 {
915 	uint16_t val;
916 	int rc;
917 	int temp;
918 	device_t dev = arg1;
919 	struct jedec_dimm_softc *sc;
920 
921 	sc = device_get_softc(dev);
922 
923 	rc = jedec_dimm_readw_be(sc, TSOD_REG_TEMPERATURE, &val);
924 	if (rc != 0) {
925 		goto out;
926 	}
927 
928 	/* The three MSBits are flags, and the next bit is a sign bit. */
929 	temp = val & 0xfff;
930 	if ((val & 0x1000) != 0)
931 		temp = -temp;
932 	/* Each step is 0.0625 degrees, so convert to 1000ths of a degree C. */
933 	temp *= 625;
934 	/* ... and then convert to 1000ths of a Kelvin */
935 	temp += 2731500;
936 	/* As a practical matter, few (if any) TSODs are more accurate than
937 	 * about a tenth of a degree, so round accordingly. This correlates with
938 	 * the "IK" formatting used for this sysctl.
939 	 */
940 	temp = (temp + 500) / 1000;
941 
942 	rc = sysctl_handle_int(oidp, &temp, 0, req);
943 
944 out:
945 	return (rc);
946 }
947 
948 /**
949  * Check the TSOD's Vendor ID and Device ID against the list of known TSOD
950  * devices. Return the description, or NULL if this doesn't look like a valid
951  * TSOD.
952  *
953  * @author avg
954  *
955  * @param[in] vid
956  *      The Vendor ID of the TSOD device
957  *
958  * @param[in] did
959  *      The Device ID of the TSOD device
960  *
961  * @return
962  *      The description string, or NULL for a failure to match.
963  */
964 static const char *
965 jedec_dimm_tsod_match(uint16_t vid, uint16_t did)
966 {
967 	const struct jedec_dimm_tsod_dev *d;
968 	int i;
969 
970 	for (i = 0; i < nitems(known_tsod_devices); i++) {
971 		d = &known_tsod_devices[i];
972 		if ((vid == d->vendor_id) && ((did >> 8) == d->device_id)) {
973 			return (d->description);
974 		}
975 	}
976 
977 	/* If no matches for a specific device, then check for a generic
978 	 * TSE2004av-compliant device.
979 	 */
980 	if ((did >> 8) == 0x22) {
981 		return ("TSE2004av compliant TSOD");
982 	}
983 
984 	return (NULL);
985 }
986 
987 static device_method_t jedec_dimm_methods[] = {
988 	/* Methods from the device interface */
989 	DEVMETHOD(device_probe,		jedec_dimm_probe),
990 	DEVMETHOD(device_attach,	jedec_dimm_attach),
991 	DEVMETHOD(device_detach,	jedec_dimm_detach),
992 	DEVMETHOD_END
993 };
994 
995 static driver_t jedec_dimm_driver = {
996 	.name = "jedec_dimm",
997 	.methods = jedec_dimm_methods,
998 	.size = sizeof(struct jedec_dimm_softc),
999 };
1000 
1001 static devclass_t jedec_dimm_devclass;
1002 
1003 DRIVER_MODULE(jedec_dimm, smbus, jedec_dimm_driver, jedec_dimm_devclass, 0, 0);
1004 MODULE_DEPEND(jedec_dimm, smbus, SMBUS_MINVER, SMBUS_PREFVER, SMBUS_MAXVER);
1005 MODULE_VERSION(jedec_dimm, 1);
1006 
1007 /* vi: set ts=8 sw=4 sts=8 noet: */
1008