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