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