##################################################################
#             the shmdrv shared memory allocator module
#
#  loosely based on: http://www.embrisk.com/notes/shmem.html 
#  Status: public domain
#
##################################################################

#------------------------------
# shmdrv module
#
# build for kthreads flavors
ifeq ($(BUILD_SYS),kbuild)
obj-m += shmdrv.o
shmdrv-objs := rtapi/shmdrv/shmdrv.o

$(RTLIBDIR)/shmdrv$(MODULE_EXT): $(addprefix $(OBJDIR)/,$(shmdrv-objs))

INCLUDES += rtapi/shmdrv
endif # BUILD_SYS = kbuild

#------------------------------
# shmdrv module
#
# build for all kernels in SHMDRV_KERNEL_DIRS
ifeq ($(BUILD_ALL_FLAVORS)+$(USE_SHMDRV),yes+yes)
# we have no mapping of kver to kdir, so use a timestamp and do the
# whole thing in a big ugly non-Makefile-thonic shell script
SHMDRV_SRCS = rtapi/shmdrv/shmdrv.c \
	rtapi/shmdrv/shmdrv.h \
	rtapi/shmdrv/Makefile
objects/.shmdrv-built: $(SHMDRV_SRCS)
	for kdir in $(SHMDRV_KERNEL_DIRS); do \
	    kver=`../scripts/kernel-vers.sh $$kdir`; \
	    mkdir -p objects/userland/$$kver; \
	    cp $(SHMDRV_SRCS) objects/userland/$$kver; \
	    echo "Building userland shmdrv module for kernel version $$kver"; \
	    $(MAKE) \
		-C $$kdir \
		M=$(BASEPWD)/objects/userland/$$kver \
		CC=$(CC) KBUILD_VERBOSE=$(BUILD_VERBOSE); \
	    mkdir -p ../rtlib/userland/$$kver; \
	    cp objects/userland/$$kver/Module.symvers \
		objects/userland/$$kver/shmdrv.ko \
		../rtlib/userland/$$kver; \
	done
	touch $@

modules: objects/.shmdrv-built
endif # BUILD_ALL_FLAVORS && USE_SHMDRV

#------------------------------
# liblinuxcncshm.so shared lib

# make shmdrvapi.o a shared library, which gets around -fPIC
# issues on amd64
SHMDRVAPISRCS := rtapi/shmdrv/shmdrvapi.c

$(call TOOBJSDEPS, $(SHMDRVAPISRCS)): EXTRAFLAGS += -fPIC
SHMDRVLIB := ../lib/liblinuxcncshm.so

$(SHMDRVLIB).0: $(call TOOBJS, $(SHMDRVAPISRCS))
	$(ECHO) Creating shared library $(notdir $@)
	@mkdir -p ../lib
	@rm -f $@
	$(Q)$(CC) $(LDFLAGS)  -Wl,-soname,$(notdir $@) -shared \
	    -o $@ $^ -lrt
USERSRCS += $(SHMDRVAPISRCS) 
TARGETS += $(SHMDRVLIB) $(SHMDRVLIB).0

ifeq ($(BUILD_EXAMPLES),yes)
#------------------------------
# mutexwatch binary

# lock debugging help plus a bit of API example
MUTEXWATCH_SRCS =  rtapi/shmdrv/mutexwatch.c

$(call TOOBJSDEPS, $(MUTEXWATCH_SRCS)): \
	EXTRAFLAGS +=  $(THREADS_RTFLAGS)

../bin/mutexwatch: ../lib/liblinuxcncshm.so $(call TOOBJS, $(MUTEXWATCH_SRCS))
	$(ECHO) Linking $(notdir $@)
	$(Q)$(CC)  $(LDFLAGS) -o $@ $^  ../lib/liblinuxcncshm.so -lrt

USERSRCS += $(MUTEXWATCH_SRCS)
TARGETS += ../bin/mutexwatch

endif # BUILD_EXAMPLES


clean: shmdrv-clean
shmdrv-clean:
	rm -rf ../include/shmdrv
