forked from richardghirst/PiBits
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathservod.c
1538 lines (1368 loc) · 43.1 KB
/
servod.c
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
/*
* servod.c Multiple Servo Driver for the RaspberryPi
* Copyright (c) 2013 Richard Hirst <richardghirst@gmail.com>
* Updated 2017 Stuart Shelton <srcshelton@gmail.com>
*
* This program provides very similar functionality to servoblaster, except
* that rather than implementing it as a kernel module, servod implements
* the functionality as a usr space daemon.
*
* 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.
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* TODO: Separate idle timeout handling from genuine set-to-zero requests */
/* TODO: Add ability to specify time frame over which an adjustment should be made */
/* TODO: Add servoctl utility to set and query servo positions, etc */
/* TODO: Add slow-start option */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#include <stdint.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <getopt.h>
#include <math.h>
#include <bcm_host.h>
#include "mailbox.h"
#define DMY 255 // Used to represent an invalid P1 pin, or unmapped servo
#define NUM_P1PINS 40
#define NUM_P5PINS 8
#define MAX_SERVOS 32 /* Only 21 really, but this lets you map servo IDs
* to P1 pins, if you want to
*/
#define MAX_MEMORY_USAGE (16*1024*1024) /* Somewhat arbitrary limit of 16MB */
#define DEFAULT_CYCLE_TIME_US 20000
#define DEFAULT_STEP_TIME_US 10
#define DEFAULT_SERVO_MIN_US 500
#define DEFAULT_SERVO_MAX_US 2500
#define DEVFILE "/dev/servoblaster"
#define CFGFILE "/var/run/servoblaster.status"
#define PAGE_SIZE 4096
#define PAGE_SHIFT 12
#define DMA_CHAN_SIZE 0x100
#define DMA_CHAN_MIN 0
#define DMA_CHAN_MAX 14
#define DMA_CHAN_DEFAULT 14
#define DMA_CHAN_PI4 7
#define DMA_BASE_OFFSET 0x00007000
#define DMA_LEN DMA_CHAN_SIZE * (DMA_CHAN_MAX+1)
#define PWM_BASE_OFFSET 0x0020C000
#define PWM_LEN 0x28
#define CLK_BASE_OFFSET 0x00101000
#define CLK_LEN 0xA8
#define GPIO_BASE_OFFSET 0x00200000
#define GPIO_LEN 0x100
#define PCM_BASE_OFFSET 0x00203000
#define PCM_LEN 0x24
#define DMA_VIRT_BASE (periph_virt_base + DMA_BASE_OFFSET)
#define PWM_VIRT_BASE (periph_virt_base + PWM_BASE_OFFSET)
#define CLK_VIRT_BASE (periph_virt_base + CLK_BASE_OFFSET)
#define GPIO_VIRT_BASE (periph_virt_base + GPIO_BASE_OFFSET)
#define PCM_VIRT_BASE (periph_virt_base + PCM_BASE_OFFSET)
#define PWM_PHYS_BASE (periph_phys_base + PWM_BASE_OFFSET)
#define PCM_PHYS_BASE (periph_phys_base + PCM_BASE_OFFSET)
#define GPIO_PHYS_BASE (periph_phys_base + GPIO_BASE_OFFSET)
#define DMA_NO_WIDE_BURSTS (1<<26)
#define DMA_WAIT_RESP (1<<3)
#define DMA_D_DREQ (1<<6)
#define DMA_PER_MAP(x) ((x)<<16)
#define DMA_END (1<<1)
#define DMA_RESET (1<<31)
#define DMA_INT (1<<2)
#define DMA_CS (0x00/4)
#define DMA_CONBLK_AD (0x04/4)
#define DMA_SOURCE_AD (0x0c/4)
#define DMA_DEBUG (0x20/4)
#define GPIO_FSEL0 (0x00/4)
#define GPIO_SET0 (0x1c/4)
#define GPIO_CLR0 (0x28/4)
#define GPIO_LEV0 (0x34/4)
#define GPIO_PULLEN (0x94/4)
#define GPIO_PULLCLK (0x98/4)
#define GPIO_MODE_IN 0
#define GPIO_MODE_OUT 1
#define PWM_CTL (0x00/4)
#define PWM_DMAC (0x08/4)
#define PWM_RNG1 (0x10/4)
#define PWM_FIFO (0x18/4)
#define PWMCLK_CNTL 40
#define PWMCLK_DIV 41
#define PWMCTL_MODE1 (1<<1)
#define PWMCTL_PWEN1 (1<<0)
#define PWMCTL_CLRF (1<<6)
#define PWMCTL_USEF1 (1<<5)
#define PWMDMAC_ENAB (1<<31)
#define PWMDMAC_THRSHLD ((15<<8)|(15<<0))
#define PCM_CS_A (0x00/4)
#define PCM_FIFO_A (0x04/4)
#define PCM_MODE_A (0x08/4)
#define PCM_RXC_A (0x0c/4)
#define PCM_TXC_A (0x10/4)
#define PCM_DREQ_A (0x14/4)
#define PCM_INTEN_A (0x18/4)
#define PCM_INT_STC_A (0x1c/4)
#define PCM_GRAY (0x20/4)
#define PCMCLK_CNTL 38
#define PCMCLK_DIV 39
#define PLLDFREQ_MHZ_DEFAULT 500
#define PLLDFREQ_MHZ_PI4 750
#define DELAY_VIA_PWM 0
#define DELAY_VIA_PCM 1
#define ROUNDUP(val, blksz) (((val)+((blksz)-1)) & ~(blksz-1))
typedef struct {
uint32_t info, src, dst, length,
stride, next, pad[2];
} dma_cb_t;
#define BUS_TO_PHYS(x) ((x)&~0xC0000000)
/* Define which P1 header pins to use by default. These are the eight standard
* GPIO pins (those coloured green in the diagram on this page:
* http://elinux.org/Rpi_Low-level_peripherals
*
* Which P1 header pins are actually used can be overridden via command line
* parameter '--p1pins=...'.
*/
static char *default_p1_pins = "7,11,12,13,15,16,18,22";
static char *default_p5_pins = "";
static uint8_t rev1_p1pin2gpio_map[] = {
DMY, // P1-1 3v3
DMY, // P1-2 5v
0, // P1-3 GPIO 0 (SDA)
DMY, // P1-4 5v
1, // P1-5 GPIO 1 (SCL)
DMY, // P1-6 Ground
4, // P1-7 GPIO 4 (GPCLK0)
14, // P1-8 GPIO 14 (TXD)
DMY, // P1-9 Ground
15, // P1-10 GPIO 15 (RXD)
17, // P1-11 GPIO 17
18, // P1-12 GPIO 18 (PCM_CLK)
21, // P1-13 GPIO 21
DMY, // P1-14 Ground
22, // P1-15 GPIO 22
23, // P1-16 GPIO 23
DMY, // P1-17 3v3
24, // P1-18 GPIO 24
10, // P1-19 GPIO 10 (MOSI)
DMY, // P1-20 Ground
9, // P1-21 GPIO 9 (MISO)
25, // P1-22 GPIO 25
11, // P1-23 GPIO 11 (SCLK)
8, // P1-24 GPIO 8 (CE0)
DMY, // P1-25 Ground
7, // P1-26 GPIO 7 (CE1)
};
static uint8_t rev1_p5pin2gpio_map[] = {
DMY, // (P5-1 on rev 2 boards)
DMY, // (P5-2 on rev 2 boards)
DMY, // (P5-3 on rev 2 boards)
DMY, // (P5-4 on rev 2 boards)
DMY, // (P5-5 on rev 2 boards)
DMY, // (P5-6 on rev 2 boards)
DMY, // (P5-7 on rev 2 boards)
DMY, // (P5-8 on rev 2 boards)
};
static uint8_t rev2_p1pin2gpio_map[] = {
DMY, // P1-1 3v3
DMY, // P1-2 5v
2, // P1-3 GPIO 2 (SDA)
DMY, // P1-4 5v
3, // P1-5 GPIO 3 (SCL)
DMY, // P1-6 Ground
4, // P1-7 GPIO 4 (GPCLK0)
14, // P1-8 GPIO 14 (TXD)
DMY, // P1-9 Ground
15, // P1-10 GPIO 15 (RXD)
17, // P1-11 GPIO 17
18, // P1-12 GPIO 18 (PCM_CLK)
27, // P1-13 GPIO 27
DMY, // P1-14 Ground
22, // P1-15 GPIO 22
23, // P1-16 GPIO 23
DMY, // P1-17 3v3
24, // P1-18 GPIO 24
10, // P1-19 GPIO 10 (MOSI)
DMY, // P1-20 Ground
9, // P1-21 GPIO 9 (MISO)
25, // P1-22 GPIO 25
11, // P1-23 GPIO 11 (SCLK)
8, // P1-24 GPIO 8 (CE0)
DMY, // P1-25 Ground
7, // P1-26 GPIO 7 (CE1)
};
static uint8_t rev2_p5pin2gpio_map[] = {
DMY, // P5-1 5v0
DMY, // P5-2 3v3
28, // P5-3 GPIO 28 (I2C0_SDA)
29, // P5-4 GPIO 29 (I2C0_SCL)
30, // P5-5 GPIO 30
31, // P5-6 GPIO 31
DMY, // P5-7 Ground
DMY, // P5-8 Ground
};
static uint8_t bplus_p1pin2gpio_map[] = {
DMY, // P1-1 3v3
DMY, // P1-2 5v
2, // P1-3 GPIO 2 (SDA)
DMY, // P1-4 5v
3, // P1-5 GPIO 3 (SCL)
DMY, // P1-6 Ground
4, // P1-7 GPIO 4 (GPCLK0)
14, // P1-8 GPIO 14 (TXD)
DMY, // P1-9 Ground
15, // P1-10 GPIO 15 (RXD)
17, // P1-11 GPIO 17
18, // P1-12 GPIO 18 (PCM_CLK)
27, // P1-13 GPIO 27
DMY, // P1-14 Ground
22, // P1-15 GPIO 22
23, // P1-16 GPIO 23
DMY, // P1-17 3v3
24, // P1-18 GPIO 24
10, // P1-19 GPIO 10 (MOSI)
DMY, // P1-20 Ground
9, // P1-21 GPIO 9 (MISO)
25, // P1-22 GPIO 25
11, // P1-23 GPIO 11 (SCLK)
8, // P1-24 GPIO 8 (CE0)
DMY, // P1-25 Ground
7, // P1-26 GPIO 7 (CE1)
DMY, // P1-27 ID_SD
DMY, // P1-28 ID_SC
5, // P1-29 GPIO 5
DMY, // P1-30 Ground
6, // P1-31 GPIO 5
12, // P1-32 GPIO 12
13, // P1-33 GPIO 13
DMY, // P1-34 Ground
19, // P1-35 GPIO 19
16, // P1-36 GPIO 16
26, // P1-37 GPIO 26
20, // P1-38 GPIO 20
DMY, // P1-39 Ground
21, // P1-40 GPIO 21
};
// bcm_host_get_model_type() return values to name mapping
static const char *model_names[] = {
"A", "B", "A+", "B+", "2B", "Alpha", "CM", "CM2", "3B", "Zero", "CM3",
"Custom", "ZeroW", "3B+", "3A+", "FPGA", "CM3+", "4B"
};
#define NUM_MODELS (sizeof(model_names)/sizeof(*model_names))
// cycle_time_us is the pulse cycle time per servo, in microseconds.
// Typically it should be 20ms, or 20000us.
// step_time_us is the pulse width increment granularity, again in microseconds.
// Setting step_time_us too low will likely cause problems as the DMA controller
// will use too much memory bandwidth. 10us is a good value, though you
// might be ok setting it as low as 2us.
static int cycle_time_us;
static int step_time_us;
static uint8_t servo2gpio[MAX_SERVOS];
static uint8_t p1pin2servo[NUM_P1PINS+1];
static uint8_t p5pin2servo[NUM_P5PINS+1];
static int servostart[MAX_SERVOS];
static int servowidth[MAX_SERVOS];
static int num_servos;
static uint32_t gpiomode[MAX_SERVOS];
static int restore_gpio_modes;
static volatile uint32_t *pwm_reg;
static volatile uint32_t *pcm_reg;
static volatile uint32_t *clk_reg;
static volatile uint32_t *dma_reg;
static volatile uint32_t *gpio_reg;
static int delay_hw = DELAY_VIA_PWM;
static struct timeval *servo_kill_time;
static uint32_t plldfreq_mhz;
static int dma_chan;
static int idle_timeout;
static int invert = 0;
static int servo_min_ticks;
static int servo_max_ticks;
static int num_samples;
static int num_cbs;
static int num_pages;
static uint32_t *turnoff_mask;
static uint32_t *turnon_mask;
static dma_cb_t *cb_base;
static int board_is_model_1;
static int gpio_cfg;
static uint32_t periph_phys_base;
static uint32_t periph_virt_base;
static uint32_t dram_phys_base;
static uint32_t mem_flag;
static char *gpio_desc[] = {
"Unknown",
"P1 (26 pins)",
"P1 (26 pins), P5 (8 pins)",
"P1 (40 pins)"
};
static struct {
int handle; /* From mbox_open() */
uint32_t size; /* Required size */
unsigned mem_ref; /* From mem_alloc() */
unsigned bus_addr; /* From mem_lock() */
uint8_t *virt_addr; /* From mapmem() */
} mbox;
static void udelay(const int us);
static void terminate(__attribute__((unused)) const int dummy);
static void fatal(const char *fmt, ...);
static void init_idle_timers(void);
static void update_idle_time(const int servo);
static void get_next_idle_timeout(struct timeval *tv);
static uint32_t gpio_get_mode(const uint32_t gpio);
static void gpio_set_mode(const uint32_t gpio, const uint32_t mode);
static void gpio_set(const int gpio, const int level);
static uint32_t mem_virt_to_phys(void *virt);
static void *map_peripheral(const uint32_t base, const uint32_t len);
static void set_servo_idle(const int servo);
static void set_servo(const int servo, const int width);
static void setup_sighandlers(void);
static void init_ctrl_data(void);
static void init_hardware(void);
static void do_status(const char *filename);
static void do_debug(void);
static int parse_width(const int servo, const char *width_arg);
static void go_go_go(void);
static void get_model_and_revision(void);
static void parse_pin_lists(const int p1first, const char *p1pins, const char*p5pins);
static uint8_t gpiosearch(const uint8_t gpio, const uint8_t *map, const int len);
static char *gpio2pinname(const uint8_t gpio);
static int parse_min_max_arg(const char *arg, const char *name);
int main(int argc, char **argv);
static void
udelay(const int us)
{
struct timespec ts = { 0, us * 1000 };
nanosleep(&ts, NULL);
}
static void
terminate(__attribute__((unused))const int dummy)
{
int i;
if (dma_reg && mbox.virt_addr) {
for (i = 0; i < MAX_SERVOS; i++) {
if (servo2gpio[i] != DMY)
set_servo(i, 0);
}
udelay(cycle_time_us);
dma_reg[DMA_CS] = DMA_RESET;
udelay(10);
}
if (restore_gpio_modes) {
for (i = 0; i < MAX_SERVOS; i++) {
if (servo2gpio[i] != DMY)
gpio_set_mode(servo2gpio[i], gpiomode[i]);
}
}
if (mbox.virt_addr != NULL) {
unmapmem(mbox.virt_addr, mbox.size);
mem_unlock(mbox.handle, mbox.mem_ref);
mem_free(mbox.handle, mbox.mem_ref);
if (mbox.handle >= 0)
mbox_close(mbox.handle);
}
unlink(DEVFILE);
unlink(CFGFILE);
exit(1);
}
static void
fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
terminate(0);
}
static void
init_idle_timers(void)
{
servo_kill_time = calloc(MAX_SERVOS, sizeof(struct timeval));
if (!servo_kill_time)
fatal("servod: calloc() failed\n");
}
static void
update_idle_time(const int servo)
{
if (idle_timeout == 0)
return;
gettimeofday(servo_kill_time + servo, NULL);
servo_kill_time[servo].tv_sec += idle_timeout / 1000;
servo_kill_time[servo].tv_usec += (idle_timeout % 1000) * 1000;
while (servo_kill_time[servo].tv_usec >= 1000000) {
servo_kill_time[servo].tv_usec -= 1000000;
servo_kill_time[servo].tv_sec++;
}
}
static void
get_next_idle_timeout(struct timeval *tv)
{
int i;
struct timeval now;
struct timeval min = { 60, 0 };
long this_diff, min_diff;
gettimeofday(&now, NULL);
for (i = 0; i < MAX_SERVOS; i++) {
if (servo2gpio[i] == DMY || servo_kill_time[i].tv_sec == 0)
continue;
else if (servo_kill_time[i].tv_sec < now.tv_sec ||
(servo_kill_time[i].tv_sec == now.tv_sec &&
servo_kill_time[i].tv_usec <= now.tv_usec)) {
servo_kill_time[i].tv_sec = 0;
set_servo_idle(i);
} else {
this_diff = (servo_kill_time[i].tv_sec - now.tv_sec) * 1000000
+ servo_kill_time[i].tv_usec - now.tv_usec;
min_diff = min.tv_sec * 1000000 + min.tv_usec;
if (this_diff < min_diff) {
min.tv_sec = this_diff / 1000000;
min.tv_usec = this_diff % 1000000;
}
}
}
*tv = min;
}
static uint32_t
gpio_get_mode(const uint32_t gpio)
{
uint32_t fsel = gpio_reg[GPIO_FSEL0 + gpio/10];
return (fsel >> ((gpio % 10) * 3)) & 7;
}
static void
gpio_set_mode(const uint32_t gpio, const uint32_t mode)
{
uint32_t fsel = gpio_reg[GPIO_FSEL0 + gpio/10];
fsel &= ~(7 << ((gpio % 10) * 3));
fsel |= mode << ((gpio % 10) * 3);
gpio_reg[GPIO_FSEL0 + gpio/10] = fsel;
}
static void
gpio_set(const int gpio, const int level)
{
if (level)
gpio_reg[GPIO_SET0] = 1 << gpio;
else
gpio_reg[GPIO_CLR0] = 1 << gpio;
}
static uint32_t
mem_virt_to_phys(void *virt)
{
uint32_t offset = (uint8_t *)virt - mbox.virt_addr;
return mbox.bus_addr + offset;
}
static void *
map_peripheral(const uint32_t base, const uint32_t len)
{
int fd = open("/dev/mem", O_RDWR|O_SYNC);
void * vaddr;
if (fd < 0)
fatal("servod: Failed to open /dev/mem: %m\n");
vaddr = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, base);
if (vaddr == MAP_FAILED)
fatal("servod: Failed to map peripheral at 0x%08x: %m\n", base);
close(fd);
return vaddr;
}
static void
set_servo_idle(const int servo)
{
/* Just remove the 'turn-on' action and allow the 'turn-off' action at
* the end of the current pulse to turn it off. Special case if
* current width is 100%; in that case there will be no 'turn-off'
* action, so we will need to force the output off here. We must not
* force the output in other cases, because that might lead to
* truncated pulses which would make a servo change position.
*/
turnon_mask[servo] = 0;
if (servowidth[servo] == num_samples)
gpio_set(servo2gpio[servo], invert ? 1 : 0);
}
/* Carefully add or remove bits from the turnoff_mask such that regardless
* of where the DMA controller is in its cycle, and whether we are increasing
* or decreasing the pulse width, the generated pulse will only ever be the
* old width or the new width. If we don't take such care then there could be
* a cycle with some pulse width between the two requested ones. That doesn't
* really matter for servos, but when driving LEDs some odd intensity for one
* cycle can be noticeable. It may be that the servo output has been turned
* off via the inactivity timer, which is handled by always setting the turnon
* mask appropriately at the end of this function.
*/
static void
set_servo(const int servo, const int width)
{
volatile uint32_t *dp;
int i;
uint32_t mask = 1 << servo2gpio[servo];
if (width > servowidth[servo]) {
dp = turnoff_mask + servostart[servo] + width;
if (dp >= turnoff_mask + num_samples)
dp -= num_samples;
for (i = width; i > servowidth[servo]; i--) {
dp--;
if (dp < turnoff_mask)
dp = turnoff_mask + num_samples - 1;
//printf("%5d, clearing at %p\n", dp - ctl->turnoff, dp);
*dp &= ~mask;
}
} else if (width < servowidth[servo]) {
dp = turnoff_mask + servostart[servo] + width;
if (dp >= turnoff_mask + num_samples)
dp -= num_samples;
for (i = width; i < servowidth[servo]; i++) {
//printf("%5d, setting at %p\n", dp - ctl->turnoff, dp);
*dp++ |= mask;
if (dp >= turnoff_mask + num_samples)
dp = turnoff_mask;
}
}
servowidth[servo] = width;
if (width == 0) {
turnon_mask[servo] = 0;
} else {
turnon_mask[servo] = mask;
}
update_idle_time(servo);
}
static void
setup_sighandlers(void)
{
int i;
// Catch all signals possible - it is vital we kill the DMA engine
// on process exit!
for (i = 0; i < 64; i++) {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = terminate;
sigaction(i, &sa, NULL);
}
}
static void
init_ctrl_data(void)
{
dma_cb_t *cbp = cb_base;
uint32_t phys_fifo_addr, cbinfo;
uint32_t phys_gpclr0;
uint32_t phys_gpset0;
int servo, i, numservos = 0, curstart = 0;
uint32_t maskall = 0;
if (invert) {
phys_gpclr0 = GPIO_PHYS_BASE + 0x1c;
phys_gpset0 = GPIO_PHYS_BASE + 0x28;
} else {
phys_gpclr0 = GPIO_PHYS_BASE + 0x28;
phys_gpset0 = GPIO_PHYS_BASE + 0x1c;
}
if (delay_hw == DELAY_VIA_PWM) {
phys_fifo_addr = PWM_PHYS_BASE + 0x18;
cbinfo = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ | DMA_PER_MAP(5);
} else {
phys_fifo_addr = PCM_PHYS_BASE + 0x04;
cbinfo = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP | DMA_D_DREQ | DMA_PER_MAP(2);
}
memset(turnon_mask, 0, MAX_SERVOS * sizeof(*turnon_mask));
for (servo = 0 ; servo < MAX_SERVOS; servo++) {
servowidth[servo] = 0;
if (servo2gpio[servo] != DMY) {
numservos++;
maskall |= 1 << servo2gpio[servo];
}
}
for (i = 0; i < num_samples; i++)
turnoff_mask[i] = maskall;
for (servo = 0; servo < MAX_SERVOS; servo++) {
if (servo2gpio[servo] != DMY) {
servostart[servo] = curstart;
curstart += num_samples / num_servos;
}
}
servo = 0;
while (servo < MAX_SERVOS && servo2gpio[servo] == DMY)
servo++;
for (i = 0; i < num_samples; i++) {
cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP;
cbp->src = mem_virt_to_phys(turnoff_mask + i);
cbp->dst = phys_gpclr0;
cbp->length = 4;
cbp->stride = 0;
cbp->next = mem_virt_to_phys(cbp + 1);
cbp++;
if (i == servostart[servo]) {
cbp->info = DMA_NO_WIDE_BURSTS | DMA_WAIT_RESP;
cbp->src = mem_virt_to_phys(turnon_mask + servo);
cbp->dst = phys_gpset0;
cbp->length = 4;
cbp->stride = 0;
cbp->next = mem_virt_to_phys(cbp + 1);
cbp++;
servo++;
while (servo < MAX_SERVOS && servo2gpio[servo] == DMY)
servo++;
}
// Delay
cbp->info = cbinfo;
cbp->src = mem_virt_to_phys(turnoff_mask); // Any data will do
cbp->dst = phys_fifo_addr;
cbp->length = 4;
cbp->stride = 0;
cbp->next = mem_virt_to_phys(cbp + 1);
cbp++;
}
cbp--;
cbp->next = mem_virt_to_phys(cb_base);
}
static void
init_hardware(void)
{
if (delay_hw == DELAY_VIA_PWM) {
// Initialise PWM
pwm_reg[PWM_CTL] = 0;
udelay(10);
clk_reg[PWMCLK_CNTL] = 0x5A000006; // Source=PLLD (500MHz or 750MHz on Pi4)
udelay(100);
clk_reg[PWMCLK_DIV] = 0x5A000000 | (plldfreq_mhz<<12); // set pwm div to give 1MHz
udelay(100);
clk_reg[PWMCLK_CNTL] = 0x5A000016; // Source=PLLD and enable
udelay(100);
pwm_reg[PWM_RNG1] = step_time_us;
udelay(10);
pwm_reg[PWM_DMAC] = PWMDMAC_ENAB | PWMDMAC_THRSHLD;
udelay(10);
pwm_reg[PWM_CTL] = PWMCTL_CLRF;
udelay(10);
pwm_reg[PWM_CTL] = PWMCTL_USEF1 | PWMCTL_PWEN1;
udelay(10);
} else {
// Initialise PCM
pcm_reg[PCM_CS_A] = 1; // Disable Rx+Tx, Enable PCM block
udelay(100);
clk_reg[PCMCLK_CNTL] = 0x5A000006; // Source=PLLD (500MHz or 750MHz on Pi4)
udelay(100);
clk_reg[PCMCLK_DIV] = 0x5A000000 | (plldfreq_mhz<<12); // Set pcm div to give 1MHz
udelay(100);
clk_reg[PCMCLK_CNTL] = 0x5A000016; // Source=PLLD and enable
udelay(100);
pcm_reg[PCM_TXC_A] = 0<<31 | 1<<30 | 0<<20 | 0<<16; // 1 channel, 8 bits
udelay(100);
pcm_reg[PCM_MODE_A] = (step_time_us - 1) << 10;
udelay(100);
pcm_reg[PCM_CS_A] |= 1<<4 | 1<<3; // Clear FIFOs
udelay(100);
pcm_reg[PCM_DREQ_A] = 64<<24 | 64<<8; // DMA Req when one slot is free?
udelay(100);
pcm_reg[PCM_CS_A] |= 1<<9; // Enable DMA
udelay(100);
}
// Initialise the DMA
dma_reg[DMA_CS] = DMA_RESET;
udelay(10);
dma_reg[DMA_CS] = DMA_INT | DMA_END;
dma_reg[DMA_CONBLK_AD] = mem_virt_to_phys(cb_base);
dma_reg[DMA_DEBUG] = 7; // clear debug error flags
dma_reg[DMA_CS] = 0x10880001; // go, mid priority, wait for outstanding writes
if (delay_hw == DELAY_VIA_PCM) {
pcm_reg[PCM_CS_A] |= 1<<2; // Enable Tx
}
}
static void
do_status(const char *filename)
{
uint32_t last;
int status = -1;
char *f, *of, *p;
int fd;
const char *dma_dead = "ERROR: DMA not running\n";
if (!strlen(filename) || *filename == '\n') {
fprintf(stderr, "ERROR: A filename into which to write status information is required\n");
return;
}
if ((f = malloc(strlen(filename) + 1 )) == NULL)
fatal("servod: malloc() failed");
of = f;
strcpy(f, filename);
while (*f == ' ')
f++;
if (of + strlen(of) == f || *f == '\n') {
fprintf(stderr, "ERROR: Invalid filename '%.*s'\n", strlen(filename) - 1, filename);
free(of);
return;
}
p = f + strlen(f) - 1;
while (p > f && (*p == '\n' || *p == '\r' || *p == ' '))
*p-- = '\0';
if (!strlen(f)) {
fprintf(stderr, "ERROR: Invalid filename '%.*s'\n", strlen(filename) - 1, filename);
free(of);
return;
}
last = dma_reg[DMA_CONBLK_AD];
udelay(step_time_us*2);
if (dma_reg[DMA_CONBLK_AD] != last)
status = 0;
if ((fd = open(f, O_WRONLY|O_CREAT, 0666)) >= 0) {
if (status == 0)
write(fd, "OK\n", 3);
else
write(fd, dma_dead, strlen(dma_dead));
close(fd);
printf("INFO: Status information written to file '%s'\n", f);
} else {
fprintf(stderr, "ERROR: Failed to open %s for writing: %m\n", f);
}
free(of);
}
static void
do_debug(void)
{
int i;
uint32_t mask = 0;
uint32_t last;
last = dma_reg[DMA_CONBLK_AD];
udelay(step_time_us*2);
printf("%08x %08x\n", last, dma_reg[DMA_CONBLK_AD]);
printf("---------------------------\n");
printf("Servo Start Width TurnOn\n");
for (i = 0; i < MAX_SERVOS; i++) {
if (servo2gpio[i] != DMY) {
printf("%3d: %6d %6d %6d\n", i, servostart[i],
servowidth[i], !!turnon_mask[i]);
mask |= 1 << servo2gpio[i];
}
}
printf("\nData:\n");
last = 0xffffffff;
for (i = 0; i < num_samples; i++) {
uint32_t curr = turnoff_mask[i] & mask;
if (curr != last)
printf("@%5d: %08x\n", i, curr);
last = curr;
}
printf("---------------------------\n");
}
static int
parse_width(const int servo, const char *width_arg)
{
char *p, *digits, *od;
double width;
if ((digits = malloc(strlen(width_arg) + 1)) == NULL)
fatal("servod: malloc() failed");
od = digits;
strcpy(digits, width_arg);
if (*digits == '-' || *digits == '+') {
digits++;
}
if (*digits < '0' || *digits > '9') {
free(od);
return -1;
}
width = strtod(digits, &p);
if (*p == '\0') {
/* Specified in steps */
} else if (!strcmp(p, "us")) {
width /= step_time_us;
} else if (!strcmp(p, "%")) {
width = width * (servo_max_ticks - servo_min_ticks) / 100.0 + servo_min_ticks;
} else {
free(od);
return -1;
}
width = floor(width);
if (*od == '+') {
width = servowidth[servo] + width;
if (width > servo_max_ticks)
width = servo_max_ticks;
} else if (*od == '-') {
width = servowidth[servo] - width;
if (width < servo_min_ticks)
width = servo_min_ticks;
}
free(od);
if (width == 0) {
return (int)width;
} else if (width < servo_min_ticks || width > servo_max_ticks) {
return -1;
} else {
return (int)width;
}
}
static void
go_go_go(void)
{
int fd;
struct timeval tv;
static char line[128];
int nchars = 0;
if ((fd = open(DEVFILE, O_RDWR|O_NONBLOCK)) == -1)
fatal("servod: Failed to open %s: %m\n", DEVFILE);
for (;;) {
int n, width, servo;
fd_set ifds;
char width_arg[64];
FD_ZERO(&ifds);
FD_SET(fd, &ifds);
get_next_idle_timeout(&tv);
if ((n = select(fd+1, &ifds, NULL, NULL, &tv)) != 1)
continue;
while (read(fd, line+nchars, 1) == 1) {
if (line[nchars] == '\n') {
line[++nchars] = '\0';
nchars = 0;
if (line[0] == 'p' || line[0] == 'P') {
int hdr, pin, width;
n = sscanf(line+1, "%d-%d=%s", &hdr, &pin, width_arg);
if (n != 3) {
fprintf(stderr, "ERROR: Unknown command '%.*s'\n", strlen(line) - 1, line);
} else if (hdr != 1 && hdr != 5) {
fprintf(stderr, "ERROR: Invalid header 'P%d'\n", hdr);
} else if (pin < 1 ||
(hdr == 1 && pin > NUM_P1PINS) ||
(hdr == 5 && pin > NUM_P5PINS)) {
fprintf(stderr, "ERROR: Invalid pin number 'P%d-%d'\n", hdr, pin);
} else if ((hdr == 1 && p1pin2servo[pin] == DMY) ||
(hdr == 5 && p5pin2servo[pin] == DMY)) {
fprintf(stderr, "ERROR: Pin 'P%d-%d' is not mapped to a servo\n", hdr, pin);
} else {
if (hdr == 1) {
servo = p1pin2servo[pin];
} else {
servo = p5pin2servo[pin];
}
if ((width = parse_width(servo, width_arg)) < 0) {
fprintf(stderr, "ERROR: Invalid width '%s'\n", width_arg);
} else {
set_servo(servo, width);
}
}
} else {
n = sscanf(line, "%d=%s", &servo, width_arg);
if (!strcmp(line, "debug\n")) {
do_debug();
} else if (!strncmp(line, "status ", 7)) {
do_status(line + 7);
} else if (n != 2) {
fprintf(stderr, "ERROR: Unknown command '%.*s'\n", strlen(line) - 1, line);
} else if (servo < 0 || servo >= MAX_SERVOS) {
fprintf(stderr, "ERROR: Invalid servo number '%d'\n", servo);
} else if (servo2gpio[servo] == DMY) {
fprintf(stderr, "ERROR: Servo '%d' is not mapped to a GPIO pin\n", servo);
} else if ((width = parse_width(servo, width_arg)) < 0) {
fprintf(stderr, "ERROR: Invalid width '%s'\n", width_arg);
} else {
set_servo(servo, width);
}
}
} else {
if (++nchars >= 126) {
fprintf(stderr, "ERROR: Input too long '%s'\n", line);
nchars = 0;
}
}
}
}
}
/* Extract board revision from /proc/cpuinfo, and from that determine the
* mem_flag to use, and what the GPIO config is (26 pins, 40 pins, whether
* there is a separate P5 GPIO header). Query the bcm library for SDRAM
* and peripheral base addresses.
*/
static void
get_model_and_revision(void)
{