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