Skip to contentSkip to conversation

LinuxPPS - definitive version

PATCH In review Rodolfo Giometti 8 participants 43 messages Jul 17, 2007 – Aug 1, 2007

Subsystems (6)
lore
Share & tools
lore

Rodolfo Giometti

author maintainer
#0 lore raw

PATCH 1/1 LinuxPPS - definitive version

Hello,

here my last patch for PPS support.

In my opinion it should be ok for inclusion... please, let me know if something should be still changed.

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
Documentation/pps/Makefile new file +27 -0
new file mode 100644
index 0000000..a2660a2
@@ -0,0 +1,27 @@
+TARGETS = ppstest ppsctl
+
+CFLAGS += -Wall -O2 -D_GNU_SOURCE
+CFLAGS += -I .
+CFLAGS += -ggdb
+
+# -- Actions section ----------------------------------------------------------
+
+.PHONY : all depend dep
+
+all : .depend $(TARGETS)
+
+.depend depend dep :
+	$(CC) $(CFLAGS) -M $(TARGETS:=.c) > .depend
+
+ifeq (.depend,$(wildcard .depend))
+include .depend
+endif
+
+
+# -- Clean section ------------------------------------------------------------
+
+.PHONY : clean
+
+clean :
+	rm -f *.o *~ core .depend
+	rm -f ${TARGETS}
Documentation/pps/pps.txt new file +211 -0

212 lines not on this page · raw message

Documentation/pps/ppsctl.c new file +61 -0

61 lines not on this page · raw message

Documentation/pps/ppstest.c new file +199 -0

199 lines not on this page · raw message

Documentation/pps/timepps.h new file +236 -0

236 lines not on this page · raw message

MAINTAINERS +7 -0
index df40a4e..17e9a02 100644
@@ -2903,6 +2903,13 @@ P:	Michal Ostrowski
 M:	[email protected]
 S:	Maintained
 
+PPS SUPPORT
+P:	Rodolfo Giometti
+M:	[email protected]
+W:	http://wiki.enneenne.com/index.php/LinuxPPS_support
+L:	[email protected]
+S:	Maintained
+
 PREEMPTIBLE KERNEL
 P:	Robert Love
 M:	[email protected]
arch/i386/kernel/syscall_table.S +5 -0
index bf6adce..f1bf4ff 100644
@@ -323,3 +323,8 @@ ENTRY(sys_call_table)
 	.long sys_signalfd
 	.long sys_timerfd
 	.long sys_eventfd
+	.long sys_time_pps_cmd
+	.long sys_time_pps_getparams	/* 325 */
+	.long sys_time_pps_setparams
+	.long sys_time_pps_getcap
+	.long sys_time_pps_fetch
drivers/Kconfig +2 -0
index 050323f..bb54cab 100644
@@ -52,6 +52,8 @@ source "drivers/i2c/Kconfig"
 
 source "drivers/spi/Kconfig"
 
+source "drivers/pps/Kconfig"
+
 source "drivers/w1/Kconfig"
 
 source "drivers/hwmon/Kconfig"
drivers/Makefile +1 -0
index adad2f3..985d495 100644
@@ -60,6 +60,7 @@ obj-$(CONFIG_INPUT)		+= input/
 obj-$(CONFIG_I2O)		+= message/
 obj-$(CONFIG_RTC_LIB)		+= rtc/
 obj-y				+= i2c/
+obj-$(CONFIG_PPS)		+= pps/
 obj-$(CONFIG_W1)		+= w1/
 obj-$(CONFIG_HWMON)		+= hwmon/
 obj-$(CONFIG_PHONE)		+= telephony/
drivers/char/lp.c +58 -0

76 lines not on this page · raw message

drivers/pps/Kconfig new file +34 -0
new file mode 100644
index 0000000..1d16f14
@@ -0,0 +1,34 @@
+#
+# Character device configuration
+#
+
+menu "PPS support"
+
+config PPS
+	bool "PPS support"
+	depends on EXPERIMENTAL
+	---help---
+	  PPS (Pulse Per Second) is a special pulse provided by some GPS
+	  antennae. Userland can use it to get an high time reference.
+
+	  Some antennae's PPS signals are connected with the CD (Carrier
+	  Detect) pin of the serial line they use to communicate with the
+	  host. In this case use the SERIAL_LINE client support.
+
+	  Some antennae's PPS signals are connected with some special host
+	  inputs so you have to enable the corresponding client support.
+
+	  This PPS support can also be built as a module.  If so, the module
+	  will be called pps-core.
+
+config PPS_DEBUG
+	bool "PPS debugging messages"
+	depends on PPS 
+	help
+	  Say Y here if you want the PPS support to produce a bunch of debug
+	  messages to the system log.  Select this if you are having a
+	  problem with PPS support and want to see more of what is going on.
+
+source drivers/pps/clients/Kconfig
+
+endmenu
drivers/pps/Makefile new file +7 -0
new file mode 100644
index 0000000..76101cd
@@ -0,0 +1,7 @@
+#
+# Makefile for the PPS core.
+#
+
+pps_core-objs			+= pps.o kapi.o sysfs.o
+obj-$(CONFIG_PPS)		+= pps_core.o
+obj-y				+= clients/
drivers/pps/clients/Kconfig new file +30 -0
new file mode 100644
index 0000000..867df3a
@@ -0,0 +1,30 @@
+#
+# LinuxPPS clients configuration
+#
+
+if PPS
+
+comment "PPS clients support"
+
+config PPS_CLIENT_KTIMER
+	tristate "Kernel timer client (Testing client, use for debug)"
+	help
+	  If you say yes here you get support for a PPS debugging client
+	  which uses a kernel timer to generate the PPS signal.
+
+	  This driver can also be built as a module.  If so, the module
+	  will be called ktimer.o.
+
+config PPS_CLIENT_UART
+	bool "UART serial support"
+	help
+	  If you say yes here you get support for a PPS source connected
+	  with the CD (Carrier Detect) pin of your serial port.
+
+config PPS_CLIENT_LP
+	bool "Parallel printer support"
+	help
+	  If you say yes here you get support for a PPS source connected
+	  with the interrupt pin of your parallel port.
+
+endif
drivers/pps/clients/Makefile new file +6 -0
new file mode 100644
index 0000000..3ecca41
@@ -0,0 +1,6 @@
+#
+# Makefile for miscellaneous I2C chip drivers.
+#
+
+obj-$(CONFIG_PPS_CLIENT_KTIMER)	+= ktimer.o
+
drivers/pps/clients/ktimer.c new file +113 -0

113 lines not on this page · raw message

drivers/pps/kapi.c new file +215 -0

215 lines not on this page · raw message

drivers/pps/pps.c new file +398 -0

398 lines not on this page · raw message

drivers/pps/sysfs.c new file +217 -0

217 lines not on this page · raw message

drivers/serial/8250.c +2 -0
index c84dab0..0c9a307 100644
@@ -2101,6 +2101,8 @@ serial8250_set_termios(struct uart_port *port, struct ktermios *termios,
 		up->ier |= UART_IER_MSI;
 	if (up->capabilities & UART_CAP_UUE)
 		up->ier |= UART_IER_UUE | UART_IER_RTOIE;
+	if (up->port.flags & UPF_HARDPPS_CD)
+		up->ier |= UART_IER_MSI;	/* enable interrupts */
 
 	serial_out(up, UART_IER, up->ier);
 
drivers/serial/serial_core.c +68 -1

103 lines not on this page · raw message

include/asm-i386/unistd.h +6 -1
index e84ace1..36746dc 100644
@@ -329,10 +329,15 @@
 #define __NR_signalfd		321
 #define __NR_timerfd		322
 #define __NR_eventfd		323
+#define __NR_time_pps_cmd	324
+#define __NR_time_pps_getparams	325
+#define __NR_time_pps_setparams	326
+#define __NR_time_pps_getcap	327
+#define __NR_time_pps_fetch	328
 
 #ifdef __KERNEL__
 
-#define NR_syscalls 324
+#define NR_syscalls 329
 
 #define __ARCH_WANT_IPC_PARSE_VERSION
 #define __ARCH_WANT_OLD_READDIR
include/linux/Kbuild +1 -0
index f317c27..a10d20a 100644
@@ -293,6 +293,7 @@ unifdef-y += pmu.h
 unifdef-y += poll.h
 unifdef-y += ppp_defs.h
 unifdef-y += ppp-comp.h
+unifdef-y += pps.h
 unifdef-y += ptrace.h
 unifdef-y += qnx4_fs.h
 unifdef-y += quota.h
include/linux/parport.h +12 -0
index 9cdd694..f53d9f4 100644
@@ -100,6 +100,7 @@ typedef enum {
 #include <linux/proc_fs.h>
 #include <linux/spinlock.h>
 #include <linux/wait.h>
+#include <linux/pps.h>
 #include <asm/system.h>
 #include <asm/ptrace.h>
 #include <asm/semaphore.h>
@@ -327,6 +328,11 @@ struct parport {
 
 	struct list_head full_list;
 	struct parport *slaves[3];
+
+#ifdef CONFIG_PPS_CLIENT_LP
+	struct pps_source_info_s pps_info;
+	int pps_source;		/* PPS source ID */
+#endif
 };
 
 #define DEFAULT_SPIN_TIME 500 /* us */
@@ -517,6 +523,12 @@ extern int parport_daisy_select (struct parport *port, int daisy, int mode);
 /* Lowlevel drivers _can_ call this support function to handle irqs.  */
 static __inline__ void parport_generic_irq(int irq, struct parport *port)
 {
+#ifdef CONFIG_PPS_CLIENT_LP
+	pps_event(port->pps_source, PPS_CAPTUREASSERT, port);
+	pps_dbg("parport_pc: PPS assert event at %lu on source #%d",
+		jiffies, port->pps_source);
+#endif
+
 	parport_ieee1284_interrupt (irq, port);
 	read_lock(&port->cad_lock);
 	if (port->cad && port->cad->irq_func)
include/linux/pps.h new file +207 -0

207 lines not on this page · raw message

include/linux/serial_core.h +28 -5
index 7f2c99d..ba4503e 100644
@@ -153,6 +153,7 @@
 #include <linux/tty.h>
 #include <linux/mutex.h>
 #include <linux/sysrq.h>
+#include <linux/pps.h>
 
 struct uart_port;
 struct uart_info;
@@ -232,6 +233,9 @@ struct uart_port {
 	unsigned char		regshift;		/* reg offset shift */
 	unsigned char		iotype;			/* io access style */
 	unsigned char		unused1;
+#ifdef CONFIG_PPS_CLIENT_UART
+	int			pps_source;		/* PPS source ID */
+#endif
 
 #define UPIO_PORT		(0)
 #define UPIO_HUB6		(1)
@@ -276,7 +280,8 @@ struct uart_port {
 #define UPF_IOREMAP		((__force upf_t) (1 << 31))
 
 #define UPF_CHANGE_MASK		((__force upf_t) (0x17fff))
-#define UPF_USR_MASK		((__force upf_t) (UPF_SPD_MASK|UPF_LOW_LATENCY))
+#define UPF_USR_MASK		((__force upf_t) (UPF_SPD_MASK|UPF_LOW_LATENCY\
+							|UPF_HARDPPS_CD))
 
 	unsigned int		mctrl;			/* current modem ctrl settings */
 	unsigned int		timeout;		/* character-based timeout */
@@ -308,6 +313,10 @@ struct uart_state {
 	struct uart_info	*info;
 	struct uart_port	*port;
 
+#ifdef CONFIG_PPS_CLIENT_UART
+        struct pps_source_info_s pps_info;
+#endif
+
 	struct mutex		mutex;
 };
 
@@ -472,13 +481,27 @@ uart_handle_dcd_change(struct uart_port *port, unsigned int status)
 {
 	struct uart_info *info = port->info;
 
-	port->icount.dcd++;
+#ifdef CONFIG_PPS_CLIENT_UART
+	struct tty_driver *drv = port->info->tty->driver;
 
-#ifdef CONFIG_HARD_PPS
-	if ((port->flags & UPF_HARDPPS_CD) && status)
-		hardpps();
+	if (port->flags & UPF_HARDPPS_CD) {
+		if (status) {
+			pps_event(port->pps_source, PPS_CAPTUREASSERT, port);
+			pps_dbg("%s%d: PPS assert event at %lu on source #%d",
+				drv->driver_name, port->line,
+				jiffies, port->pps_source);
+		}
+		else {
+			pps_event(port->pps_source, PPS_CAPTURECLEAR, port);
+			pps_dbg("%s%d: PPS clear event at %lu on source #%d",
+				drv->driver_name, port->line,
+				jiffies, port->pps_source);
+		}
+	}
 #endif
 
+	port->icount.dcd++;
+
 	if (info->flags & UIF_CHECK_CD) {
 		if (status)
 			wake_up_interruptible(&info->open_wait);
include/linux/syscalls.h +10 -0
index 83d0ec1..bfc8899 100644
@@ -65,6 +65,7 @@ struct getcpu_cache;
 #include <asm/signal.h>
 #include <linux/quota.h>
 #include <linux/key.h>
+#include <linux/pps.h>
 
 asmlinkage long sys_time(time_t __user *tloc);
 asmlinkage long sys_stime(time_t __user *tptr);
@@ -611,6 +612,15 @@ asmlinkage long sys_timerfd(int ufd, int clockid, int flags,
 			    const struct itimerspec __user *utmr);
 asmlinkage long sys_eventfd(unsigned int count);
 
+asmlinkage long sys_time_pps_cmd(int cmd, void __user *arg);
+asmlinkage long sys_time_pps_getparams(int source,
+				       struct pps_kparams __user *params);
+asmlinkage long sys_time_pps_setparams(int source,
+				       const struct pps_kparams __user *params);
+asmlinkage long sys_time_pps_getcap(int source, int __user *mode);
+asmlinkage long sys_time_pps_fetch(int source, struct pps_kinfo __user *info,
+				       const struct pps_ktime __user *timeout);
+
 int kernel_execve(const char *filename, char *const argv[], char *const envp[]);
 
 #endif
kernel/sys_ni.c +7 -0
index 7e11e2c..e0fccc2 100644
@@ -148,3 +148,10 @@ cond_syscall(sys_timerfd);
 cond_syscall(compat_sys_signalfd);
 cond_syscall(compat_sys_timerfd);
 cond_syscall(sys_eventfd);
+
+/* PPS dependent */
+cond_syscall(sys_time_pps_find);
+cond_syscall(sys_time_pps_getparams);
+cond_syscall(sys_time_pps_setparams);
+cond_syscall(sys_time_pps_getcap);
+cond_syscall(sys_time_pps_fetch);
#1 lore raw
Quoted 6 lines · Rodolfo Giometti

Hello,

here my last patch for PPS support.

In my opinion it should be ok for inclusion... please, let me know if something should be still changed.

s/Documentaion/Documentation/ in the last line of Documentation/pps/pps.txt

Please feed it to scripts/checkpatch.pl -- you can ignore all the warnings about lines greater than 80 characters, and the complete crap about "declaring multiple variables together should be avoided", but some of what it points out is valid. Including the one about 'volatile' -- your explanation lacked credibility. If you really need 'volatile' then put it at the places you actually need it; not the declaration of the structure.

You've also reverted to structures which vary between 32-bit and 64-bit userspace, because they use 'long' and 'struct timespec', but you haven't provided the compat_* routines which are then necessary.

+typedef int pps_handle_t; /* represents a PPS source */
+typedef unsigned long pps_seq_t; /* sequence number */
+typedef struct ntp_fp ntp_fp_t; /* NTP-compatible time stamp */
+typedef union pps_timeu pps_timeu_t; /* generic data type to represent time s
tamps */
+typedef struct pps_info pps_info_t;
+typedef struct pps_params pps_params_t;

Don't do this for the structures. It's dubious enough for the integer types.

Signature · 1 line
dwmw2
author maintainer
#2 lore raw
Quoted 2 lines · David Woodhouse

s/Documentaion/Documentation/ in the last line of Documentation/pps/pps.txt

Fixed.

Quoted 4 lines

Please feed it to scripts/checkpatch.pl -- you can ignore all the warnings about lines greater than 80 characters, and the complete crap about "declaring multiple variables together should be avoided", but some of what it points out is valid. Including the one about 'volatile'

Ok, I'll do it.

Quoted 3 lines

-- your explanation lacked credibility. If you really need 'volatile' then put it at the places you actually need it; not the declaration of the structure.

About this debate, please, take a look at the pps_event() function:

void pps_event(int source, int event, void *data)

{
        struct timespec __ts;
        struct pps_ktime ts;

        /* First of all we get the time stamp... */
        getnstimeofday(&__ts);

        /* ... and translate it to PPS time data struct */
        ts.sec = __ts.tv_sec;
        ts.nsec = __ts.tv_nsec;

        if ((event & (PPS_CAPTUREASSERT | PPS_CAPTURECLEAR)) == 0 ) {
                pps_err("unknow event (%x) for source %d", event, source);
                return;
        }

        /* We wish not using locks at all into this function... a possible
         * solution is to check the "info" field against the pointer to
         * "dummy_info".
         * If "info" points to "dummy_info" we can return doing nothing since,
         * even if a new PPS source is registered by another CPU we can
         * safely not register current event.
         * If "info" points to a valid PPS source's info data we can continue
         * without problem since, even if current PPS source is deregistered
         * by another CPU, we still continue writing data into a valid area
         * (dummy_info).
         */
        if (pps_source[source].info == &dummy_info)
                return;

        /* Must call the echo function? */
        if ((pps_source[source].params.mode & (PPS_ECHOASSERT | PPS_ECHOCLEAR)))
                pps_source[source].info->echo(source, event, data);

        /* Check the event */
        pps_source[source].current_mode = pps_source[source].params.mode;
        if (event & PPS_CAPTUREASSERT) {
                /* We have to add an offset? */
                if (pps_source[source].params.mode & PPS_OFFSETASSERT)
                        pps_add_offset(&ts,
                                &pps_source[source].params.assert_off_tu);

                /* Save the time stamp */
                pps_source[source].assert_tu = ts;
                pps_source[source].assert_sequence++;
                pps_dbg("capture assert seq #%u for source %d",
                        pps_source[source].assert_sequence, source);
        }
        if (event & PPS_CAPTURECLEAR) {
                /* We have to add an offset? */
                if (pps_source[source].params.mode & PPS_OFFSETCLEAR)
                        pps_add_offset(&ts,
                                &pps_source[source].params.clear_off_tu);

                /* Save the time stamp */
                pps_source[source].clear_tu = ts;
                pps_source[source].clear_sequence++;
                pps_dbg("capture clear seq #%u for source %d",
                        pps_source[source].clear_sequence, source);
        }

        pps_source[source].go = ~0;
        wake_up_interruptible(&pps_source[source].queue);
}

The problems should arise at:

	if (pps_source[source].info == &dummy_info)
		return;

but as explained into the comment there should be no problems at all...

About "where" to put the "volatile" attribute I don't understand what you mean... such attribute is needed (IMHO) for "assert_sequence"&C, where should I put it? :-o

Quoted 3 lines

You've also reverted to structures which vary between 32-bit and 64-bit userspace, because they use 'long' and 'struct timespec', but you haven't provided the compat_* routines which are then necessary.

As already suggested I used fixed size variables. See the new struct "struct pps_ktime".

Quoted 10 lines
Documentation/pps/timepps.h new file +4 -0
+typedef int pps_handle_t;              /* represents a PPS source */
+typedef unsigned long pps_seq_t;       /* sequence number */
+typedef struct ntp_fp ntp_fp_t;                /* NTP-compatible time stamp */
+typedef union pps_timeu pps_timeu_t;   /* generic data type to represent time s

tamps */

Documentation/pps/timepps.h new file +2 -0
+typedef struct pps_info pps_info_t;    
+typedef struct pps_params pps_params_t;

Don't do this for the structures. It's dubious enough for the integer types.

Such code is for userland since RFC2783 requires such types... I moved all userland code into Documentation/pps/timepps.h which can be used by userland programs whose require RFC compatibility.

I'll post a new patch ASAP.

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#3 lore raw
In reply to David Woodhouse
Quoted 4 lines · On Mon, 23 Jul 2007 14:35:16 +0100 David Woodhouse <[email protected]> wrote:

Please feed it to scripts/checkpatch.pl -- you can ignore all the warnings about lines greater than 80 characters, and the complete crap about "declaring multiple variables together should be avoided", but some of what it points out is valid.

The above are David's opinions. Many, probably most kernel developers do not agree with them.

And there are good reasons for ignoring David's opinions here. To understand those reasons, try looking at some MTD code.

#4 lore raw
Quoted 10 lines · Andrew Morton
Quoted 4 lines · On Mon, 23 Jul 2007 14:35:16 +0100 David Woodhouse <[email protected]> wrote:

Please feed it to scripts/checkpatch.pl -- you can ignore all the warnings about lines greater than 80 characters, and the complete crap about "declaring multiple variables together should be avoided", but some of what it points out is valid.

The above are David's opinions. Many, probably most kernel developers do not agree with them.

Linus called the 80-column thing a 'Nazi dream' and I'm inclined to agree with him. It's something to bear in mind, of course, but sometimes it's best ignored.

And the 'declaring multiple variables together' is something I've _never_ heard of. Might be applicable if you're actually giving them initial values, but just declaring them together is fine, surely?

Signature · 1 line
dwmw2
author maintainer
#5 lore raw
In reply to David Woodhouse
Quoted 2 lines · David Woodhouse

s/Documentaion/Documentation/ in the last line of Documentation/pps/pps.txt

Fixed.

Quoted 3 lines

Please feed it to scripts/checkpatch.pl -- you can ignore all the warnings about lines greater than 80 characters, and the complete crap about "declaring multiple variables together should be avoided", but

Done. Most fixed.

Quoted 4 lines

some of what it points out is valid. Including the one about 'volatile' -- your explanation lacked credibility. If you really need 'volatile' then put it at the places you actually need it; not the declaration of the structure.

Can you please explain better where should I put the 'volatile' attribute? :-o

Quoted 3 lines

You've also reverted to structures which vary between 32-bit and 64-bit userspace, because they use 'long' and 'struct timespec', but you haven't provided the compat_* routines which are then necessary.

This should be not needed due new 'struct pps_ktime'.

Quoted 10 lines
(quoted diff) +4 -0
+typedef int pps_handle_t;              /* represents a PPS source */
+typedef unsigned long pps_seq_t;       /* sequence number */
+typedef struct ntp_fp ntp_fp_t;                /* NTP-compatible time stamp */
+typedef union pps_timeu pps_timeu_t;   /* generic data type to represent time s

tamps */

(quoted diff) +2 -0
+typedef struct pps_info pps_info_t;    
+typedef struct pps_params pps_params_t;

Don't do this for the structures. It's dubious enough for the integer types.

These typedefs are into timepps.h which is an userland file (located into Documentation/pps/) and are requested by the RFC.

Attached you can find my last patch.

Thanks again,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
Documentation/pps/Makefile new file +27 -0
new file mode 100644
index 0000000..a2660a2
@@ -0,0 +1,27 @@
+TARGETS = ppstest ppsctl
+
+CFLAGS += -Wall -O2 -D_GNU_SOURCE
+CFLAGS += -I .
+CFLAGS += -ggdb
+
+# -- Actions section ----------------------------------------------------------
+
+.PHONY : all depend dep
+
+all : .depend $(TARGETS)
+
+.depend depend dep :
+	$(CC) $(CFLAGS) -M $(TARGETS:=.c) > .depend
+
+ifeq (.depend,$(wildcard .depend))
+include .depend
+endif
+
+
+# -- Clean section ------------------------------------------------------------
+
+.PHONY : clean
+
+clean :
+	rm -f *.o *~ core .depend
+	rm -f ${TARGETS}
Documentation/pps/pps.txt new file +211 -0

211 lines not on this page · raw message

Documentation/pps/ppsctl.c new file +61 -0

61 lines not on this page · raw message

Documentation/pps/ppstest.c new file +201 -0

201 lines not on this page · raw message

Documentation/pps/timepps.h new file +234 -0

234 lines not on this page · raw message

MAINTAINERS +7 -0
index df40a4e..17e9a02 100644
@@ -2903,6 +2903,13 @@ P:	Michal Ostrowski
 M:	[email protected]
 S:	Maintained
 
+PPS SUPPORT
+P:	Rodolfo Giometti
+M:	[email protected]
+W:	http://wiki.enneenne.com/index.php/LinuxPPS_support
+L:	[email protected]
+S:	Maintained
+
 PREEMPTIBLE KERNEL
 P:	Robert Love
 M:	[email protected]
arch/i386/kernel/syscall_table.S +5 -0
index bf6adce..f1bf4ff 100644
@@ -323,3 +323,8 @@ ENTRY(sys_call_table)
 	.long sys_signalfd
 	.long sys_timerfd
 	.long sys_eventfd
+	.long sys_time_pps_cmd
+	.long sys_time_pps_getparams	/* 325 */
+	.long sys_time_pps_setparams
+	.long sys_time_pps_getcap
+	.long sys_time_pps_fetch
drivers/Kconfig +2 -0
index 050323f..bb54cab 100644
@@ -52,6 +52,8 @@ source "drivers/i2c/Kconfig"
 
 source "drivers/spi/Kconfig"
 
+source "drivers/pps/Kconfig"
+
 source "drivers/w1/Kconfig"
 
 source "drivers/hwmon/Kconfig"
drivers/Makefile +1 -0
index adad2f3..985d495 100644
@@ -60,6 +60,7 @@ obj-$(CONFIG_INPUT)		+= input/
 obj-$(CONFIG_I2O)		+= message/
 obj-$(CONFIG_RTC_LIB)		+= rtc/
 obj-y				+= i2c/
+obj-$(CONFIG_PPS)		+= pps/
 obj-$(CONFIG_W1)		+= w1/
 obj-$(CONFIG_HWMON)		+= hwmon/
 obj-$(CONFIG_PHONE)		+= telephony/
drivers/char/lp.c +58 -0

76 lines not on this page · raw message

drivers/pps/Kconfig new file +31 -0
new file mode 100644
index 0000000..a00b59a
@@ -0,0 +1,31 @@
+#
+# PPS support configuration
+#
+
+menu "PPS support"
+
+config PPS
+	bool "PPS support"
+	depends on EXPERIMENTAL
+	---help---
+	  PPS (Pulse Per Second) is a special pulse provided by some GPS
+	  antennae. Userland can use it to get an high time reference.
+
+	  Some antennae's PPS signals are connected with the CD (Carrier
+	  Detect) pin of the serial line they use to communicate with the
+	  host. In this case use the SERIAL_LINE client support.
+
+	  Some antennae's PPS signals are connected with some special host
+	  inputs so you have to enable the corresponding client support.
+
+config PPS_DEBUG
+	bool "PPS debugging messages"
+	depends on PPS 
+	help
+	  Say Y here if you want the PPS support to produce a bunch of debug
+	  messages to the system log.  Select this if you are having a
+	  problem with PPS support and want to see more of what is going on.
+
+source drivers/pps/clients/Kconfig
+
+endmenu
drivers/pps/Makefile new file +7 -0
new file mode 100644
index 0000000..76101cd
@@ -0,0 +1,7 @@
+#
+# Makefile for the PPS core.
+#
+
+pps_core-objs			+= pps.o kapi.o sysfs.o
+obj-$(CONFIG_PPS)		+= pps_core.o
+obj-y				+= clients/
drivers/pps/clients/Kconfig new file +30 -0
new file mode 100644
index 0000000..58a1e55
@@ -0,0 +1,30 @@
+#
+# PPS clients configuration
+#
+
+if PPS
+
+comment "PPS clients support"
+
+config PPS_CLIENT_KTIMER
+	tristate "Kernel timer client (Testing client, use for debug)"
+	help
+	  If you say yes here you get support for a PPS debugging client
+	  which uses a kernel timer to generate the PPS signal.
+
+	  This driver can also be built as a module.  If so, the module
+	  will be called ktimer.ko.
+
+config PPS_CLIENT_UART
+	bool "UART serial support"
+	help
+	  If you say yes here you get support for a PPS source connected
+	  with the CD (Carrier Detect) pin of your serial port.
+
+config PPS_CLIENT_LP
+	bool "Parallel printer support"
+	help
+	  If you say yes here you get support for a PPS source connected
+	  with the interrupt pin of your parallel port.
+
+endif
drivers/pps/clients/Makefile new file +6 -0
new file mode 100644
index 0000000..10d1dfa
@@ -0,0 +1,6 @@
+#
+# Makefile for PPS clients.
+#
+
+obj-$(CONFIG_PPS_CLIENT_KTIMER)	+= ktimer.o
+
drivers/pps/clients/ktimer.c new file +114 -0

114 lines not on this page · raw message

drivers/pps/kapi.c new file +215 -0

215 lines not on this page · raw message

drivers/pps/pps.c new file +398 -0

398 lines not on this page · raw message

drivers/pps/sysfs.c new file +217 -0

217 lines not on this page · raw message

drivers/serial/8250.c +2 -0
index c84dab0..0c9a307 100644
@@ -2101,6 +2101,8 @@ serial8250_set_termios(struct uart_port *port, struct ktermios *termios,
 		up->ier |= UART_IER_MSI;
 	if (up->capabilities & UART_CAP_UUE)
 		up->ier |= UART_IER_UUE | UART_IER_RTOIE;
+	if (up->port.flags & UPF_HARDPPS_CD)
+		up->ier |= UART_IER_MSI;	/* enable interrupts */
 
 	serial_out(up, UART_IER, up->ier);
 
drivers/serial/serial_core.c +69 -1

104 lines not on this page · raw message

include/asm-i386/unistd.h +6 -1
index e84ace1..36746dc 100644
@@ -329,10 +329,15 @@
 #define __NR_signalfd		321
 #define __NR_timerfd		322
 #define __NR_eventfd		323
+#define __NR_time_pps_cmd	324
+#define __NR_time_pps_getparams	325
+#define __NR_time_pps_setparams	326
+#define __NR_time_pps_getcap	327
+#define __NR_time_pps_fetch	328
 
 #ifdef __KERNEL__
 
-#define NR_syscalls 324
+#define NR_syscalls 329
 
 #define __ARCH_WANT_IPC_PARSE_VERSION
 #define __ARCH_WANT_OLD_READDIR
include/linux/Kbuild +1 -0
index f317c27..a10d20a 100644
@@ -293,6 +293,7 @@ unifdef-y += pmu.h
 unifdef-y += poll.h
 unifdef-y += ppp_defs.h
 unifdef-y += ppp-comp.h
+unifdef-y += pps.h
 unifdef-y += ptrace.h
 unifdef-y += qnx4_fs.h
 unifdef-y += quota.h
include/linux/parport.h +12 -0
index 9cdd694..f53d9f4 100644
@@ -100,6 +100,7 @@ typedef enum {
 #include <linux/proc_fs.h>
 #include <linux/spinlock.h>
 #include <linux/wait.h>
+#include <linux/pps.h>
 #include <asm/system.h>
 #include <asm/ptrace.h>
 #include <asm/semaphore.h>
@@ -327,6 +328,11 @@ struct parport {
 
 	struct list_head full_list;
 	struct parport *slaves[3];
+
+#ifdef CONFIG_PPS_CLIENT_LP
+	struct pps_source_info_s pps_info;
+	int pps_source;		/* PPS source ID */
+#endif
 };
 
 #define DEFAULT_SPIN_TIME 500 /* us */
@@ -517,6 +523,12 @@ extern int parport_daisy_select (struct parport *port, int daisy, int mode);
 /* Lowlevel drivers _can_ call this support function to handle irqs.  */
 static __inline__ void parport_generic_irq(int irq, struct parport *port)
 {
+#ifdef CONFIG_PPS_CLIENT_LP
+	pps_event(port->pps_source, PPS_CAPTUREASSERT, port);
+	pps_dbg("parport_pc: PPS assert event at %lu on source #%d",
+		jiffies, port->pps_source);
+#endif
+
 	parport_ieee1284_interrupt (irq, port);
 	read_lock(&port->cad_lock);
 	if (port->cad && port->cad->irq_func)
include/linux/pps.h new file +207 -0

207 lines not on this page · raw message

include/linux/serial_core.h +27 -5
index 7f2c99d..654ad19 100644
@@ -153,6 +153,7 @@
 #include <linux/tty.h>
 #include <linux/mutex.h>
 #include <linux/sysrq.h>
+#include <linux/pps.h>
 
 struct uart_port;
 struct uart_info;
@@ -232,6 +233,9 @@ struct uart_port {
 	unsigned char		regshift;		/* reg offset shift */
 	unsigned char		iotype;			/* io access style */
 	unsigned char		unused1;
+#ifdef CONFIG_PPS_CLIENT_UART
+	int			pps_source;		/* PPS source ID */
+#endif
 
 #define UPIO_PORT		(0)
 #define UPIO_HUB6		(1)
@@ -276,7 +280,8 @@ struct uart_port {
 #define UPF_IOREMAP		((__force upf_t) (1 << 31))
 
 #define UPF_CHANGE_MASK		((__force upf_t) (0x17fff))
-#define UPF_USR_MASK		((__force upf_t) (UPF_SPD_MASK|UPF_LOW_LATENCY))
+#define UPF_USR_MASK		((__force upf_t) (UPF_SPD_MASK|UPF_LOW_LATENCY\
+							|UPF_HARDPPS_CD))
 
 	unsigned int		mctrl;			/* current modem ctrl settings */
 	unsigned int		timeout;		/* character-based timeout */
@@ -308,6 +313,10 @@ struct uart_state {
 	struct uart_info	*info;
 	struct uart_port	*port;
 
+#ifdef CONFIG_PPS_CLIENT_UART
+	struct pps_source_info_s pps_info;
+#endif
+
 	struct mutex		mutex;
 };
 
@@ -472,13 +481,26 @@ uart_handle_dcd_change(struct uart_port *port, unsigned int status)
 {
 	struct uart_info *info = port->info;
 
-	port->icount.dcd++;
+#ifdef CONFIG_PPS_CLIENT_UART
+	struct tty_driver *drv = port->info->tty->driver;
 
-#ifdef CONFIG_HARD_PPS
-	if ((port->flags & UPF_HARDPPS_CD) && status)
-		hardpps();
+	if (port->flags & UPF_HARDPPS_CD) {
+		if (status) {
+			pps_event(port->pps_source, PPS_CAPTUREASSERT, port);
+			pps_dbg("%s%d: PPS assert event at %lu on source #%d",
+				drv->driver_name, port->line,
+				jiffies, port->pps_source);
+		} else {
+			pps_event(port->pps_source, PPS_CAPTURECLEAR, port);
+			pps_dbg("%s%d: PPS clear event at %lu on source #%d",
+				drv->driver_name, port->line,
+				jiffies, port->pps_source);
+		}
+	}
 #endif
 
+	port->icount.dcd++;
+
 	if (info->flags & UIF_CHECK_CD) {
 		if (status)
 			wake_up_interruptible(&info->open_wait);
include/linux/syscalls.h +10 -0
index 83d0ec1..bfc8899 100644
@@ -65,6 +65,7 @@ struct getcpu_cache;
 #include <asm/signal.h>
 #include <linux/quota.h>
 #include <linux/key.h>
+#include <linux/pps.h>
 
 asmlinkage long sys_time(time_t __user *tloc);
 asmlinkage long sys_stime(time_t __user *tptr);
@@ -611,6 +612,15 @@ asmlinkage long sys_timerfd(int ufd, int clockid, int flags,
 			    const struct itimerspec __user *utmr);
 asmlinkage long sys_eventfd(unsigned int count);
 
+asmlinkage long sys_time_pps_cmd(int cmd, void __user *arg);
+asmlinkage long sys_time_pps_getparams(int source,
+				       struct pps_kparams __user *params);
+asmlinkage long sys_time_pps_setparams(int source,
+				       const struct pps_kparams __user *params);
+asmlinkage long sys_time_pps_getcap(int source, int __user *mode);
+asmlinkage long sys_time_pps_fetch(int source, struct pps_kinfo __user *info,
+				       const struct pps_ktime __user *timeout);
+
 int kernel_execve(const char *filename, char *const argv[], char *const envp[]);
 
 #endif
kernel/sys_ni.c +7 -0
index 7e11e2c..e0fccc2 100644
@@ -148,3 +148,10 @@ cond_syscall(sys_timerfd);
 cond_syscall(compat_sys_signalfd);
 cond_syscall(compat_sys_timerfd);
 cond_syscall(sys_eventfd);
+
+/* PPS dependent */
+cond_syscall(sys_time_pps_find);
+cond_syscall(sys_time_pps_getparams);
+cond_syscall(sys_time_pps_setparams);
+cond_syscall(sys_time_pps_getcap);
+cond_syscall(sys_time_pps_fetch);
#6 lore raw
Quoted 5 lines · Rodolfo Giometti
Quoted 2 lines · David Woodhouse

s/Documentaion/Documentation/ in the last line of Documentation/pps/pps.txt

Fixed.

Also 's/unknow /unknown /' (2 instances)

Quoted 5 lines
Quoted 3 lines

Please feed it to scripts/checkpatch.pl -- you can ignore all the warnings about lines greater than 80 characters, and the complete crap about "declaring multiple variables together should be avoided", but

Done. Most fixed.

Looks better.

Quoted 7 lines
Quoted 4 lines

some of what it points out is valid. Including the one about 'volatile' -- your explanation lacked credibility. If you really need 'volatile' then put it at the places you actually need it; not the declaration of the structure.

Can you please explain better where should I put the 'volatile' attribute? :-o

Am I right in thinking that the only place it matters is within pps_event()? In that case, at the very least you should probably remove the 'volatile' from the definition of the structure, and _cast_ to volatile where you want it treated that way.

But I don't see why you can't protect it with a spinlock. As long as you acquire that spinlock _after_ your call to getnstimeofday() what's the problem?

Quoted 5 lines
Quoted 1 line

...

This should be not needed due new 'struct pps_ktime'.

Quoted 1 line

...

These typedefs are into timepps.h which is an userland file (located into Documentation/pps/) and are requested by the RFC.

Sorry, yes. I shouldn't have been looking at that as if it was kernel code.

I think you still haven't quite got the 32-bit vs. 64-bit compatibility right. Remember that on i386, the alignment of a uint64_t is only 4 bytes, while on most other architectures it's 8 bytes. On i386, there will be no padding between the two consecutive 'struct pps_ktime' members of struct pps_kinfo and struct pps_kparams. But on most platforms there will be padding to ensure correct alignment.

The simple fix is probably to make the 'nsec' member a 64-bit integer too. Then it'll be the same for i386 and x86_64 and you won't need a compatibility syscall routine.

In order for your handling of 'pps_source[source].info' to be safe with respect to pps_unregister_source(), you have to guarantee that pps_event() has finished -- and can't be in progress on another CPU -- by the time your client's call to pps_unregister_source() completes. At first glance I think your existing clients have that right (you have del_timer_sync() before pps_unregister_source() in ktimer.c, for example). But you should make sure it's clearly documented for new clients.

Shouldn't your PPS_CLIENT_LP and PPS_CLIENT_UART options depend on PARPORT and SERIAL_CORE respectively?

Signature · 1 line
dwmw2
author maintainer
#7 lore raw
Quoted 1 line · David Woodhouse

Also 's/unknow /unknown /' (2 instances)

?? I didn't find them:

   $ grep 'unknow ' Documentation/pps/pps.txt
Quoted 4 lines

Am I right in thinking that the only place it matters is within pps_event()? In that case, at the very least you should probably remove the 'volatile' from the definition of the structure, and _cast_ to volatile where you want it treated that way.

Ok, I see.

Quoted 3 lines

But I don't see why you can't protect it with a spinlock. As long as you acquire that spinlock _after_ your call to getnstimeofday() what's the problem?

The problem is that we can have several PPS sources into a system and all these sources will arise their IRQ line (quasi)simultaneously and I don't wish a CPU may delay one of these IRQ handler due a spinlock into the pps_event().

That's why I'm trying to avoid any lock into pps_event().

Quoted 10 lines

I think you still haven't quite got the 32-bit vs. 64-bit compatibility right. Remember that on i386, the alignment of a uint64_t is only 4 bytes, while on most other architectures it's 8 bytes. On i386, there will be no padding between the two consecutive 'struct pps_ktime' members of struct pps_kinfo and struct pps_kparams. But on most platforms there will be padding to ensure correct alignment.

The simple fix is probably to make the 'nsec' member a 64-bit integer too. Then it'll be the same for i386 and x86_64 and you won't need a compatibility syscall routine.

Ok. I'll add your comment too.

Quoted 8 lines

In order for your handling of 'pps_source[source].info' to be safe with respect to pps_unregister_source(), you have to guarantee that pps_event() has finished -- and can't be in progress on another CPU -- by the time your client's call to pps_unregister_source() completes. At first glance I think your existing clients have that right (you have del_timer_sync() before pps_unregister_source() in ktimer.c, for example). But you should make sure it's clearly documented for new clients.

This can be done only with locks, but it's not necessary since even if a pps_unregister_source() runs while pps_event() executes on another CPU the latter will write always on a valid area (even if it could be a dummy one) and the data are not corrupted (note also that the data will be, in any case, discarted since we are executing a pps_unregister_source()).

Quoted 2 lines

Shouldn't your PPS_CLIENT_LP and PPS_CLIENT_UART options depend on PARPORT and SERIAL_CORE respectively?

No. These options can be enabled but if no serial/parallel driver is loaded no PPS source is registered.

Thanks,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#8 lore raw
Quoted 6 lines · Rodolfo Giometti

The problem is that we can have several PPS sources into a system and all these sources will arise their IRQ line (quasi)simultaneously and I don't wish a CPU may delay one of these IRQ handler due a spinlock into the pps_event().

That's why I'm trying to avoid any lock into pps_event().

The spinlock really wouldn't be held for long. It really shouldn't be a problem, and it shouldn't hold up your timings at all. And presumably you'd have a _different_ spinlock for each source, so they wouldn't stomp on each other at all.

Signature · 1 line
dwmw2
#9 lore raw
In reply to Rodolfo Giometti
Quoted 7 lines · Rodolfo Giometti
Quoted 1 line · David Woodhouse

Also 's/unknow /unknown /' (2 instances)

?? I didn't find them:

   $ grep 'unknow ' Documentation/pps/pps.txt

Elsewhere in the patch.

Quoted 9 lines
Quoted 8 lines

In order for your handling of 'pps_source[source].info' to be safe with respect to pps_unregister_source(), you have to guarantee that pps_event() has finished -- and can't be in progress on another CPU -- by the time your client's call to pps_unregister_source() completes. At first glance I think your existing clients have that right (you have del_timer_sync() before pps_unregister_source() in ktimer.c, for example). But you should make sure it's clearly documented for new clients.

Quoted 6 lines

This can be done only with locks, but it's not necessary since even if a pps_unregister_source() runs while pps_event() executes on another CPU the latter will write always on a valid area (even if it could be a dummy one) and the data are not corrupted (note also that the data will be, in any case, discarted since we are executing a pps_unregister_source()).

Read Documentation/memory-barriers.txt

There is a tiny but possibly non-zero chance that one CPU could be in pps_event() and might not yet have 'seen' the change to the .info field. Releasing the pps_mutex provides a write-barrier on the CPU which runs pps_unregister_source(), but there's no corresponding read-barrier on the CPU running pps_event(). You have to be careful about when pps_event() is run. It _MUST_ not touch the old info structure after pps_unregister_source() has completed.

At the moment, I think it's OK because you won't be calling pps_event() at the wrong times. But you do need to make sure that requirement is documented. And I think you can remove the whole dummy_info thing because it's not necessary.

Signature · 1 line
dwmw2
author maintainer
#10 lore raw
Quoted 2 lines · David Woodhouse

Elsewhere in the patch.

Got, thanks.

Quoted 10 lines

Read Documentation/memory-barriers.txt

There is a tiny but possibly non-zero chance that one CPU could be in pps_event() and might not yet have 'seen' the change to the .info field. Releasing the pps_mutex provides a write-barrier on the CPU which runs pps_unregister_source(), but there's no corresponding read-barrier on the CPU running pps_event(). You have to be careful about when pps_event() is run. It _MUST_ not touch the old info structure after pps_unregister_source() has completed.

Quoted 4 lines

At the moment, I think it's OK because you won't be calling pps_event() at the wrong times. But you do need to make sure that requirement is documented. And I think you can remove the whole dummy_info thing because it's not necessary.

What about this new solution involving tasklets? The pps_event() now just records data and then a tasklet do the data management job. :)

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
Documentation/pps/Makefile new file +27 -0
new file mode 100644
index 0000000..a2660a2
@@ -0,0 +1,27 @@
+TARGETS = ppstest ppsctl
+
+CFLAGS += -Wall -O2 -D_GNU_SOURCE
+CFLAGS += -I .
+CFLAGS += -ggdb
+
+# -- Actions section ----------------------------------------------------------
+
+.PHONY : all depend dep
+
+all : .depend $(TARGETS)
+
+.depend depend dep :
+	$(CC) $(CFLAGS) -M $(TARGETS:=.c) > .depend
+
+ifeq (.depend,$(wildcard .depend))
+include .depend
+endif
+
+
+# -- Clean section ------------------------------------------------------------
+
+.PHONY : clean
+
+clean :
+	rm -f *.o *~ core .depend
+	rm -f ${TARGETS}
Documentation/pps/pps.txt new file +211 -0

211 lines not on this page · raw message

Documentation/pps/ppsctl.c new file +61 -0

61 lines not on this page · raw message

Documentation/pps/ppstest.c new file +201 -0

201 lines not on this page · raw message

Documentation/pps/timepps.h new file +234 -0

234 lines not on this page · raw message

MAINTAINERS +7 -0
index df40a4e..17e9a02 100644
@@ -2903,6 +2903,13 @@ P:	Michal Ostrowski
 M:	[email protected]
 S:	Maintained
 
+PPS SUPPORT
+P:	Rodolfo Giometti
+M:	[email protected]
+W:	http://wiki.enneenne.com/index.php/LinuxPPS_support
+L:	[email protected]
+S:	Maintained
+
 PREEMPTIBLE KERNEL
 P:	Robert Love
 M:	[email protected]
arch/i386/kernel/syscall_table.S +5 -0
index bf6adce..f1bf4ff 100644
@@ -323,3 +323,8 @@ ENTRY(sys_call_table)
 	.long sys_signalfd
 	.long sys_timerfd
 	.long sys_eventfd
+	.long sys_time_pps_cmd
+	.long sys_time_pps_getparams	/* 325 */
+	.long sys_time_pps_setparams
+	.long sys_time_pps_getcap
+	.long sys_time_pps_fetch
drivers/Kconfig +2 -0
index 050323f..bb54cab 100644
@@ -52,6 +52,8 @@ source "drivers/i2c/Kconfig"
 
 source "drivers/spi/Kconfig"
 
+source "drivers/pps/Kconfig"
+
 source "drivers/w1/Kconfig"
 
 source "drivers/hwmon/Kconfig"
drivers/Makefile +1 -0
index adad2f3..985d495 100644
@@ -60,6 +60,7 @@ obj-$(CONFIG_INPUT)		+= input/
 obj-$(CONFIG_I2O)		+= message/
 obj-$(CONFIG_RTC_LIB)		+= rtc/
 obj-y				+= i2c/
+obj-$(CONFIG_PPS)		+= pps/
 obj-$(CONFIG_W1)		+= w1/
 obj-$(CONFIG_HWMON)		+= hwmon/
 obj-$(CONFIG_PHONE)		+= telephony/
drivers/char/lp.c +58 -0

76 lines not on this page · raw message

drivers/pps/Kconfig new file +31 -0
new file mode 100644
index 0000000..a00b59a
@@ -0,0 +1,31 @@
+#
+# PPS support configuration
+#
+
+menu "PPS support"
+
+config PPS
+	bool "PPS support"
+	depends on EXPERIMENTAL
+	---help---
+	  PPS (Pulse Per Second) is a special pulse provided by some GPS
+	  antennae. Userland can use it to get an high time reference.
+
+	  Some antennae's PPS signals are connected with the CD (Carrier
+	  Detect) pin of the serial line they use to communicate with the
+	  host. In this case use the SERIAL_LINE client support.
+
+	  Some antennae's PPS signals are connected with some special host
+	  inputs so you have to enable the corresponding client support.
+
+config PPS_DEBUG
+	bool "PPS debugging messages"
+	depends on PPS 
+	help
+	  Say Y here if you want the PPS support to produce a bunch of debug
+	  messages to the system log.  Select this if you are having a
+	  problem with PPS support and want to see more of what is going on.
+
+source drivers/pps/clients/Kconfig
+
+endmenu
drivers/pps/Makefile new file +7 -0
new file mode 100644
index 0000000..76101cd
@@ -0,0 +1,7 @@
+#
+# Makefile for the PPS core.
+#
+
+pps_core-objs			+= pps.o kapi.o sysfs.o
+obj-$(CONFIG_PPS)		+= pps_core.o
+obj-y				+= clients/
drivers/pps/clients/Kconfig new file +30 -0
new file mode 100644
index 0000000..58a1e55
@@ -0,0 +1,30 @@
+#
+# PPS clients configuration
+#
+
+if PPS
+
+comment "PPS clients support"
+
+config PPS_CLIENT_KTIMER
+	tristate "Kernel timer client (Testing client, use for debug)"
+	help
+	  If you say yes here you get support for a PPS debugging client
+	  which uses a kernel timer to generate the PPS signal.
+
+	  This driver can also be built as a module.  If so, the module
+	  will be called ktimer.ko.
+
+config PPS_CLIENT_UART
+	bool "UART serial support"
+	help
+	  If you say yes here you get support for a PPS source connected
+	  with the CD (Carrier Detect) pin of your serial port.
+
+config PPS_CLIENT_LP
+	bool "Parallel printer support"
+	help
+	  If you say yes here you get support for a PPS source connected
+	  with the interrupt pin of your parallel port.
+
+endif
drivers/pps/clients/Makefile new file +6 -0
new file mode 100644
index 0000000..10d1dfa
@@ -0,0 +1,6 @@
+#
+# Makefile for PPS clients.
+#
+
+obj-$(CONFIG_PPS_CLIENT_KTIMER)	+= ktimer.o
+
drivers/pps/clients/ktimer.c new file +114 -0

114 lines not on this page · raw message

drivers/pps/kapi.c new file +242 -0

242 lines not on this page · raw message

drivers/pps/pps.c new file +399 -0

399 lines not on this page · raw message

drivers/pps/sysfs.c new file +217 -0

217 lines not on this page · raw message

drivers/serial/8250.c +2 -0
index c84dab0..0c9a307 100644
@@ -2101,6 +2101,8 @@ serial8250_set_termios(struct uart_port *port, struct ktermios *termios,
 		up->ier |= UART_IER_MSI;
 	if (up->capabilities & UART_CAP_UUE)
 		up->ier |= UART_IER_UUE | UART_IER_RTOIE;
+	if (up->port.flags & UPF_HARDPPS_CD)
+		up->ier |= UART_IER_MSI;	/* enable interrupts */
 
 	serial_out(up, UART_IER, up->ier);
 
drivers/serial/serial_core.c +69 -1

104 lines not on this page · raw message

include/asm-i386/unistd.h +6 -1
index e84ace1..36746dc 100644
@@ -329,10 +329,15 @@
 #define __NR_signalfd		321
 #define __NR_timerfd		322
 #define __NR_eventfd		323
+#define __NR_time_pps_cmd	324
+#define __NR_time_pps_getparams	325
+#define __NR_time_pps_setparams	326
+#define __NR_time_pps_getcap	327
+#define __NR_time_pps_fetch	328
 
 #ifdef __KERNEL__
 
-#define NR_syscalls 324
+#define NR_syscalls 329
 
 #define __ARCH_WANT_IPC_PARSE_VERSION
 #define __ARCH_WANT_OLD_READDIR
include/linux/Kbuild +1 -0
index f317c27..a10d20a 100644
@@ -293,6 +293,7 @@ unifdef-y += pmu.h
 unifdef-y += poll.h
 unifdef-y += ppp_defs.h
 unifdef-y += ppp-comp.h
+unifdef-y += pps.h
 unifdef-y += ptrace.h
 unifdef-y += qnx4_fs.h
 unifdef-y += quota.h
include/linux/parport.h +12 -0
index 9cdd694..f53d9f4 100644
@@ -100,6 +100,7 @@ typedef enum {
 #include <linux/proc_fs.h>
 #include <linux/spinlock.h>
 #include <linux/wait.h>
+#include <linux/pps.h>
 #include <asm/system.h>
 #include <asm/ptrace.h>
 #include <asm/semaphore.h>
@@ -327,6 +328,11 @@ struct parport {
 
 	struct list_head full_list;
 	struct parport *slaves[3];
+
+#ifdef CONFIG_PPS_CLIENT_LP
+	struct pps_source_info_s pps_info;
+	int pps_source;		/* PPS source ID */
+#endif
 };
 
 #define DEFAULT_SPIN_TIME 500 /* us */
@@ -517,6 +523,12 @@ extern int parport_daisy_select (struct parport *port, int daisy, int mode);
 /* Lowlevel drivers _can_ call this support function to handle irqs.  */
 static __inline__ void parport_generic_irq(int irq, struct parport *port)
 {
+#ifdef CONFIG_PPS_CLIENT_LP
+	pps_event(port->pps_source, PPS_CAPTUREASSERT, port);
+	pps_dbg("parport_pc: PPS assert event at %lu on source #%d",
+		jiffies, port->pps_source);
+#endif
+
 	parport_ieee1284_interrupt (irq, port);
 	read_lock(&port->cad_lock);
 	if (port->cad && port->cad->irq_func)
include/linux/pps.h new file +213 -0

213 lines not on this page · raw message

include/linux/serial_core.h +27 -5
index 7f2c99d..654ad19 100644
@@ -153,6 +153,7 @@
 #include <linux/tty.h>
 #include <linux/mutex.h>
 #include <linux/sysrq.h>
+#include <linux/pps.h>
 
 struct uart_port;
 struct uart_info;
@@ -232,6 +233,9 @@ struct uart_port {
 	unsigned char		regshift;		/* reg offset shift */
 	unsigned char		iotype;			/* io access style */
 	unsigned char		unused1;
+#ifdef CONFIG_PPS_CLIENT_UART
+	int			pps_source;		/* PPS source ID */
+#endif
 
 #define UPIO_PORT		(0)
 #define UPIO_HUB6		(1)
@@ -276,7 +280,8 @@ struct uart_port {
 #define UPF_IOREMAP		((__force upf_t) (1 << 31))
 
 #define UPF_CHANGE_MASK		((__force upf_t) (0x17fff))
-#define UPF_USR_MASK		((__force upf_t) (UPF_SPD_MASK|UPF_LOW_LATENCY))
+#define UPF_USR_MASK		((__force upf_t) (UPF_SPD_MASK|UPF_LOW_LATENCY\
+							|UPF_HARDPPS_CD))
 
 	unsigned int		mctrl;			/* current modem ctrl settings */
 	unsigned int		timeout;		/* character-based timeout */
@@ -308,6 +313,10 @@ struct uart_state {
 	struct uart_info	*info;
 	struct uart_port	*port;
 
+#ifdef CONFIG_PPS_CLIENT_UART
+	struct pps_source_info_s pps_info;
+#endif
+
 	struct mutex		mutex;
 };
 
@@ -472,13 +481,26 @@ uart_handle_dcd_change(struct uart_port *port, unsigned int status)
 {
 	struct uart_info *info = port->info;
 
-	port->icount.dcd++;
+#ifdef CONFIG_PPS_CLIENT_UART
+	struct tty_driver *drv = port->info->tty->driver;
 
-#ifdef CONFIG_HARD_PPS
-	if ((port->flags & UPF_HARDPPS_CD) && status)
-		hardpps();
+	if (port->flags & UPF_HARDPPS_CD) {
+		if (status) {
+			pps_event(port->pps_source, PPS_CAPTUREASSERT, port);
+			pps_dbg("%s%d: PPS assert event at %lu on source #%d",
+				drv->driver_name, port->line,
+				jiffies, port->pps_source);
+		} else {
+			pps_event(port->pps_source, PPS_CAPTURECLEAR, port);
+			pps_dbg("%s%d: PPS clear event at %lu on source #%d",
+				drv->driver_name, port->line,
+				jiffies, port->pps_source);
+		}
+	}
 #endif
 
+	port->icount.dcd++;
+
 	if (info->flags & UIF_CHECK_CD) {
 		if (status)
 			wake_up_interruptible(&info->open_wait);
include/linux/syscalls.h +10 -0
index 83d0ec1..bfc8899 100644
@@ -65,6 +65,7 @@ struct getcpu_cache;
 #include <asm/signal.h>
 #include <linux/quota.h>
 #include <linux/key.h>
+#include <linux/pps.h>
 
 asmlinkage long sys_time(time_t __user *tloc);
 asmlinkage long sys_stime(time_t __user *tptr);
@@ -611,6 +612,15 @@ asmlinkage long sys_timerfd(int ufd, int clockid, int flags,
 			    const struct itimerspec __user *utmr);
 asmlinkage long sys_eventfd(unsigned int count);
 
+asmlinkage long sys_time_pps_cmd(int cmd, void __user *arg);
+asmlinkage long sys_time_pps_getparams(int source,
+				       struct pps_kparams __user *params);
+asmlinkage long sys_time_pps_setparams(int source,
+				       const struct pps_kparams __user *params);
+asmlinkage long sys_time_pps_getcap(int source, int __user *mode);
+asmlinkage long sys_time_pps_fetch(int source, struct pps_kinfo __user *info,
+				       const struct pps_ktime __user *timeout);
+
 int kernel_execve(const char *filename, char *const argv[], char *const envp[]);
 
 #endif
kernel/sys_ni.c +7 -0
index 7e11e2c..e0fccc2 100644
@@ -148,3 +148,10 @@ cond_syscall(sys_timerfd);
 cond_syscall(compat_sys_signalfd);
 cond_syscall(compat_sys_timerfd);
 cond_syscall(sys_eventfd);
+
+/* PPS dependent */
+cond_syscall(sys_time_pps_find);
+cond_syscall(sys_time_pps_getparams);
+cond_syscall(sys_time_pps_setparams);
+cond_syscall(sys_time_pps_getcap);
+cond_syscall(sys_time_pps_fetch);
author maintainer
#11 lore raw

LinuxPPS & spinlocks

In reply to David Woodhouse

By looking at spinlocks and thinking better to the lock problems for pps_events() I found this (possible) solution...

The pps_event() is now protected by a spinlock against pps_register_source() and pps_unregister_source(), but since I cannot disable IRQs I used the spin_trylock() into the pps_events() so even if the process context holds the lock and an PPS event arrives (IRQ) the system doesn't hang. Note that we cannot lose an event without problems.

It could be more acceptable? I removed the "volatile" attribute! :)

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
Documentation/pps/Makefile new file +27 -0
new file mode 100644
index 0000000..a2660a2
@@ -0,0 +1,27 @@
+TARGETS = ppstest ppsctl
+
+CFLAGS += -Wall -O2 -D_GNU_SOURCE
+CFLAGS += -I .
+CFLAGS += -ggdb
+
+# -- Actions section ----------------------------------------------------------
+
+.PHONY : all depend dep
+
+all : .depend $(TARGETS)
+
+.depend depend dep :
+	$(CC) $(CFLAGS) -M $(TARGETS:=.c) > .depend
+
+ifeq (.depend,$(wildcard .depend))
+include .depend
+endif
+
+
+# -- Clean section ------------------------------------------------------------
+
+.PHONY : clean
+
+clean :
+	rm -f *.o *~ core .depend
+	rm -f ${TARGETS}
Documentation/pps/pps.txt new file +211 -0

211 lines not on this page · raw message

Documentation/pps/ppsctl.c new file +61 -0

61 lines not on this page · raw message

Documentation/pps/ppstest.c new file +201 -0

201 lines not on this page · raw message

Documentation/pps/timepps.h new file +234 -0

234 lines not on this page · raw message

MAINTAINERS +7 -0
index df40a4e..17e9a02 100644
@@ -2903,6 +2903,13 @@ P:	Michal Ostrowski
 M:	[email protected]
 S:	Maintained
 
+PPS SUPPORT
+P:	Rodolfo Giometti
+M:	[email protected]
+W:	http://wiki.enneenne.com/index.php/LinuxPPS_support
+L:	[email protected]
+S:	Maintained
+
 PREEMPTIBLE KERNEL
 P:	Robert Love
 M:	[email protected]
arch/i386/kernel/syscall_table.S +5 -0
index bf6adce..f1bf4ff 100644
@@ -323,3 +323,8 @@ ENTRY(sys_call_table)
 	.long sys_signalfd
 	.long sys_timerfd
 	.long sys_eventfd
+	.long sys_time_pps_cmd
+	.long sys_time_pps_getparams	/* 325 */
+	.long sys_time_pps_setparams
+	.long sys_time_pps_getcap
+	.long sys_time_pps_fetch
drivers/Kconfig +2 -0
index 050323f..bb54cab 100644
@@ -52,6 +52,8 @@ source "drivers/i2c/Kconfig"
 
 source "drivers/spi/Kconfig"
 
+source "drivers/pps/Kconfig"
+
 source "drivers/w1/Kconfig"
 
 source "drivers/hwmon/Kconfig"
drivers/Makefile +1 -0
index adad2f3..985d495 100644
@@ -60,6 +60,7 @@ obj-$(CONFIG_INPUT)		+= input/
 obj-$(CONFIG_I2O)		+= message/
 obj-$(CONFIG_RTC_LIB)		+= rtc/
 obj-y				+= i2c/
+obj-$(CONFIG_PPS)		+= pps/
 obj-$(CONFIG_W1)		+= w1/
 obj-$(CONFIG_HWMON)		+= hwmon/
 obj-$(CONFIG_PHONE)		+= telephony/
drivers/char/lp.c +60 -0

78 lines not on this page · raw message

drivers/pps/Kconfig new file +31 -0
new file mode 100644
index 0000000..a00b59a
@@ -0,0 +1,31 @@
+#
+# PPS support configuration
+#
+
+menu "PPS support"
+
+config PPS
+	bool "PPS support"
+	depends on EXPERIMENTAL
+	---help---
+	  PPS (Pulse Per Second) is a special pulse provided by some GPS
+	  antennae. Userland can use it to get an high time reference.
+
+	  Some antennae's PPS signals are connected with the CD (Carrier
+	  Detect) pin of the serial line they use to communicate with the
+	  host. In this case use the SERIAL_LINE client support.
+
+	  Some antennae's PPS signals are connected with some special host
+	  inputs so you have to enable the corresponding client support.
+
+config PPS_DEBUG
+	bool "PPS debugging messages"
+	depends on PPS 
+	help
+	  Say Y here if you want the PPS support to produce a bunch of debug
+	  messages to the system log.  Select this if you are having a
+	  problem with PPS support and want to see more of what is going on.
+
+source drivers/pps/clients/Kconfig
+
+endmenu
drivers/pps/Makefile new file +11 -0
new file mode 100644
index 0000000..d8ec308
@@ -0,0 +1,11 @@
+#
+# Makefile for the PPS core.
+#
+
+pps_core-objs			+= pps.o kapi.o sysfs.o
+obj-$(CONFIG_PPS)		+= pps_core.o
+obj-y				+= clients/
+
+ifeq ($(CONFIG_PPS_DEBUG),y)
+EXTRA_CFLAGS += -DDEBUG
+endif
drivers/pps/clients/Kconfig new file +30 -0
new file mode 100644
index 0000000..58a1e55
@@ -0,0 +1,30 @@
+#
+# PPS clients configuration
+#
+
+if PPS
+
+comment "PPS clients support"
+
+config PPS_CLIENT_KTIMER
+	tristate "Kernel timer client (Testing client, use for debug)"
+	help
+	  If you say yes here you get support for a PPS debugging client
+	  which uses a kernel timer to generate the PPS signal.
+
+	  This driver can also be built as a module.  If so, the module
+	  will be called ktimer.ko.
+
+config PPS_CLIENT_UART
+	bool "UART serial support"
+	help
+	  If you say yes here you get support for a PPS source connected
+	  with the CD (Carrier Detect) pin of your serial port.
+
+config PPS_CLIENT_LP
+	bool "Parallel printer support"
+	help
+	  If you say yes here you get support for a PPS source connected
+	  with the interrupt pin of your parallel port.
+
+endif
drivers/pps/clients/Makefile new file +9 -0
new file mode 100644
index 0000000..f3c1e39
@@ -0,0 +1,9 @@
+#
+# Makefile for PPS clients.
+#
+
+obj-$(CONFIG_PPS_CLIENT_KTIMER)	+= ktimer.o
+
+ifeq ($(CONFIG_PPS_DEBUG),y)
+EXTRA_CFLAGS += -DDEBUG
+endif
drivers/pps/clients/ktimer.c new file +114 -0

114 lines not on this page · raw message

drivers/pps/kapi.c new file +222 -0

222 lines not on this page · raw message

drivers/pps/pps.c new file +391 -0

391 lines not on this page · raw message

drivers/pps/sysfs.c new file +217 -0

217 lines not on this page · raw message

drivers/serial/8250.c +2 -0
index c84dab0..0c9a307 100644
@@ -2101,6 +2101,8 @@ serial8250_set_termios(struct uart_port *port, struct ktermios *termios,
 		up->ier |= UART_IER_MSI;
 	if (up->capabilities & UART_CAP_UUE)
 		up->ier |= UART_IER_UUE | UART_IER_RTOIE;
+	if (up->port.flags & UPF_HARDPPS_CD)
+		up->ier |= UART_IER_MSI;	/* enable interrupts */
 
 	serial_out(up, UART_IER, up->ier);
 
drivers/serial/serial_core.c +69 -1

104 lines not on this page · raw message

include/asm-i386/unistd.h +6 -1
index e84ace1..36746dc 100644
@@ -329,10 +329,15 @@
 #define __NR_signalfd		321
 #define __NR_timerfd		322
 #define __NR_eventfd		323
+#define __NR_time_pps_cmd	324
+#define __NR_time_pps_getparams	325
+#define __NR_time_pps_setparams	326
+#define __NR_time_pps_getcap	327
+#define __NR_time_pps_fetch	328
 
 #ifdef __KERNEL__
 
-#define NR_syscalls 324
+#define NR_syscalls 329
 
 #define __ARCH_WANT_IPC_PARSE_VERSION
 #define __ARCH_WANT_OLD_READDIR
include/linux/Kbuild +1 -0
index f317c27..a10d20a 100644
@@ -293,6 +293,7 @@ unifdef-y += pmu.h
 unifdef-y += poll.h
 unifdef-y += ppp_defs.h
 unifdef-y += ppp-comp.h
+unifdef-y += pps.h
 unifdef-y += ptrace.h
 unifdef-y += qnx4_fs.h
 unifdef-y += quota.h
include/linux/parport.h +12 -0
index 9cdd694..0ecce1f 100644
@@ -100,6 +100,7 @@ typedef enum {
 #include <linux/proc_fs.h>
 #include <linux/spinlock.h>
 #include <linux/wait.h>
+#include <linux/pps.h>
 #include <asm/system.h>
 #include <asm/ptrace.h>
 #include <asm/semaphore.h>
@@ -327,6 +328,11 @@ struct parport {
 
 	struct list_head full_list;
 	struct parport *slaves[3];
+
+#ifdef CONFIG_PPS_CLIENT_LP
+	struct pps_source_info_s pps_info;
+	int pps_source;		/* PPS source ID */
+#endif
 };
 
 #define DEFAULT_SPIN_TIME 500 /* us */
@@ -517,6 +523,12 @@ extern int parport_daisy_select (struct parport *port, int daisy, int mode);
 /* Lowlevel drivers _can_ call this support function to handle irqs.  */
 static __inline__ void parport_generic_irq(int irq, struct parport *port)
 {
+#ifdef CONFIG_PPS_CLIENT_LP
+	pps_event(port->pps_source, PPS_CAPTUREASSERT, port);
+	dev_dbg(port->dev, "PPS assert at %lu on source #%d\n",
+		jiffies, port->pps_source);
+#endif
+
 	parport_ieee1284_interrupt (irq, port);
 	read_lock(&port->cad_lock);
 	if (port->cad && port->cad->irq_func)
include/linux/pps.h new file +206 -0

206 lines not on this page · raw message

include/linux/serial_core.h +24 -6
index 7f2c99d..01f3459 100644
@@ -153,6 +153,7 @@
 #include <linux/tty.h>
 #include <linux/mutex.h>
 #include <linux/sysrq.h>
+#include <linux/pps.h>
 
 struct uart_port;
 struct uart_info;
@@ -232,6 +233,9 @@ struct uart_port {
 	unsigned char		regshift;		/* reg offset shift */
 	unsigned char		iotype;			/* io access style */
 	unsigned char		unused1;
+#ifdef CONFIG_PPS_CLIENT_UART
+	int			pps_source;		/* PPS source ID */
+#endif
 
 #define UPIO_PORT		(0)
 #define UPIO_HUB6		(1)
@@ -276,7 +280,8 @@ struct uart_port {
 #define UPF_IOREMAP		((__force upf_t) (1 << 31))
 
 #define UPF_CHANGE_MASK		((__force upf_t) (0x17fff))
-#define UPF_USR_MASK		((__force upf_t) (UPF_SPD_MASK|UPF_LOW_LATENCY))
+#define UPF_USR_MASK		((__force upf_t) (UPF_SPD_MASK|UPF_LOW_LATENCY\
+							|UPF_HARDPPS_CD))
 
 	unsigned int		mctrl;			/* current modem ctrl settings */
 	unsigned int		timeout;		/* character-based timeout */
@@ -308,6 +313,10 @@ struct uart_state {
 	struct uart_info	*info;
 	struct uart_port	*port;
 
+#ifdef CONFIG_PPS_CLIENT_UART
+	struct pps_source_info_s pps_info;
+#endif
+
 	struct mutex		mutex;
 };
 
@@ -472,13 +481,22 @@ uart_handle_dcd_change(struct uart_port *port, unsigned int status)
 {
 	struct uart_info *info = port->info;
 
-	port->icount.dcd++;
-
-#ifdef CONFIG_HARD_PPS
-	if ((port->flags & UPF_HARDPPS_CD) && status)
-		hardpps();
+#ifdef CONFIG_PPS_CLIENT_UART
+	if (port->flags & UPF_HARDPPS_CD) {
+		if (status) {
+			pps_event(port->pps_source, PPS_CAPTUREASSERT, port);
+			dev_dbg(port->dev, "PPS assert at %lu on source #%d\n",
+				jiffies, port->pps_source);
+		} else {
+			pps_event(port->pps_source, PPS_CAPTURECLEAR, port);
+			dev_dbg(port->dev, "PPS clear at %lu on source #%d\n",
+				jiffies, port->pps_source);
+		}
+	}
 #endif
 
+	port->icount.dcd++;
+
 	if (info->flags & UIF_CHECK_CD) {
 		if (status)
 			wake_up_interruptible(&info->open_wait);
include/linux/syscalls.h +10 -0
index 83d0ec1..bfc8899 100644
@@ -65,6 +65,7 @@ struct getcpu_cache;
 #include <asm/signal.h>
 #include <linux/quota.h>
 #include <linux/key.h>
+#include <linux/pps.h>
 
 asmlinkage long sys_time(time_t __user *tloc);
 asmlinkage long sys_stime(time_t __user *tptr);
@@ -611,6 +612,15 @@ asmlinkage long sys_timerfd(int ufd, int clockid, int flags,
 			    const struct itimerspec __user *utmr);
 asmlinkage long sys_eventfd(unsigned int count);
 
+asmlinkage long sys_time_pps_cmd(int cmd, void __user *arg);
+asmlinkage long sys_time_pps_getparams(int source,
+				       struct pps_kparams __user *params);
+asmlinkage long sys_time_pps_setparams(int source,
+				       const struct pps_kparams __user *params);
+asmlinkage long sys_time_pps_getcap(int source, int __user *mode);
+asmlinkage long sys_time_pps_fetch(int source, struct pps_kinfo __user *info,
+				       const struct pps_ktime __user *timeout);
+
 int kernel_execve(const char *filename, char *const argv[], char *const envp[]);
 
 #endif
kernel/sys_ni.c +7 -0
index 7e11e2c..e0fccc2 100644
@@ -148,3 +148,10 @@ cond_syscall(sys_timerfd);
 cond_syscall(compat_sys_signalfd);
 cond_syscall(compat_sys_timerfd);
 cond_syscall(sys_eventfd);
+
+/* PPS dependent */
+cond_syscall(sys_time_pps_find);
+cond_syscall(sys_time_pps_getparams);
+cond_syscall(sys_time_pps_setparams);
+cond_syscall(sys_time_pps_getcap);
+cond_syscall(sys_time_pps_fetch);
#12 lore raw

Re: LinuxPPS & spinlocks

Quoted 2 lines · Rodolfo Giometti

The pps_event() is now protected by a spinlock against pps_register_source() and pps_unregister_source()...

Locks protect data, not code. It may make more sense to identify the specific data being protected by the spinlock.

Chris

author maintainer
#13 lore raw

Re: LinuxPPS & spinlocks

Quoted 7 lines · Chris Friesen
Quoted 2 lines · Rodolfo Giometti

The pps_event() is now protected by a spinlock against pps_register_source() and pps_unregister_source()...

Locks protect data, not code. It may make more sense to identify the specific data being protected by the spinlock.

What do you mean? Did you find an error into my patch? :-o

Functions pps_event() and pps_register_source()/pps_unregister_source() take accesso to shared data, that's why I used spinlocks.

Thanks,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#14 lore raw

Re: LinuxPPS & spinlocks

Quoted 5 lines · Rodolfo Giometti

What do you mean? Did you find an error into my patch? :-o

Functions pps_event() and pps_register_source()/pps_unregister_source() take accesso to shared data, that's why I used spinlocks.

My point is that the lock should be used to protect specific data. Thus, it would be more correct to say, "spinlock foo is taken because pps_register_source() accesses variable bar".

That way, if someone else wants to access "bar", they know that they need to take lock "foo".

Chris

author maintainer
#15 lore raw

Re: LinuxPPS & spinlocks

Quoted 7 lines · Chris Friesen

My point is that the lock should be used to protect specific data. Thus, it would be more correct to say, "spinlock foo is taken because pps_register_source() accesses variable bar".

That way, if someone else wants to access "bar", they know that they need to take lock "foo".

Ah, ok! I see. :)

Thanks,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#16 lore raw

Re: LinuxPPS & spinlocks

Hi Rodolfo,

Quoted 10 lines · Rodolfo Giometti
Quoted 7 lines · Chris Friesen

My point is that the lock should be used to protect specific data. Thus, it would be more correct to say, "spinlock foo is taken because pps_register_source() accesses variable bar".

That way, if someone else wants to access "bar", they know that they need to take lock "foo".

Ah, ok! I see. :)

I only glanced through the code, so could be wrong, but I noticed that the only global / shared data you have in there is a global "pps_source" array of pps_s structs. That's accessed / modified from the various syscalls introduced in the API exported to userspace, as well as the register/unregister/pps_event API exported to in-kernel client subsystems, yes? So it looks like you need to introduce proper locking for it, simply type-qualifying it as "volatile" is not enough.

However, I think you've introduced two locks for it. The syscalls (that run in process context, obviously) seem to use a pps_mutex and pps_event() seems to be using the pps_lock spinlock (because that gets executed from interrupt context) -- and from the looks of it, the register/unregister functions are using /both/ the mutex and spinlock (!)

This isn't quite right, (in fact there's nothing to protect pps_event from racing against a syscall), so you should use *only* the spinlock for synchronization -- the spin_lock_irqsave/restore() variants, in fact.

[ Also, have you considered making pps_source a list and not an array? It'll help you lose a whole lot of MAX_SOURCES, pps_is_allocated, etc kind of gymnastics in there, and you _can_ return a pointer to the corresponding pps source struct from the register() function to the in-kernel users, so that way you get to retain the O(1) access to the corresponding source when a client calls into pps_event(), similar to how you're using the array index presently. ]

I also noticed code like (from pps_event):

+ /* Try to grab the lock, if not we prefere loose the event... */
+ if (!spin_trylock(&pps_lock))
+ return;

which looks worrisome and unnecessary. That spinlock looks to be of fine enough granularity to me, do you think there'd be any contention on it? I /think/ you can simply make that a spin_lock().

Overall the code looks simple / straightforward enough to me (except for the parport / uart stuff that I have no clue about), and I'll also read up on the relevant RFC for this and would hopefully try and give you a more meaningful review over the weekend.

Thanks,
Satyam

#17 lore raw

Re: LinuxPPS & spinlocks

Hi,

Quoted 28 lines · Satyam Sharma

Hi Rodolfo,

Quoted 10 lines · Rodolfo Giometti
Quoted 7 lines · Chris Friesen

My point is that the lock should be used to protect specific data. Thus, it would be more correct to say, "spinlock foo is taken because pps_register_source() accesses variable bar".

That way, if someone else wants to access "bar", they know that they need to take lock "foo".

Ah, ok! I see. :)

I only glanced through the code, so could be wrong, but I noticed that the only global / shared data you have in there is a global "pps_source" array of pps_s structs. That's accessed / modified from the various syscalls introduced in the API exported to userspace, as well as the register/unregister/pps_event API exported to in-kernel client subsystems, yes? So it looks like you need to introduce proper locking for it, simply type-qualifying it as "volatile" is not enough.

However, I think you've introduced two locks for it. The syscalls (that run in process context, obviously) seem to use a pps_mutex and pps_event() seems to be using the pps_lock spinlock (because that gets executed from interrupt context) -- and from the looks of it, the register/unregister functions are using /both/ the mutex and spinlock (!)

Quoted 3 lines

This isn't quite right, (in fact there's nothing to protect pps_event from racing against a syscall), so you should use *only* the spinlock for synchronization -- the spin_lock_irqsave/restore() variants, in fact.

Take the race between the time_pps_setparams() syscall and a concurrent pps_event() from an interrupt for instance. From sys_time_pps_setparams, the parameters for an existing source are not modified / set atomically, which means a pps_event() called on the same source in between will see invalid parameters ... and bad things will happen.

Quoted 7 lines

[ Also, have you considered making pps_source a list and not an array? It'll help you lose a whole lot of MAX_SOURCES, pps_is_allocated, etc kind of gymnastics in there, and you _can_ return a pointer to the corresponding pps source struct from the register() function to the in-kernel users, so that way you get to retain the O(1) access to the corresponding source when a client calls into pps_event(), similar to how you're using the array index presently. ]

I think the above would be sane and safe -- your driver has pretty simple lifetime rules, and "sources" are only created / destroyed from within kernel, as and when clients call pps_register_source() and pps_unregister_source(). So pps_event() can be called on a given source only between the corresponding register() and unregister() -- which means register() can return us a reference/pointer on the source after allocating / adding it to the list (instead of the fixed array index as it presently is), which remains valid for the entire duration of the source, till unregister() is called, after which we can't be calling pps_event() on the same source anyway.

Quoted 6 lines

I also noticed code like (from pps_event):

drivers/pps/kapi.c new file +3 -0
+       /* Try to grab the lock, if not we prefere loose the event... */
+       if (!spin_trylock(&pps_lock))
+               return;
Quoted 8 lines

which looks worrisome and unnecessary. That spinlock looks to be of fine enough granularity to me, do you think there'd be any contention on it? I /think/ you can simply make that a spin_lock().

Overall the code looks simple / straightforward enough to me (except for the parport / uart stuff that I have no clue about), and I'll also read up on the relevant RFC for this and would hopefully try and give you a more meaningful review over the weekend.

Ok, I've looked through (most of) the RFC and code now, and am only commenting on a design-level for now. Anyway, I didn't like the way you've significantly drifted from the RFC in several ways:

1. The RFC mandates no such userspace interface / syscall as the time_pps_cmd() that you've implemented -- it looks, smells, and feels like an ioctl, in fact that's what it is for practical purposes. I'm confused as to why didn't you just go ahead and implement the special-file-and- file-descriptor based approach as advocated / mandated there.

[ You've implemented the (optional, as per RFC) time_pps_findsource operation in the kernel using the above "pseudo-ioctl", but that wasn't necessary -- as the RFC itself illustrates, it's something that can easily be done (in fact should be done) completely in userspace itself. ]

2. If you fix the above two issues, you'll notice that you don't need to short-circuit the (RFC-mandated) time_pps_create/destroy(handle) syscalls in the userspace header/library anymore, as you presently are.

Here's how I'd go about desiging/implementing this:

* At the time of pps_register_source() -- called by an in-kernel client subsystem that creates a PPS source -- allocate a pps source, generate an identifier for it, instantiate a special file -- the RFC does not mention whether a char or block device, but char device (I noticed an example in the RFC where they've used /dev/ppsXX as a possible path) would be proper for this. Finally add it to the list of sources. This returns a reference/pointer on that source back to the in-kernel client, which then passes *that* to pps_event(), similar to how you're presently using the array index.

[ The way you've passed the path of the parport/uart device itself (/dev/lpXX or [/dev/%s%d, drv->name, port->line]) to register_source() in pps_info.path doesn't quite look right to me. Note that the userspace is expected to open(2) the special file corresponding to the *PPS* source, as instantiated from the above code, and not the /dev/xyz special file of the *physical* port through which a pulse-generating device may be connected to the PC. ]

* Userspace will open(2) the special file, and get an fd. Then calls the time_pps_create(fd, &handle) syscall -- kernel will find the pps source that matches that passed fd from the list of sources, and instantiates a "handle" associated with that source and returns that back to userspace.

The rest would happen as usual / as you've currently implemented.

I /think/ the RFC does envision such an implementation, so it helps us comply with that standard, and would also get rid of a lot of kludgy "findpath" and "findsource" stuff that we otherwise have to do in-kernel and userspace, as we're presently doing in the patch.

[ BTW, it would be nice if you submit this stuff as a patchset that brings in functionality over a series of multiple patches -- the sysfs interface bits can be introduced in a different patch from the syscalls, which can be introduced in a different patch from the kernel-side API, etc ... that helps a code-level review. ]

Satyam

author maintainer
#18 lore raw

Re: LinuxPPS & spinlocks

Quoted 6 lines · Satyam Sharma

Take the race between the time_pps_setparams() syscall and a concurrent pps_event() from an interrupt for instance. From sys_time_pps_setparams, the parameters for an existing source are not modified / set atomically, which means a pps_event() called on the same source in between will see invalid parameters ... and bad things will happen.

I are right. I'll add spinlocks. :)

Quoted 8 lines
Quoted 7 lines

[ Also, have you considered making pps_source a list and not an array? It'll help you lose a whole lot of MAX_SOURCES, pps_is_allocated, etc kind of gymnastics in there, and you _can_ return a pointer to the corresponding pps source struct from the register() function to the in-kernel users, so that way you get to retain the O(1) access to the corresponding source when a client calls into pps_event(), similar to how you're using the array index presently. ]

Quoted 9 lines

I think the above would be sane and safe -- your driver has pretty simple lifetime rules, and "sources" are only created / destroyed from within kernel, as and when clients call pps_register_source() and pps_unregister_source(). So pps_event() can be called on a given source only between the corresponding register() and unregister() -- which means register() can return us a reference/pointer on the source after allocating / adding it to the list (instead of the fixed array index as it presently is), which remains valid for the entire duration of the source, till unregister() is called, after which we can't be calling pps_event() on the same source anyway.

Ok. I see. I'll study the problem but I think this is can be done later, now I think is better having a working code. :)

Quoted 9 lines

Ok, I've looked through (most of) the RFC and code now, and am only commenting on a design-level for now. Anyway, I didn't like the way you've significantly drifted from the RFC in several ways:

1. The RFC mandates no such userspace interface / syscall as the time_pps_cmd() that you've implemented -- it looks, smells, and feels like an ioctl, in fact that's what it is for practical purposes. I'm confused as to why didn't you just go ahead and implement the special-file-and- file-descriptor based approach as advocated / mandated there.

This is because is not always true that a PPS source is connected with a char (or other) device. People whose designed RFC didn't think about systems where the PPS signal is connected with a CPU's GPIO and the O.S. doesn't provide any char device to refere with!

In the common desktop PCs the GPS antenna is connected with the serial line and the PPS source is attached to the serial CD, but in the embedded systems this is _not_ true. GPS antennae may still be connected with serial line but the PPS signal is usually connected with a GPIO pin.

In this scenario you cannot use the serial file descriptor to manage the PPS signal since it cannot goes to the serial port.

Quoted 4 lines

[ You've implemented the (optional, as per RFC) time_pps_findsource operation in the kernel using the above "pseudo-ioctl", but that wasn't necessary -- as the RFC itself illustrates, it's something that can easily be done (in fact should be done) completely in userspace itself. ]

I used pseudo-ioctl interface since it allows me to easily extend PPS support with special, and uncommon, commands.

Quoted 3 lines

2. If you fix the above two issues, you'll notice that you don't need to short-circuit the (RFC-mandated) time_pps_create/destroy(handle) syscalls in the userspace header/library anymore, as you presently are.

This is just the reason why I added those functions. :)

Quoted 11 lines

Here's how I'd go about desiging/implementing this:

* At the time of pps_register_source() -- called by an in-kernel client subsystem that creates a PPS source -- allocate a pps source, generate an identifier for it, instantiate a special file -- the RFC does not mention whether a char or block device, but char device (I noticed an example in the RFC where they've used /dev/ppsXX as a possible path) would be proper for this. Finally add it to the list of sources. This returns a reference/pointer on that source back to the in-kernel client, which then passes *that* to pps_event(), similar to how you're presently using the array index.

If your GPS antenna is connected with a CPU's GPIO you have _no_ in-kernel client subsystem that creates a PPS source.

Quoted 7 lines

[ The way you've passed the path of the parport/uart device itself (/dev/lpXX or [/dev/%s%d, drv->name, port->line]) to register_source() in pps_info.path doesn't quite look right to me. Note that the userspace is expected to open(2) the special file corresponding to the *PPS* source, as instantiated from the above code, and not the /dev/xyz special file of the *physical* port through which a pulse-generating device may be connected to the PC. ]

As above, if your GPS antenna is connected with a CPU's GPIO you have _no_ device to open at all, that's why you need at least a function like pps_findsource().

Note that in this case the pps_info.path is void. Please, see the special client drivers/pps/clients/ktimer.c, it emulates the case where you have no /dev/XXX to open(2). If your modifications resolve the problems to manage the ktimer client you are going in the right direction.

Quoted 4 lines

* Userspace will open(2) the special file, and get an fd. Then calls the time_pps_create(fd, &handle) syscall -- kernel will find the pps source that matches that passed fd from the list of sources, and instantiates a "handle" associated with that source and returns that back to userspace.

Ditto.

Quoted 6 lines

The rest would happen as usual / as you've currently implemented.

I /think/ the RFC does envision such an implementation, so it helps us comply with that standard, and would also get rid of a lot of kludgy "findpath" and "findsource" stuff that we otherwise have to do in-kernel and userspace, as we're presently doing in the patch.

Unluckily the RFC does _not_ take into account PPS sources connected with CPU's GPIO... in this case, in fact, you have _no_ char/block device to open().

Quoted 5 lines

[ BTW, it would be nice if you submit this stuff as a patchset that brings in functionality over a series of multiple patches -- the sysfs interface bits can be introduced in a different patch from the syscalls, which can be introduced in a different patch from the kernel-side API, etc ... that helps a code-level review. ]

Ok, I see, but I think this should be done when everithing is ok. I think after fixing locking issue I can do it, can't I?

Thanks,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#19 lore raw

Re: LinuxPPS & spinlocks

Hi,

Quoted 20 lines · Rodolfo Giometti
Quoted 8 lines · Satyam Sharma
Quoted 7 lines

[ Also, have you considered making pps_source a list and not an array? It'll help you lose a whole lot of MAX_SOURCES, pps_is_allocated, etc kind of gymnastics in there, and you _can_ return a pointer to the corresponding pps source struct from the register() function to the in-kernel users, so that way you get to retain the O(1) access to the corresponding source when a client calls into pps_event(), similar to how you're using the array index presently. ]

Quoted 9 lines

I think the above would be sane and safe -- your driver has pretty simple lifetime rules, and "sources" are only created / destroyed from within kernel, as and when clients call pps_register_source() and pps_unregister_source(). So pps_event() can be called on a given source only between the corresponding register() and unregister() -- which means register() can return us a reference/pointer on the source after allocating / adding it to the list (instead of the fixed array index as it presently is), which remains valid for the entire duration of the source, till unregister() is called, after which we can't be calling pps_event() on the same source anyway.

Quoted 2 lines

Ok. I see. I'll study the problem but I think this is can be done later, now I think is better having a working code. :)

Fair enough, but I think the code could become a trifle simpler/easier after the conversion, so probably greater chances of getting merged :-)

Quoted 4 lines
Quoted 4 lines

Ok, I've looked through (most of) the RFC and code now, and am only commenting on a design-level for now. Anyway, I didn't like the way you've significantly drifted from the RFC in several ways:

Quoted 8 lines
Quoted 5 lines

1. The RFC mandates no such userspace interface / syscall as the time_pps_cmd() that you've implemented -- it looks, smells, and feels like an ioctl, in fact that's what it is for practical purposes. I'm confused as to why didn't you just go ahead and implement the special-file-and- file-descriptor based approach as advocated / mandated there.

This is because is not always true that a PPS source is connected with a char (or other) device.

But that's alright -- see, as I said, you're confusing between the "special device" that represents the *PPS source* itself, with the port or device that it uses to *physically* connect to the PC.

In the RFC, when they say that the userspace app must open(2) the PPS source (as they have illustrated in the example too), they mean that it open(2)'s the special device/file associated with the PPS source, and *not* the /dev/lpXXX or /dev/ttySXXX that it might be connected through physically.

So they mean something like /dev/pps0, /dev/pps1 etc instead. Of course, no such special device exists on a Linux box already, but that's fine and obvious! *You* are supposed to create / instantiate that when a pps_register_source() is done from some in-kernel subsystem.

Quoted 3 lines

People whose designed RFC didn't think about
systems where the PPS signal is connected with a CPU's GPIO and the O.S. doesn't provide any char device to refere with!

As I said, it's not the char device for the physical interface itself being discussed there. That could be parport, uart, some arbit GPIO pin whatever. But whenever the corresponding kernel subsystem does a register_source(), you could create the /dev/ppsXXX device ...

Quoted 8 lines

In the common desktop PCs the GPS antenna is connected with the serial line and the PPS source is attached to the serial CD, but in the embedded systems this is _not_ true. GPS antennae may still be connected with serial line but the PPS signal is usually connected with a GPIO pin.

In this scenario you cannot use the serial file descriptor to manage the PPS signal since it cannot goes to the serial port.

See above.

Quoted 7 lines
Quoted 4 lines

[ You've implemented the (optional, as per RFC) time_pps_findsource operation in the kernel using the above "pseudo-ioctl", but that wasn't necessary -- as the RFC itself illustrates, it's something that can easily be done (in fact should be done) completely in userspace itself. ]

I used pseudo-ioctl interface since it allows me to easily extend PPS support with special, and uncommon, commands.

Hmm, but that's a non-standard, not-mandated-by-RFC syscall. I don't see how you can get this merged, really :-)

Quoted 10 lines
Quoted 9 lines

* At the time of pps_register_source() -- called by an in-kernel client subsystem that creates a PPS source -- allocate a pps source, generate an identifier for it, instantiate a special file -- the RFC does not mention whether a char or block device, but char device (I noticed an example in the RFC where they've used /dev/ppsXX as a possible path) would be proper for this. Finally add it to the list of sources. This returns a reference/pointer on that source back to the in-kernel client, which then passes *that* to pps_event(), similar to how you're presently using the array index.

Quoted 2 lines

If your GPS antenna is connected with a CPU's GPIO you have _no_ in-kernel client subsystem that creates a PPS source.

See above.

Quoted 12 lines
Quoted 7 lines

[ The way you've passed the path of the parport/uart device itself (/dev/lpXX or [/dev/%s%d, drv->name, port->line]) to register_source() in pps_info.path doesn't quite look right to me. Note that the userspace is expected to open(2) the special file corresponding to the *PPS* source, as instantiated from the above code, and not the /dev/xyz special file of the *physical* port through which a pulse-generating device may be connected to the PC. ]

As above, if your GPS antenna is connected with a CPU's GPIO you have _no_ device to open at all, that's why you need at least a function like pps_findsource().

Quoted 5 lines

Note that in this case the pps_info.path is void. Please, see the special client drivers/pps/clients/ktimer.c, it emulates the case where you have no /dev/XXX to open(2). If your modifications resolve the problems to manage the ktimer client you are going in the right direction.

Again, see above.

Quoted 8 lines
Quoted 4 lines

I /think/ the RFC does envision such an implementation, so it helps us comply with that standard, and would also get rid of a lot of kludgy "findpath" and "findsource" stuff that we otherwise have to do in-kernel and userspace, as we're presently doing in the patch.

Unluckily the RFC does _not_ take into account PPS sources connected with CPU's GPIO... in this case, in fact, you have _no_ char/block device to open().

And again, see above.

Satyam

author maintainer
#20 lore raw

Re: LinuxPPS & spinlocks

Quoted 3 lines · Satyam Sharma

Fair enough, but I think the code could become a trifle simpler/easier after the conversion, so probably greater chances of getting merged :-)

I see. I'll start thinging about it.

Quoted 10 lines

But that's alright -- see, as I said, you're confusing between the "special device" that represents the *PPS source* itself, with the port or device that it uses to *physically* connect to the PC.

In the RFC, when they say that the userspace app must open(2) the PPS source (as they have illustrated in the example too), they mean that it open(2)'s the special device/file associated with the PPS source, and *not* the /dev/lpXXX or /dev/ttySXXX that it might be connected through physically.

Quoted 4 lines

So they mean something like /dev/pps0, /dev/pps1 etc instead. Of course, no such special device exists on a Linux box already, but that's fine and obvious! *You* are supposed to create / instantiate that when a pps_register_source() is done from some in-kernel subsystem.

So your are proposing to create a char device interface then using syscalls one? In this case how do you manage the case where your GPS antenna and PPS source are both connected with the serial port (i.e. /dev/ttyS0)?

Currently the RFC says to you that you should open the serial port:

	fd = open("/dev/ttyS0", ...);

and the passing its filedes to pps_time_create() in order to get the corresponding PPS source handler:

	pps_time_create(fd, &handler);

As you propose you need _two_ open() and not just one... and even if you decide to open the /dev/ppsX inside the pps_time_create(), how do you recognise _which_ /dev/ppsX is connected with filedse "fd"?

I quite sure that RFC is broken since it doesn't take in account that a PPS source maybe not connected with any cahr device at all. I tried to explain this problem to RFC's gurus but they never answered to me, so I decided to resolve the problem by myself. ;)

Quoted 4 lines

As I said, it's not the char device for the physical interface itself being discussed there. That could be parport, uart, some arbit GPIO pin whatever. But whenever the corresponding kernel subsystem does a register_source(), you could create the /dev/ppsXXX device ...

Ok, but in this case you still are _not_ RFC compliant (as showed above). You need that users give to you _two_ devices (the serial line and the PPS source), meanwhile, for the RFC, you just need one. So no differences from my solution from this point of view.

Quoted 2 lines

Hmm, but that's a non-standard, not-mandated-by-RFC syscall. I don't see how you can get this merged, really :-)

They are not-mandated-by-RFC since simply RFC _is broken_! :)

I need them (or just one of them) in order to find a PPS source into the system. Just as you need the second device name in your solution with char devices.

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#21 lore raw

Re: LinuxPPS & spinlocks

Quoted 22 lines · Rodolfo Giometti
Quoted 3 lines · Satyam Sharma

Fair enough, but I think the code could become a trifle simpler/easier after the conversion, so probably greater chances of getting merged :-)

I see. I'll start thinging about it.

Quoted 10 lines

But that's alright -- see, as I said, you're confusing between the "special device" that represents the *PPS source* itself, with the port or device that it uses to *physically* connect to the PC.

In the RFC, when they say that the userspace app must open(2) the PPS source (as they have illustrated in the example too), they mean that it open(2)'s the special device/file associated with the PPS source, and *not* the /dev/lpXXX or /dev/ttySXXX that it might be connected through physically.

Quoted 4 lines

So they mean something like /dev/pps0, /dev/pps1 etc instead. Of course, no such special device exists on a Linux box already, but that's fine and obvious! *You* are supposed to create / instantiate that when a pps_register_source() is done from some in-kernel subsystem.

Quoted 4 lines

So your are proposing to create a char device interface then using syscalls one? In this case how do you manage the case where your GPS antenna and PPS source are both connected with the serial port (i.e. /dev/ttyS0)?

That's *precisely* what I just explained above!

You create that special device at the time of pps_register_source()!

Quoted 3 lines

Currently the RFC says to you that you should open the serial port:

	fd = open("/dev/ttyS0", ...);

No, it does *NOT*. All it says is:

The time_pps_create() is used to convert an already-open UNIX file descriptor, for an appropriate special file, into a PPS handle.

See? What I said is precisely the implementation the RFC envisages (and the only sane way to implement it too).

And later, where it gives an example, it shows:

    fd = open(PPSfilename, O_RDWR, 0);

What I'm saying is that the "PPSfilename", as is obvious from the name itself, is *not* a port such as lpXXX or ttySXXX, but an "appropriate special file" corresponding to a ... PPS source! Really, the RFC is quite clear and easy to read, I have no idea how to explain that more clearly ...

Quoted 4 lines

and the passing its filedes to pps_time_create() in order to get the corresponding PPS source handler:

	pps_time_create(fd, &handler);

Yes.

Quoted 1 line

As you propose you need _two_ open() and not just one...

No, why?

Quoted 3 lines

and even if
you decide to open the /dev/ppsX inside the pps_time_create(), how do you recognise _which_ /dev/ppsX is connected with filedse "fd"?

That's trivial to implement in the kernel code for the time_pps_create() syscall.

Quoted 4 lines

I quite sure that RFC is broken since it doesn't take in account that a PPS source maybe not connected with any cahr device at all. I tried to explain this problem to RFC's gurus but they never answered to me, so I decided to resolve the problem by myself. ;)

Nopes, the RFC is not broken at all. All this physical-connection-port device vs PPS-source-device confusion is just in your mind :-)

Quoted 9 lines
Quoted 4 lines

As I said, it's not the char device for the physical interface itself being discussed there. That could be parport, uart, some arbit GPIO pin whatever. But whenever the corresponding kernel subsystem does a register_source(), you could create the /dev/ppsXXX device ...

Ok, but in this case you still are _not_ RFC compliant (as showed above). You need that users give to you _two_ devices (the serial line and the PPS source), meanwhile, for the RFC, you just need one. So no differences from my solution from this point of view.

Yeah, so how am I not RFC compliant? Userspace will *only* open(2) the special char device of the *PPS source*, and have *nothing* to do with the device corresponding to the physical device/port it is connected through!

Quoted 4 lines
Quoted 2 lines

Hmm, but that's a non-standard, not-mandated-by-RFC syscall. I don't see how you can get this merged, really :-)

They are not-mandated-by-RFC since simply RFC _is broken_! :)

It is not ...

Quoted 3 lines

I need them (or just one of them) in order to find a PPS source into the system. Just as you need the second device name in your solution with char devices.

No, I don't need any "second device". I *only* need the "appropriate special file" as mentioned in the RFC. I don't give a *damn* for what *physical device/port* the source is actually connected through. I suggest you should read the RFC again ...

Satyam

#22 lore raw

Re: LinuxPPS & spinlocks

Quoted 7 lines · Satyam Sharma <satyam <at> infradead.org> writes:
Quoted 4 lines · Rodolfo Giometti

On Mon, Jul 30, 2007 at 10:33:35AM +0530, Satyam Sharma wrote:
Currently the RFC says to you that you should open the serial port:

	fd = open("/dev/ttyS0", ...);
Quoted 7 lines

No, it does *NOT*. All it says is:

The time_pps_create() is used to convert an already-open UNIX file descriptor, for an appropriate special file, into a PPS handle.

See? What I said is precisely the implementation the RFC envisages (and the only sane way to implement it too).

If we were totally rigurous about representing each device as a device node, your solution would be fine. But we don't.

The clocksource model (/sys/devices/system/clocksource) is a better way to go. One sysfs file is used to enumerate the possible sources and another is
used to read or set the current source. No new system calls; no new ioctls.

-ch

ch (at) murgatroid (dot) com
ch (at) hpl (dot) hp (dot) com

#23 lore raw

Re: LinuxPPS & spinlocks

Hi,

Quoted 10 lines · Christopher Hoover
Quoted 9 lines · Satyam Sharma <satyam <at> infradead.org> writes:
Quoted 4 lines · Rodolfo Giometti

On Mon, Jul 30, 2007 at 10:33:35AM +0530, Satyam Sharma wrote:
Currently the RFC says to you that you should open the serial port:

	fd = open("/dev/ttyS0", ...);

No, it does *NOT*. All it says is:

Quoted 8 lines
Quoted 5 lines

The time_pps_create() is used to convert an already-open UNIX file descriptor, for an appropriate special file, into a PPS handle.

See? What I said is precisely the implementation the RFC envisages (and the only sane way to implement it too).

If we were totally rigurous about representing each device as a device node, your solution would be fine. But we don't.

Of course.

Quoted 3 lines

The clocksource model (/sys/devices/system/clocksource) is a better way to go. One sysfs file is used to enumerate the possible sources and another is
used to read or set the current source. No new system calls; no new ioctls.

Oh, not introducing any syscalls _at all_ would be fine, too. But the RFC does /require/ an implementation to have them. I was only mentioning the kind of implementation the RFC had in mind. But there are other ways to achieve the same end goal, and yes, probably it's better to avoid introducing syscalls in the first place and think of other mechanisms.

[ It's not that we're talking of IPsec or IPv6 or something here --
so RFC-compliance isn't overly important. But the final result needs to be good, secure and well-designed, still. ]

Satyam

author maintainer
#24 lore raw

Re: LinuxPPS & spinlocks

In reply to Satyam Sharma
Quoted 4 lines · Satyam Sharma

Ok, I've looked through (most of) the RFC and code now, and am only commenting on a design-level for now. Anyway, I didn't like the way you've significantly drifted from the RFC in several ways:

Please, read documentation file Documentation/pps/pps.txt where I exaplain why I did such RFC changes in my implementation.

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
author maintainer
#25 lore raw

Re: LinuxPPS & spinlocks

In reply to Satyam Sharma
Quoted 5 lines · Satyam Sharma

Take the race between the time_pps_setparams() syscall and a concurrent pps_event() from an interrupt for instance. From sys_time_pps_setparams, the parameters for an existing source are not modified / set atomically, which means a pps_event() called on the same source in between will see invalid parameters ... and bad things will happen.

I think this should be a good solution... :)

drivers/pps/kapi.c +0 -6
index 08de71d..f0c42ec 100644
@@ -29,12 +29,6 @@
 #include <linux/pps.h>
 
 /*
- * Local variables
- */
-
-static spinlock_t pps_lock = SPIN_LOCK_UNLOCKED;
-
-/*
  * Local functions
  */
 
drivers/pps/pps.c +5 -0
index 9176c01..91b7e4d 100644
@@ -35,6 +35,7 @@
 
 struct pps_s pps_source[PPS_MAX_SOURCES];
 DEFINE_MUTEX(pps_mutex);
+spinlock_t pps_lock = SPIN_LOCK_UNLOCKED;
 
 /*
  * Misc functions
@@ -227,6 +228,8 @@ asmlinkage long sys_time_pps_setparams(int source,
                goto sys_time_pps_setparams_exit;
        }
 
+       spin_lock(&pps_lock);
+
        /* Save the new parameters */
        ret = copy_from_user(&pps_source[source].params, params,
                                                sizeof(struct pps_kparams));
@@ -245,6 +248,8 @@ asmlinkage long sys_time_pps_setparams(int source,
                pps_source[source].params.mode |= PPS_CANWAIT;
        pps_source[source].params.api_version = PPS_API_VERS;
 
+       spin_unlock(&pps_lock);
+
 sys_time_pps_setparams_exit:
        mutex_unlock(&pps_mutex);
 
include/linux/pps.h +1 -0
index 6eca3ea..93e7384 100644
@@ -174,6 +174,7 @@ struct pps_s {
 
 extern struct pps_s pps_source[PPS_MAX_SOURCES];
 extern struct mutex pps_mutex;
+extern spinlock_t pps_lock;
 
 /*
  * Global functions

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#26 lore raw

Re: LinuxPPS & spinlocks

Hi Rodolfo,

Quoted 49 lines · Rodolfo Giometti
Quoted 5 lines · Satyam Sharma

Take the race between the time_pps_setparams() syscall and a concurrent pps_event() from an interrupt for instance. From sys_time_pps_setparams, the parameters for an existing source are not modified / set atomically, which means a pps_event() called on the same source in between will see invalid parameters ... and bad things will happen.

I think this should be a good solution... :)

drivers/pps/kapi.c +0 -6
index 08de71d..f0c42ec 100644
@@ -29,12 +29,6 @@
 #include <linux/pps.h>
 
 /*
- * Local variables
- */
-
-static spinlock_t pps_lock = SPIN_LOCK_UNLOCKED;
-
-/*
  * Local functions
  */
 
drivers/pps/pps.c +3 -0
index 9176c01..91b7e4d 100644
@@ -35,6 +35,7 @@
 
 struct pps_s pps_source[PPS_MAX_SOURCES];
 DEFINE_MUTEX(pps_mutex);
+spinlock_t pps_lock = SPIN_LOCK_UNLOCKED;
 
 /*
  * Misc functions
@@ -227,6 +228,8 @@ asmlinkage long sys_time_pps_setparams(int source,
                goto sys_time_pps_setparams_exit;
        }
 
+       spin_lock(&pps_lock);
+
        /* Save the new parameters */
        ret = copy_from_user(&pps_source[source].params, params,
                                                sizeof(struct pps_kparams));

drivers/pps/pps.c asmlinkage long sys_time_pps_setparams(int source, · line 254

Quoted 7 lines
drivers/pps/pps.c +2 -0
@@ -245,6 +248,8 @@ asmlinkage long sys_time_pps_setparams(int source,
                pps_source[source].params.mode |= PPS_CANWAIT;
        pps_source[source].params.api_version = PPS_API_VERS;
 
+       spin_unlock(&pps_lock);
+
 sys_time_pps_setparams_exit:
        mutex_unlock(&pps_mutex);

Nopes, this isn't quite correct/safe. I suggest you should read:

http://www.kernel.org/pub/linux/kernel/people/rusty/kernel-locking/

Satyam

author maintainer
#27 lore raw

Re: LinuxPPS & spinlocks

Quoted 4 lines · Satyam Sharma

Nopes, this isn't quite correct/safe. I suggest you should read:

http://www.kernel.org/pub/linux/kernel/people/rusty/kernel-locking/

I read it but still I don't see why my solution isn't correct/safe. :)

Can you please propose to me your solution?

Thanks a lot for you time!

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#28 lore raw

Re: LinuxPPS & spinlocks

Hi Rodolfo,

Quoted 7 lines · Rodolfo Giometti
Quoted 4 lines · Satyam Sharma

Nopes, this isn't quite correct/safe. I suggest you should read:

http://www.kernel.org/pub/linux/kernel/people/rusty/kernel-locking/

I read it but still I don't see why my solution isn't correct/safe. :)

What does the section on locking between hard irq contexts (or between user process context and hard irq context) say?

Quoted 1 line

Can you please propose to me your solution?

As I said, you could just use the spin_lock_irqsave/restore() variants ... If you want, I can try and implement the other bits that I had suggested for the other things as well :-)

Ciao,
Satyam

author maintainer
#29 lore raw

Re: LinuxPPS & spinlocks

Quoted 8 lines · Satyam Sharma
Quoted 5 lines · Rodolfo Giometti

In pps_event() is not useful using spin_lock_irqsave/restore() since the only difference between spin_lock_irqsave() and spin_lock() is that the former will turn off interrupts if they are on, otherwise does nothing (if we are already in an interrupt handler).

Yup. But two pps_event()'s on different CPU's could still race.

??? :-o

Maybe one CPU spins 'till the other holds the lock but any races should happen...

Quoted 5 lines
Quoted 2 lines

Maybe you meant I should using spin_lock_irqsave/restore() in user context, but doing like this I will disable interrupts

Yup, but the goal is to avoid races. Otherwise why bother doing any locking at all?

I meant that if you have to lock between user context and interrupt context you have two choises:

1) using spin_lock_irqsave/restore() in user context and spin_lock/unlock() in the interrupt context (as Rusty says),

2) or using spin_lock/unlock() in user context and spin_trylock/unlock() in the interrupt context in order to avoid dead locks.

Is that correct?

Quoted 11 lines
Quoted 3 lines

Of course, I meant "protecting data". In fact to protect pps_source[] I need spin_lock() to protect user context from interrupt context and mutex to protect user context from itself.

But that's nonsensical! That's not how you implement locking!

First, spin_lock() is *not* enough to protect access from process context from access from interrupt context.

Second, if you *already* have a lock to protect any data, introducing *another* lock to protect the same data is ... utterly crazy!

I see what you mean. But my question is about using spin_locks where we can sleep. Let me explain, consider sys_time_pps_getparams():

   asmlinkage long sys_time_pps_getparams(int source,
                                           struct pps_kparams __user *params)
   {
           int ret = 0;
           pr_debug("%s: source %d\n", __FUNCTION__, source);

           /* Sanity checks */
           if (!params)
                   return -EINVAL;

           if (mutex_lock_interruptible(&pps_mutex))
                   return -EINTR;

           ret = pps_check_source(source);
           if (ret < 0) {
                   ret = -ENODEV;
                   goto sys_time_pps_getparams_exit;
           }

           /* Return current parameters */
           ret = copy_to_user(params, &pps_source[source].params,
                                                   sizeof(struct pps_kparams));
           if (ret)
                   ret = -EFAULT;
   sys_time_pps_getparams_exit:
           mutex_unlock(&pps_mutex);
           return ret;

}

The copy_to_user() may sleep and if I change mutex_lock_interruptible() with a spin_lock I may hold it and then going to sleep... using mutex we can use the CPU for other computations.

Quoted 9 lines
Quoted 6 lines

I see. But consider pps_register_source(). This function should provide protection of pps_source against both interrupt context (pps_event()) and user context (maybe pps_unregister_source() or one syscalls). Using only mutex is not possible, since we cannot use mutex in interrupt context, and using only spin_locks is not possible since in UP() they became void.

Yup, but that's okay. On UP, spin_lock_irqsave() becomes local_irq_save() which is what you want anyway on UP.

But doing like this may happen that I first execute local_irq_save() and then go to sleep due copy_to_user()? :-o

Quoted 3 lines

The simplest, most straightforward, and safest, most correct, way would be to just use spin_lock_irqsave/restore() to around all access to the shared/global data, from _any_ context.

Even if I may sleep while holding a spinlock? Rusty says here
(http://www.kernel.org/pub/linux/kernel/people/rusty/kernel-locking/c557.html)
that:

Many functions in the kernel sleep (ie. call schedule()) directly or indirectly: you can never call them while __holding a spinlock__, or with preemption disabled. This also means you need to be in user context: calling them from an interrupt is illegal.

Quoted 2 lines

Anyway, I'll try and see if I find some time this week to implement what I was mentioning ...

Thanks a lot, so we can discuss on code. :)

Quoted 7 lines
Quoted 3 lines

That's the point. I don't wish using _irqsave/restore() since they may delay interrupt handler execution. As above, I prefere loosing the event then registering it at wrong time.

Ok, think of it this way -- you don't have an option. You just *have* to use them. As I said, please read Rusty Russell's introduction to locking in the kernel.

I see but I don't see why using spin_lock/unlock() in user contex and spin_trylock/unlock() in interrupt context is wrong. :)

Quoted 8 lines
Quoted 2 lines

Why you wish using one lock per sources? Just one lock for the list/array is not enought? :-o

No, I am *not* wishing / advocating that at all. Just that you appear so _reluctant_ to use spinlocks and are unnecessarily worrying about contention, disabling interrupts, etc etc.

Just use the spin_lock_irqsave/restore() variants, and you'll be fine.

What I wish is just to avoid disabling IRQs in user context in order to minimize the possibility to delay events recording. We this requirement the only solution I see is using spin_trylock/unlock() in interrupt context.

Another requirement is __not__ going to sleep while holding a spinlock (as Rusty says) and again the only solution I see is using mutex.

Looking at my previous patch I found that it should be written like this:

@@ -199,6 +200,7 @@ asmlinkage long sys_time_pps_setparams(int source,

                                        const struct pps_kparams __user *params) {
        int ret;

+ struct pps_kparams temp;

        pr_debug(``%s: source %d\n'', __FUNCTION__, source);

@@ -228,13 +230,16 @@ asmlinkage long sys_time_pps_setparams(int source,

        }
 
        /* Save the new parameters */
-       ret = copy_from_user(&pps_source[source].params, params,
-                                               sizeof(struct pps_kparams));
+       ret = copy_from_user(&temp, params, sizeof(struct pps_kparams));
        if (ret) {
                ret = -EFAULT;
                goto sys_time_pps_setparams_exit;
        }

+ spin_lock(&pps_lock);
+
+ pps_source[source].params = temp;
+

        /* Restore the read only parameters */
        if ((params->mode & (PPS_TSFMT_TSPEC | PPS_TSFMT_NTPFP)) == 0) {
                /* section 3.3 of RFC 2783 interpreted */
@@ -245,6 +250,8 @@ asmlinkage long sys_time_pps_setparams(int source,
                pps_source[source].params.mode |= PPS_CANWAIT;
        pps_source[source].params.api_version = PPS_API_VERS;

+ spin_unlock(&pps_lock);
+
sys_time_pps_setparams_exit:

        mutex_unlock(&pps_mutex);

In this manner I can going to sleep in copy_from_user() whitout holding any locks.

Quoted 11 lines · Satyam Sharma

No, it does *NOT*. All it says is:

The time_pps_create() is used to convert an already-open UNIX file descriptor, for an appropriate special file, into a PPS handle.

See? What I said is precisely the implementation the RFC envisages (and the only sane way to implement it too).

And later, where it gives an example, it shows:

Quoted 7 lines
    fd = open(PPSfilename, O_RDWR, 0);

What I'm saying is that the "PPSfilename", as is obvious from the name itself, is *not* a port such as lpXXX or ttySXXX, but an "appropriate special file" corresponding to a ... PPS source! Really, the RFC is quite clear and easy to read, I have no idea how to explain that more clearly ...

Ok, I see, but how you can get your PPS source data struct starting from a file descriptor? :-o

Quoted 3 lines
Quoted 1 line

As you propose you need _two_ open() and not just one...

No, why?

Please, take alook at NTPD code. Common usage is:

   fd = open("/dev/ttyS0", ...);

   pps_time_create(fd, &handler);

since RFC supposes that at filedes "fd" is mapped both GPS data _and_ PPS source.

With your suggestion code should be changed as follow:

   fd_gps = open("/dev/ttyS0", ...);

   fd_pps = open("/dev/pps0", ...);

   pps_time_create(fd_pps, &handler);
Quoted 6 lines
Quoted 3 lines

and even if
you decide to open the /dev/ppsX inside the pps_time_create(), how do you recognise _which_ /dev/ppsX is connected with filedse "fd"?

That's trivial to implement in the kernel code for the time_pps_create() syscall.

I didn't find a good solution for it.

Furthermore with my pps_findpath() I can do:

   fd = open("/dev/ttyS0", ...);

   handler = pps_findpath("/dev/ttyS0", ...);

which in most cases its more easy to manage for both user and kernel land.

Can do the same with char devices? Maybe you can easily create /dev/pps0 but how can you relate it with the /dev/ttyS0 if your GPS antenna and PPS source share the same serial port?

I studied the problem trying to find a good solution for both NTPD code (tring to change it as less as possible) and PPS sources connected with CPU's GPIOs, but currently I find nothing better that this.

Quoted 7 lines
Quoted 4 lines

I quite sure that RFC is broken since it doesn't take in account that a PPS source maybe not connected with any cahr device at all. I tried to explain this problem to RFC's gurus but they never answered to me, so I decided to resolve the problem by myself. ;)

Nopes, the RFC is not broken at all. All this physical-connection-port device vs PPS-source-device confusion is just in your mind :-)

Ok, if you don't think so try looking at NTPD code (written by RFC's gurus) and try to resolve the problem where both GPS antenna and PPS source are connected with a serial port, and the problem where only the GPS antenna is connected with the serial port but the PPS source is connected with a CPU's GPIO.

If you solve both them all PPS users will thank you a lot forever! :)

Quoted 9 lines
Quoted 4 lines

Ok, but in this case you still are _not_ RFC compliant (as showed above). You need that users give to you _two_ devices (the serial line and the PPS source), meanwhile, for the RFC, you just need one. So no differences from my solution from this point of view.

Yeah, so how am I not RFC compliant? Userspace will *only* open(2) the special char device of the *PPS source*, and have *nothing* to do with the device corresponding to the physical device/port it is connected through!

Ok, in your sceraio no problem, but continue to read RFC:

All of the other functions in the PPS API operate on PPS handles (type: pps_handle_t). The time_pps_create() is used to convert an already-open UNIX file descriptor, for an appropriate special file, into a PPS handle.

The definition of what special files are appropriate for use with the PPS API is outside the scope of this specification, and may vary based on both operating system implementation, and local system configuration. One typical case is a serial line, whose DCD pin is connected to a source of PPS events.

This shows that RFC creators though only at PPS sources connected with an _already_ opened device (as serial ports or parallel one), if not why don't define the function time_pps_create() as:

   int time_pps_create(char *ppsdev, pps_handle_t *handle);

???

No, they require an _already_ opened file descriptor because they supposed you can use serial line file descriptor! So, if this is not your case (because your PPS source is connected with a CPU's GPIO) you _must_ use a second open() (not considere at all into NTPD code) or, as I did, use a special function like pps_findsource/path().

Quoted 8 lines
Quoted 3 lines

I need them (or just one of them) in order to find a PPS source into the system. Just as you need the second device name in your solution with char devices.

No, I don't need any "second device". I *only* need the "appropriate special file" as mentioned in the RFC. I don't give a *damn* for what *physical device/port* the source is actually connected through. I suggest you should read the RFC again ...

I read it. Ok, according your solution and not considering the two open()s to do we should do:

   fd_pps = open("/dev/pps0", ...);

   time_pps_create(fd_pps, &handle);

ok? Two qeustions:

1) If the RFC wan't broken why it doesn't simply say that you can use fd_pps and pps handler?

2) How can you get kernel PPS source data just getting as input fd_pps value?

Again, RFC was sane if it said that you can get a PPS hadler by simply doing:

   time_pps_create("/dev/pps0", &handle);

this could be easily implemented with just an open()...

They didn't like this because they __never__ considered the case where the PPS source is not connected at all with any serial/parallel decices.

Quoted 3 lines · Satyam Sharma

What does the section on locking between hard irq contexts (or between user process context and hard irq context) say?

That I should use spin_lock_irqsave() but the document also:

1) says that I cannot hold spinlocks while sleeping and

2) doesn't say that using spin_lock/unlock() in user context and spin_trylock/unlock() in interrupt context is wrong.

Quoted 3 lines

As I said, you could just use the spin_lock_irqsave/restore() variants ... If you want, I can try and implement the other bits that I had suggested for the other things as well :-)

Great! Thanks a lot, so we can discuss on them and maybe we can prive Linux of this PPS support! :)

Thanks a lot for your time, this discussion was most important for me in better understanding locks problems (and also to improve my poor english, eheheheh :).

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#30 lore raw

Re: LinuxPPS & spinlocks

Hi Rodolfo,

Quoted 5 lines · Rodolfo Giometti
Quoted 3 lines · Satyam Sharma
Quoted 2 lines

Maybe you meant I should using spin_lock_irqsave/restore() in user context, but doing like this I will disable interrupts

Quoted 8 lines
Quoted 2 lines

Yup, but the goal is to avoid races. Otherwise why bother doing any locking at all?

I meant that if you have to lock between user context and interrupt context you have two choises:

1) using spin_lock_irqsave/restore() in user context and spin_lock/unlock() in the interrupt context (as Rusty says),

Yes, but we need to use spin_lock_irqsave() from interrupt context to synchronize between two hard irq contexts themselves.

Quoted 3 lines

2) or using spin_lock/unlock() in user context and spin_trylock/unlock() in the interrupt context in order to avoid dead locks.

Yup, this would avoid races, but then we will lose events. Why is that acceptable, when better alternative (above) exists?

Seriously, your aversion to implement good, safe locking is amazing! :-)

Quoted 12 lines
Quoted 11 lines
Quoted 3 lines

Of course, I meant "protecting data". In fact to protect pps_source[] I need spin_lock() to protect user context from interrupt context and mutex to protect user context from itself.

But that's nonsensical! That's not how you implement locking!

First, spin_lock() is *not* enough to protect access from process context from access from interrupt context.

Second, if you *already* have a lock to protect any data, introducing *another* lock to protect the same data is ... utterly crazy!

Quoted 7 lines

I see what you mean. But my question is about using spin_locks where we can sleep. Let me explain, consider sys_time_pps_getparams():
[...]
The copy_to_user() may sleep and if I change mutex_lock_interruptible() with a spin_lock I may hold it and then going to sleep... using mutex we can use the CPU for other computations.

The proper way to do this is to use a kernel buffer to do all kernel-side work (you acquire/release lock during that work) and then copy_to_user() later, at the end. [ And something opposite for the set_xxx syscall, i.e. first off copy_from_user() to a kernel buffer up front, before doing anything else itself, and then do all the work in the kernel on that. ]

BTW your syscall implementations totally lack any kind of security checks whatsoever ...

Quoted 11 lines
Quoted 8 lines
Quoted 2 lines

Why you wish using one lock per sources? Just one lock for the list/array is not enought? :-o

No, I am *not* wishing / advocating that at all. Just that you appear so _reluctant_ to use spinlocks and are unnecessarily worrying about contention, disabling interrupts, etc etc.

Just use the spin_lock_irqsave/restore() variants, and you'll be fine.

What I wish is just to avoid disabling IRQs in user context in order to minimize the possibility to delay events recording.

Amazing. On the one hand, you want to use spin_trylock() in the hard irq handler and spin_lock() (not irq safe) in the process context, because you "don't care about losing some events". And now you want to avoid "disabling irqs in user context to minimize possibility to delay events recording"?

Anyway, any such requirement you're talking about is just bogus, IMHO. You're just disabling interrupts to access a data structure, for Gods' sakes, how many nanoseconds do you imagine would you be "delaying"?

Quoted 4 lines
Quoted 3 lines
Quoted 1 line

As you propose you need _two_ open() and not just one...

No, why?

Quoted 8 lines

Please, take alook at NTPD code. Common usage is:

   fd = open("/dev/ttyS0", ...);

   pps_time_create(fd, &handler);

since RFC supposes that at filedes "fd" is mapped both GPS data _and_ PPS source.

Umm, I don't think the RFC supposes/assumes this anywhere.

Quoted 10 lines

Furthermore with my pps_findpath() I can do:

   fd = open("/dev/ttyS0", ...);

   handler = pps_findpath("/dev/ttyS0", ...);

which in most cases its more easy to manage for both user and kernel land.

Can do the same with char devices?

Of course. BTW time_pps_findpath/findsource do not have to be kernel implemented syscalls in the first place. The best, simplest and most straightforward place to implement them is in userspace -- the RFC mentions this as well.

Quoted 3 lines

Maybe you can easily create
/dev/pps0 but how can you relate it with the /dev/ttyS0 if your GPS antenna and PPS source share the same serial port?

A solution I can think of is to create a mapping at the time of pps_register_source() between the PPS source (physically) and the special char device. Userspace open(2)'s the special char device corresponding to the PPS source, and then issues the time_pps_create() syscall. Here, we lookup the mapping previously created and return handle to the PPS source based on the special device's fd that's passed to us in time_pps_create().

Quoted 8 lines
Quoted 7 lines
Quoted 4 lines

I quite sure that RFC is broken since it doesn't take in account that a PPS source maybe not connected with any cahr device at all. I tried to explain this problem to RFC's gurus but they never answered to me, so I decided to resolve the problem by myself. ;)

Nopes, the RFC is not broken at all. All this physical-connection-port device vs PPS-source-device confusion is just in your mind :-)

Quoted 7 lines

Ok, if you don't think so try looking at NTPD code (written by RFC's gurus) and try to resolve the problem where both GPS antenna and PPS source are connected with a serial port, and the problem where only the GPS antenna is connected with the serial port but the PPS source is connected with a CPU's GPIO.

If you solve both them all PPS users will thank you a lot forever! :)

Ok, I'll take a look, thanks :-)

[ what's the URL for these sources? ]

Quoted 2 lines

No, they require an _already_ opened file descriptor because they supposed you can use serial line file descriptor!

open(PPSfilename, O_RDWR) doesn't sound like that at all. If the device for the serial port / parport was intended, it wouldn't be called "PPSfilename", would it?

Quoted 10 lines

Again, RFC was sane if it said that you can get a PPS hadler by simply doing:

   time_pps_create("/dev/pps0", &handle);

this could be easily implemented with just an open()...

They didn't like this because they __never__ considered the case where the PPS source is not connected at all with any serial/parallel decices.

The physical port/device through which a PPS source is connected is immaterial. Anyway, I'll take a look at the NTPD/userspace code you are mentioning as well. [ again, could you point me to URL of source code? ]

Quoted 5 lines
Quoted 2 lines

If you want, I can try and implement the other bits that I had suggested for the other things as well :-)

Great! Thanks a lot, so we can discuss on them and maybe we can prive Linux of this PPS support! :)

Sure, I'll get to implementing what I have in mind here -- will be glad to be of any help, thanks.

Satyam

author maintainer
#31 lore raw

Re: LinuxPPS & spinlocks

Quoted 1 line · Satyam Sharma

Hi Rodolfo,

Hi :)

Quoted 2 lines

Yup, this would avoid races, but then we will lose events. Why is that acceptable, when better alternative (above) exists?

Because is better lossign events then recording them delayed. In the past we (LinuxPPS users) noticed that just postponing of one instruction the timestamp recording degrade the timesetting of about 50%!

Quoted 1 line

Seriously, your aversion to implement good, safe locking is amazing! :-)

I averse not by default. :) But I just wish understand _why_ a solution is better then other.

I'm sure my solution is not the best at all, but before changing it I wish understand if the new proposal is better.

Quoted 5 lines

The proper way to do this is to use a kernel buffer to do all kernel-side work (you acquire/release lock during that work) and then copy_to_user() later, at the end. [ And something opposite for the set_xxx syscall, i.e. first off copy_from_user() to a kernel buffer up front, before doing anything else itself, and then do all the work in the kernel on that. ]

Mmm... I think this is not easy at all for sys_time_pps_fetch(). I suppose you have to complicate its code a lot!

I don't undestand why we must complicate, and made unreadable, a code in order to follow the rule use-only-one-lock-mechanism. If by using mutex and spinlocks the code is more readable, where is the fault?

Quoted 2 lines

BTW your syscall implementations totally lack any kind of security checks whatsoever ...

Ok, we can correct them. :)

Quoted 5 lines

Amazing. On the one hand, you want to use spin_trylock() in the hard irq handler and spin_lock() (not irq safe) in the process context, because you "don't care about losing some events". And now you want to avoid "disabling irqs in user context to minimize possibility to delay events recording"?

Just for not delaying the IRQ handler. As already said, I prefere loosing events that delaying their timestamps recording.

Quoted 3 lines

Anyway, any such requirement you're talking about is just bogus, IMHO. You're just disabling interrupts to access a data structure, for Gods' sakes, how many nanoseconds do you imagine would you be "delaying"?

As already said we noticed that just delaying of one instruction the timestamp recording the time setting degrades of about 50%.

We have to take care of this point. It's _very_ important that _each_ event had its timestamp recorded with delay as small as possible.

Quoted 10 lines
Quoted 8 lines

Please, take alook at NTPD code. Common usage is:

   fd = open("/dev/ttyS0", ...);

   pps_time_create(fd, &handler);

since RFC supposes that at filedes "fd" is mapped both GPS data _and_ PPS source.

Umm, I don't think the RFC supposes/assumes this anywhere.

I think so. If not, why they pretend an _already opened_ filedes then just a filename to be used as parameter for the open(2) syscall? :)

Again, it was simpler, and more logic, define the time_pps_create as follow:

   time_pps_create(char *ppsdev, pps_handle_t *handle);

this definition resolves very well all possibile cases.

Quoted 4 lines

Of course. BTW time_pps_findpath/findsource do not have to be kernel implemented syscalls in the first place. The best, simplest and most straightforward place to implement them is in userspace -- the RFC mentions this as well.

Ok, I'll wait for your modification to see how you can do it.

Quoted 6 lines

A solution I can think of is to create a mapping at the time of pps_register_source() between the PPS source (physically) and the special char device. Userspace open(2)'s the special char device corresponding to the PPS source, and then issues the time_pps_create() syscall. Here, we lookup the mapping previously created and return handle to the PPS source based on the special device's fd that's passed to us in time_pps_create().

Ok, just what pps_findpath&C. does... however if you now how to implement it I'll be very to see the code. :)

But, as you can see, this is due the bogus RFC specification. It was more easier define the time_pps_create() as suggested above and you didn't need no mapping at all.

Quoted 3 lines

Ok, I'll take a look, thanks :-)

[ what's the URL for these sources? ]

Oh, yes... sorry, here the NTP main site:

http://www.ntp.org

Quoted 3 lines

open(PPSfilename, O_RDWR) doesn't sound like that at all. If the device for the serial port / parport was intended, it wouldn't be called "PPSfilename", would it?

No, I meant that if they require an already opened file descriptor is beacuse they simply don't suppose that a PPS source may be totally uncollerated to any device. If not they had two possibilities:

1) just using an open(2) to access a PPS source and using the returned filedes as PPS handler,

2) or, just to be more general, define the time_pps_create() as above, with the "char *ppsdevice" as parameter (then on UNIX systems we implement it with open(2)).

Quoted 3 lines

The physical port/device through which a PPS source is connected is immaterial. Anyway, I'll take a look at the NTPD/userspace code you are mentioning as well. [ again, could you point me to URL of source code? ]

http://www.ntp.org/downloads.html

Quoted 2 lines

Sure, I'll get to implementing what I have in mind here -- will be glad to be of any help, thanks.

If you wish proving patches to LinuxPPS I just created a "develop" branch into my GIT repository:

http://gitweb.enneenne.com/?p=linuxpps;a=shortlog;h=develop

Please, provide patch against that branch.

Thanks a lot,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#32 lore raw

Re: LinuxPPS & spinlocks

Quoted 23 lines · Rodolfo Giometti
Quoted 2 lines · Satyam Sharma

Yup, this would avoid races, but then we will lose events. Why is that acceptable, when better alternative (above) exists?

Because is better lossign events then recording them delayed. In the past we (LinuxPPS users) noticed that just postponing of one instruction the timestamp recording degrade the timesetting of about 50%!

Quoted 5 lines

Amazing. On the one hand, you want to use spin_trylock() in the hard irq handler and spin_lock() (not irq safe) in the process context, because you "don't care about losing some events". And now you want to avoid "disabling irqs in user context to minimize possibility to delay events recording"?

Just for not delaying the IRQ handler. As already said, I prefere loosing events that delaying their timestamps recording.

Quoted 3 lines

Anyway, any such requirement you're talking about is just bogus, IMHO. You're just disabling interrupts to access a data structure, for Gods' sakes, how many nanoseconds do you imagine would you be "delaying"?

Quoted 5 lines

As already said we noticed that just delaying of one instruction the timestamp recording the time setting degrades of about 50%.

We have to take care of this point. It's _very_ important that _each_ event had its timestamp recorded with delay as small as possible.

That's just absolute bullshit.

I'm sorry to say this, Rodolfo, but _all_ your arguments above are *totally* nonsensical and factually incorrect -- and I have had enough of trying to talk sense to you, it's been ~15 mails in this thread already, and I've been WASTING my time trying to teach / explain to you, but it's just *shocking* that you prefer to stick to a wholly incorrect (which I suspect you've already understood by now anyway) position rather than just accepting that the present patch is wrong and go about correcting it instead.

Quoted 6 lines
Quoted 5 lines

The proper way to do this is to use a kernel buffer to do all kernel-side work (you acquire/release lock during that work) and then copy_to_user() later, at the end. [ And something opposite for the set_xxx syscall, i.e. first off copy_from_user() to a kernel buffer up front, before doing anything else itself, and then do all the work in the kernel on that. ]

Quoted 6 lines

Mmm... I think this is not easy at all for sys_time_pps_fetch(). I suppose you have to complicate its code a lot!

I don't undestand why we must complicate, and made unreadable, a code in order to follow the rule use-only-one-lock-mechanism. If by using mutex and spinlocks the code is more readable, where is the fault?

More nonsense. Utter nonsense. I really don't want to reply anymore ...

Quoted 11 lines
Quoted 2 lines

BTW your syscall implementations totally lack any kind of security checks whatsoever ...

Ok, we can correct them. :)

Quoted 6 lines
Quoted 6 lines

Please, take alook at NTPD code. Common usage is:

   fd = open("/dev/ttyS0", ...);

   pps_time_create(fd, &handler);
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

since RFC supposes that at filedes "fd" is mapped both GPS data _and_ PPS source.

Umm, I don't think the RFC supposes/assumes this anywhere.

I think so. If not, why they pretend an _already opened_ filedes then just a filename to be used as parameter for the open(2) syscall? :)

Try reading the RFC again, please. And *think*.

Anyway, considering:

1. broken/nonsensical locking,
2. wrong (completely RFC non-compliant) implementation,
3. a syscall (time_pps_cmd) that has no semantics defined anywhere, not even mandated by the RFC, is (as you yourself admitted) a pseudo-ioctl for all practical purposes,
4. abject lack of security in the syscall implementations,

But MOST importantly:

5. your _sticking_ to the broken implementation and being so (shockingly!) unwilling to correct these,

I really cannot see how I can support this stuff in getting merged at all, sorry.

Satyam

author maintainer
#33 lore raw

Re: LinuxPPS & spinlocks

Quoted 1 line · Satyam Sharma

That's just absolute bullshit.

...

Quoted 9 lines

I'm sorry to say this, Rodolfo, but _all_ your arguments above are *totally* nonsensical and factually incorrect -- and I have had enough of trying to talk sense to you, it's been ~15 mails in this thread already, and I've been WASTING my time trying to teach / explain to you, but it's just *shocking* that you prefer to stick to a wholly incorrect (which I suspect you've already understood by now anyway) position rather than just accepting that the present patch is wrong and go about correcting it instead.
[snip]

Sorry for wasting your time. :'( Maybe you can provide your solution for PPS support and get it included into kernel tree so we can use it and live happy! :)

Several people (Andrew, David, et all) wrote to me a lot of letters without loosing their patience. I'm a poor programmer, not a «guru» like you, and I need more time to understand things. I'm trying to do my best. :)

However I'm very proud to be a "poor programmer" (slow in understanding things) but a gentleman rather than a "kernel-guru" like you but totally ill-mannered.

Thanks anyway for your (precious) time,

Rodolfo

P.S. A gentle programmer just wrote to me a letter where, proposing code/patches, showed to me possible good solutions, so I think I'm going to modify again the locking code soon.

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#34 lore raw

Re: LinuxPPS & spinlocks

Hi,

Quoted 3 lines · Rodolfo Giometti

Sorry for wasting your time. :'( Maybe you can provide your solution for PPS support and get it included into kernel tree so we can use it and live happy! :)

Please stop embarrassing me (and yourself).

Sorry, I did lose my patience (others you mention did not) but then that's precisely because of my own _less_ experience, if anything.

No, it's not like I "want to provide my solution for PPS support and get it included into kernel tree" like you wrote above -- I simply identified 4 problem areas in your implementation and wanted them to be addressed. [If you can do so yourself, good enough, otherwise I'm happy to send patch based on your earlier one too -- the modifications I have in mind are few and simple.] I have no personal stake in this PPS stuff anyway, this is just a normal peer review of submissions that should always happen.

Thanks,

Satyam

author maintainer
#35 lore raw

Re: LinuxPPS & spinlocks

In reply to Satyam Sharma
Quoted 9 lines · Satyam Sharma

I only glanced through the code, so could be wrong, but I noticed that the only global / shared data you have in there is a global "pps_source" array of pps_s structs. That's accessed / modified from the various syscalls introduced in the API exported to userspace, as well as the register/unregister/pps_event API exported to in-kernel client subsystems, yes? So it looks like you need to introduce proper locking for it, simply type-qualifying it as "volatile" is not enough.

Quoted 5 lines

However, I think you've introduced two locks for it. The syscalls (that run in process context, obviously) seem to use a pps_mutex and pps_event() seems to be using the pps_lock spinlock (because that gets executed from interrupt context) -- and from the looks of it, the register/unregister functions are using /both/ the mutex and spinlock (!)

This is right.

Quoted 3 lines

This isn't quite right, (in fact there's nothing to protect pps_event from racing against a syscall), so you should use *only* the spinlock for synchronization -- the spin_lock_irqsave/restore() variants, in fact.

We can't use the spin_lock_irqsave/restore() variants since PPS sources cannot manage IRQ enable/disable. For instance, the serial source doesn't manage IRQs directly but just uses it to record PPS events. The serial driver manages the IRQ enable/disable, not the PPS source which only uses the IRQ handler to records events.

About using both mutex and spinlock I did it since (I think) I should protect syscalls from each others and from pps_register/unregister(), and pps_event() against pps_register/unregister().

Quoted 14 lines

[ Also, have you considered making pps_source a list and not an array? It'll help you lose a whole lot of MAX_SOURCES, pps_is_allocated, etc kind of gymnastics in there, and you _can_ return a pointer to the corresponding pps source struct from the register() function to the in-kernel users, so that way you get to retain the O(1) access to the corresponding source when a client calls into pps_event(), similar to how you're using the array index presently. ]

I also noticed code like (from pps_event):

drivers/pps/kapi.c new file +3 -0
+	/* Try to grab the lock, if not we prefere loose the event... */
+	if (!spin_trylock(&pps_lock))
+		return;
Quoted 3 lines

which looks worrisome and unnecessary. That spinlock looks to be of fine enough granularity to me, do you think there'd be any contention on it? I /think/ you can simply make that a spin_lock().

This is due the fact I cannot manage IRQ enable/disable.

Quoted 4 lines

Overall the code looks simple / straightforward enough to me (except for the parport / uart stuff that I have no clue about), and I'll also read up on the relevant RFC for this and would hopefully try and give you a more meaningful review over the weekend.

Thanks a lot for your help!

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#36 lore raw

Re: LinuxPPS & spinlocks

Hi Rodolfo,

Quoted 22 lines · Rodolfo Giometti
Quoted 9 lines · Satyam Sharma

I only glanced through the code, so could be wrong, but I noticed that the only global / shared data you have in there is a global "pps_source" array of pps_s structs. That's accessed / modified from the various syscalls introduced in the API exported to userspace, as well as the register/unregister/pps_event API exported to in-kernel client subsystems, yes? So it looks like you need to introduce proper locking for it, simply type-qualifying it as "volatile" is not enough.

Quoted 5 lines

However, I think you've introduced two locks for it. The syscalls (that run in process context, obviously) seem to use a pps_mutex and pps_event() seems to be using the pps_lock spinlock (because that gets executed from interrupt context) -- and from the looks of it, the register/unregister functions are using /both/ the mutex and spinlock (!)

This is right.

Quoted 3 lines

This isn't quite right, (in fact there's nothing to protect pps_event from racing against a syscall), so you should use *only* the spinlock for synchronization -- the spin_lock_irqsave/restore() variants, in fact.

Quoted 5 lines

We can't use the spin_lock_irqsave/restore() variants since PPS sources cannot manage IRQ enable/disable. For instance, the serial source doesn't manage IRQs directly but just uses it to record PPS events. The serial driver manages the IRQ enable/disable, not the PPS source which only uses the IRQ handler to records events.

Hmm? I still don't see why you can't introduce spin_lock_irqsave/restore() in pps_event() around the access to pps_source.

Quoted 3 lines

About using both mutex and spinlock I did it since (I think) I should protect syscalls from each others and from pps_register/unregister(), and pps_event() against pps_register/unregister().

Nopes, it's not about protecting code from each other, you're needlessly complicating things. Locking is pretty simple, really -- any shared data, that can be concurrently accessed by multiple threads (or from interrupts) must be protected with a lock. Note that *data* is protected by a lock, and not "code" that handles it (well, this is the kind of behaviour most cases need, at least, including yours).

So here we're introducing the lock to protect *pps_source*, and not keep *threads* of execution from stepping over each other. So, simply, just ensure you grab the lock whenever you want to start accessing the shared data, and release it when you're done.

The _irqsave/restore() variants are required because (say) one of the syscalls executing in process context grabs the spinlock. Then, before it has released it, it gets interrupted and pps_event() begins executing. Now pps_event() also wants to grab the lock, but the syscall already has it, so will continue spinning and deadlock!

Quoted 14 lines
Quoted 14 lines

[ Also, have you considered making pps_source a list and not an array? It'll help you lose a whole lot of MAX_SOURCES, pps_is_allocated, etc kind of gymnastics in there, and you _can_ return a pointer to the corresponding pps source struct from the register() function to the in-kernel users, so that way you get to retain the O(1) access to the corresponding source when a client calls into pps_event(), similar to how you're using the array index presently. ]

I also noticed code like (from pps_event):

(quoted diff) +3 -0
+	/* Try to grab the lock, if not we prefere loose the event... */
+	if (!spin_trylock(&pps_lock))
+		return;
Quoted 5 lines
Quoted 3 lines

which looks worrisome and unnecessary. That spinlock looks to be of fine enough granularity to me, do you think there'd be any contention on it? I /think/ you can simply make that a spin_lock().

This is due the fact I cannot manage IRQ enable/disable.

What I meant is that you could make it a proper spin_lock() -- or spin_lock_irqsave(), actually -- instead of the _trylock_ variant that it currently is.

I think you're unnecessarily worrying about contention here -- you can have multiple locks (one for the list, and separate ones for your sources) if you're really worrying about contention -- or probably rwlocks. But really, rwlocks would end up being *slower* than spinlocks, unless the contention is really heavy and it helps to keep multiple readers in the critical section. But frankly, with at max a few (I'd expect generally one) PPS sources ever to be connected / registered with teh system, and just one-pulse-per-second, I don't see why any contention is ever gonna happen.

Satyam

author maintainer
#37 lore raw

Re: LinuxPPS & spinlocks

Quoted 3 lines · Satyam Sharma

Hmm? I still don't see why you can't introduce spin_lock_irqsave/restore() in pps_event() around the access to pps_source.

In pps_event() is not useful using spin_lock_irqsave/restore() since the only difference between spin_lock_irqsave() and spin_lock() is that the former will turn off interrupts if they are on, otherwise does nothing (if we are already in an interrupt handler).

Maybe you meant I should using spin_lock_irqsave/restore() in user context, but doing like this I will disable interrupts and I don't wish doing it since, in this manner, the interrupt handler will be delayed and the (probably) PPS event recording will be wrong. I prefere loosing the event that registering it at delayed time.

Quoted 10 lines
Quoted 3 lines

About using both mutex and spinlock I did it since (I think) I should protect syscalls from each others and from pps_register/unregister(), and pps_event() against pps_register/unregister().

Nopes, it's not about protecting code from each other, you're needlessly complicating things. Locking is pretty simple, really -- any shared data, that can be concurrently accessed by multiple threads (or from interrupts) must be protected with a lock. Note that *data* is protected by a lock, and not "code" that handles it (well, this is the kind of behaviour most cases need, at least, including yours).

Of course, I meant "protecting data". In fact to protect pps_source[] I need spin_lock() to protect user context from interrupt context and mutex to protect user context from itself.

Quoted 4 lines

So here we're introducing the lock to protect *pps_source*, and not keep *threads* of execution from stepping over each other. So, simply, just ensure you grab the lock whenever you want to start accessing the shared data, and release it when you're done.

I see. But consider pps_register_source(). This function should provide protection of pps_source against both interrupt context (pps_event()) and user context (maybe pps_unregister_source() or one syscalls). Using only mutex is not possible, since we cannot use mutex in interrupt context, and using only spin_locks is not possible since in UP() they became void.

Can you please show me how I could write pps_register_source() in order to be correct from your point of view?

Quoted 5 lines

The _irqsave/restore() variants are required because (say) one of the syscalls executing in process context grabs the spinlock. Then, before it has released it, it gets interrupted and pps_event() begins executing. Now pps_event() also wants to grab the lock, but the syscall already has it, so will continue spinning and deadlock!

That's the point. I don't wish using _irqsave/restore() since they may delay interrupt handler execution. As above, I prefere loosing the event then registering it at wrong time.

Quoted 9 lines

I think you're unnecessarily worrying about contention here -- you can have multiple locks (one for the list, and separate ones for your sources) if you're really worrying about contention -- or probably rwlocks. But really, rwlocks would end up being *slower* than spinlocks, unless the contention is really heavy and it helps to keep multiple readers in the critical section. But frankly, with at max a few (I'd expect generally one) PPS sources ever to be connected / registered with teh system, and just one-pulse-per-second, I don't see why any contention is ever gonna happen.

Why you wish using one lock per sources? Just one lock for the list/array is not enought? :-o

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#38 lore raw

Re: LinuxPPS & spinlocks

Hi,

Quoted 9 lines · Rodolfo Giometti
Quoted 3 lines · Satyam Sharma

Hmm? I still don't see why you can't introduce spin_lock_irqsave/restore() in pps_event() around the access to pps_source.

In pps_event() is not useful using spin_lock_irqsave/restore() since the only difference between spin_lock_irqsave() and spin_lock() is that the former will turn off interrupts if they are on, otherwise does nothing (if we are already in an interrupt handler).

Yup. But two pps_event()'s on different CPU's could still race.

Quoted 2 lines

Maybe you meant I should using spin_lock_irqsave/restore() in user context, but doing like this I will disable interrupts

Yup, but the goal is to avoid races. Otherwise why bother doing any locking at all?

Quoted 4 lines

and I don't
wish doing it since, in this manner, the interrupt handler will be delayed and the (probably) PPS event recording will be wrong. I prefere loosing the event that registering it at delayed time.

What you're risking is not "losing an event" (which, btw, you should not be, either), but a *deadlock*.

Quoted 11 lines
Quoted 10 lines
Quoted 3 lines

About using both mutex and spinlock I did it since (I think) I should protect syscalls from each others and from pps_register/unregister(), and pps_event() against pps_register/unregister().

Nopes, it's not about protecting code from each other, you're needlessly complicating things. Locking is pretty simple, really -- any shared data, that can be concurrently accessed by multiple threads (or from interrupts) must be protected with a lock. Note that *data* is protected by a lock, and not "code" that handles it (well, this is the kind of behaviour most cases need, at least, including yours).

Quoted 3 lines

Of course, I meant "protecting data". In fact to protect pps_source[] I need spin_lock() to protect user context from interrupt context and mutex to protect user context from itself.

But that's nonsensical! That's not how you implement locking!

First, spin_lock() is *not* enough to protect access from process context from access from interrupt context.

Second, if you *already* have a lock to protect any data, introducing *another* lock to protect the same data is ... utterly crazy!

Quoted 11 lines
Quoted 4 lines

So here we're introducing the lock to protect *pps_source*, and not keep *threads* of execution from stepping over each other. So, simply, just ensure you grab the lock whenever you want to start accessing the shared data, and release it when you're done.

I see. But consider pps_register_source(). This function should provide protection of pps_source against both interrupt context (pps_event()) and user context (maybe pps_unregister_source() or one syscalls). Using only mutex is not possible, since we cannot use mutex in interrupt context, and using only spin_locks is not possible since in UP() they became void.

Yup, but that's okay. On UP, spin_lock_irqsave() becomes local_irq_save() which is what you want anyway on UP.

Quoted 2 lines

Can you please show me how I could write pps_register_source() in order to be correct from your point of view?

The simplest, most straightforward, and safest, most correct, way would be to just use spin_lock_irqsave/restore() to around all access to the shared/global data, from _any_ context.

Anyway, I'll try and see if I find some time this week to implement what I was mentioning ...

Quoted 9 lines
Quoted 5 lines

The _irqsave/restore() variants are required because (say) one of the syscalls executing in process context grabs the spinlock. Then, before it has released it, it gets interrupted and pps_event() begins executing. Now pps_event() also wants to grab the lock, but the syscall already has it, so will continue spinning and deadlock!

That's the point. I don't wish using _irqsave/restore() since they may delay interrupt handler execution. As above, I prefere loosing the event then registering it at wrong time.

Ok, think of it this way -- you don't have an option. You just *have* to use them. As I said, please read Rusty Russell's introduction to locking in the kernel.

Quoted 10 lines
Quoted 9 lines

I think you're unnecessarily worrying about contention here -- you can have multiple locks (one for the list, and separate ones for your sources) if you're really worrying about contention -- or probably rwlocks. But really, rwlocks would end up being *slower* than spinlocks, unless the contention is really heavy and it helps to keep multiple readers in the critical section. But frankly, with at max a few (I'd expect generally one) PPS sources ever to be connected / registered with teh system, and just one-pulse-per-second, I don't see why any contention is ever gonna happen.

Quoted 2 lines

Why you wish using one lock per sources? Just one lock for the list/array is not enought? :-o

No, I am *not* wishing / advocating that at all. Just that you appear so _reluctant_ to use spinlocks and are unnecessarily worrying about contention, disabling interrupts, etc etc.

Just use the spin_lock_irqsave/restore() variants, and you'll be fine.

Satyam

author maintainer
#39 lore raw
In reply to David Woodhouse
Quoted 11 lines · David Woodhouse

I think you still haven't quite got the 32-bit vs. 64-bit compatibility right. Remember that on i386, the alignment of a uint64_t is only 4 bytes, while on most other architectures it's 8 bytes. On i386, there will be no padding between the two consecutive 'struct pps_ktime' members of struct pps_kinfo and struct pps_kparams. But on most platforms there will be padding to ensure correct alignment.

The simple fix is probably to make the 'nsec' member a 64-bit integer too. Then it'll be the same for i386 and x86_64 and you won't need a compatibility syscall routine.

By doing:

 struct pps_ktime {
        __u64 sec;

- __u32 nsec;
+ __u64 nsec;
};

I got:

  GEN     .version
  CHK     include/linux/compile.h
  UPD     include/linux/compile.h
  CC      init/version.o
  LD      init/built-in.o
  LD      .tmp_vmlinux1

drivers/built-in.o: In function `sys_time_pps_fetch':
(.text+0x5f05e): undefined reference to `__udivdi3'
make: *** [.tmp_vmlinux1] Error 1

I suppose the problem is here:

                ticks = to.sec * HZ;
                ticks += to.nsec / (NSEC_PER_SEC / HZ);

Suggestions? :)

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#40 lore raw
Quoted 2 lines · Rodolfo Giometti

drivers/built-in.o: In function `sys_time_pps_fetch':
(.text+0x5f05e): undefined reference to `__udivdi3'

Hm, not sure. Maybe put it back to uint32_t and then add another uint32_t of explicit padding, or maybe just cast it to uint32_t when you divide:

	ticks += (uint32_t)to.nsec / (NSEC_PER_SEC/HZ);
Signature · 1 line
dwmw2
author maintainer
#41 lore raw
Quoted 9 lines · David Woodhouse
Quoted 2 lines · Rodolfo Giometti

drivers/built-in.o: In function `sys_time_pps_fetch':
(.text+0x5f05e): undefined reference to `__udivdi3'

Hm, not sure. Maybe put it back to uint32_t and then add another uint32_t of explicit padding, or maybe just cast it to uint32_t when you divide:

	ticks += (uint32_t)to.nsec / (NSEC_PER_SEC/HZ);

Ok, padding data added. :)

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail:    [email protected]
Linux Device Driver                             [email protected]
Embedded Systems                     		[email protected]
UNIX programming                     phone:     +39 349 2432127
#42 lore raw
In reply to Rodolfo Giometti

Hi,

Review

Quoted 7 lines · Rodolfo Giometti

By doing:

 struct pps_ktime {
        __u64 sec;
(quoted diff) +1 -1
-       __u32 nsec;
+       __u64 nsec;
 };

Just using __u32 for both works as well...

bye, Roman