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