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