xref: /netbsd-src/usr.sbin/fwctl/fwcontrol.c (revision c2f76ff004a2cb67efe5b12d97bd3ef7fe89e18d)
1 /*	$NetBSD: fwcontrol.c,v 1.13 2011/01/04 20:45:13 christos Exp $	*/
2 /*
3  * Copyright (C) 2002
4  * 	Hidetoshi Shimokawa. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *
17  *	This product includes software developed by Hidetoshi Shimokawa.
18  *
19  * 4. Neither the name of the author nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 #include <sys/cdefs.h>
36 //__FBSDID("$FreeBSD: src/usr.sbin/fwcontrol/fwcontrol.c,v 1.23 2006/10/26 22:33:38 imp Exp $");
37 __RCSID("$NetBSD: fwcontrol.c,v 1.13 2011/01/04 20:45:13 christos Exp $");
38 
39 #include <sys/param.h>
40 #include <sys/malloc.h>
41 #include <sys/types.h>
42 #include <sys/sysctl.h>
43 #include <sys/socket.h>
44 #include <sys/ioctl.h>
45 #include <sys/errno.h>
46 #include "eui64.h"
47 #include <dev/ieee1394/firewire.h>
48 #include <dev/ieee1394/iec13213.h>
49 #include <dev/ieee1394/fwphyreg.h>
50 #include <dev/ieee1394/iec68113.h>
51 
52 #include <netinet/in.h>
53 #include <fcntl.h>
54 #include <stdio.h>
55 #include <err.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <sysexits.h>
59 #include <unistd.h>
60 #include "fwmethods.h"
61 
62 static void sysctl_set_int(const char *, int);
63 
64 static void
65 usage(void)
66 {
67 	fprintf(stderr,
68 	    "%s [-prt] [-b pri_req] [-c node] [-d node] [-f force_root ]\n"
69 	    "\t[-g gap_count] [-l file] [-M mode] [-m EUI64 | hostname]\n"
70 	    "\t[-o node] [-R filename] [-S filename] [-s node] [-u bus_num]\n"
71 	    "\n"
72 	    "\t-b: set PRIORITY_BUDGET register on all supported nodes\n"
73 	    "\t-c: read configuration ROM\n"
74 	    "\t-d: hex dump of configuration ROM\n"
75 	    "\t-f: force root node\n"
76 	    "\t-g: broadcast gap_count by phy_config packet\n"
77 	    "\t-l: load and parse hex dump file of configuration ROM\n"
78 	    "\t-M: specify dv or mpeg\n"
79 	    "\t-m: set fwmem target\n"
80 	    "\t-o: send link-on packet to the node\n"
81 	    "\t-p: dump PHY registers\n"
82 	    "\t-R: receive DV or MPEG TS stream\n"
83 	    "\t-r: bus reset\n"
84 	    "\t-S: send DV stream\n"
85 	    "\t-s: write RESET_START register on the node\n"
86 	    "\t-t: read topology map\n"
87 	    "\t-u: specify bus number\n", getprogname());
88 	exit(EX_USAGE);
89 }
90 
91 static void
92 fweui2eui64(const struct fw_eui64 *fweui, struct eui64 *eui)
93 {
94 	*(uint32_t*)&(eui->octet[0]) = htonl(fweui->hi);
95 	*(uint32_t*)&(eui->octet[4]) = htonl(fweui->lo);
96 }
97 
98 static void
99 get_dev(int fd, struct fw_devlstreq *data)
100 {
101 
102 	if (data == NULL)
103 		err(EX_SOFTWARE, "%s: data malloc", __func__);
104 	if (ioctl(fd, FW_GDEVLST, data) < 0)
105 		err(EX_IOERR, "%s: ioctl", __func__);
106 }
107 
108 static int
109 str2node(int fd, const char *nodestr)
110 {
111 	struct eui64 eui, tmpeui;
112 	struct fw_devlstreq *data;
113 	char *endptr;
114 	int i;
115 	long node;
116 
117 	if (nodestr == '\0')
118 		return -1;
119 
120 	/*
121 	 * Deal with classic node specifications.
122 	 */
123 	node = strtol(nodestr, &endptr, 0);
124 	if (*endptr == '\0')
125 		goto gotnode;
126 
127 	/*
128 	 * Try to get an eui and match it against available nodes.
129 	 */
130 	if (eui64_hostton(nodestr, &eui) != 0 && eui64_aton(nodestr, &eui) != 0)
131 		return -1;
132 
133 	data = malloc(sizeof(*data));
134 	if (data == NULL)
135 		err(EX_SOFTWARE, "%s: data malloc", __func__);
136 	get_dev(fd,data);
137 
138 	for (i = 0; i < data->info_len; i++) {
139 		fweui2eui64(&data->dev[i].eui, &tmpeui);
140 		if (memcmp(&eui, &tmpeui, sizeof(eui)) == 0) {
141 			node = data->dev[i].dst;
142 			if (data != NULL)
143 				free(data);
144 			goto gotnode;
145 		}
146 	}
147 	if (i >= data->info_len) {
148 		if (data != NULL)
149 			free(data);
150 		return -1;
151 	}
152 
153 gotnode:
154 	if (node < 0 || node > 63)
155 		return -1;
156 	else
157 		return (int)node;
158 }
159 
160 static void
161 list_dev(int fd)
162 {
163 	struct fw_devlstreq *data;
164 	struct fw_devinfo *devinfo;
165 	struct eui64 eui;
166 	char addr[EUI64_SIZ], hostname[40];
167 	int i;
168 
169 	data = malloc(sizeof(*data));
170 	if (data == NULL)
171 		err(EX_SOFTWARE, "%s:data malloc", __func__);
172 	get_dev(fd, data);
173 	printf("%d devices (info_len=%d)\n", data->n, data->info_len);
174 	printf("node           EUI64          status    hostname\n");
175 	for (i = 0; i < data->info_len; i++) {
176 		devinfo = &data->dev[i];
177 		fweui2eui64(&devinfo->eui, &eui);
178 		eui64_ntoa(&eui, addr, sizeof(addr));
179 		if (eui64_ntohost(hostname, sizeof(hostname), &eui))
180 			hostname[0] = 0;
181 		printf("%4d  %s %6d    %s\n",
182 		    (devinfo->status || i == 0) ? devinfo->dst : -1,
183 		    addr, devinfo->status, hostname);
184 	}
185 	free(data);
186 }
187 
188 static uint32_t
189 read_write_quad(int fd, struct fw_eui64 eui, uint32_t addr_lo, int readmode,
190 		uint32_t data)
191 {
192         struct fw_asyreq *asyreq;
193 	uint32_t *qld, res;
194 
195 	asyreq = malloc(sizeof(*asyreq) + 16);
196 	if (asyreq == NULL)
197 		err(EX_SOFTWARE, "%s: asyreq malloc", __func__);
198 	asyreq->req.len = 16;
199 #if 0
200 	asyreq->req.type = FWASREQNODE;
201 	asyreq->pkt.mode.rreqq.dst = FWLOCALBUS | node;
202 #else
203 	asyreq->req.type = FWASREQEUI;
204 	asyreq->req.dst.eui = eui;
205 #endif
206 	asyreq->pkt.mode.rreqq.tlrt = 0;
207 	if (readmode)
208 		asyreq->pkt.mode.rreqq.tcode = FWTCODE_RREQQ;
209 	else
210 		asyreq->pkt.mode.rreqq.tcode = FWTCODE_WREQQ;
211 
212 	asyreq->pkt.mode.rreqq.dest_hi = 0xffff;
213 	asyreq->pkt.mode.rreqq.dest_lo = addr_lo;
214 
215 	qld = (uint32_t *)&asyreq->pkt;
216 	if (!readmode)
217 		asyreq->pkt.mode.wreqq.data = htonl(data);
218 
219 	if (ioctl(fd, FW_ASYREQ, asyreq) < 0)
220 		err(EX_IOERR, "%s: ioctl", __func__);
221 	res = qld[3];
222 	free(asyreq);
223 	if (readmode)
224 		return ntohl(res);
225 	else
226 		return 0;
227 }
228 
229 /*
230  * Send a PHY Config Packet
231  * ieee 1394a-2005 4.3.4.3
232  *
233  * Message ID   Root ID    R  T   Gap Count
234  * 00(2 bits)   (6 bits)   1  1   (6 bits)
235  *
236  * if "R" is set, then Root ID will be the next
237  * root node upon the next bus reset.
238  * if "T" is set, then Gap Count will be the
239  * value that all nodes use for their Gap Count
240  * if "R" and "T" are not set, then this message
241  * is either ignored or interpreted as an extended
242  * PHY config Packet as per 1394a-2005 4.3.4.4
243  */
244 static void
245 send_phy_config(int fd, int root_node, int gap_count)
246 {
247         struct fw_asyreq *asyreq;
248 
249 	asyreq = malloc(sizeof(*asyreq) + 12);
250 	if (asyreq == NULL)
251 		err(EX_SOFTWARE, "%s: asyreq malloc", __func__);
252 	asyreq->req.len = 12;
253 	asyreq->req.type = FWASREQNODE;
254 	asyreq->pkt.mode.ld[0] = 0;
255 	asyreq->pkt.mode.ld[1] = 0;
256 	asyreq->pkt.mode.common.tcode = FWTCODE_PHY;
257 	if (root_node >= 0)
258 		asyreq->pkt.mode.ld[1] |= ((root_node << 24) | (1 << 23));
259 	if (gap_count >= 0)
260 		asyreq->pkt.mode.ld[1] |= ((1 << 22) | (gap_count << 16));
261 	asyreq->pkt.mode.ld[2] = ~asyreq->pkt.mode.ld[1];
262 
263 	printf("send phy_config root_node=%d gap_count=%d\n",
264 	    root_node, gap_count);
265 
266 	if (ioctl(fd, FW_ASYREQ, asyreq) < 0)
267 		err(EX_IOERR, "%s: ioctl", __func__);
268 	free(asyreq);
269 }
270 
271 static void
272 link_on(int fd, int node)
273 {
274         struct fw_asyreq *asyreq;
275 
276 	asyreq = malloc(sizeof(*asyreq) + 12);
277 	if (asyreq == NULL)
278 		err(EX_SOFTWARE, "%s: asyreq malloc", __func__);
279 	asyreq->req.len = 12;
280 	asyreq->req.type = FWASREQNODE;
281 	asyreq->pkt.mode.common.tcode = FWTCODE_PHY;
282 	asyreq->pkt.mode.ld[1] |= (1 << 30) | ((node & 0x3f) << 24);
283 	asyreq->pkt.mode.ld[2] = ~asyreq->pkt.mode.ld[1];
284 
285 	if (ioctl(fd, FW_ASYREQ, asyreq) < 0)
286 		err(EX_IOERR, "%s: ioctl", __func__);
287 	free(asyreq);
288 }
289 
290 static void
291 reset_start(int fd, int node)
292 {
293         struct fw_asyreq *asyreq;
294 
295 	asyreq = malloc(sizeof(*asyreq) + 16);
296 	if (asyreq == NULL)
297 		err(EX_SOFTWARE, "%s: asyreq malloc", __func__);
298 	asyreq->req.len = 16;
299 	asyreq->req.type = FWASREQNODE;
300 	asyreq->pkt.mode.wreqq.dst = FWLOCALBUS | (node & 0x3f);
301 	asyreq->pkt.mode.wreqq.tlrt = 0;
302 	asyreq->pkt.mode.wreqq.tcode = FWTCODE_WREQQ;
303 
304 	asyreq->pkt.mode.wreqq.dest_hi = 0xffff;
305 	asyreq->pkt.mode.wreqq.dest_lo = 0xf0000000 | RESET_START;
306 
307 	asyreq->pkt.mode.wreqq.data = htonl(0x1);
308 
309 	if (ioctl(fd, FW_ASYREQ, asyreq) < 0)
310 		err(EX_IOERR, "%s: ioctl", __func__);
311 	free(asyreq);
312 }
313 
314 static void
315 set_pri_req(int fd, uint32_t pri_req)
316 {
317 	struct fw_devlstreq *data;
318 	struct fw_devinfo *devinfo;
319 	struct eui64 eui;
320 	char addr[EUI64_SIZ];
321 	uint32_t max, reg, old;
322 	int i;
323 
324 	data = malloc(sizeof(*data));
325 	if (data == NULL)
326 		err(EX_SOFTWARE, "%s: data malloc", __func__);
327 	get_dev(fd, data);
328 #define BUGET_REG 0xf0000218
329 	for (i = 0; i < data->info_len; i++) {
330 		devinfo = &data->dev[i];
331 		if (!devinfo->status)
332 			continue;
333 		reg = read_write_quad(fd, devinfo->eui, BUGET_REG, 1, 0);
334 		fweui2eui64(&devinfo->eui, &eui);
335 		eui64_ntoa(&eui, addr, sizeof(addr));
336 		printf("%d %s, %08x",
337 			devinfo->dst, addr, reg);
338 		if (reg > 0) {
339 			old = (reg & 0x3f);
340 			max = (reg & 0x3f00) >> 8;
341 			if (pri_req > max)
342 				pri_req =  max;
343 			printf(" 0x%x -> 0x%x\n", old, pri_req);
344 			read_write_quad(fd, devinfo->eui, BUGET_REG, 0, pri_req);
345 		} else {
346 			printf("\n");
347 		}
348 	}
349 	free(data);
350 }
351 
352 static void
353 parse_bus_info_block(uint32_t *p)
354 {
355 	char addr[EUI64_SIZ];
356 	struct bus_info *bi;
357 	struct eui64 eui;
358 
359 	bi = (struct bus_info *)p;
360 	fweui2eui64(&bi->eui64, &eui);
361 	eui64_ntoa(&eui, addr, sizeof(addr));
362 	printf("bus_name: 0x%04x\n"
363 		"irmc:%d cmc:%d isc:%d bmc:%d pmc:%d\n"
364 		"cyc_clk_acc:%d max_rec:%d max_rom:%d\n"
365 		"generation:%d link_spd:%d\n"
366 		"EUI64: %s\n",
367 		bi->bus_name,
368 		bi->irmc, bi->cmc, bi->isc, bi->bmc, bi->pmc,
369 		bi->cyc_clk_acc, bi->max_rec, bi->max_rom,
370 		bi->generation, bi->link_spd,
371 		addr);
372 }
373 
374 static int
375 get_crom(int fd, int node, void *crom_buf, int len)
376 {
377 	struct fw_crom_buf buf;
378 	int i, error;
379 	struct fw_devlstreq *data;
380 
381 	data = malloc(sizeof(*data));
382 	if (data == NULL)
383 		err(EX_SOFTWARE, "%s: data malloc", __func__);
384 	get_dev(fd, data);
385 
386 	for (i = 0; i < data->info_len; i++)
387 		if (data->dev[i].dst == node && data->dev[i].eui.lo != 0)
388 			break;
389 	if (i == data->info_len)
390 		errx(EX_SOFTWARE, "%s: no such node %d", __func__, node);
391 	else
392 		buf.eui = data->dev[i].eui;
393 	free(data);
394 
395 	buf.len = len;
396 	buf.ptr = crom_buf;
397 	memset(crom_buf, 0, len);
398 	if ((error = ioctl(fd, FW_GCROM, &buf)) < 0)
399 		err(EX_IOERR, "%s: ioctl", __func__);
400 
401 	return error;
402 }
403 
404 static void
405 show_crc(uint16_t crc, uint16_t good_crc)
406 {
407 	if (crc == good_crc)
408 		printf("(OK)\n");
409 	else
410 		printf("(NG, 0x%x)\n", good_crc);
411 }
412 
413 static void
414 show_crom(uint32_t *crom_buf)
415 {
416 	int i;
417 	struct crom_context cc;
418 	const char *desc;
419 	char info[256];
420 	static const char *key_types = "ICLD";
421 	struct csrreg *reg;
422 	struct csrdirectory *dir;
423 	struct csrhdr *hdr;
424 	uint16_t crc;
425 
426 	printf("first quad: 0x%08x ", *crom_buf);
427 	if (crom_buf[0] == 0) {
428 		printf("(Invalid Configuration ROM)\n");
429 		return;
430 	}
431 	hdr = (struct csrhdr *)crom_buf;
432 	if (hdr->info_len == 1) {
433 		/* minimum ROM */
434 		reg = (struct csrreg *)hdr;
435 		printf("vendor ID: 0x%06x\n", reg->val);
436 		return;
437 	}
438 	crc = crom_crc(crom_buf+1, hdr->crc_len);
439 	printf("info_len=%d crc_len=%d crc=0x%04x ",
440 		hdr->info_len, hdr->crc_len, crc);
441 	show_crc(crc, hdr->crc);
442 	parse_bus_info_block(crom_buf+1);
443 
444 	crom_init_context(&cc, crom_buf);
445 	dir = cc.stack[0].dir;
446 	if (!dir) {
447 		printf("no root directory - giving up\n");
448 		return;
449 	}
450 	crc = crom_crc((uint32_t *)&dir->entry[0], dir->crc_len);
451 	printf("root_directory: len=0x%04x(%d) crc=0x%04x ",
452 			dir->crc_len, dir->crc_len, crc);
453 	show_crc(crc, dir->crc);
454 	if (dir->crc_len < 1)
455 		return;
456 	while (cc.depth >= 0) {
457 		desc = crom_desc(&cc, info, sizeof(info));
458 		reg = crom_get(&cc);
459 		for (i = 0; i < cc.depth; i++)
460 			printf("\t");
461 		printf("%02x(%c:%02x) %06x %s: %s\n",
462 			reg->key,
463 			key_types[(reg->key & CSRTYPE_MASK)>>6],
464 			reg->key & CSRKEY_MASK, reg->val,
465 			desc, info);
466 		crom_next(&cc);
467 	}
468 }
469 
470 #define DUMP_FORMAT	"%08x %08x %08x %08x %08x %08x %08x %08x\n"
471 
472 static void
473 dump_crom(uint32_t *p)
474 {
475 	int len=1024, i;
476 
477 	for (i = 0; i < len/(4*8); i ++) {
478 		printf(DUMP_FORMAT,
479 			p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
480 		p += 8;
481 	}
482 }
483 
484 static void
485 load_crom(const char *filename, uint32_t *p)
486 {
487 	FILE *file;
488 	int len=1024, i;
489 
490 	if ((file = fopen(filename, "r")) == NULL)
491 		err(EX_IOERR, "%s: load_crom %s", __func__, filename);
492 	for (i = 0; i < len/(4*8); i ++) {
493 		fscanf(file, DUMP_FORMAT,
494 		    p, p+1, p+2, p+3, p+4, p+5, p+6, p+7);
495 		p += 8;
496 	}
497 	(void)fclose(file);
498 }
499 
500 static void
501 show_topology_map(int fd)
502 {
503 	struct fw_topology_map *tmap;
504 	union fw_self_id sid;
505 	int i;
506 	static const char *port_status[] = {" ", "-", "P", "C"};
507 	static const char *pwr_class[] = {" 0W", "15W", "30W", "45W",
508 					"-1W", "-2W", "-5W", "-9W"};
509 	static const char *speed[] = {"S100", "S200", "S400", "S800"};
510 
511 	tmap = malloc(sizeof(*tmap));
512 	if (tmap == NULL)
513 		err(EX_SOFTWARE, "%s: tmap malloc", __func__);
514 	if (ioctl(fd, FW_GTPMAP, tmap) < 0)
515 		err(EX_IOERR, "%s: ioctl", __func__);
516 	printf("crc_len: %d generation:%d node_count:%d sid_count:%d\n",
517 		tmap->crc_len, tmap->generation,
518 		tmap->node_count, tmap->self_id_count);
519 	printf("id link gap_cnt speed delay cIRM power port0 port1 port2"
520 		" ini more\n");
521 	for (i = 0; i < tmap->crc_len - 2; i++) {
522 		sid = tmap->self_id[i];
523 		if (sid.p0.sequel) {
524 			printf("%02d sequel packet\n", sid.p0.phy_id);
525 			continue;
526 		}
527 		printf("%02d   %2d      %2d  %4s     %d   %3s"
528 				"     %s     %s     %s   %d    %d\n",
529 			sid.p0.phy_id,
530 			sid.p0.link_active,
531 			sid.p0.gap_count,
532 			speed[sid.p0.phy_speed],
533 			sid.p0.contender,
534 			pwr_class[sid.p0.power_class],
535 			port_status[sid.p0.port0],
536 			port_status[sid.p0.port1],
537 			port_status[sid.p0.port2],
538 			sid.p0.initiated_reset,
539 			sid.p0.more_packets
540 		);
541 	}
542 	free(tmap);
543 }
544 
545 static void
546 read_phy_registers(int fd, uint8_t *buf, int offset, int len)
547 {
548 	struct fw_reg_req_t reg;
549 	int i;
550 
551 	for (i = 0; i < len; i++) {
552 		reg.addr = offset + i;
553 		if (ioctl(fd, FWOHCI_RDPHYREG, &reg) < 0)
554 			err(EX_IOERR, "%s: ioctl", __func__);
555 		buf[i] = (uint8_t) reg.data;
556 		printf("0x%02x ",  reg.data);
557 	}
558 	printf("\n");
559 }
560 
561 static void
562 read_phy_page(int fd, uint8_t *buf, int page, int port)
563 {
564 	struct fw_reg_req_t reg;
565 
566 	reg.addr = 0x7;
567 	reg.data = ((page & 7) << 5) | (port & 0xf);
568 	if (ioctl(fd, FWOHCI_WRPHYREG, &reg) < 0)
569 		err(EX_IOERR, "%s: ioctl", __func__);
570 	read_phy_registers(fd, buf, 8, 8);
571 }
572 
573 static void
574 dump_phy_registers(int fd)
575 {
576 	struct phyreg_base b;
577 	struct phyreg_page0 p;
578 	struct phyreg_page1 v;
579 	int i;
580 
581 	printf("=== base register ===\n");
582 	read_phy_registers(fd, (uint8_t *)&b, 0, 8);
583 	printf(
584 	    "Physical_ID:%d  R:%d  CPS:%d\n"
585 	    "RHB:%d  IBR:%d  Gap_Count:%d\n"
586 	    "Extended:%d Num_Ports:%d\n"
587 	    "PHY_Speed:%d Delay:%d\n"
588 	    "LCtrl:%d C:%d Jitter:%d Pwr_Class:%d\n"
589 	    "WDIE:%d ISBR:%d CTOI:%d CPSI:%d STOI:%d PEI:%d EAA:%d EMC:%d\n"
590 	    "Max_Legacy_SPD:%d BLINK:%d Bridge:%d\n"
591 	    "Page_Select:%d Port_Select%d\n",
592 	    b.phy_id, b.r, b.cps,
593 	    b.rhb, b.ibr, b.gap_count,
594 	    b.extended, b.num_ports,
595 	    b.phy_speed, b.delay,
596 	    b.lctrl, b.c, b.jitter, b.pwr_class,
597 	    b.wdie, b.isbr, b.ctoi, b.cpsi, b.stoi, b.pei, b.eaa, b.emc,
598 	    b.legacy_spd, b.blink, b.bridge,
599 	    b.page_select, b.port_select
600 	);
601 
602 	for (i = 0; i < b.num_ports; i ++) {
603 		printf("\n=== page 0 port %d ===\n", i);
604 		read_phy_page(fd, (uint8_t *)&p, 0, i);
605 		printf(
606 		    "Astat:%d BStat:%d Ch:%d Con:%d RXOK:%d Dis:%d\n"
607 		    "Negotiated_speed:%d PIE:%d Fault:%d Stanby_fault:%d Disscrm:%d B_Only:%d\n"
608 		    "DC_connected:%d Max_port_speed:%d LPP:%d Cable_speed:%d\n"
609 		    "Connection_unreliable:%d Beta_mode:%d\n"
610 		    "Port_error:0x%x\n"
611 		    "Loop_disable:%d In_standby:%d Hard_disable:%d\n",
612 		    p.astat, p.bstat, p.ch, p.con, p.rxok, p.dis,
613 		    p.negotiated_speed, p.pie, p.fault, p.stanby_fault, p.disscrm, p.b_only,
614 		    p.dc_connected, p.max_port_speed, p.lpp, p.cable_speed,
615 		    p.connection_unreliable, p.beta_mode,
616 		    p.port_error,
617 		    p.loop_disable, p.in_standby, p.hard_disable
618 		);
619 	}
620 	printf("\n=== page 1 ===\n");
621 	read_phy_page(fd, (uint8_t *)&v, 1, 0);
622 	printf(
623 	    "Compliance:%d\n"
624 	    "Vendor_ID:0x%06x\n"
625 	    "Product_ID:0x%06x\n",
626 	    v.compliance,
627 	    (v.vendor_id[0] << 16) | (v.vendor_id[1] << 8) | v.vendor_id[2],
628 	    (v.product_id[0] << 16) | (v.product_id[1] << 8) | v.product_id[2]
629 	);
630 }
631 
632 static int
633 open_dev(int *fd, const char *_devname)
634 {
635 
636 	if (*fd < 0) {
637 		*fd = open(_devname, O_RDWR);
638 		if (*fd < 0)
639 			return -1;
640 	}
641 	return 0;
642 }
643 
644 static void
645 sysctl_set_int(const char *name, int val)
646 {
647 	if (sysctlbyname(name, NULL, NULL, &val, sizeof(val)) < 0)
648 		err(EX_SOFTWARE, "%s: sysctl %s failed.", __func__, name);
649 }
650 
651 static fwmethod *
652 detect_recv_fn(int fd, char ich)
653 {
654 	char *buf;
655 	struct fw_isochreq isoreq;
656 	struct fw_isobufreq bufreq;
657 	int len;
658 	uint32_t *ptr;
659 	struct ciphdr *ciph;
660 	fwmethod *retfn;
661 #define RECV_NUM_PACKET	16
662 #define RECV_PACKET_SZ	1024
663 
664 	bufreq.rx.nchunk = 8;
665 	bufreq.rx.npacket = RECV_NUM_PACKET;
666 	bufreq.rx.psize = RECV_PACKET_SZ;
667 	bufreq.tx.nchunk = 0;
668 	bufreq.tx.npacket = 0;
669 	bufreq.tx.psize = 0;
670 
671 	if (ioctl(fd, FW_SSTBUF, &bufreq) < 0)
672 		err(EX_IOERR, "%s: ioctl FW_SSTBUF", __func__);
673 
674 	isoreq.ch = ich & 0x3f;
675 	isoreq.tag = (ich >> 6) & 3;
676 
677 	if (ioctl(fd, FW_SRSTREAM, &isoreq) < 0)
678 		err(EX_IOERR, "%s: ioctl FW_SRSTREAM", __func__);
679 
680 	buf = malloc(RECV_NUM_PACKET * RECV_PACKET_SZ);
681 	if (buf == NULL)
682 		err(EX_SOFTWARE, "%s: buf malloc", __func__);
683 	/*
684 	 * fwdev.c seems to return EIO on error and
685 	 * the return value of the last uiomove
686 	 * on success.  For now, checking that the
687 	 * return is not less than zero should be
688 	 * sufficient.  fwdev.c::fw_read() should
689 	 * return the total length read, not the value
690 	 * of the last uiomove().
691 	 */
692 	len = read(fd, buf, RECV_NUM_PACKET * RECV_PACKET_SZ);
693 	if (len < 0)
694 		err(EX_IOERR, "%s: error reading from device", __func__);
695 	ptr = (uint32_t *) buf;
696 	ciph = (struct ciphdr *)(ptr + 1);
697 
698 	switch (ciph->fmt) {
699 	case CIP_FMT_DVCR:
700 		fprintf(stderr, "Detected DV format on input.\n");
701 		retfn = dvrecv;
702 		break;
703 	case CIP_FMT_MPEG:
704 		fprintf(stderr, "Detected MPEG TS format on input.\n");
705 		retfn = mpegtsrecv;
706 		break;
707 	default:
708 		errx(EXIT_FAILURE,
709 		    "%s: Unsupported format for receiving: fmt=0x%x", __func__,
710 		    ciph->fmt);
711 	}
712 	free(buf);
713 	return retfn;
714 }
715 
716 int
717 main(int argc, char **argv)
718 {
719 #define MAX_BOARDS 10
720 	uint32_t crom_buf[1024/4];
721 	uint32_t crom_buf_hex[1024/4];
722 	char devbase[64];
723 	const char *device_string = "/dev/fw";
724 	int fd = -1, ch, len=1024;
725 	int32_t current_board = 0;
726 /*
727  * If !command_set, then -u will display the nodes for the board.
728  * This emulates the previous behavior when -u is passed by itself
729  */
730 	bool command_set = false;
731 	bool open_needed = false;
732 	long tmp;
733 	struct fw_eui64 eui;
734 	struct eui64 target;
735 	fwmethod *recvfn = NULL;
736 
737 /*
738  * Holders for which functions
739  * to iterate through
740  */
741 	bool display_board_only = false;
742 	bool display_crom = false;
743 	bool send_bus_reset = false;
744 	bool display_crom_hex = false;
745 	bool load_crom_from_file = false;
746 	bool set_fwmem_target = false;
747 	bool dump_topology = false;
748 	bool dump_phy_reg = false;
749 
750 	int32_t priority_budget = -1;
751 	int32_t set_root_node = -1;
752 	int32_t set_gap_count = -1;
753 	int32_t send_link_on = -1;
754 	int32_t send_reset_start = -1;
755 
756 	char *crom_string = NULL;
757 	char *crom_string_hex = NULL;
758 	char *recv_data = NULL;
759 	char *send_data = NULL;
760 
761 	if (argc < 2) {
762 		for (current_board = 0; current_board < MAX_BOARDS; current_board++) {
763 			snprintf(devbase, sizeof(devbase), "%s%d.0", device_string, current_board);
764 			if (open_dev(&fd, devbase) < 0) {
765 				if (current_board == 0) {
766 					usage();
767 					err(EX_IOERR, "%s: Error opening "
768 					    "firewire controller #%d %s",
769 					    __func__, current_board, devbase);
770 				}
771 				return EIO;
772 			}
773 			list_dev(fd);
774 			close(fd);
775 			fd = -1;
776 		}
777 	}
778 	/*
779 	 * Parse all command line options, then execute requested operations.
780 	 */
781 	while ((ch = getopt(argc, argv, "b:c:d:f:g:l:M:m:o:pR:rS:s:tu:")) != -1) {
782 		switch (ch) {
783 		case 'b':
784 			priority_budget = strtol(optarg, NULL, 0);
785 			if (priority_budget < 0 || priority_budget > INT32_MAX)
786 				errx(EX_USAGE,
787 				    "%s: priority_budget out of range: %s",
788 				    __func__, optarg);
789 			command_set = true;
790 			open_needed = true;
791 			display_board_only = false;
792 			break;
793 		case 'c':
794 			crom_string = strdup(optarg);
795 			if (crom_string == NULL)
796 				err(EX_SOFTWARE, "%s: crom_string malloc",
797 				    __func__);
798 			if (strtol(crom_string, NULL, 0) < 0 ||
799 			    strtol(crom_string, NULL, 0) > MAX_BOARDS)
800 				errx(EX_USAGE, "%s: Invalid value for node",
801 				    __func__);
802 			display_crom = 1;
803 			open_needed = true;
804 			command_set = true;
805 			display_board_only = false;
806 			break;
807 		case 'd':
808 			crom_string_hex = strdup(optarg);
809 			if (crom_string_hex == NULL)
810 				err(EX_SOFTWARE, "%s: crom_string_hex malloc",
811 				    __func__);
812 			display_crom_hex = 1;
813 			open_needed = true;
814 			command_set = true;
815 			display_board_only = false;
816 			break;
817 		case 'f':
818 #define MAX_PHY_CONFIG 0x3f
819 			set_root_node = strtol(optarg, NULL, 0);
820 			if (set_root_node < 0 || set_root_node > MAX_PHY_CONFIG)
821 				errx(EX_USAGE, "%s: set_root_node out of range",
822 				    __func__);
823 			open_needed = true;
824 			command_set = true;
825 			display_board_only = false;
826 			break;
827 		case 'g':
828 			set_gap_count = strtol(optarg, NULL, 0);
829 			if (set_gap_count < 0 || set_gap_count > MAX_PHY_CONFIG)
830 				errx(EX_USAGE, "%s: set_gap_count out of range",
831 				    __func__);
832 			open_needed = true;
833 			command_set = true;
834 			display_board_only = false;
835 			break;
836 		case 'l':
837 			load_crom_from_file = 1;
838 			load_crom(optarg, crom_buf);
839 			command_set = true;
840 			display_board_only = false;
841 			break;
842 		case 'm':
843 			set_fwmem_target = 1;
844 			open_needed = 0;
845 			command_set = true;
846 			display_board_only = false;
847 			if (eui64_hostton(optarg, &target) != 0 &&
848 			    eui64_aton(optarg, &target) != 0)
849 				errx(EX_USAGE, "%s: invalid target: %s",
850 				    __func__, optarg);
851 			break;
852 		case 'o':
853 			send_link_on = str2node(fd, optarg);
854 			if (send_link_on < 0 || send_link_on > MAX_PHY_CONFIG)
855 				errx(EX_USAGE, "%s: node out of range: %s",
856 				    __func__, optarg);
857 			open_needed = true;
858 			command_set = true;
859 			display_board_only = false;
860 			break;
861 		case 'p':
862 			dump_phy_reg = 1;
863 			open_needed = true;
864 			command_set = true;
865 			display_board_only = false;
866 			break;
867 		case 'r':
868 			send_bus_reset = 1;
869 			open_needed = true;
870 			command_set = true;
871 			display_board_only = false;
872 			break;
873 		case 's':
874 			send_reset_start  = str2node(fd, optarg);
875 			if (send_reset_start < 0 ||
876 			    send_reset_start > MAX_PHY_CONFIG)
877 				errx(EX_USAGE, "%s: node out of range: %s",
878 				    __func__, optarg);
879 			open_needed = true;
880 			command_set = true;
881 			display_board_only = false;
882 			break;
883 		case 't':
884 			dump_topology = 1;
885 			open_needed = true;
886 			command_set = true;
887 			display_board_only = false;
888 			break;
889 		case 'u':
890 			if (!command_set)
891 				display_board_only = true;
892 			current_board = strtol(optarg, NULL, 0);
893 			open_needed = true;
894 			break;
895 		case 'M':
896 			switch (optarg[0]) {
897 			case 'm':
898 				recvfn = mpegtsrecv;
899 				break;
900 			case 'd':
901 				recvfn = dvrecv;
902 				break;
903 			default:
904 				errx(EX_USAGE, "%s: unrecognized method: %s",
905 				    __func__, optarg);
906 			}
907 			command_set = true;
908 			display_board_only = false;
909 			break;
910 		case 'R':
911 			recv_data = strdup(optarg);
912 			if (recv_data == NULL)
913 				err(EX_SOFTWARE, "%s: recv_data malloc",
914 				    __func__);
915 			open_needed = false;
916 			command_set = true;
917 			display_board_only = false;
918 			break;
919 		case 'S':
920 			send_data = strdup(optarg);
921 			if (send_data == NULL)
922 				err(EX_SOFTWARE, "%s: send_data malloc",
923 				    __func__);
924 			open_needed = true;
925 			command_set = true;
926 			display_board_only = false;
927 			break;
928 		case '?':
929 		default:
930 			usage();
931 			errx(EINVAL, "%s: Unknown command line arguments",
932 			    __func__);
933 			return 0;
934 		}
935 	} /* end while */
936 
937 	/*
938 	 * Catch the error case when the user
939 	 * executes the command with non ''-''
940 	 * delimited arguments.
941 	 * Generate the usage() display and exit.
942 	 */
943 	if (!command_set && !display_board_only) {
944 		usage();
945 		errx(EINVAL, "%s: Unknown command line arguments", __func__);
946 		return 0;
947 	}
948 
949 	/*
950 	 * If -u <bus_number> is passed, execute
951 	 * command for that card only.
952 	 *
953 	 * If -u <bus_number> is not passed, execute
954 	 * command for card 0 only.
955 	 *
956 	 */
957 	if (open_needed) {
958 		snprintf(devbase, sizeof(devbase),
959 		    "%s%d.0", device_string, current_board);
960 		if (open_dev(&fd, devbase) < 0) {
961 			err(EX_IOERR,
962 			    "%s: Error opening firewire controller #%d %s",
963 			    __func__, current_board, devbase);
964 		}
965 	}
966 	/*
967 	 * display the nodes on this board "-u" only
968 	*/
969 	if (display_board_only)
970 		list_dev(fd);
971 
972 	/*
973 	 * dump_phy_reg "-p"
974 	 */
975 	if (dump_phy_reg)
976 		dump_phy_registers(fd);
977 
978 	/*
979 	 * send a BUS_RESET Event "-r"
980 	 */
981 	if (send_bus_reset)
982 		if (ioctl(fd, FW_IBUSRST, &tmp) < 0)
983 			err(EX_IOERR, "%s: Ioctl of bus reset failed for %s",
984 			    __func__, devbase);
985 	/*
986 	 * Print out the CROM for this node "-c"
987 	 */
988 	if (display_crom) {
989 		tmp = str2node(fd, crom_string);
990 		get_crom(fd, tmp, crom_buf, len);
991 		show_crom(crom_buf);
992 		free(crom_string);
993 	}
994 	/*
995 	 * Hex Dump the CROM for this node "-d"
996 	 */
997 	if (display_crom_hex) {
998 		tmp = str2node(fd, crom_string_hex);
999 		get_crom(fd, tmp, crom_buf_hex, len);
1000 		dump_crom(crom_buf_hex);
1001 		free(crom_string_hex);
1002 	}
1003 	/*
1004 	 * Set Priority Budget to value for this node "-b"
1005 	 */
1006 	if (priority_budget >= 0)
1007 		set_pri_req(fd, priority_budget);
1008 
1009 	/*
1010 	 * Explicitly set the root node of this bus to value "-f"
1011 	 */
1012 	if (set_root_node >= 0)
1013 		send_phy_config(fd, set_root_node, -1);
1014 
1015 	/*
1016 	 * Set the gap count for this card/bus  "-g"
1017 	 */
1018 	if (set_gap_count >= 0)
1019 		send_phy_config(fd, -1, set_gap_count);
1020 
1021 	/*
1022 	 * Load a CROM from a file "-l"
1023 	 */
1024 	if (load_crom_from_file)
1025 		show_crom(crom_buf);
1026 	/*
1027 	 * Set the fwmem target for a node to argument "-m"
1028 	 */
1029 	if (set_fwmem_target) {
1030 		eui.hi = ntohl(*(uint32_t*)&(target.octet[0]));
1031 		eui.lo = ntohl(*(uint32_t*)&(target.octet[4]));
1032 		sysctl_set_int("hw.fwmem.eui64_hi", eui.hi);
1033 		sysctl_set_int("hw.fwmem.eui64_lo", eui.lo);
1034 	}
1035 
1036 	/*
1037 	 * Send a link on to this board/bus "-o"
1038 	 */
1039 	if (send_link_on >= 0)
1040 		link_on(fd, send_link_on);
1041 
1042 	/*
1043 	 * Send a reset start to this board/bus "-s"
1044 	 */
1045 	if (send_reset_start >= 0)
1046 		reset_start(fd, send_reset_start);
1047 
1048 	/*
1049 	 * Dump the node topology for this board/bus "-t"
1050 	 */
1051 	if (dump_topology)
1052 		show_topology_map(fd);
1053 
1054 	/*
1055 	 * Recieve data file from node "-R"
1056 	 */
1057 #define TAG	(1<<6)
1058 #define CHANNEL	63
1059 	if (recv_data != NULL){
1060 		if (recvfn == NULL) { /* guess... */
1061 			recvfn = detect_recv_fn(fd, TAG | CHANNEL);
1062 			close(fd);
1063 			fd = -1;
1064 		}
1065 		snprintf(devbase, sizeof(devbase), "%s%d.0",
1066 		    device_string, current_board);
1067 		if (open_dev(&fd, devbase) < 0)
1068 			err(EX_IOERR, "%s: Error opening firewire "
1069 			    "controller #%d %s in recv_data",
1070 			    __func__, current_board, devbase);
1071 		(*recvfn)(fd, recv_data, TAG | CHANNEL, -1);
1072 		free(recv_data);
1073 	}
1074 
1075 	/*
1076 	 * Send data file to node "-S"
1077 	 */
1078 	if (send_data != NULL){
1079 		dvsend(fd, send_data, TAG | CHANNEL, -1);
1080 		free(send_data);
1081 	}
1082 
1083 	if (fd > 0) {
1084 		close(fd);
1085 		fd = -1;
1086 	}
1087 	return 0;
1088 }
1089