summaryrefslogtreecommitdiffstats
path: root/fs/tftp.c
blob: ada6ad08de486c1ede6bd6c5cb02b1cd335b25ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
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
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
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
/*
 * tftp.c
 *
 * Copyright (c) 2011 Sascha Hauer <s.hauer@pengutronix.de>, Pengutronix
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 *
 * 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.
 *
 */

#define pr_fmt(fmt) "tftp: " fmt

#include <common.h>
#include <command.h>
#include <net.h>
#include <driver.h>
#include <clock.h>
#include <fs.h>
#include <errno.h>
#include <libgen.h>
#include <fcntl.h>
#include <getopt.h>
#include <globalvar.h>
#include <init.h>
#include <linux/bitmap.h>
#include <linux/stat.h>
#include <linux/err.h>
#include <linux/kernel.h>
#include <kfifo.h>
#include <parseopt.h>
#include <linux/sizes.h>

#include "tftp-selftest.h"

#define TFTP_PORT	69	/* Well known TFTP port number */

/* Seconds to wait before remote server is allowed to resend a lost packet */
#define TIMEOUT		5

/* After this time without a response from the server we will resend a packet */
#define TFTP_RESEND_TIMEOUT	SECOND

/* After this time without progress we will bail out */
#define TFTP_TIMEOUT		((TIMEOUT * 3) * SECOND)

/*
 *	TFTP operations.
 */
#define TFTP_RRQ	1
#define TFTP_WRQ	2
#define TFTP_DATA	3
#define TFTP_ACK	4
#define TFTP_ERROR	5
#define TFTP_OACK	6

#define STATE_INVALID	0
#define STATE_RRQ	1
#define STATE_WRQ	2
#define STATE_RDATA	3
#define STATE_WDATA	4
/* OACK from server has been received and we can begin to sent either the ACK
   (for RRQ) or data (for WRQ) */
#define STATE_START	5
#define STATE_WAITACK	6
#define STATE_LAST	7
#define STATE_DONE	8

#define TFTP_BLOCK_SIZE		512	/* default TFTP block size */
#define TFTP_MTU_SIZE		1432	/* MTU based block size */
#define TFTP_MAX_WINDOW_SIZE	CONFIG_FS_TFTP_MAX_WINDOW_SIZE

/* allocate this number of blocks more than needed in the fifo */
#define TFTP_EXTRA_BLOCKS	2

/* size of cache which deals with udp reordering */
#define TFTP_WINDOW_CACHE_NUM	CONFIG_FS_TFTP_REORDER_CACHE_SIZE

/* marker for an emtpy 'tftp_cache' */
#define TFTP_CACHE_NO_ID	(-1)

#define TFTP_ERR_RESEND	1

#if defined(DEBUG) || IS_ENABLED(CONFIG_SELFTEST_TFTP)
#  define debug_assert(_cond)	BUG_ON(!(_cond))
#else
#  define debug_assert(_cond) do {			\
		if (!(_cond))				\
			__builtin_unreachable();	\
	} while (0)
#endif

static int g_tftp_window_size = DIV_ROUND_UP(TFTP_MAX_WINDOW_SIZE, 2);

struct tftp_block {
	uint16_t id;
	uint16_t len;

	struct list_head head;
	uint8_t data[];
};

struct tftp_cache {
	/* The id located at @pos or TFTP_CACHE_NO_ID when cache is empty.  It
	   is possible that the corresponding bit in @used is NOT set. */
	unsigned int		id;
	unsigned int		pos;

	/* bitmask */
	unsigned long		used[BITS_TO_LONGS(TFTP_WINDOW_CACHE_NUM)];

	/* size of the cache; is limited by TFTP_WINDOW_CACHE_NUM and the
	   actual window size */
	unsigned int		size;
	unsigned int		block_len;
	struct tftp_block	*blocks[TFTP_WINDOW_CACHE_NUM];
};

struct file_priv {
	struct net_connection *tftp_con;
	int push;
	uint16_t block;
	uint16_t last_block;
	uint16_t ack_block;
	int state;
	int err;
	char *filename;
	loff_t filesize;
	uint64_t resend_timeout;
	uint64_t progress_timeout;
	struct kfifo *fifo;
	void *buf;
	int blocksize;
	unsigned int windowsize;
	bool is_getattr;
	struct tftp_cache cache;
};

struct tftp_priv {
	IPaddr_t server;
};

static inline bool is_block_before(uint16_t a, uint16_t b)
{
	return (int16_t)(b - a) > 0;
}

static inline uint16_t get_block_delta(uint16_t a, uint16_t b)
{
	debug_assert(!is_block_before(b, a));

	return b - a;
}

static bool in_window(uint16_t block, uint16_t start, uint16_t end)
{
	/* handle the three cases:
	   - [ ......... | start | .. | BLOCK | .. | end | ......... ]
	   - [ ..| BLOCK | .. | end | ................. | start | .. ]
	   - [ ..| end | ................. | start | .. | BLOCK | .. ]
	*/
	return ((start <= block && block <= end) ||
		(block <= end   && end   <= start) ||
		(end   <= start && start <= block));
}

static inline size_t tftp_window_cache_size(struct tftp_cache const *cache)
{
	/* allows to optimize away the cache code when TFTP_WINDOW_CACHE_SIZE
	   is 0 */
	return TFTP_WINDOW_CACHE_NUM == 0 ? 0 : cache->size;
}

static void tftp_window_cache_init(struct tftp_cache *cache,
				   uint16_t block_len, uint16_t window_size)
{
	debug_assert(window_size > 0);

	*cache = (struct tftp_cache) {
		.id		= TFTP_CACHE_NO_ID,
		.block_len	= block_len,
		.size		= min_t(uint16_t, window_size - 1,
					ARRAY_SIZE(cache->blocks)),
	};
}

static void tftp_window_cache_free(struct tftp_cache *cache)
{
	size_t	cache_size = tftp_window_cache_size(cache);
	size_t	i;

	for (i = 0; i < cache_size; ++i) {
		free(cache->blocks[i]);
		cache->blocks[i] = NULL;
	}
}

static void tftp_window_cache_reset(struct tftp_cache *cache)
{
	cache->id = TFTP_CACHE_NO_ID;
	memset(cache->used, 0, sizeof cache->used);
}

static int tftp_window_cache_get_pos(struct tftp_cache const *cache, uint16_t id)
{
	size_t		cache_size = tftp_window_cache_size(cache);
	unsigned int	pos;

	if (cache_size == 0)
		return -1;

	if (cache->id == TFTP_CACHE_NO_ID)
		return -1;

	if (!in_window(id, cache->id, cache->id + cache_size - 1))
		return -1;

	pos  = cache->pos + get_block_delta(cache->id, id);
	pos %= cache_size;

	return pos;
}

/* returns whether the first cached element has the given @id */
static bool tftp_window_cache_starts_with(struct tftp_cache const *cache,
					  uint16_t id)
{
	return (TFTP_WINDOW_CACHE_NUM > 0 &&
		cache->id != TFTP_CACHE_NO_ID &&
		cache->id == id &&
		test_bit(cache->pos, cache->used));
}

static bool tftp_window_cache_is_empty(struct tftp_cache const *cache)
{
	/* use this indirection to avoid warnings about a '0 < 0' comparison
	   in the loop condition when TFTP_WINDOW_CACHE_NUM is zero */
	size_t	cache_size = ARRAY_SIZE(cache->used);
	size_t	i;

	for (i = 0; i < cache_size; ++i) {
		if (cache->used[i] != 0)
			return false;
	}

	return true;
}

static int tftp_window_cache_insert(struct tftp_cache *cache, uint16_t id,
				    void const *data, size_t len)
{
	size_t const		cache_size = tftp_window_cache_size(cache);
	int			pos;
	struct tftp_block	*block;

	if (cache_size == 0)
		return -ENOSPC;

	if (cache->id == TFTP_CACHE_NO_ID) {
		/* initialize cache when it does not contain elements yet */
		cache->id = id;
		cache->pos = 0;

		/* sanity check; cache is expected to be empty */
		debug_assert(tftp_window_cache_is_empty(cache));
	}

	pos = tftp_window_cache_get_pos(cache, id);
	if (pos < 0)
		return -ENOSPC;

	debug_assert(pos < cache_size);

	if (test_bit(pos, cache->used))
		/* block already cached */
		return 0;

	block = cache->blocks[pos];
	if (!block) {
		/* allocate space for the block; after being released, this
		   memory can be reused for other blocks during the same tftp
		   transfer */
		block = malloc(sizeof *block + cache->block_len);
		if (!block)
			return -ENOMEM;

		cache->blocks[pos] = block;
	}

	__set_bit(pos, cache->used);
	memcpy(block->data, data, len);
	block->id = id;
	block->len = len;

	return 0;
}

/* Marks the element at 'pos' as unused and updates internal cache information.
   Returns true iff element at pos was valid. */
static bool tftp_window_cache_remove(struct tftp_cache *cache, unsigned int pos)
{
	size_t const	cache_size = tftp_window_cache_size(cache);
	bool		res;

	if (cache_size == 0)
		return 0;

	res = __test_and_clear_bit(pos, cache->used);

	if (tftp_window_cache_is_empty(cache)) {
		/* cache has been cleared; reset pointers */
		cache->id = TFTP_CACHE_NO_ID;
	} else if (pos != cache->pos) {
		/* noop; elements has been removed from the middle of cache */
	} else {
		/* first element of cache has been removed; proceed to the
		   next one */
		cache->id  += 1;
		cache->pos += 1;
		cache->pos %= cache_size;
	}

	return res;
}

/* Releases the first element from the cache and returns its content.
 *
 * Function can return NULL when the element is not cached
 */
static struct tftp_block *tftp_window_cache_pop(struct tftp_cache *cache)
{
	unsigned int	pos = cache->pos;

	debug_assert(cache->id != TFTP_CACHE_NO_ID);

	if (!tftp_window_cache_remove(cache, pos))
		return NULL;

	return cache->blocks[pos];
}

static bool tftp_window_cache_remove_id(struct tftp_cache *cache, uint16_t id)
{
	int		pos = tftp_window_cache_get_pos(cache, id);

	if (pos < 0)
		return false;

	return tftp_window_cache_remove(cache, pos);
}

static int tftp_truncate(struct device_d *dev, FILE *f, loff_t size)
{
	return 0;
}

static char const * const tftp_states[] = {
	[STATE_INVALID] = "INVALID",
	[STATE_RRQ] = "RRQ",
	[STATE_WRQ] = "WRQ",
	[STATE_RDATA] = "RDATA",
	[STATE_WDATA] = "WDATA",
	[STATE_WAITACK] = "WAITACK",
	[STATE_LAST] = "LAST",
	[STATE_DONE] = "DONE",
	[STATE_START] = "START",
};

static int tftp_send(struct file_priv *priv)
{
	unsigned char *xp;
	int len = 0;
	uint16_t *s;
	unsigned char *pkt = net_udp_get_payload(priv->tftp_con);
	unsigned int window_size;
	int ret;

	pr_vdebug("%s: state %s\n", __func__, tftp_states[priv->state]);

	switch (priv->state) {
	case STATE_RRQ:
	case STATE_WRQ:
		if (priv->push || priv->is_getattr)
			/* atm, windowsize is supported only for RRQ and there
			   is no need to request a full window when we are
			   just looking up file attributes */
			window_size = 1;
		else
			window_size = min_t(unsigned int, g_tftp_window_size,
					    TFTP_MAX_WINDOW_SIZE);

		xp = pkt;
		s = (uint16_t *)pkt;
		if (priv->state == STATE_RRQ)
			*s++ = htons(TFTP_RRQ);
		else
			*s++ = htons(TFTP_WRQ);
		pkt = (unsigned char *)s;
		pkt += sprintf((unsigned char *)pkt,
				"%s%c"
				"octet%c"
				"timeout%c"
				"%d%c"
				"blksize%c"
				"%u",
				priv->filename + 1, '\0',
				'\0',	/* "octet" */
				'\0',	/* "timeout" */
				TIMEOUT, '\0',
				'\0',	/* "blksize" */
				/* use only a minimal blksize for getattr
				   operations, */
				priv->is_getattr ? TFTP_BLOCK_SIZE : TFTP_MTU_SIZE);
		pkt++;

		if (!priv->push)
			/* we do not know the filesize in WRQ requests and
			   'priv->filesize' will always be zero */
			pkt += sprintf((unsigned char *)pkt,
				       "tsize%c%lld%c",
				       '\0', priv->filesize,
				       '\0');

		if (window_size > 1)
			pkt += sprintf((unsigned char *)pkt,
				       "windowsize%c%u%c",
				       '\0', window_size,
				       '\0');

		len = pkt - xp;
		break;

	case STATE_RDATA:
		xp = pkt;
		s = (uint16_t *)pkt;
		*s++ = htons(TFTP_ACK);
		*s++ = htons(priv->last_block);
		priv->ack_block  = priv->last_block;
		priv->ack_block += priv->windowsize;
		pkt = (unsigned char *)s;
		len = pkt - xp;
		tftp_window_cache_reset(&priv->cache);
		break;
	}

	ret = net_udp_send(priv->tftp_con, len);

	return ret;
}

static int tftp_send_write(struct file_priv *priv, void *buf, int len)
{
	uint16_t *s;
	unsigned char *pkt = net_udp_get_payload(priv->tftp_con);
	int ret;

	s = (uint16_t *)pkt;
	*s++ = htons(TFTP_DATA);
	*s++ = htons(priv->block);
	memcpy((void *)s, buf, len);
	if (len < priv->blocksize)
		priv->state = STATE_LAST;
	len += 4;

	ret = net_udp_send(priv->tftp_con, len);
	priv->last_block = priv->block;
	priv->state = STATE_WAITACK;

	return ret;
}

static int tftp_poll(struct file_priv *priv)
{
	if (ctrlc()) {
		priv->state = STATE_DONE;
		priv->err = -EINTR;
		return -EINTR;
	}

	if (is_timeout(priv->resend_timeout, TFTP_RESEND_TIMEOUT)) {
		printf("T ");
		priv->resend_timeout = get_time_ns();
		return TFTP_ERR_RESEND;
	}

	if (is_timeout(priv->progress_timeout, TFTP_TIMEOUT)) {
		priv->state = STATE_DONE;
		priv->err = -ETIMEDOUT;
		return -ETIMEDOUT;
	}

	net_poll();

	return 0;
}

static int tftp_parse_oack(struct file_priv *priv, unsigned char *pkt, int len)
{
	unsigned char *opt, *val, *s;

	pkt[len - 1] = 0;

	pr_debug("got OACK\n");
#ifdef DEBUG
	memory_display(pkt, 0, len, 1, 0);
#endif

	s = pkt;

	while (s < pkt + len) {
		opt = s;
		val = s + strlen(s) + 1;
		if (val > s + len)
			break;
		if (!strcmp(opt, "tsize"))
			priv->filesize = simple_strtoull(val, NULL, 10);
		if (!strcmp(opt, "blksize"))
			priv->blocksize = simple_strtoul(val, NULL, 10);
		if (!strcmp(opt, "windowsize"))
			priv->windowsize = simple_strtoul(val, NULL, 10);
		pr_debug("OACK opt: %s val: %s\n", opt, val);
		s = val + strlen(val) + 1;
	}

	if (priv->blocksize > TFTP_MTU_SIZE ||
	    priv->windowsize > TFTP_MAX_WINDOW_SIZE ||
	    priv->windowsize == 0) {
		pr_warn("tftp: invalid oack response\n");
		return -EINVAL;
	}

	return 0;
}

static void tftp_timer_reset(struct file_priv *priv)
{
	priv->progress_timeout = priv->resend_timeout = get_time_ns();
}

static int tftp_allocate_transfer(struct file_priv *priv)
{
	debug_assert(!priv->fifo);
	debug_assert(!priv->buf);

	/* multiplication is safe; both operands were checked in tftp_parse_oack()
	   and are small integers */
	priv->fifo = kfifo_alloc(priv->blocksize *
				 (priv->windowsize + TFTP_EXTRA_BLOCKS));
	if (!priv->fifo)
		goto err;

	if (priv->push) {
		priv->buf = xmalloc(priv->blocksize);
		if (!priv->buf) {
			kfifo_free(priv->fifo);
			priv->fifo = NULL;
			goto err;
		}
	} else {
		tftp_window_cache_init(&priv->cache,
				       priv->blocksize, priv->windowsize);
	}

	return 0;

err:
	priv->err = -ENOMEM;
	priv->state = STATE_DONE;

	return priv->err;
}

static void tftp_put_data(struct file_priv *priv, uint16_t block,
			  void const *pkt, size_t len)
{
	unsigned int sz;

	if (len > priv->blocksize) {
		pr_warn("tftp: oversized packet (%zu > %d) received\n",
			len, priv->blocksize);
		return;
	}

	priv->last_block = block;

	sz = kfifo_put(priv->fifo, pkt, len);

	if (sz != len) {
		pr_err("tftp: not enough room in kfifo (only %u out of %zu written)\n",
		       sz, len);
		priv->err = -ENOMEM;
		priv->state = STATE_DONE;
	} else if (len < priv->blocksize) {
		tftp_send(priv);
		priv->err = 0;
		priv->state = STATE_DONE;
	}
}

static void tftp_apply_window_cache(struct file_priv *priv)
{
	struct tftp_cache *cache = &priv->cache;

	while (tftp_window_cache_starts_with(cache, priv->last_block + 1)) {
		struct tftp_block *block;

		/* can be changed by tftp_put_data() below and must be
		   checked in each loop */
		if (priv->state != STATE_RDATA)
			return;

		block = tftp_window_cache_pop(cache);

		debug_assert(block);
		debug_assert(block->id == (uint16_t)(priv->last_block + 1));

		tftp_put_data(priv, block->id, block->data, block->len);
	}
}

static void tftp_handle_data(struct file_priv *priv, uint16_t block,
			     void const *data, size_t len)
{
	uint16_t exp_block;
	int rc;

	exp_block = priv->last_block + 1;

	if (exp_block == block) {
		/* datagram over network is the expected one; put it in the
		   fifo directly and try to apply cached items then */
		tftp_timer_reset(priv);
		tftp_put_data(priv, block, data, len);
		tftp_window_cache_remove_id(&priv->cache, block);
		tftp_apply_window_cache(priv);
	} else if (!in_window(block, exp_block, priv->ack_block)) {
		/* completely unexpected and unrelated to actual window;
		   ignore the packet. */
		printf("B");
	} else {
		/* The 'rc < 0' below happens e.g. when datagrams in the first
		   part of the transfer window are dropped.

		   TODO: this will usually result in a timeout
		   (TFTP_RESEND_TIMEOUT).  It should be possible to bypass
		   this timeout by acknowledging the last packet (e.g. by
		   doing 'priv->ack_block = priv->last_block' here). */
		rc = tftp_window_cache_insert(&priv->cache, block, data, len);
		if (rc < 0)
			printf("M");
	}
}

static void tftp_recv(struct file_priv *priv,
			uint8_t *pkt, unsigned len, uint16_t uh_sport)
{
	uint16_t opcode;
	uint16_t block;
	int rc;

	/* according to RFC1350 minimal tftp packet length is 4 bytes */
	if (len < 4)
		return;

	opcode = ntohs(*(uint16_t *)pkt);

	/* skip tftp opcode 2-byte field */
	len -= 2;
	pkt += 2;

	pr_vdebug("%s: opcode 0x%04x\n", __func__, opcode);

	switch (opcode) {
	case TFTP_RRQ:
	case TFTP_WRQ:
	default:
		break;
	case TFTP_ACK:
		if (!priv->push)
			break;

		block = ntohs(*(uint16_t *)pkt);
		if (block != priv->last_block) {
			pr_vdebug("ack %d != %d\n", block, priv->last_block);
			break;
		}

		switch (priv->state) {
		case STATE_WRQ:
			priv->tftp_con->udp->uh_dport = uh_sport;
			priv->state = STATE_START;
			break;

		case STATE_WAITACK:
			priv->state = STATE_WDATA;
			break;

		case STATE_LAST:
			priv->state = STATE_DONE;
			break;

		default:
			pr_warn("ACK packet in %s state\n",
				tftp_states[priv->state]);
			goto ack_out;
		}

		priv->block = block + 1;
		tftp_timer_reset(priv);

	ack_out:
		break;

	case TFTP_OACK:
		if (priv->state != STATE_RRQ && priv->state != STATE_WRQ) {
			pr_warn("OACK packet in %s state\n",
				tftp_states[priv->state]);
			break;
		}

		priv->tftp_con->udp->uh_dport = uh_sport;

		if (tftp_parse_oack(priv, pkt, len) < 0) {
			priv->err = -EINVAL;
			priv->state = STATE_DONE;
			break;
		}

		priv->state = STATE_START;
		break;

	case TFTP_DATA:
		len -= 2;
		block = ntohs(*(uint16_t *)pkt);

		if (priv->state == STATE_RRQ) {
			/* first block received; entered only with non rfc
			   2347 (TFTP Option extension) compliant servers */
			priv->tftp_con->udp->uh_dport = uh_sport;
			priv->state = STATE_RDATA;
			priv->last_block = 0;
			priv->ack_block = priv->windowsize;

			rc = tftp_allocate_transfer(priv);
			if (rc < 0)
				break;
		}

		if (priv->state != STATE_RDATA) {
			pr_warn("DATA packet in %s state\n",
				tftp_states[priv->state]);
			break;
		}

		tftp_handle_data(priv, block, pkt + 2, len);
		break;

	case TFTP_ERROR:
		pr_debug("error: '%s' (%d)\n", pkt + 2, ntohs(*(uint16_t *)pkt));
		switch (ntohs(*(uint16_t *)pkt)) {
		case 1:
			priv->err = -ENOENT;
			break;
		case 2:
			priv->err = -EACCES;
			break;
		default:
			priv->err = -EINVAL;
			break;
		}
		priv->state = STATE_DONE;
		break;
	}
}

static void tftp_handler(void *ctx, char *packet, unsigned len)
{
	struct file_priv *priv = ctx;
	char *pkt = net_eth_to_udp_payload(packet);
	struct udphdr *udp = net_eth_to_udphdr(packet);

	(void)len;
	tftp_recv(priv, pkt, net_eth_to_udplen(packet), udp->uh_sport);
}

static int tftp_start_transfer(struct file_priv *priv)
{
	int rc;

	rc = tftp_allocate_transfer(priv);
	if (rc < 0)
		/* function sets 'priv->state = STATE_DONE' and 'priv->err' in
		   error case */
		return rc;

	if (priv->push) {
		/* send first block */
		priv->state = STATE_WDATA;
		priv->block = 1;
	} else {
		/* send ACK */
		priv->state = STATE_RDATA;
		priv->last_block = 0;
		tftp_send(priv);
	}

	return 0;
}

static struct file_priv *tftp_do_open(struct device_d *dev,
		int accmode, struct dentry *dentry, bool is_getattr)
{
	struct fs_device_d *fsdev = dev_to_fs_device(dev);
	struct file_priv *priv;
	struct tftp_priv *tpriv = dev->priv;
	int ret;
	unsigned short port = TFTP_PORT;

	priv = xzalloc(sizeof(*priv));

	switch (accmode & O_ACCMODE) {
	case O_RDONLY:
		priv->push = 0;
		priv->state = STATE_RRQ;
		break;
	case O_WRONLY:
		priv->push = 1;
		priv->state = STATE_WRQ;
		break;
	case O_RDWR:
		ret = -ENOSYS;
		goto out;
	}

	priv->block = 1;
	priv->err = -EINVAL;
	priv->filename = dpath(dentry, fsdev->vfsmount.mnt_root);
	priv->blocksize = TFTP_BLOCK_SIZE;
	priv->windowsize = 1;
	priv->is_getattr = is_getattr;

	parseopt_hu(fsdev->options, "port", &port);

	priv->tftp_con = net_udp_new(tpriv->server, port, tftp_handler, priv);
	if (IS_ERR(priv->tftp_con)) {
		ret = PTR_ERR(priv->tftp_con);
		goto out;
	}

	ret = tftp_send(priv);
	if (ret)
		goto out1;

	tftp_timer_reset(priv);

	/* - 'ret < 0'  ... error
	   - 'ret == 0' ... further tftp_poll() required
	   - 'ret == 1' ... startup finished */
	do {
		switch (priv->state) {
		case STATE_DONE:
			/* branch is entered in two situations:
			   - non rfc 2347 compliant servers finished the
			     transfer by sending a small file
			   - some error occurred */
			if (priv->err < 0)
				ret = priv->err;
			else
				ret = 1;
			break;

		case STATE_START:
			ret = tftp_start_transfer(priv);
			if (!ret)
				ret = 1;
			break;

		case STATE_RDATA:
			/* first data block of non rfc 2347 servers */
			ret = 1;
			break;

		case STATE_RRQ:
		case STATE_WRQ:
			ret = tftp_poll(priv);
			if (ret == TFTP_ERR_RESEND) {
				tftp_send(priv);
				ret = 0;
			}
			break;

		default:
			debug_assert(false);
			break;
		}
	} while (ret == 0);

	if (ret < 0)
		goto out1;

	return priv;
out1:
	net_unregister(priv->tftp_con);
out:
	if (priv->fifo)
		kfifo_free(priv->fifo);

	free(priv->filename);
	free(priv->buf);
	free(priv);

	return ERR_PTR(ret);
}

static int tftp_open(struct device_d *dev, FILE *file, const char *filename)
{
	struct file_priv *priv;

	priv = tftp_do_open(dev, file->flags, file->dentry, false);
	if (IS_ERR(priv))
		return PTR_ERR(priv);

	file->priv = priv;

	return 0;
}

static int tftp_do_close(struct file_priv *priv)
{
	int ret;

	if (priv->push && priv->state != STATE_DONE) {
		int len;

		len = kfifo_get(priv->fifo, priv->buf, priv->blocksize);
		tftp_send_write(priv, priv->buf, len);
		priv->state = STATE_LAST;

		tftp_timer_reset(priv);

		while (priv->state != STATE_DONE) {
			ret = tftp_poll(priv);
			if (ret == TFTP_ERR_RESEND)
				tftp_send_write(priv, priv->buf, len);
			if (ret < 0)
				break;
		}
	}

	if (!priv->push && priv->state != STATE_DONE) {
		uint16_t *pkt = net_udp_get_payload(priv->tftp_con);
		*pkt++ = htons(TFTP_ERROR);
		*pkt++ = 0;
		*pkt++ = 0;
		net_udp_send(priv->tftp_con, 6);
	}

	net_unregister(priv->tftp_con);
	tftp_window_cache_free(&priv->cache);
	kfifo_free(priv->fifo);
	free(priv->filename);
	free(priv->buf);
	free(priv);

	return 0;
}

static int tftp_close(struct device_d *dev, FILE *f)
{
	struct file_priv *priv = f->priv;

	return tftp_do_close(priv);
}

static int tftp_write(struct device_d *_dev, FILE *f, const void *inbuf,
		size_t insize)
{
	struct file_priv *priv = f->priv;
	size_t size, now;
	int ret;

	pr_vdebug("%s: %zu\n", __func__, insize);

	size = insize;

	while (size) {
		now = kfifo_put(priv->fifo, inbuf, size);

		while (kfifo_len(priv->fifo) >= priv->blocksize) {
			kfifo_get(priv->fifo, priv->buf, priv->blocksize);

			tftp_send_write(priv, priv->buf, priv->blocksize);
			tftp_timer_reset(priv);

			while (priv->state == STATE_WAITACK) {
				ret = tftp_poll(priv);
				if (ret == TFTP_ERR_RESEND)
					tftp_send_write(priv, priv->buf,
							priv->blocksize);
				if (ret < 0)
					return ret;
			}
		}
		size -= now;
		inbuf += now;
	}

	return insize;
}

static int tftp_read(struct device_d *dev, FILE *f, void *buf, size_t insize)
{
	struct file_priv *priv = f->priv;
	size_t outsize = 0, now;
	int ret;

	pr_vdebug("%s %zu\n", __func__, insize);

	while (insize) {
		now = kfifo_get(priv->fifo, buf, insize);
		outsize += now;
		buf += now;
		insize -= now;
		if (priv->state == STATE_DONE)
			return outsize;

		/* send the ACK only when fifo has been nearly depleted; else,
		   when tftp_read() is called with small 'insize' values, it
		   is possible that there is read more data from the network
		   than consumed by kfifo_get() and the fifo overflows */
		if (priv->last_block == priv->ack_block &&
		    kfifo_len(priv->fifo) <= TFTP_EXTRA_BLOCKS * priv->blocksize)
			tftp_send(priv);

		ret = tftp_poll(priv);
		if (ret == TFTP_ERR_RESEND)
			tftp_send(priv);
		if (ret < 0)
			return ret;
	}

	return outsize;
}

static int tftp_lseek(struct device_d *dev, FILE *f, loff_t pos)
{
	/* We cannot seek backwards without reloading or caching the file */
	loff_t f_pos = f->pos;

	if (pos >= f_pos) {
		int ret = 0;
		char *buf = xmalloc(1024);

		while (pos > f_pos) {
			size_t len = min_t(size_t, 1024, pos - f_pos);

			ret = tftp_read(dev, f, buf, len);

			if (!ret)
				/* EOF, so the desired pos is invalid. */
				ret = -EINVAL;
			if (ret < 0)
				goto out_free;

			f_pos += ret;
		}

out_free:
		free(buf);
		if (ret < 0) {
			/*
			 * Update f->pos even if the overall request
			 * failed since we can't move backwards
			 */
			f->pos = f_pos;
			return ret;
		}

		return 0;
	}

	return -ENOSYS;
}

static const struct inode_operations tftp_file_inode_operations;
static const struct inode_operations tftp_dir_inode_operations;
static const struct file_operations tftp_file_operations;

static struct inode *tftp_get_inode(struct super_block *sb, const struct inode *dir,
                                     umode_t mode)
{
	struct inode *inode = new_inode(sb);

	if (!inode)
		return NULL;

	inode->i_ino = get_next_ino();
	inode->i_mode = mode;

	switch (mode & S_IFMT) {
	default:
		return NULL;
	case S_IFREG:
		inode->i_op = &tftp_file_inode_operations;
		inode->i_fop = &tftp_file_operations;
		break;
	case S_IFDIR:
		inode->i_op = &tftp_dir_inode_operations;
		inode->i_fop = &simple_dir_operations;
		inc_nlink(inode);
		break;
	}

	return inode;
}

static int tftp_create(struct inode *dir, struct dentry *dentry, umode_t mode)
{
	struct inode *inode;

	inode = tftp_get_inode(dir->i_sb, dir, mode);
	if (!inode)
		return -EPERM;

	inode->i_size = 0;

	d_instantiate(dentry, inode);

	return 0;
}

static struct dentry *tftp_lookup(struct inode *dir, struct dentry *dentry,
			    unsigned int flags)
{
	struct super_block *sb = dir->i_sb;
	struct fs_device_d *fsdev = container_of(sb, struct fs_device_d, sb);
	struct inode *inode;
	struct file_priv *priv;
	loff_t filesize;

	priv = tftp_do_open(&fsdev->dev, O_RDONLY, dentry, true);
	if (IS_ERR(priv))
		return NULL;

	filesize = priv->filesize;

	tftp_do_close(priv);

	inode = tftp_get_inode(dir->i_sb, dir, S_IFREG | S_IRWXUGO);
	if (!inode)
		return ERR_PTR(-ENOMEM);

	if (filesize)
		inode->i_size = filesize;
	else
		inode->i_size = FILE_SIZE_STREAM;

	d_add(dentry, inode);

	return NULL;
}

static const struct inode_operations tftp_dir_inode_operations =
{
	.lookup = tftp_lookup,
	.create = tftp_create,
};

static const struct super_operations tftp_ops;

static int tftp_probe(struct device_d *dev)
{
	struct fs_device_d *fsdev = dev_to_fs_device(dev);
	struct tftp_priv *priv = xzalloc(sizeof(struct tftp_priv));
	struct super_block *sb = &fsdev->sb;
	struct inode *inode;
	int ret;

	dev->priv = priv;

	ret = resolv(fsdev->backingstore, &priv->server);
	if (ret) {
		pr_err("Cannot resolve \"%s\": %s\n", fsdev->backingstore, strerror(-ret));
		goto err;
	}

	sb->s_op = &tftp_ops;
	sb->s_d_op = &no_revalidate_d_ops;

	inode = tftp_get_inode(sb, NULL, S_IFDIR);
	sb->s_root = d_make_root(inode);

	return 0;
err:
	free(priv);

	return ret;
}

static void tftp_remove(struct device_d *dev)
{
	struct tftp_priv *priv = dev->priv;

	free(priv);
}

static struct fs_driver_d tftp_driver = {
	.open      = tftp_open,
	.close     = tftp_close,
	.read      = tftp_read,
	.lseek     = tftp_lseek,
	.write     = tftp_write,
	.truncate  = tftp_truncate,
	.flags     = 0,
	.drv = {
		.probe  = tftp_probe,
		.remove = tftp_remove,
		.name = "tftp",
	}
};

static int tftp_init(void)
{
	globalvar_add_simple_int("tftp.windowsize", &g_tftp_window_size, "%u");

	return register_fs_driver(&tftp_driver);
}
coredevice_initcall(tftp_init);


BSELFTEST_GLOBALS();

static int __maybe_unused tftp_window_cache_selftest(void)
{
	struct tftp_cache	*cache = malloc(sizeof *cache);

	if (!cache)
		return -ENOMEM;

	(void)skipped_tests;

	expect_it( is_block_before(0, 1));
	expect_it(!is_block_before(1, 0));
	expect_it( is_block_before(65535, 0));
	expect_it(!is_block_before(0, 65535));

	expect_eq(get_block_delta(0, 1),     1);
	expect_eq(get_block_delta(65535, 0), 1);
	expect_eq(get_block_delta(65535, 1), 2);

	expect_it(!in_window(0, 1, 3));
	expect_it( in_window(1, 1, 3));
	expect_it( in_window(2, 1, 3));
	expect_it( in_window(3, 1, 3));
	expect_it(!in_window(4, 1, 3));

	expect_it(!in_window(65534, 65535, 1));
	expect_it( in_window(65535, 65535, 1));
	expect_it( in_window(    0, 65535, 1));
	expect_it( in_window(    1, 65535, 1));
	expect_it(!in_window(    2, 65535, 1));


	tftp_window_cache_init(cache, 512, 5);

	if (tftp_window_cache_size(cache) < 4)
		goto out;

	expect_eq(tftp_window_cache_size(cache), 4);

	/* sequence 1 */
	expect_ok (tftp_window_cache_insert(cache, 20, "20", 2));
	expect_ok (tftp_window_cache_insert(cache, 22, "22", 2));
	expect_ok (tftp_window_cache_insert(cache, 21, "21", 2));
	expect_ok (tftp_window_cache_insert(cache, 23, "23", 2));
	expect_err(tftp_window_cache_insert(cache, 24, "24", 2));
	expect_err(tftp_window_cache_insert(cache, 19, "19", 2));
	expect_ok (tftp_window_cache_insert(cache, 22, "22", 2));
	expect_ok (tftp_window_cache_insert(cache, 20, "20", 2));

	expect_eq(tftp_window_cache_pop(cache)->id, 20);
	expect_eq(tftp_window_cache_pop(cache)->id, 21);
	expect_eq(tftp_window_cache_pop(cache)->id, 22);
	expect_eq(tftp_window_cache_pop(cache)->id, 23);
	expect_eq(cache->id, TFTP_CACHE_NO_ID);

	/* sequence 2 */
	expect_ok (tftp_window_cache_insert(cache, 30, "30", 2));
	expect_ok (tftp_window_cache_insert(cache, 32, "32", 2));
	expect_err(tftp_window_cache_insert(cache, 34, "34", 2));

	expect_it(tftp_window_cache_starts_with(cache, 30));
	expect_eq(tftp_window_cache_pop(cache)->id, 30);

	expect_ok (tftp_window_cache_insert(cache, 34, "34", 2));
	expect_err(tftp_window_cache_insert(cache, 35, "35", 2));

	expect_it(!tftp_window_cache_starts_with(cache, 30));
	expect_it(!tftp_window_cache_starts_with(cache, 31));
	expect_it(!tftp_window_cache_starts_with(cache, 32));
	expect_NULL(tftp_window_cache_pop(cache));

	expect_it(tftp_window_cache_starts_with(cache, 32));
	expect_eq(tftp_window_cache_pop(cache)->id, 32);

	expect_NULL(tftp_window_cache_pop(cache));
	expect_eq(tftp_window_cache_pop(cache)->id, 34);

	expect_eq(cache->id, TFTP_CACHE_NO_ID);

	/* sequence 3 */
	expect_ok(tftp_window_cache_insert(cache, 40, "40", 2));
	expect_ok(tftp_window_cache_insert(cache, 42, "42", 2));
	expect_ok(tftp_window_cache_insert(cache, 43, "43", 2));

	expect_it(!tftp_window_cache_remove_id(cache, 30));
	expect_it(!tftp_window_cache_remove_id(cache, 41));
	expect_it(!tftp_window_cache_remove_id(cache, 44));

	expect_it( tftp_window_cache_remove_id(cache, 42));
	expect_it(!tftp_window_cache_remove_id(cache, 42));

out:
	tftp_window_cache_free(cache);

	return 0;
}
#ifdef CONFIG_SELFTEST_TFTP
bselftest(core, tftp_window_cache_selftest);
#endif