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