]> cloudbase.mooo.com Git - z180-stamp.git/blob - avr/env.c
ENV_SIZE
[z180-stamp.git] / avr / env.c
1 /*
2 * (C) Copyright 2014 Leo C. <erbl259-lmu@yahoo.de>
3 *
4 * SPDX-License-Identifier: GPL-2.0
5 */
6
7 #include "env.h"
8 #include <avr/eeprom.h>
9
10 #include "config.h"
11 #include "debug.h"
12 #include "crc.h"
13 #include "getopt-min.h"
14
15 #define DEBUG_ENV 0 /* set to 1 to debug */
16
17 #define debug_env(fmt, args...) \
18 debug_cond(DEBUG_ENV, fmt, ##args)
19
20
21 /*
22 * Default Environment
23 */
24
25 #define DELIM "\0"
26
27 const FLASH char default_env[] = {
28 ENV_BAUDRATE "=" "115200" DELIM
29 ENV_BOOTDELAY "=" "3" DELIM
30 ENV_BOOTCMD "=" "pin ${pins};loadcpm3;go ${startaddress}" DELIM
31 ENV_CPM3_SYSFILE "=" CONFIG_CPM3_SYSFILE DELIM
32 ENV_PINALIAS "=" "0:PG5,1:PG4,2:PB4,3:PB5,4:PB6,5:PB7,"
33 "6:PG3,7:PG2,8:PG1,9:PG0,10:PE7" DELIM
34 //ENV_STARTADDRESS "=" "0" DELIM
35 "pins" "=" "2,8 low 9 high 3 2" DELIM
36 DELIM
37 };
38
39
40 #define ENV_SIZE (CONFIG_ENV_SIZE - sizeof(uint16_t) - sizeof(uint8_t))
41
42 #define ENVLIST_DELETE (1<<0)
43
44
45 /* EEPROM storage */
46 typedef struct environment_s {
47 uint16_t crc; /* CRC16 over data bytes */
48 uint8_t flags; /* active/obsolete flags */
49 #define ACTIVE_FLAG 1
50 #define OBSOLETE_FLAG 0
51 char data[ENV_SIZE]; /* Environment data */
52 } env_t;
53
54
55 static uint8_t env_valid;
56 static char env_list[ENV_SIZE];
57
58 static
59 char env_get_char(uint_fast16_t index)
60 {
61 unsigned int off = CONFIG_ENV_OFFSET;
62 char ret;
63
64 switch (env_valid) {
65 case 2:
66 off += CONFIG_ENV_SIZE;
67 case 1:
68 ret = (char) eeprom_read_byte((const uint8_t *)off + index +
69 offsetof(env_t, data));
70 break;
71
72 default:
73 ret = default_env[index];
74 }
75
76 return ret;
77 }
78
79 static void envlist_clear(void)
80 {
81 memset(env_list, 0, sizeof env_list);
82 }
83
84 static
85 int env_item_delete(char *ep)
86 {
87 char *next = ep + strlen(ep) + 1;
88 char *end = next;
89 while (*end++ != 0)
90 while (*end++ != 0);
91
92 memmove(ep, next, end - next);
93
94 return 0;
95 }
96
97 static int envcmp(const char *s1, const char *s2)
98 {
99 const unsigned char *u1 = (const unsigned char *)s1;
100 const unsigned char *u2 = (const unsigned char *)s2;
101 unsigned char c1, c2;
102
103 do {
104 c1 = *u1++; c2 = *u2++;
105 if (c1 == '=') c1 = '\0';
106 if (c2 == '=') c2 = '\0';
107 } while (c1 != 0 && c1 - c2 == 0);
108
109 return c1 - c2;
110 }
111
112 static char *envlist_search(const MEMX char *name)
113 {
114 char key[CONFIG_SYS_ENV_NAMELEN + 1];
115 const MEMX char *np = name;
116 int keylen = 0;
117 char c;
118
119 while (keylen <= CONFIG_SYS_ENV_NAMELEN && (c = *np++) != '\0')
120 key[keylen++] = c;
121 key[keylen] = '\0';
122
123 for (char *lp = env_list; *lp != 0; ++lp) {
124
125 if (envcmp(lp, key) == 0)
126 return lp;
127
128 while (*lp != 0)
129 ++lp;
130 }
131
132 return NULL;
133 }
134
135 static char *env_item_insert_name(char *pos, const char *name, int len)
136 {
137 char *dstp = pos + len + 1;
138 char *end = pos;
139 while (*end++ != 0)
140 while (*end++ != 0);
141
142 if (end + len >= env_list + ENV_SIZE)
143 return NULL;
144
145 memmove(dstp, pos, end - pos);
146 strcpy(pos, name);
147 memset(pos + strlen(name), '=', dstp - pos - strlen(name));
148 *(dstp - 1) = '\0';
149
150 return pos;
151 }
152
153
154 static char *envlist_alloc(const char *name, int len)
155 {
156 char *lp;
157 int rc;
158
159
160 for (lp = env_list; *lp != 0; ++lp) {
161
162 rc = envcmp(lp, name);
163 if (rc >= 0)
164 break;
165
166 /* rc < 0 : check next place */
167 while (*lp != 0)
168 ++lp;
169 }
170
171 /* rc == 0 : entry found, replace */
172 if (rc == 0)
173 env_item_delete(lp);
174
175 /* rc > 0 : entry not in list, insert */
176 /* *lp == 0 : entry not in list, insert */
177
178 lp = env_item_insert_name(lp, name, len);
179
180 return lp;
181 }
182
183 #if 0
184 static char *env_item_insert(char *pos, const char *envstr)
185 {
186 char *dstp = pos + strlen(envstr) + 1;
187 char *end = pos;
188 while (*end++ != 0)
189 while (*end++ != 0);
190
191 if (end > env_list + ENV_SIZE)
192 return NULL;
193
194 memmove(dstp, pos, end - pos);
195 strcpy(pos, envstr);
196
197 return pos;
198 }
199
200 static char *envlist_enter(const char *ep)
201 {
202 char *lp;
203 int rc;
204
205 for (lp = env_list; *lp != 0; ++lp) {
206
207 rc = envcmp(lp, ep);
208 if (rc >= 0)
209 break;
210
211 /* rc < 0 : check next place */
212 while (*lp != 0)
213 ++lp;
214 }
215
216 /* rc == 0 : entry found, replace */
217 if (rc == 0)
218 env_item_delete(lp);
219
220 /* rc > 0 : entry not in list, insert */
221 /* *lp == 0 : entry not in list, insert */
222
223 lp = env_item_insert(lp, ep);
224
225 return lp;
226 }
227 #endif
228
229 static
230 int envlist_delete(const MEMX char *name)
231 {
232 char *ep = envlist_search(name);
233
234 if (ep != NULL)
235 return env_item_delete(ep);
236
237 return 1;
238 }
239
240 static
241 int envlist_import(uint8_t flags)
242 {
243 if ((flags & ENVLIST_DELETE) != 0)
244 envlist_clear();
245
246 for (uint_fast16_t index = 0; env_get_char(index) != '\0'; ) {
247 char name[CONFIG_SYS_ENV_NAMELEN+1];
248 uint_fast8_t nlen = 0;
249 size_t len;
250 char ch;
251 for (len = 0; (ch = env_get_char(index + len)) != '\0'; ++len) {
252 if ((index + len) >= ENV_SIZE)
253 return -1;
254 if (nlen == 0) {
255 if (ch == '=') {
256 nlen = len;
257 name[nlen] = '\0';
258 } else {
259 if (len > CONFIG_SYS_ENV_NAMELEN)
260 return -1;
261 name[len] = ch;
262 }
263 }
264 }
265
266 char *ep = envlist_alloc(name, len);
267 if (ep == NULL) {
268 printf_P(PSTR("## Error inserting \"%s\" variable.\n"), name);
269 return 1;
270 }
271
272 index += nlen;
273 char *p = ep + nlen;
274 while ((*p++ = env_get_char(index++)) != '\0')
275 ;
276 }
277 return 0;
278 }
279
280
281 static
282 uint16_t env_crc(uint16_t data_offset)
283 {
284 uint16_t crc;
285 uint16_t i;
286 char c, c0;
287
288 crc = 0xffff;
289 c = 0xff;
290 for (i = 0; !(c == 0 && c0 == 0) && i < ENV_SIZE; i++)
291 {
292 c0 = c;
293 c = eeprom_read_byte((const uint8_t *) data_offset + i);
294 crc = crc16(crc, c);
295 }
296 return crc ;
297 }
298
299
300 /**
301 * return valid env
302 */
303 static
304 int env_check_valid(void)
305 {
306 const uint16_t offset[2] = {CONFIG_ENV_OFFSET,
307 CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE};
308 uint_fast8_t flags[2], crc_ok[2];
309 int rc;
310
311 /* read FLAGS */
312 flags[0] = eeprom_read_byte ((uint8_t *) offset[0] +
313 offsetof(env_t, flags));
314 flags[1] = eeprom_read_byte ((uint8_t *) offset[1] +
315 offsetof(env_t, flags));
316
317 /* check CRC */
318 crc_ok[0] = (
319 eeprom_read_word((uint16_t *) offset[0] +
320 offsetof(env_t, crc))
321 == env_crc(offset[0] + offsetof(env_t, data))
322 );
323 crc_ok[1] = (
324 eeprom_read_word((uint16_t *) offset[1] +
325 offsetof(env_t, crc))
326 == env_crc(offset[1] + offsetof(env_t, data))
327 );
328
329 if (!crc_ok[0] && !crc_ok[1]) {
330 rc = 0;
331
332 } else if (crc_ok[0] && !crc_ok[1]) {
333 rc = 1;
334 } else if (!crc_ok[0] && crc_ok[1]) {
335 rc = 2;
336 } else {
337 /* both ok - check serial */
338 #if 1
339 if (flags[1] == ACTIVE_FLAG && flags[0] != ACTIVE_FLAG)
340 rc = 2;
341 else if (flags[1] == OBSOLETE_FLAG && flags[0] == 0xFF)
342 rc = 2;
343 else
344 rc = 1;
345 #else
346 if (flags[0] == ACTIVE_FLAG && flags[1] == OBSOLETE_FLAG)
347 rc = 1;
348 else if (flags[0] == OBSOLETE_FLAG && flags[1] == ACTIVE_FLAG)
349 rc = 2;
350 else if (flags[0] == 0xFF && flags[1] == 0)
351 rc = 2;
352 else if (flags[1] == 0xFF && flags[0] == 0)
353 rc = 1;
354 else /* flags are equal - almost impossible */
355 rc = 1;
356 #endif
357 }
358
359 return rc;
360 }
361
362
363 int env_init(void)
364 {
365 env_valid = env_check_valid();
366 if (env_valid == 0) {
367 printf_P(PSTR("*** Warning - bad CRC, "
368 "using default environment\n\n"));
369 }
370
371 envlist_import(ENVLIST_DELETE);
372 return 0;
373 }
374
375
376 char *getenv_str(const MEMX char *name)
377 {
378 char *ep = envlist_search(name);
379 if (ep != NULL)
380 return strchr(ep, '=') + 1;
381 else
382 return NULL;
383 }
384
385 static
386 int env_item_save(char *ep, uint16_t offset, int space_left)
387 {
388 int len;
389
390 len = strlen(ep);
391 if (len == 0)
392 return 0;
393 len += 1;
394 if (len > space_left)
395 return 0;
396
397 eeprom_update_block(ep, (uint8_t *) offset, len);
398
399 return len;
400 }
401
402
403 static
404 int saveenv(void)
405 {
406 unsigned int off = CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE;
407 unsigned int off_red = CONFIG_ENV_OFFSET;
408 unsigned int pos;
409 int len, left;
410 uint16_t crc;
411 int rc = 0;
412
413 if (env_valid == 2) {
414 off = CONFIG_ENV_OFFSET;
415 off_red = CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE;
416 }
417
418 eeprom_update_byte((uint8_t *) off + offsetof(env_t, flags), 0xff);
419
420 pos = off + offsetof(env_t, data);
421 left = ENV_SIZE - 1;
422
423 char *ep = env_list;
424 while (*ep) {
425 len = env_item_save(ep, pos, left);
426 if (len == 0) {
427 return 1;
428 }
429 pos += len;
430 left -= len;
431 while (*ep++);
432 }
433
434 /* terminate list */
435 eeprom_update_byte((uint8_t *) pos, 0);
436 crc = env_crc(off + offsetof(env_t, data));
437 eeprom_update_word((uint16_t *) off + offsetof(env_t, crc), crc);
438 eeprom_update_byte((uint8_t *) off + offsetof(env_t, flags),
439 ACTIVE_FLAG);
440
441 if (rc == 0) {
442 eeprom_update_byte((uint8_t *) off_red + offsetof(env_t, flags),
443 OBSOLETE_FLAG);
444 env_valid = (env_valid == 2) ? 1 : 2;
445 }
446
447 return rc;
448 }
449
450
451 static
452 int env_item_print(char *ep, bool mode)
453 {
454 int len = strlen(ep) + 1;
455
456 if (mode) {
457 my_puts_P(PSTR("setenv "));
458 char ch;
459 while ((ch = *ep++) != '=')
460 putchar(ch);
461 printf_P(PSTR(" '%s'\n"), ep);
462 } else {
463 puts(ep);
464 }
465
466 return len;
467 }
468
469
470 /*
471 * Command interface: print one or all environment variables
472 *
473 * Returns -1 in case of error, or length of printed string
474 */
475 static
476 int env_print(const char *name, bool mode)
477 {
478 int len = -1;
479 char *ep;
480
481 if (name != NULL) { /* print a single name */
482
483 ep = envlist_search(name);
484 if (ep != NULL)
485 len = env_item_print(ep, mode);
486
487 } else { /* print whole list */
488 len = 0;
489 ep = env_list;
490 while (*ep) {
491 len += env_item_print(ep, mode);
492 while (*ep++);
493 }
494 }
495 return len;
496 }
497
498
499 /**
500 * Set or delete environment variable
501 *
502 * Set a new environment variable,
503 * or replace or delete an existing one.
504 *
505 * @param flag (not used)
506 * @param argc
507 * @param argv[1] Environment variable to set or delete
508 * if no more args
509 * @param argv[2] ... Value to set it to
510 *
511 * @return 0 if ok, 1 on error
512 */
513 static
514 command_ret_t _do_env_set(uint_fast8_t flag UNUSED, int argc, char * const argv[])
515 {
516 char *name = argv[1];
517
518 if (strchr(name, '=')) {
519 printf_P(PSTR("## Error: illegal character '='"
520 "in variable name \"%s\"\n"), name);
521 return CMD_RET_FAILURE;
522 }
523 size_t len = strlen(name);
524 if (len > CONFIG_SYS_ENV_NAMELEN) {
525 printf_P(PSTR("## Error: Variable name \"%s\" too long. "
526 "(max %d characters)\n"), name, CONFIG_SYS_ENV_NAMELEN);
527 return CMD_RET_FAILURE;
528 }
529
530 /* Delete only ? */
531 if (argc < 3) {
532 int rc = envlist_delete(name);
533 return rc ? CMD_RET_FAILURE : CMD_RET_SUCCESS;
534 }
535
536 /* Insert / replace new value */
537
538 for (int_fast8_t i = 2; i < argc; ++i)
539 len += strlen(argv[i]) + 1;
540
541 char *pos = envlist_alloc(name, len);
542 if (pos == NULL) {
543 printf_P(PSTR("## Error inserting \"%s\" variable.\n"), name);
544 return CMD_RET_FAILURE;
545 }
546
547 char *vp = pos + strlen(name) + 1;
548 for (int_fast8_t i = 2; i < argc; ++i) {
549 char *ap = argv[i];
550 while ((*vp++ = *ap++) != '\0');
551 //if (i < argc-1)
552 *(vp-1) = ' ';
553 }
554 *(vp-1) = '\0';
555
556 return CMD_RET_SUCCESS;
557 }
558
559 /**
560 * Set an environment variable
561 *
562 * @param varname Environment variable to set
563 * @param varvalue Value to set it to
564 * @return 0 if ok, 1 on error
565 */
566 static
567 int setenv(const MEMX char *varname, const char *varvalue)
568 {
569 int rc;
570
571 #ifdef __MEMX
572 char *tmpname;
573 if (__builtin_avr_flash_segment(varname) != -1) {
574 tmpname = malloc(strlen_P(varname)+1);
575 if (tmpname == NULL) {
576 printf_P(PSTR("setenv: Out of Memory!\n"));
577 return 1;
578 }
579 strcpy_P(tmpname, varname);
580 } else
581 tmpname = (char *) varname;
582
583 const char * const argv[3] = { NULL, tmpname, varvalue };
584 #else
585 const char * const argv[3] = { NULL, varname, varvalue };
586 #endif
587
588 int argc = 3;
589
590 if (varvalue == NULL || varvalue[0] == '\0')
591 --argc;
592
593 rc = (int) _do_env_set(0, argc, (char * const *)argv);
594
595 #ifdef __MEMX
596 if (__builtin_avr_flash_segment(varname) != -1)
597 free(tmpname);
598 #endif
599 return rc;
600 }
601
602 /**
603 * Set an environment variable to an integer value
604 *
605 * @param name Environment variable to set
606 * @param value Value to set it to
607 * @param radix Base
608 * @return 0 if ok, 1 on error
609 */
610 static
611 int setenv_intval(const MEMX char *name, unsigned long value, int radix)
612 {
613 char buf[11];
614
615 ultoa(value, buf, radix);
616
617 return setenv(name, buf);
618 }
619
620 /**
621 * Set an environment variable to a decimal integer value
622 *
623 * @param name Environment variable to set
624 * @param value Value to set it to
625 * @return 0 if ok, 1 on error
626 */
627 int setenv_ulong(const MEMX char *name, unsigned long value)
628 {
629 return setenv_intval(name, value, 10);
630 }
631
632
633 /**
634 * Set an environment variable to a value in hex
635 *
636 * @param name Environment variable to set
637 * @param value Value to set it to
638 * @return 0 if ok, 1 on error
639 */
640 int setenv_hex(const MEMX char *name, unsigned long value)
641 {
642 return setenv_intval(name, value, 16);
643 }
644
645
646 /**
647 * Decode the integer value of an environment variable and return it.
648 *
649 * @param name Name of environemnt variable
650 * @param base Number base to use (normally 10, or 16 for hex)
651 * @param default_val Default value to return if the variable is not
652 * found
653 * @return the decoded value, or default_val if not found
654 */
655 unsigned long getenv_ulong(const MEMX char *name, int base, unsigned long default_val)
656 {
657 unsigned long value;
658 char *vp, *endp;
659
660 vp = getenv_str(name);
661
662 if (vp != NULL ) {
663 value = strtoul(vp, &endp, base);
664 if (endp != vp)
665 return value;
666 }
667
668 return default_val;
669 }
670
671
672 /*
673 * Read an environment variable as a boolean
674 */
675 bool getenv_yesno(const MEMX char *name)
676 {
677 char *s = getenv_str(name);
678
679 if (s == NULL)
680 return false;
681
682 return strchr_P(PSTR("1yYtT"), *s) != NULL;
683
684 /*
685 return *s == '1' || *s == 'y' || *s == 'Y' || *s == 't' || *s == 'T' ?
686 1 : 0;
687 */
688 }
689
690 command_ret_t do_env_print(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED,
691 int argc, char * const argv[])
692 {
693 bool mode = 0;
694 command_ret_t rc = CMD_RET_SUCCESS;
695
696 /* reset getopt() */
697 optind = 0;
698
699 int opt;
700 while ((opt = getopt(argc, argv, PSTR("s"))) != -1) {
701 switch (opt) {
702 case 's':
703 mode = 1;
704 break;
705 default: /* '?' */
706 return CMD_RET_USAGE;
707 }
708 }
709
710 if (optind == argc) {
711 /* print all env vars */
712 int size = env_print(NULL, mode);
713 if (size < 0)
714 return CMD_RET_FAILURE;
715 if (mode == 0)
716 printf_P(PSTR("\nEnvironment size: %d/%d bytes\n"),
717 size, ENV_SIZE - 1);
718 return CMD_RET_SUCCESS;
719 }
720
721 /* print selected env vars */
722 while (optind < argc) {
723 int rc = env_print(argv[optind], mode);
724 if (rc < 0) {
725 printf_P(PSTR("## Error: \"%s\" not defined\n"), argv[optind]);
726 rc = CMD_RET_FAILURE;
727 }
728 optind++;
729 }
730
731 return rc;
732 }
733
734
735 command_ret_t do_env_set(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag, int argc, char * const argv[])
736 {
737 if (argc < 2)
738 return CMD_RET_USAGE;
739
740 return _do_env_set(flag, argc, argv);
741 }
742
743
744 command_ret_t do_env_default(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED,
745 int argc UNUSED, char * const argv[] UNUSED)
746 {
747 uint8_t tmp = env_valid;
748 env_valid = 0;
749
750 /* Reset the whole environment */
751 printf_P(PSTR("## Resetting to default environment\n"));
752 envlist_import(ENVLIST_DELETE);
753
754 env_valid = tmp;
755
756 return CMD_RET_SUCCESS;
757 }
758
759
760 command_ret_t do_env_save(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc UNUSED, char * const argv[] UNUSED)
761 {
762 printf_P(PSTR("Saving Environment ...\n"));
763 return saveenv() ? CMD_RET_FAILURE : CMD_RET_SUCCESS;
764 }
765
766
767 #if defined(CONFIG_AUTO_COMPLETE)
768 int env_complete(char *var, int maxv, char *cmdv[], int bufsz, char *buf)
769 {
770 ENTRY *match;
771 int found, idx;
772
773 idx = 0;
774 found = 0;
775 cmdv[0] = NULL;
776
777 while ((idx = hmatch_r(var, idx, &match, &env_htab))) {
778 int vallen = strlen(match->key) + 1;
779
780 if (found >= maxv - 2 || bufsz < vallen)
781 break;
782
783 cmdv[found++] = buf;
784 memcpy(buf, match->key, vallen);
785 buf += vallen;
786 bufsz -= vallen;
787 }
788
789 qsort(cmdv, found, sizeof(cmdv[0]), strcmp_compar);
790
791 if (idx)
792 cmdv[found++] = "...";
793
794 cmdv[found] = NULL;
795 return found;
796 }
797 #endif