ecosboard.c 39 KB
Newer Older
1
/***************************************************************************
2
 *   Copyright (C) 2007-2010 by Øyvind Harboe                              *
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

24
#include <helper/types.h>
25
#include <jtag/jtag.h>
26
#include <helper/ioutil.h>
27
#include <helper/util.h>
28
#include <helper/configuration.h>
29

30
#include <server/server.h>
31
#include <server/telnet_server.h>
32
#include <server/gdb_server.h>
33
#include <openocd.h>
34

35
#include <helper/time_support.h>
36

37
38
39
40
41
42
43
44
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#include <cyg/io/flash.h>
45
46
47
#include <pkgconf/fs_jffs2.h>	// Address of JFFS2
#include <network.h>

48
#include <fcntl.h>
49
#include <sys/stat.h>
50
51
#include <cyg/fileio/fileio.h>
#include <dirent.h>
52
53
54
55
56
#include <cyg/athttpd/http.h>
#include <cyg/athttpd/socket.h>
#include <cyg/athttpd/handler.h>
#include <cyg/athttpd/cgi.h>
#include <cyg/athttpd/forms.h>
oharboe's avatar
oharboe committed
57
#include <cyg/discover/discover.h>
58
#include <cyg/io/io.h>
59
#include <cyg/io/serialio.h>
60
#include <netinet/tcp.h>
61
#include <cyg/hal/hal_diag.h>
62

63
#include "rom.h"
64

Øyvind Harboe's avatar
Øyvind Harboe committed
65
#ifdef CYGPKG_HAL_NIOS2
66
#include <cyg/hal/io.h>
Øyvind Harboe's avatar
Øyvind Harboe committed
67
68
69
70
71
72
73
#define ZY1000_SER_DEV "/dev/uart_0"
#else
#define ZY1000_SER_DEV "/dev/ser0"

#endif


74
75
76
77
78
79
80
81
82
#define MAX_IFS 64
#if defined(CYGPKG_NET_FREEBSD_STACK)
#include <tftp_support.h>
/* posix compatibility broken*/
struct tftpd_fileops fileops =
{
	(int (*)(const char *, int))open,
	close,
	(int (*)(int, const void *, int))write,
83
	(int (*)(int, void *, int))read
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
};

#endif


void diag_write(char *buf, int len)
{
	int j;
	for (j = 0; j < len; j++)
	{
		diag_printf("%c", buf[j]);
	}
}

static bool serialLog = true;
static bool writeLog = true;

101
char hwaddr[512];
102
103
104
105
106
107

#ifdef CYGPKG_PROFILE_GPROF
#include <cyg/profile/profile.h>

extern char _stext, _etext; // Defined by the linker

oharboe's avatar
oharboe committed
108
109
110
static char *start_of_code=&_stext;
static char *end_of_code=&_etext;

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
void start_profile(void)
{
	// This starts up the system-wide profiling, gathering
	// profile information on all of the code, with a 16 byte
	// "bucket" size, at a rate of 100us/profile hit.
	// Note: a bucket size of 16 will give pretty good function
	//       resolution.  Much smaller and the buffer becomes
	//       much too large for very little gain.
	// Note: a timer period of 100us is also a reasonable
	//       compromise.  Any smaller and the overhead of
	//       handling the timter (profile) interrupt could
	//       swamp the system.  A fast processor might get
	//       by with a smaller value, but a slow one could
	//       even be swamped by this value.  If the value is
	//       too large, the usefulness of the profile is reduced.

	// no more interrupts than 1/10ms.
	//profile_on((void *)0, (void *)0x40000, 16, 10000); // SRAM
129
	//	profile_on(0, &_etext, 16, 10000); // SRAM & DRAM
oharboe's avatar
oharboe committed
130
	profile_on(start_of_code, end_of_code, 16, 10000); // Nios DRAM
131
132
133
134
135
136
137
}
#endif

static FILE *log;

static char reboot_stack[2048];

138
static void zylinjtag_reboot(cyg_addrword_t data)
139
140
{
	serialLog = true;
141
142
	diag_printf("Rebooting in 500 ticks..\n");
	cyg_thread_delay(500);
143
144
145
	diag_printf("Unmounting /config..\n");
	umount("/config");
	diag_printf("Rebooting..\n");
146
147
148
149
150
151
#ifdef CYGPKG_HAL_NIOS2
	/* This will reboot & reconfigure the FPGA from the bootloader
	 * and on.
	 */
	IOWR(REMOTE_UPDATE_BASE, 0x20, 0x1);
#else
152
	HAL_PLATFORM_RESET();
153
#endif
154
155
156
157
158
159
}
static cyg_thread zylinjtag_thread_object;
static cyg_handle_t zylinjtag_thread_handle;

void reboot(void)
{
160
161
162
	cyg_thread_create(1, zylinjtag_reboot, (cyg_addrword_t) 0, "reboot Thread",
			(void *) reboot_stack, sizeof(reboot_stack),
			&zylinjtag_thread_handle, &zylinjtag_thread_object);
163
164
165
	cyg_thread_resume(zylinjtag_thread_handle);
}

166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
static char zylinjtag_reboot_port_stack[2048];
static cyg_thread zylinjtag_reboot_port_thread_object;
static cyg_handle_t zylinjtag_reboot_port_thread_handle;

static void zylinjtag_reboot_port_task(cyg_addrword_t data)
{
	int so_reuseaddr_option = 1;

	int fd;
	if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		LOG_ERROR("error creating socket: %s", strerror(errno));
		exit(-1);
	}

	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void*) &so_reuseaddr_option,
			sizeof(int));

	struct sockaddr_in sin;
	unsigned int address_size;
	address_size = sizeof(sin);
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;
	sin.sin_port = htons(1234);

	if (bind(fd, (struct sockaddr *) &sin, sizeof(sin)) == -1)
	{
		LOG_ERROR("couldn't bind to socket: %s", strerror(errno));
		exit(-1);
	}

	if (listen(fd, 1) == -1)
	{
		LOG_ERROR("couldn't listen on socket: %s", strerror(errno));
		exit(-1);
	}
	//	socket_nonblock(fd);


	accept(fd, (struct sockaddr *) &sin, &address_size);

	diag_printf("Got reboot signal on port 1234");

	reboot();

}

void reboot_port(void)
{
	cyg_thread_create(1, zylinjtag_reboot_port_task, (cyg_addrword_t) 0, "wait for reboot signal on port 1234",
			(void *) zylinjtag_reboot_port_stack, sizeof(zylinjtag_reboot_port_stack),
			&zylinjtag_reboot_port_thread_handle, &zylinjtag_reboot_port_thread_object);
	cyg_thread_resume(zylinjtag_reboot_port_thread_handle);
}

222
int configuration_output_handler(struct command_context *context,
223
		const char* line)
224
225
226
227
228
229
{
	diag_printf("%s", line);

	return ERROR_OK;
}

230
int zy1000_configuration_output_handler_log(struct command_context *context,
231
		const char* line)
232
233
234
235
236
237
238
{
	LOG_USER_N("%s", line);

	return ERROR_OK;
}

#ifdef CYGPKG_PROFILE_GPROF
239
//extern int64_t totaltime;
240

241
242
static int zylinjtag_Jim_Command_profile(Jim_Interp *interp, int argc,
		Jim_Obj * const *argv)
243
{
244
245
246
247
248
249
250
251
252
253
	if ((argc == 2) && (strcmp(Jim_GetString(argv[1], NULL), "stats")==0))
	{
//		profile_off();
		//LOG_USER("Stats %dms sleeping in select()", (int)totaltime);
	} else
	{
		LOG_USER("Profiling started");
		start_profile();
		//totaltime = 0;
	}
254
255
256
257
258
	return ERROR_OK;
}

#endif

259
externC void phi_init_all_network_interfaces(void);
260

261
struct command_context *cmd_ctx;
262
263
264

static bool webRunning = false;

265
void keep_webserver(void)
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
{
	// Target initialisation is only attempted at startup, so we sleep forever and
	// let the http server bail us out(i.e. get config files set up).
	diag_printf("OpenOCD has invoked exit().\n"
		"Use web server to correct any configuration settings and reboot.\n");
	if (!webRunning)
		reboot();

	// exit() will terminate the current thread and we we'll then sleep eternally or
	// we'll have a reboot scheduled.
}

extern void printDccChar(char c);

static char logBuffer[128 * 1024];
static const int logSize = sizeof(logBuffer);
int writePtr = 0;
int logCount = 0;

void _zylinjtag_diag_write_char(char c, void **param)
{
	if (writeLog)
	{
		logBuffer[writePtr] = c;
		writePtr = (writePtr + 1) % logSize;
		logCount++;
	}
	if (serialLog)
	{
		if (c == '\n')
		{
			HAL_DIAG_WRITE_CHAR('\r');
		}
		HAL_DIAG_WRITE_CHAR(c);
	}

oharboe's avatar
oharboe committed
302
#ifdef CYGPKG_HAL_ZYLIN_PHI
303
	printDccChar(c);
oharboe's avatar
oharboe committed
304
#endif
305
306
}

307
void copyfile(char *name2, char *name1);
308

309
void copydir(char *name, char *destdir);
310
311

#if 0
312
MTAB_ENTRY(romfs_mte1,
313
314
315
		"/rom",
		"romfs",
		"",
316
		(CYG_ADDRWORD) &filedata[0]);
317
318
#endif

319
void openocd_sleep_prelude(void)
320
321
322
323
{
	cyg_mutex_unlock(&httpstate.jim_lock);
}

324
void openocd_sleep_postlude(void)
325
326
327
328
{
	cyg_mutex_lock(&httpstate.jim_lock);
}

oharboe's avatar
wip    
oharboe committed
329
330
void format(void)
{
331
#ifdef CYGDAT_IO_FLASH_BLOCK_DEVICE_NAME_1
oharboe's avatar
wip    
oharboe committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345
	diag_printf("Formatting JFFS2...\n");

	cyg_io_handle_t handle;

	Cyg_ErrNo err;
	err = cyg_io_lookup(CYGDAT_IO_FLASH_BLOCK_DEVICE_NAME_1, &handle);
	if (err != ENOERR)
	{
		diag_printf("Flash Error cyg_io_lookup: %d\n", err);
		reboot();
	}

	cyg_uint32 len;
	cyg_io_flash_getconfig_devsize_t ds;
346
347
	len = sizeof(ds);
	err = cyg_io_get_config(handle, CYG_IO_GET_CONFIG_FLASH_DEVSIZE, &ds, &len);
oharboe's avatar
wip    
oharboe committed
348
349
350
351
352
353
354
	if (err != ENOERR)
	{
		diag_printf("Flash error cyg_io_get_config %d\n", err);
		reboot();
	}

	cyg_io_flash_getconfig_erase_t e;
355
	len = sizeof(e);
oharboe's avatar
wip    
oharboe committed
356
357
358
359

	e.offset = 0;
	e.len = ds.dev_size;

oharboe's avatar
oharboe committed
360
	diag_printf("Formatting 0x%08x bytes\n", (int)ds.dev_size);
361
	err = cyg_io_get_config(handle, CYG_IO_GET_CONFIG_FLASH_ERASE, &e, &len);
oharboe's avatar
wip    
oharboe committed
362
363
	if (err != ENOERR)
	{
oharboe's avatar
oharboe committed
364
		diag_printf("Flash erase error %d offset 0x%08x\n", err, e.err_address);
oharboe's avatar
wip    
oharboe committed
365
366
367
368
		reboot();
	}

	diag_printf("Flash formatted successfully\n");
369
#endif
oharboe's avatar
wip    
oharboe committed
370
371
372
373

	reboot();
}

374
static int zylinjtag_Jim_Command_format_jffs2(Jim_Interp *interp, int argc,
oharboe's avatar
wip    
oharboe committed
375
376
377
378
379
380
381
382
		Jim_Obj * const *argv)
{
	if (argc != 1)
	{
		return JIM_ERR;
	}

	format();
383
384
	for (;;)
		;
385
386
}

387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
static int zylinjtag_Jim_Command_threads(Jim_Interp *interp, int argc,
		Jim_Obj * const *argv)
{
	cyg_handle_t thread = 0;
	cyg_uint16 id = 0;
	Jim_Obj *threads = Jim_NewListObj(interp, NULL, 0);

	/* Loop over the threads, and generate a table row for
	 * each.
	 */
	while (cyg_thread_get_next(&thread, &id))
	{
		Jim_Obj *threadObj = Jim_NewListObj(interp, NULL, 0);

		cyg_thread_info info;
		char *state_string;

		cyg_thread_get_info(thread, id, &info);

		if (info.name == NULL)
			info.name = "<no name>";

		Jim_ListAppendElement(interp, threadObj, Jim_NewStringObj(interp,
				info.name, strlen(info.name)));

		/* Translate the state into a string.
		 */
		if (info.state == 0)
			state_string = "RUN";
		else if (info.state & 0x04)
			state_string = "SUSP";
		else
			switch (info.state & 0x1b)
			{
			case 0x01:
				state_string = "SLEEP";
				break;
			case 0x02:
				state_string = "CNTSLEEP";
				break;
			case 0x08:
				state_string = "CREATE";
				break;
			case 0x10:
				state_string = "EXIT";
				break;
			default:
				state_string = "????";
				break;
			}

		Jim_ListAppendElement(interp, threadObj, Jim_NewStringObj(interp,
				state_string, strlen(state_string)));

441
442
443
444
445
		Jim_ListAppendElement(interp, threadObj, Jim_NewIntObj(interp, id));
		Jim_ListAppendElement(interp, threadObj, Jim_NewIntObj(interp,
				info.set_pri));
		Jim_ListAppendElement(interp, threadObj, Jim_NewIntObj(interp,
				info.cur_pri));
446
447
448

		Jim_ListAppendElement(interp, threads, threadObj);
	}
449
	Jim_SetResult(interp, threads);
450
451
452
453

	return JIM_OK;
}

454
static int zylinjtag_Jim_Command_log(Jim_Interp *interp, int argc,
455
456
457
458
459
460
		Jim_Obj * const *argv)
{
	Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);

	if (logCount >= logSize)
	{
461
462
		Jim_AppendString(httpstate.jim_interp, tclOutput, logBuffer + logCount
				% logSize, logSize - logCount % logSize);
463
464
465
466
467
468
469
	}
	Jim_AppendString(httpstate.jim_interp, tclOutput, logBuffer, writePtr);

	Jim_SetResult(interp, tclOutput);
	return JIM_OK;
}

470
static int zylinjtag_Jim_Command_reboot(Jim_Interp *interp, int argc,
471
472
473
474
475
476
		Jim_Obj * const *argv)
{
	reboot();
	return JIM_OK;
}

477
static void zylinjtag_startNetwork(void)
478
479
480
481
482
483
484
485
486
487
488
489
490
491
{
	// Bring TCP/IP up immediately before we're ready to accept commands.
	//
	// That is as soon as a PING responds, we're accepting telnet sessions.
#if defined(CYGPKG_NET_FREEBSD_STACK)
	phi_init_all_network_interfaces();
#else
	lwip_init();
#endif
	if (!eth0_up)
	{
		diag_printf("Network not up and running\n");
		exit(-1);
	}
492
493
494
495

	/* very first thing we want is a reboot capability */
	reboot_port();

496
497
498
499
500
501
502
#if defined(CYGPKG_NET_FREEBSD_STACK)
	/*start TFTP*/
	tftpd_start(69, &fileops);
#endif

	cyg_httpd_init_tcl_interpreter();

Øyvind Harboe's avatar
Øyvind Harboe committed
503
504
505
506
	// Kludge! Why can't I do this from httpd.c??? I get linker errors...
	// some of that --start/end-group stuff?
    Jim_InitStaticExtensions(httpstate.jim_interp);

507
508
	Jim_CreateCommand(httpstate.jim_interp, "log", zylinjtag_Jim_Command_log,
			NULL, NULL);
509
	Jim_CreateCommand(httpstate.jim_interp, "zy1000_reboot",
510
511
512
513
514
			zylinjtag_Jim_Command_reboot, NULL, NULL);
	Jim_CreateCommand(httpstate.jim_interp, "threads",
			zylinjtag_Jim_Command_threads, NULL, NULL);
	Jim_CreateCommand(httpstate.jim_interp, "format_jffs2",
			zylinjtag_Jim_Command_format_jffs2, NULL, NULL);
515
516
517
518
519
520

	cyg_httpd_start();

	webRunning = true;

	diag_printf("Web server running\n");
oharboe's avatar
oharboe committed
521

522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
	int s;
	struct ifreq ifr;
	s = socket(AF_INET, SOCK_DGRAM, 0);
	if (s >= 0)
	{
		strcpy(ifr.ifr_name, "eth0");
		int res;
		res = ioctl(s, SIOCGIFHWADDR, &ifr);
		close(s);

		if (res < 0)
		{
			diag_printf("Can't obtain MAC address\n");
			reboot();
		}
	}

	sprintf(hwaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
			(int) ((unsigned char *) &ifr.ifr_hwaddr.sa_data)[0],
			(int) ((unsigned char *) &ifr.ifr_hwaddr.sa_data)[1],
			(int) ((unsigned char *) &ifr.ifr_hwaddr.sa_data)[2],
			(int) ((unsigned char *) &ifr.ifr_hwaddr.sa_data)[3],
			(int) ((unsigned char *) &ifr.ifr_hwaddr.sa_data)[4],
			(int) ((unsigned char *) &ifr.ifr_hwaddr.sa_data)[5]);

547
548
	discover_message
			= alloc_printf("ZY1000 Zylin JTAG debugger MAC %s", hwaddr);
549

oharboe's avatar
oharboe committed
550
	discover_launch();
551
552
}

553
554
static void print_exception_handler(cyg_addrword_t data, cyg_code_t exception,
		cyg_addrword_t info)
555
556
557
558
559
560
{
	writeLog = false;
	serialLog = true;
	char *infoStr = "unknown";
	switch (exception)
	{
oharboe's avatar
oharboe committed
561
#ifdef CYGNUM_HAL_VECTOR_UNDEF_INSTRUCTION
562
	case CYGNUM_HAL_VECTOR_UNDEF_INSTRUCTION:
563
564
	infoStr = "undefined instruction";
	break;
565
	case CYGNUM_HAL_VECTOR_SOFTWARE_INTERRUPT:
566
567
	infoStr = "software interrupt";
	break;
568
	case CYGNUM_HAL_VECTOR_ABORT_PREFETCH:
569
570
	infoStr = "abort prefetch";
	break;
571
	case CYGNUM_HAL_VECTOR_ABORT_DATA:
572
573
	infoStr = "abort data";
	break;
oharboe's avatar
oharboe committed
574
#endif
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
	default:
		break;
	}

	diag_printf("Exception: %08x(%s) %08x\n", exception, infoStr, info);

	diag_printf("Dumping log\n---\n");
	if (logCount >= logSize)
	{
		diag_write(logBuffer + logCount % logSize, logSize - logCount % logSize);
	}
	diag_write(logBuffer, writePtr);

	diag_printf("---\nLogdump complete.\n");
	diag_printf("Exception: %08x(%s) %08x\n", exception, infoStr, info);
	diag_printf("\n---\nRebooting\n");
	HAL_PLATFORM_RESET();

}

Øyvind Harboe's avatar
Øyvind Harboe committed
595
#ifdef CYGNUM_HAL_VECTOR_UNDEF_INSTRUCTION
596
597
598
599
600
static void setHandler(cyg_code_t exception)
{
	cyg_exception_handler_t *old_handler;
	cyg_addrword_t old_data;

601
602
	cyg_exception_set_handler(exception, print_exception_handler, 0,
			&old_handler, &old_data);
603
}
Øyvind Harboe's avatar
Øyvind Harboe committed
604
#endif
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630

static cyg_thread zylinjtag_uart_thread_object;
static cyg_handle_t zylinjtag_uart_thread_handle;
static char uart_stack[4096];

static char forwardBuffer[1024]; // NB! must be smaller than a TCP/IP packet!!!!!
static char backwardBuffer[1024];

void setNoDelay(int session, int flag)
{
#if 1
	// This decreases latency dramatically for e.g. GDB load which
	// does not have a sliding window protocol
	//
	// Can cause *lots* of TCP/IP packets to be sent and it would have
	// to be enabled/disabled on the fly to avoid the CPU being
	// overloaded...
	setsockopt(session, /* socket affected */
	IPPROTO_TCP, /* set option at TCP level */
	TCP_NODELAY, /* name of option */
	(char *) &flag, /* the cast is historical
	 cruft */
	sizeof(int)); /* length of option value */
#endif
}

631
632
633
#define TEST_TCPIP() 0

#if TEST_TCPIP
634
635
636
637
638
639
640
641
struct
{
	int req;
	int actual;
	int req2;
	int actual2;
} tcpipSent[512 * 1024];
int cur;
642
#endif
643

644
static void zylinjtag_uart(cyg_addrword_t data)
645
646
647
648
649
650
651
652
653
654
{
	int so_reuseaddr_option = 1;

	int fd;
	if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		LOG_ERROR("error creating socket: %s", strerror(errno));
		exit(-1);
	}

655
656
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void*) &so_reuseaddr_option,
			sizeof(int));
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691

	struct sockaddr_in sin;
	unsigned int address_size;
	address_size = sizeof(sin);
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;
	sin.sin_port = htons(5555);

	if (bind(fd, (struct sockaddr *) &sin, sizeof(sin)) == -1)
	{
		LOG_ERROR("couldn't bind to socket: %s", strerror(errno));
		exit(-1);
	}

	if (listen(fd, 1) == -1)
	{
		LOG_ERROR("couldn't listen on socket: %s", strerror(errno));
		exit(-1);
	}
	//	socket_nonblock(fd);


	for (;;)
	{
		int session = accept(fd, (struct sockaddr *) &sin, &address_size);
		if (session < 0)
		{
			continue;
		}

		setNoDelay(session, 1);
		int oldopts = fcntl(session, F_GETFL, 0);
		fcntl(session, F_SETFL, oldopts | O_NONBLOCK); //

Øyvind Harboe's avatar
Øyvind Harboe committed
692
		int serHandle = open(ZY1000_SER_DEV, O_RDWR | O_NONBLOCK);
693
694
695
696
697
698
		if (serHandle < 0)
		{
			close(session);
			continue;
		}

oharboe's avatar
oharboe committed
699
#ifdef CYGPKG_PROFILE_GPROF
700
		start_profile();
oharboe's avatar
oharboe committed
701
#endif
oharboe's avatar
oharboe committed
702
703
704
		size_t actual = 0;
		size_t actual2 = 0;
		size_t pos, pos2;
705
706
		pos = 0;
		pos2 = 0;
707
#if TEST_TCPIP
708
		cur = 0;
709
#endif
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
		for (;;)
		{
			fd_set write_fds;
			fd_set read_fds;
			FD_ZERO(&write_fds);
			FD_ZERO(&read_fds);
			int fd_max = -1;
			FD_SET(session, &read_fds);
			fd_max = session;
			FD_SET(serHandle, &read_fds);
			if (serHandle > fd_max)
			{
				fd_max = serHandle;
			}
			/* Wait... */

			cyg_thread_delay(5); // 50ms fixed delay to wait for data to be sent/received
			if ((actual == 0) && (actual2 == 0))
			{
				int retval = select(fd_max + 1, &read_fds, NULL, NULL, NULL);
				if (retval <= 0)
				{
					break;
				}
			}

			if (actual2 <= 0)
			{
				memset(backwardBuffer, 's', sizeof(backwardBuffer));
oharboe's avatar
oharboe committed
739
740
				int t;
				t = read(serHandle, backwardBuffer,
741
						sizeof(backwardBuffer));
oharboe's avatar
oharboe committed
742
743
				actual2 = t;
				if (t < 0)
744
745
746
747
748
749
750
751
752
753
				{
					if (errno != EAGAIN)
					{
						goto closeSession;
					}
					actual2 = 0;
				}
				pos2 = 0;
			}

oharboe's avatar
oharboe committed
754
			size_t y = 0;
755
756
757
758
759
760
761
762
763
764
			if (actual2 > 0)
			{
				int written = write(session, backwardBuffer + pos2, actual2);
				if (written <= 0)
					goto closeSession;
				actual2 -= written;
				pos2 += written;
				y = written;
			}

765
766
			if (FD_ISSET(session, &read_fds)
					&& (sizeof(forwardBuffer) > actual))
767
768
769
770
771
772
773
			{
				// NB! Here it is important that we empty the TCP/IP read buffer
				// to make transmission tick right
				memmove(forwardBuffer, forwardBuffer + pos, actual);
				pos = 0;
				int t;
				// this will block if there is no data at all
774
775
				t = read_socket(session, forwardBuffer + actual,
						sizeof(forwardBuffer) - actual);
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
				if (t <= 0)
				{
					goto closeSession;
				}
				actual += t;
			}

			int y2 = 0;
			if (actual > 0)
			{
				/* Do not put things into the serial buffer if it has something to send
				 * as that can cause a single byte to be sent at the time.
				 *
				 *
				 */
				int written = write(serHandle, forwardBuffer + pos, actual);
				if (written < 0)
				{
					if (errno != EAGAIN)
					{
						goto closeSession;
					}
					// The serial buffer is full
					written = 0;
800
801
				}
				else
802
803
804
805
806
807
				{
					actual -= written;
					pos += written;
				}
				y2 = written;
			}
808
#if TEST_TCPIP
809
810
811
812
813
814
815
816
			if (cur < 1024)
			{
				tcpipSent[cur].req = x;
				tcpipSent[cur].actual = y;
				tcpipSent[cur].req2 = x2;
				tcpipSent[cur].actual2 = y2;
				cur++;
			}
817
#endif
818
		}
819
		closeSession: close(session);
820
821
		close(serHandle);

822
#if TEST_TCPIP
823
824
825
		int i;
		for (i = 0; i < 1024; i++)
		{
826
827
			diag_printf("%d %d %d %d\n", tcpipSent[i].req, tcpipSent[i].actual,
					tcpipSent[i].req2, tcpipSent[i].actual2);
828
829

		}
830
#endif
831
832
833
834
835
836
837
	}
	close(fd);

}

void startUart(void)
{
838
839
840
	cyg_thread_create(1, zylinjtag_uart, (cyg_addrword_t) 0, "uart thread",
			(void *) uart_stack, sizeof(uart_stack),
			&zylinjtag_uart_thread_handle, &zylinjtag_uart_thread_object);
841
842
843
844
	cyg_thread_set_priority(zylinjtag_uart_thread_handle, 1); // low priority as it sits in a busy loop
	cyg_thread_resume(zylinjtag_uart_thread_handle);
}

845
846
static int zylinjtag_Jim_Command_uart(Jim_Interp *interp, int argc,
		Jim_Obj * const *argv)
847
{
848
	static int current_baud = 38400;
849
	if (argc == 1)
850
	{
851
		Jim_SetResult(interp, Jim_NewIntObj(interp, current_baud));
852
		return JIM_OK;
853
	}
854
	else if (argc != 2)
855
	{
856
		return JIM_ERR;
857
858
	}

859
860
861
862
863
	long new_baudrate;
	if (Jim_GetLong(interp, argv[1], &new_baudrate) != JIM_OK)
		return JIM_ERR;

	current_baud = new_baudrate;
864

865
866
	int baud;
	switch (current_baud)
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
	{
	case 9600:
		baud = CYGNUM_SERIAL_BAUD_9600;
		break;
	case 19200:
		baud = CYGNUM_SERIAL_BAUD_19200;
		break;
	case 38400:
		baud = CYGNUM_SERIAL_BAUD_38400;
		break;
	case 57600:
		baud = CYGNUM_SERIAL_BAUD_57600;
		break;
	case 115200:
		baud = CYGNUM_SERIAL_BAUD_115200;
		break;
	case 230400:
		baud = CYGNUM_SERIAL_BAUD_230400;
		break;
	default:
887
888
		Jim_SetResult(interp, Jim_NewStringObj(interp, "unsupported baudrate", -1));
		return JIM_ERR;
889
890
891
892
893
894
895
	}

	cyg_serial_info_t buf;
	cyg_uint32 len = 1;
	//get existing serial configuration
	len = sizeof(cyg_serial_info_t);
	int err;
oharboe's avatar
wip    
oharboe committed
896
897
	cyg_io_handle_t serial_handle;

Øyvind Harboe's avatar
Øyvind Harboe committed
898
	err = cyg_io_lookup(ZY1000_SER_DEV, &serial_handle);
oharboe's avatar
wip    
oharboe committed
899
900
	if (err != ENOERR)
	{
901
		Jim_SetResult(interp, Jim_NewStringObj(interp, "Could not open serial port", -1));
902
		return JIM_ERR;
oharboe's avatar
wip    
oharboe committed
903
904
	}

905
906
907
908
	err = cyg_io_get_config(serial_handle,
			CYG_IO_GET_CONFIG_SERIAL_OUTPUT_DRAIN, &buf, &len);
	err = cyg_io_get_config(serial_handle, CYG_IO_GET_CONFIG_SERIAL_INFO, &buf,
			&len);
909
910
	if (err != ENOERR)
	{
911
		Jim_SetResult(interp, Jim_NewStringObj(interp, "Failed to get serial port settings", -1));
912
		return JIM_ERR;
913
914
915
	}
	buf.baud = baud;

916
917
	err = cyg_io_set_config(serial_handle, CYG_IO_SET_CONFIG_SERIAL_INFO, &buf,
			&len);
918
919
	if (err != ENOERR)
	{
920
		Jim_SetResult(interp, Jim_NewStringObj(interp, "Failed to set serial port settings", -1));
921
		return JIM_ERR;
922
923
	}

924
	return JIM_OK;
925
926
927
928
}

bool logAllToSerial = false;

929
930
931

int boolParam(char *var);

932

oharboe's avatar
oharboe committed
933
static const char *zylin_config_dir="/config/settings";
934

935
static int add_default_dirs(void)
936
{
937
	add_script_search_dir(zylin_config_dir);
938
939
940
941
942
943
944
	add_script_search_dir("/rom/lib/openocd");
	add_script_search_dir("/rom");
	return ERROR_OK;
}

int main(int argc, char *argv[])
{
945
946
947
	/* ramblockdevice will be the same address every time. The deflate app uses a buffer 16mBytes out, so we
	 * need to allocate towards the end of the heap.  */

oharboe's avatar
oharboe committed
948
#ifdef CYGNUM_HAL_VECTOR_UNDEF_INSTRUCTION
949
950
951
	setHandler(CYGNUM_HAL_VECTOR_UNDEF_INSTRUCTION);
	setHandler(CYGNUM_HAL_VECTOR_ABORT_PREFETCH);
	setHandler(CYGNUM_HAL_VECTOR_ABORT_DATA);
oharboe's avatar
oharboe committed
952
#endif
953
954
955
956
957

	int err;

	atexit(keep_webserver);

958
959
	diag_init_putc(_zylinjtag_diag_write_char);
	// We want this in the log.
960
961
962
963
964
#ifdef CYGPKG_HAL_NIOS2
	diag_printf("Zylin ZY1000 PCB revc.\n");
#else
	diag_printf("Zylin ZY1000 PCB revb.\n");
#endif
965

966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
	err = mount("", "/ram", "ramfs");
	if (err < 0)
	{
		diag_printf("unable to mount ramfs\n");
	}
	chdir("/ram");

	char address[16];
	sprintf(address, "%p", &filedata[0]);
	err = mount(address, "/rom", "romfs");
	if (err < 0)
	{
		diag_printf("unable to mount /rom\n");
	}

	err = mount("", "/log", "logfs");
	if (err < 0)
	{
		diag_printf("unable to mount logfs\n");
	}

	err = mount("", "/tftp", "tftpfs");
	if (err < 0)
	{
		diag_printf("unable to mount logfs\n");
	}

	log = fopen("/log/log", "w");
	if (log == NULL)
	{
		diag_printf("Could not open log file /ram/log\n");
		exit(-1);
	}


1001
	copydir("/rom", "/ram/cgi");
1002

1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
#ifdef CYGPKG_HAL_NIOS2
	cyg_flashaddr_t err_address;
#define UNCACHED_EXT_FLASH_BASE (0x80000000 + EXT_FLASH_BASE)
	/* The revc flash is locked upon reset, unlock it */
#ifdef CYGHWR_IO_FLASH_BLOCK_LOCKING
	if ((err = flash_unlock((void *) UNCACHED_EXT_FLASH_BASE, EXT_FLASH_SPAN,
			(void **) &err_address)) != 0)
	{
		diag_printf("Error: could not unlock flash\n");
	}
#endif
#endif


1017
1018
1019
	err = mount("/dev/flash1", "/config", "jffs2");
	if (err < 0)
	{
oharboe's avatar
wip    
oharboe committed
1020
1021
		diag_printf("unable to mount jffs2, falling back to ram disk..\n");
		err = mount("", "/config", "ramfs");
1022
		if (err < 0)
1023
		{
oharboe's avatar
wip    
oharboe committed
1024
			diag_printf("unable to mount /config as ramdisk.\n");
1025
1026
			reboot();
		}
1027
1028
	}
	else
oharboe's avatar
wip    
oharboe committed
1029
1030
1031
1032
1033
1034
1035
	{
		/* are we using a ram disk instead of a flash disk? This is used
		 * for ZY1000 live demo...
		 *
		 * copy over flash disk to ram block device
		 */
		if (boolParam("ramdisk"))
1036
		{
oharboe's avatar
wip    
oharboe committed
1037
			diag_printf("Unmounting /config from flash and using ram instead\n");
1038
			err = umount("/config");
oharboe's avatar
wip    
oharboe committed
1039
1040
1041
1042
1043
			if (err < 0)
			{
				diag_printf("unable to unmount jffs\n");
				reboot();
			}
1044

oharboe's avatar
wip    
oharboe committed
1045
1046
1047
1048
1049
1050
			err = mount("/dev/flash1", "/config2", "jffs2");
			if (err < 0)
			{
				diag_printf("unable to mount jffs\n");
				reboot();
			}
1051

oharboe's avatar
oharboe committed
1052
			err = mount("", "/config", "ramfs");
oharboe's avatar
wip    
oharboe committed
1053
1054
1055
1056
1057
			if (err < 0)
			{
				diag_printf("unable to mount ram block device\n");
				reboot();
			}
1058

1059
			//		copydir("/config2", "/config");
oharboe's avatar
wip    
oharboe committed
1060
1061
1062
1063
1064
			copyfile("/config2/ip", "/config/ip");
			copydir("/config2/settings", "/config/settings");

			umount("/config2");
		}
1065
1066
	}

1067
	mkdir(zylin_config_dir, 0777);
zwelch's avatar
zwelch committed
1068
	char *dirname = alloc_printf("%s/target", zylin_config_dir);
1069
	mkdir(dirname, 0777);
1070
	free(dirname);
zwelch's avatar
zwelch committed
1071
	dirname = alloc_printf("%s/board", zylin_config_dir);
1072
	mkdir(dirname, 0777);
1073
	free(dirname);
zwelch's avatar
zwelch committed
1074
	dirname = alloc_printf("%s/event", zylin_config_dir);
1075
1076
	mkdir(dirname, 0777);
	free(dirname);
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090

	logAllToSerial = boolParam("logserial");

	// We need the network & web server in case there is something wrong with
	// the config files that invoke exit()
	zylinjtag_startNetwork();

	/* we're going to access the jim interpreter from here on... */
	openocd_sleep_postlude();
	startUart();

	add_default_dirs();

	/* initialize commandline interface */
1091
	struct command_context * cmd_ctx;
1092
1093
	struct command_context *setup_command_handler(Jim_Interp *interp);
	cmd_ctx = setup_command_handler(httpstate.jim_interp);
1094
1095
1096
	command_set_output_handler(cmd_ctx, configuration_output_handler, NULL);
	command_context_mode(cmd_ctx, COMMAND_CONFIG);

1097
1098
1099
	if (util_init(cmd_ctx) != ERROR_OK)
		return EXIT_FAILURE;

1100
1101
1102
	if (ioutil_init(cmd_ctx) != ERROR_OK)
		return EXIT_FAILURE;

1103
#ifdef CYGPKG_PROFILE_GPROF
1104
1105
	Jim_CreateCommand(httpstate.jim_interp, "zy1000_profile", zylinjtag_Jim_Command_profile,
			NULL, NULL);
1106
1107
#endif

1108
	Jim_CreateCommand(httpstate.jim_interp, "zy1000_uart", zylinjtag_Jim_Command_uart, NULL, NULL);
1109

1110

1111
	log_init();
1112
1113
1114
1115
1116
1117
1118
1119
1120

	set_log_output(cmd_ctx, log);

	LOG_DEBUG("log init complete");

	//	diag_printf("Executing config files\n");

	if (logAllToSerial)
	{
1121
		diag_printf(
zwelch's avatar
zwelch committed
1122
				 "%s/logserial = 1 => sending log output to serial port using \"debug_level 3\" as default.\n", zylin_config_dir);
1123
1124
1125
		command_run_line(cmd_ctx, "debug_level 3");
	}

1126
	command_run_linef(cmd_ctx, "script /rom/openocd.cfg");
1127

1128
1129
1130
1131
1132
	int ret;
	ret = server_init(cmd_ctx);
	if (ERROR_OK != ret)
		return EXIT_FAILURE;

1133
1134
1135
	/* we MUST always run the init command as it will launch telnet sessions */
	command_run_line(cmd_ctx, "init");

1136
1137
1138
1139
1140
1141
1142
	// FIX!!!  Yuk!
	// diag_printf() is really invoked from many more places than we trust it
	// not to cause instabilities(e.g. invoking fputc() from an interrupt is *BAD*).
	//
	// Disabling it here is safe and gives us enough logged debug output for now. Crossing
	// fingers that it doesn't cause any crashes.
	diag_printf("Init complete, GDB & telnet servers launched.\n");
1143
1144
	command_set_output_handler(cmd_ctx,
			zy1000_configuration_output_handler_log, NULL);
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
	if (!logAllToSerial)
	{
		serialLog = false;
	}

	/* handle network connections */
	server_loop(cmd_ctx);
	openocd_sleep_prelude();

	/* shut server down */
	server_quit();

	/* free commandline interface */
	command_done(cmd_ctx);
	umount("/config");

	exit(0);
1162
1163
	for (;;)
		;
1164
1165
}

1166
cyg_int32 cyg_httpd_exec_cgi_tcl(char *file_name);
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
cyg_int32 homeForm(CYG_HTTPD_STATE *p)
{
	cyg_httpd_exec_cgi_tcl("/ram/cgi/index.tcl");
	return 0;
}

CYG_HTTPD_HANDLER_TABLE_ENTRY(root_label, "/", homeForm);

CYG_HTTPD_MIME_TABLE_ENTRY(text_mime_label, "text", "text/plain");
CYG_HTTPD_MIME_TABLE_ENTRY(bin_mime_label, "bin", "application/octet-stream");

#include <pkgconf/system.h>
#include <pkgconf/hal.h>
#include <pkgconf/kernel.h>
#include <pkgconf/io_fileio.h>
#include <pkgconf/fs_rom.h>

#include <cyg/kernel/ktypes.h>         // base kernel types
#include <cyg/infra/cyg_trac.h>        // tracing macros
#include <cyg/infra/cyg_ass.h>         // assertion macros
#include <cyg/fileio/fileio.h>
#include <cyg/kernel/kapi.h>
#include <cyg/infra/diag.h>

//==========================================================================
// Eventually we want to eXecute In Place from the ROM in a protected
// environment, so we'll need executables to be aligned to a boundary
// suitable for MMU protection. A suitable boundary would be the 4k
// boundary in all the CPU architectures I am currently aware of.

// Forward definitions

// Filesystem operations
static int tftpfs_mount(cyg_fstab_entry *fste, cyg_mtab_entry *mte);
static int tftpfs_umount(cyg_mtab_entry *mte);
static int tftpfs_open(cyg_mtab_entry *mte, cyg_dir dir, const char *name,
		int mode, cyg_file *fte);
static int tftpfs_fo_read(struct CYG_FILE_TAG *fp, struct CYG_UIO_TAG *uio);
static int tftpfs_fo_write(struct CYG_FILE_TAG *fp, struct CYG_UIO_TAG *uio);

// File operations
static int tftpfs_fo_fsync(struct CYG_FILE_TAG *fp, int mode);
static int tftpfs_fo_close(struct CYG_FILE_TAG *fp);
static int tftpfs_fo_lseek(struct CYG_FILE_TAG *fp, off_t *apos, int whence);

//==========================================================================
// Filesystem table entries

// -------------------------------------------------------------------------
// Fstab entry.
// This defines the entry in the filesystem table.
// For simplicity we use _FILESYSTEM synchronization for all accesses since
// we should never block in any filesystem operations.
#if 1
1221
FSTAB_ENTRY(tftpfs_fste, "tftpfs", 0,
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
		CYG_SYNCMODE_NONE,
		tftpfs_mount,
		tftpfs_umount,
		tftpfs_open,
		(cyg_fsop_unlink *)cyg_fileio_erofs,
		(cyg_fsop_mkdir *)cyg_fileio_erofs,
		(cyg_fsop_rmdir *)cyg_fileio_erofs,
		(cyg_fsop_rename *)cyg_fileio_erofs,
		(cyg_fsop_link *)cyg_fileio_erofs,
		(cyg_fsop_opendir *)cyg_fileio_erofs,
		(cyg_fsop_chdir *)cyg_fileio_erofs,
		(cyg_fsop_stat *)cyg_fileio_erofs,
		(cyg_fsop_getinfo *)cyg_fileio_erofs,
		(cyg_fsop_setinfo *)cyg_fileio_erofs);
#endif

// -------------------------------------------------------------------------
// mtab entry.
// This defines a single ROMFS loaded into ROM at the configured address
//
1242
// MTAB_ENTRY(rom_mte,	// structure name
1243
1244
1245
1246
// 		"/rom",		// mount point
// 		"romfs",	// FIlesystem type
// 		"",		// hardware device
//  (CYG_ADDRWORD) CYGNUM_FS_ROM_BASE_ADDRESS	// Address in ROM
1247
//);
1248
1249
1250
1251
1252
1253
1254


// -------------------------------------------------------------------------
// File operations.
// This set of file operations are used for normal open files.

static cyg_fileops tftpfs_fileops =
1255
1256
1257
{ tftpfs_fo_read, tftpfs_fo_write, tftpfs_fo_lseek,
		(cyg_fileop_ioctl *) cyg_fileio_erofs, cyg_fileio_seltrue,
		tftpfs_fo_fsync, tftpfs_fo_close,
1258
1259
		(cyg_fileop_fstat *) cyg_fileio_erofs,
		(cyg_fileop_getinfo *) cyg_fileio_erofs,
1260
		(cyg_fileop_setinfo *) cyg_fileio_erofs, };
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283

// -------------------------------------------------------------------------
// tftpfs_mount()
// Process a mount request. This mainly finds root for the
// filesystem.

static int tftpfs_mount(cyg_fstab_entry *fste, cyg_mtab_entry *mte)
{
	return ENOERR;
}

static int tftpfs_umount(cyg_mtab_entry *mte)
{
	return ENOERR;
}

struct Tftp
{
	int write;
	int readFile;
	cyg_uint8 *mem;
	int actual;
	char *server;
1284
	int port;
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
	char *file;
};

static void freeTftp(struct Tftp *t)
{
	if (t == NULL)
		return;
	if (t->mem)
		free(t->mem);
	if (t->server)
		free(t->server);
	if (t->file)
		free(t->file);
	free(t);
}

static const int tftpMaxSize = 8192 * 1024;
static int tftpfs_open(cyg_mtab_entry *mte, cyg_dir dir, const char *name,
		int mode, cyg_file *file)
{
	struct Tftp *tftp;
	tftp = malloc(sizeof(struct Tftp));
	if (tftp == NULL)
		return EMFILE;
	memset(tftp, 0, sizeof(struct Tftp));

	file->f_flag |= mode & CYG_FILE_MODE_MASK;
	file->f_type = CYG_FILE_TYPE_FILE;
	file->f_ops = &tftpfs_fileops;
	file->f_offset = 0;
	file->f_data = 0;
	file->f_xops = 0;

	tftp->mem = malloc(tftpMaxSize);
	if (tftp->mem == NULL)
	{
		freeTftp(tftp);
		return EMFILE;
	}

	char *server = strchr(name, '/');
	if (server == NULL)
	{
		freeTftp(tftp);
		return EMFILE;
	}

	tftp->server = malloc(server - name + 1);
	if (tftp->server == NULL)
	{
		freeTftp(tftp);
		return EMFILE;
	}
	strncpy(tftp->server, name, server - name);
	tftp->server[server - name] = 0;

1341
1342
1343
1344
1345
1346
1347
1348
1349
	tftp->port = 0; /* default port 69 */
	char *port;
	port = strchr(tftp->server, ':');
	if (port != NULL)
	{
		tftp->port = atoi(port + 1);
		*port = 0;
	}

1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
	tftp->file = strdup(server + 1);
	if (tftp->file == NULL)
	{
		freeTftp(tftp);
		return EMFILE;
	}

	file->f_data = (CYG_ADDRWORD) tftp;

	return ENOERR;
}

static int fetchTftp(struct Tftp *tftp)
{
	if (!tftp->readFile)
	{
		int err;
1367
		tftp->actual = tftp_client_get(tftp->file, tftp->server, tftp->port, tftp->mem,
1368
				tftpMaxSize, TFTP_OCTET, &err);
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382

		if (tftp->actual < 0)
		{
			return EMFILE;
		}
		tftp->readFile = 1;
	}
	return ENOERR;
}

// -------------------------------------------------------------------------
// tftpfs_fo_write()
// Read data from file.

1383
static int tftpfs_fo_read(struct CYG_FILE_TAG *fp, struct CYG_UIO_TAG *uio)
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
{
	struct Tftp *tftp = (struct Tftp *) fp->f_data;

	if (fetchTftp(tftp) != ENOERR)
		return EMFILE;

	int i;
	off_t pos = fp->f_offset;
	int resid = 0;
	for (i = 0; i < uio->uio_iovcnt; i++)
	{
		cyg_iovec *iov = &uio->uio_iov[i];
		char *buf = (char *) iov->iov_base;
		off_t len = iov->iov_len;

		if (len + pos > tftp->actual)
		{
			len = tftp->actual - pos;
		}
		resid += iov->iov_len - len;

		memcpy(buf, tftp->mem + pos, len);
		pos += len;

	}
	uio->uio_resid = resid;
	fp->f_offset = pos;

	return ENOERR;
}

1415
static int tftpfs_fo_write(struct CYG_FILE_TAG *fp, struct CYG_UIO_TAG *uio)
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
{
	struct Tftp *tftp = (struct Tftp *) fp->f_data;

	int i;
	off_t pos = fp->f_offset;
	int resid = 0;
	for (i = 0; i < uio->uio_iovcnt; i++)
	{
		cyg_iovec *iov = &uio->uio_iov[i];
		char *buf = (char *) iov->iov_base;
		off_t len = iov->iov_len;

		if (len + pos > tftpMaxSize)
		{
			len = tftpMaxSize - pos;
		}
		resid += iov->iov_len - len;

		memcpy(tftp->mem + pos, buf, len);
		pos += len;

	}
	uio->uio_resid = resid;
	fp->f_offset = pos;

	tftp->write = 1;

	return ENOERR;
}

1446
static int tftpfs_fo_fsync(struct CYG_FILE_TAG *fp, int mode)
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
{
	int error = ENOERR;
	return error;
}

// -------------------------------------------------------------------------
// romfs_fo_close()
// Close a file. We just clear out the data pointer.

static int tftpfs_fo_close(struct CYG_FILE_TAG *fp)
{
	struct Tftp *tftp = (struct Tftp *) fp->f_data;
	int error = ENOERR;

	if (tftp->write)
	{
1463
1464
		tftp_client_put(tftp->file, tftp->server, 0, tftp->mem, fp->f_offset,
				TFTP_OCTET, &error);
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
	}

	freeTftp(tftp);