# /*
# Copyright (c) 2017, Intel Corp.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#    * Neither the name of Intel Corporation nor the names of its contributors
#      may be used to endorse or promote products derived from this software
#      without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# */
################################################################################
DEBUG = 0
CC = gcc

PLATFORM = $(shell uname -m | sed 's/i.86/i386/')
IOMDFILE = /usr/lib/systemd/system/iommapd.service

##############################################################################
# Determine the correct path to the kernel source for the running kernel     #
##############################################################################
KERNELDIRS = /lib/modules/$(shell uname -r)/build \
    /lib/modules/$(shell uname -r)/source \
    $(shell find /usr/src/ -maxdepth 1 -iname 'linux*' -type l | grep -v linux-obj) \
    $(shell find /usr/src/ -maxdepth 1 -type l | grep $(shell uname -r | sed 's/\([0-9]*\.[0-9]*\)\..*/\1/')) \
    /usr/src/linux-$(shell uname -r) /usr/src/kernels/$(shell uname -r) /usr/src/kernel /usr/src/kernels

#CHECKDIR = $(shell [ -e $(dir)/include/linux ] && echo $(dir))
CHECKDIR = $(shell [ -e $(dir)/include ] && echo $(dir))
KERNELDIRS := $(foreach dir, $(KERNELDIRS), $(CHECKDIR))
KERNELDIR = $(firstword $(KERNELDIRS))

ifeq ($(KERNELDIR),)
    $(warning "WARNING: No default kernel sources found. It will assign folder in /usr/src!!!")
    KERNELDIRS = $(shell find /usr/src/ -maxdepth 1 -iname '*linux*' -type d) \
                 $(shell find /usr/src/ -maxdepth 1 -type d | grep $(shell uname -r | sed 's/\([0-9]*\.[0-9]*\)\..*/\1/')) \
                 $(shell find /usr/src/kernels -maxdepth 1 -iname '*linux*' -type d) \
                 $(shell find /usr/src/kernels -maxdepth 1 | grep $(shell uname -r | sed 's/\([0-9]*\.[0-9]*\.[0-9]\).*/\1/'))
    KERNELDIRS := $(foreach dir, $(KERNELDIRS), $(CHECKDIR))
endif

KERNELDIR = $(firstword $(KERNELDIRS))

ifeq ($(KERNELDIR),)
    $(error No kernel source installed. Please install kernel source!)
endif

INCLUDE = -I $(KERNELDIR)/include
WARN = -Wall

##############################################################################
# Determine which kernel we are running (e.g. 2.4.x, 2.6.x, 3.x)             #
##############################################################################
define LINUX_KERNEL
$(shell expr $1 \* 65536 + 0$2 \* 256 + 0$3)
endef

KERNELVER := $(shell uname -r | cut -f1-3 -d. | cut -f1 -d-)
KMAJ := $(shell echo $(KERNELVER) | cut -f1 -d.)
KMIN := $(shell echo $(KERNELVER) | cut -f2 -d.)
KREV := $(shell echo $(KERNELVER) | cut -f3 -d.)
LINUX_KERNEL_VERSION := $(call LINUX_KERNEL,$(KMAJ),$(KMIN),$(KREV))

##############################################################################
# Determine which distribution we are running on.                            #
# There might be some compatibility issues with LFS.  Need to re-test        #
##############################################################################
ifneq ($(wildcard /etc/SuSE-release),)
    OSREL = SUSE
else ifneq ($(wildcard /etc/redhat-release),)
    OSREL = REDHAT
else ifneq ($(wildcard /etc/mvl-release),)
    OSREL = MVL
else ifneq ($(wildcard /etc/lsb-release),)
    OSREL = UBUNTU
else ifeq ($(shell uname -r | cut -f3 -d-), yocto)
    OSREL = UBUNTU
    OSREL2 = YOCTO
else  
    $(error Unsupported Linux distribution!)
endif

RELEASEDIR = Release-$(PLATFORM)-$(OSREL)

##############################################################################
# Setup distribution-specific commands for RPM usage                         #
##############################################################################
ifneq ($(OSREL),UBUNTU)
ifneq ($(OSREL2), YOCTO)
RPMCMD = rpmbuild -ta
SERVICECMD = /etc/init.d
RPMVERSION := $(shell rpm --version | sed -e 's/RPM version //;s/\.[0-9]//2')
RPMMAJ := $(shell echo $(RPMVERSION) | cut -f1 -d.)
RPMMIN := $(shell echo $(RPMVERSION) | cut -f2 -d.)
define RPM_VERSION
$(shell expr $1 \* 256 + 0$2)
endef
RPMVER := $(call RPM_VERSION,$(RPMMAJ),$(RPMMIN))
RPMS = $(shell rpm --eval %{_rpmdir})
SRPMS = $(shell rpm --eval %{_srcrpmdir})
SOURCES = $(shell rpm --eval %{_sourcedir})
endif
endif

ifeq ($(OSREL),SUSE)
    # SuSE 8.2 use rpm -ba
    # SuSE 9.0 use rpmbuild -ba
    RPMCMD = $(shell find /usr/bin/ -iname 'rpmbuild')
    ifeq ($(RPMCMD),)
        RPMCMD = rpm -ta
    endif
endif

ifeq ($(OSREL),REDHAT)
    SERVICECMD = /sbin/service
endif

NO_RPM_SUPPORT := GENTOO LFS
RPM_VALID = $(if $(filter $(OSREL),$(NO_RPM_SUPPORT)),$(error $(OSREL) does not support RPM),)


##############################################################################
# Determine what kernel configuration parameters are set                     #
# TODO: Determine if MVL create these autoconf files                         #
##############################################################################
CONFIGFILES := $(KERNELDIR)/include/linux/autoconf.h \
               $(KERNELDIR)/include/generated/autoconf.h \
               /boot/vmlinuz.autoconf.h
CHECKFILE = $(shell [ -f $(config) ] && echo $(config))
CONFIGFILES := $(foreach config, $(CONFIGFILES), $(CHECKFILE))
CONFIGFILE = $(firstword $(CONFIGFILES))
ifeq ($(wildcard $(CONFIGFILE)),)
    $(error Source not configured correctly - autoconf.h is missing)
endif

##############################################################################
# Compilation flags                                                          #
##############################################################################
DRIVER_NAME = iommap
SRC = main.c pcitest.c cmos.c memmap.c
HDR = $(wildcard *.h)
DOC = $(DRIVER_NAME).txt $(DRIVER_NAME).chm
MISC = *.spec $(DRIVER_NAME)d Makefile
ALL_SRC = $(SRC) $(HDR) $(DOC) $(MISC)

OBJ = $(SRC:.c=.o)

# TODO: Scrub these macros.
EXTRA_CFLAGS += -DLINUX -D__KERNEL__ -DMODULE -D_$(OSREL) -D$(PLATFORM)
EXTRA_CFLAGS += $(WARN) $(INCLUDE)

ifeq ($(shell $(CC) -E -dM $(CONFIGFILE) | grep -w CONFIG_SMP | awk '{ print $$3 }'),1)
    EXTRA_CFLAGS += -D__SMP__ -DSMP
endif

ifeq ($(PLATFORM),x86_64)
    EXTRA_CFLAGS += -mcmodel=kernel -mno-red-zone
endif

# Compilation optimization CFLAGS
# -02 works for Redhat8.2, Redhat9, AS3.0 and SuSE9
ifeq ($(DEBUG),0)
    ifeq ($(OSREL),REDHAT)
        EXTRA_CFLAGS += -O2
    else
        EXTRA_CFLAGS += -O
    endif
else
    EXTRA_CFLAGS += -g -O -D_DEBUG
endif


##############################################################################
# Kernel-specific build rules                                                #
##############################################################################
ifeq (1,$(shell [ $(LINUX_KERNEL_VERSION) -ge $(call LINUX_KERNEL,2,6,0) ] && echo 1 || echo 0))

############################
# For 2.6.0 kernels or newer
TARGET = $(DRIVER_NAME).ko

ifneq ($(PATCHLEVEL),)
obj-m := $(DRIVER_NAME).o
$(DRIVER_NAME)-objs := $(SRC:.c=.o)
else
# EXTRA_CFLAGS will be read by the kernel build framework
default: $(SRC)
	@echo "Compiling source files for OS:($(OSREL), $(KERNELVER)..."
	@echo "Kernel source files path:($(KERNELDIR))..."
	$(MAKE) -C $(KERNELDIR) SUBDIRS=$(CURDIR) modules
endif

else ifeq (1,$(shell [ $(LINUX_KERNEL_VERSION) -lt $(call LINUX_KERNEL,2,5,0) ] && echo 1 || echo 0))
ifeq (1,$(shell [ $(LINUX_KERNEL_VERSION) -ge $(call LINUX_KERNEL,2,4,0) ] && echo 1 || echo 0))

###################
# For 2.4.x kernels
TARGET = $(DRIVER_NAME).o

$(TARGET): $(OBJ)
	$(LD) -r $^ -o $@

$(OBJ): $(SRC) $(wildcard *.h) Makefile
default:
	@echo "Compiling source files for OS:($(OSREL), $(KERNELVER)..."
	@echo "Kernel source files path:($(KERNELDIR))..."
	$(CC) $(EXTRA_CFLAGS) -c $(SRC)

else
$(error Kernel not supported. Please update to the latest stable 2.4.x release)
endif # if 2.4.0 <= $(LINUX_KERNEL_VERSION) < 2.5.0 (2.4.x range)

else
$(error Kernel not supported. Please update to the latest stable release)
endif # ifeq kernel 2.4, or 2.6, or ...

##############################################################################
# Generic build rules

driver: default

conf:
	@echo "Creating default Major/Minor number in iommapd.conf configuration file..."
	@echo "MAJOR=253" > iommapd.conf
	@echo "MINOR=0" >> iommapd.conf
	@echo "OSVER=$(OSREL)" >> iommapd.conf
	@echo "TARGET=$(TARGET)" >> iommapd.conf
	@echo "AUTO_DETECT=YES" >> iommapd.conf
	@chmod 644 iommapd.conf


DRIVER_OUTPUT := $(DESTDIR)/lib/modules/$(shell uname -r)/iMTA
TARGET_OUTPUT = $(DRIVER_OUTPUT)/$(DRIVER_NAME)
SVCCTRL := $(shell test "$(KMAJ)" -ge 3 -a "$(KMIN)" -ge 1 && printf "true")

install: driver conf
ifeq ($(SVCCTRL), true)
ifneq ($(OSREL2), YOCTO)
	@echo "Kernel $(KMAJ).$(KMIN) detected..."
	@echo "Copying iommapd.service to /usr/lib/systemd/system..."
	@if [ ! -d /usr/lib/systemd/system ]; then { mkdir /usr/lib/systemd/system; } fi
	@cp -f ./iommapd.service /usr/lib/systemd/system/iommapd.service
	@chmod 777 /usr/lib/systemd/system/iommapd.service
	@systemctl daemon-reload
	@systemctl enable iommapd.service
	@echo
endif
endif
	@echo "Installing driver:($(TARGET_OUTPUT)/$(TARGET)) to run level 3 & 5..."
	@mkdir -p $(TARGET_OUTPUT)	
	@install -m 777 -t $(TARGET_OUTPUT) $(DRIVER_NAME).txt $(DRIVER_NAME).chm
	@dos2unix -k $(TARGET_OUTPUT)/*
	@install -D -m 644 $(TARGET) $(TARGET_OUTPUT)/$(TARGET)
	@dos2unix -k iommapd
	@dos2unix -k iommapd.conf
	@install -D -m 755 iommapd $(DESTDIR)/etc/init.d/iommapd
	@install -D -m 644 iommapd.conf $(DESTDIR)/etc/iommapd.conf
	@/sbin/depmod -a || true

drvstrt:	
# ifeq ($(KMAJ),3)
#	@service iommapd link
#	@service iommapd restart
# else
#	@cd /etc/init.d/
#	@./iommapd link
#	@./iommapd restart
# endif
	@sh /etc/init.d/iommapd link
	@sh /etc/init.d/iommapd restart
	@sh /etc/init.d/iommapd status

uninstall: clean
	@if [ -e $(TARGET_OUTPUT) ]; then rm -rf $(TARGET_OUTPUT); fi
	@/sbin/depmod -a
	@if [ -e /etc/init.d/iommapd ]; then rm -f /etc/init.d/iommapd; fi
	@if [ -e /etc/iommapd.conf ]; then rm -f /etc/iommapd.conf; fi


rpm: VERSION = $(shell grep -m1 "IOMMAP_VERSION" main.c | sed 's/.*"\(.*\)".*/\1/')
rpm: $(RPM_VALID) tar
	@echo "Creating RPM source and binary package file for $(DRIVER_NAME) ver:($(VERSION))..."
	@echo "RPM Version:($(RPMVERSION))..."
	@$(RPMCMD) $(DRIVER_NAME)-$(VERSION).tar.gz
	@mv $(RPMS)/$(PLATFORM)/$(DRIVER_NAME)-$(VERSION)*.rpm .


tar: VERSION = $(shell grep -m1 "IOMMAP_VERSION" main.c | sed 's/.*"\(.*\)".*/\1/')
tar: clean
	@echo "Creating source tar ball for $(DRIVER_NAME) (ver: $(VERSION))..."
	@mkdir $(DRIVER_NAME)-$(VERSION)
	@cp -p $(ALL_SRC) $(DRIVER_NAME)-$(VERSION)
	@dos2unix -k $(DRIVER_NAME)-$(VERSION)/$(DRIVER_NAME).chm
	@sed -i '/%define _target_output/s|$$| $(TARGET_OUTPUT)|' $(DRIVER_NAME)-$(VERSION)/$(DRIVER_NAME).spec
	@sed -i '/Version:/s|$$| $(VERSION)|' $(DRIVER_NAME)-$(VERSION)/$(DRIVER_NAME).spec
	@if [ $(RPMVER) -lt $(call RPM_VERSION,4,4) ]; then \
		sed -i 's/License:/Copyright:/' $(DRIVER_NAME)-$(VERSION)/$(DRIVER_NAME).spec; \
	fi
	@tar -zvcf $(DRIVER_NAME)-$(VERSION).tar.gz $(DRIVER_NAME)-$(VERSION)


dist: clean rpm
	@echo "Creating release package file for $(DRIVER_NAME) ver:($(VERSION))..."
	@if [ ! -d $(RELEASEDIR) ]; then { mkdir $(RELEASEDIR); } fi
	@cp $(SRPMS)/$(DRIVER_NAME)-$(VERSION)*.rpm $(RELEASEDIR)
	@cp $(SOURCES)/$(DRIVER_NAME)-$(VERSION)*.tar.gz $(RELEASEDIR)
	@find $(RPMS) -iname '$(DRIVER_NAME)-$(VERSION)*.rpm' -exec cp {} $(RELEASEDIR)


clean: VERSION = $(shell grep -m1 "IOMMAP_VERSION" main.c | sed 's/.*"\(.*\)".*/\1/')
clean:
	@echo "Cleaning object files, binaries and installation file..."
	@rm -rf *.o *.ko *.tar *.gz *.rpm *.order *.symvers
	@rm -rf .tmp_versions .*.cmd *.mod.* *.ko.unsigned
	@rm -rf $(RELEASEDIR)
	@rm -rf $(DRIVER_NAME)-$(VERSION)
	@rm -rf $(DRIVER_OUTPUT)
	@rm -rf /dev/$(DRIVER_NAME)
#ifneq ($(OSREL),SUSE)
ifeq ($(OSREL),REDHAT)
	@if [ -f /etc/init.d/iommapd ]; then $(SERVICECMD) iommapd unlink; fi
else
	@echo
	@sh /etc/init.d/iommapd unlink
endif
	@rm -rf /etc/init.d/iommapd
	@rm -rf /etc/iommapd.conf
ifeq ($(SVCCTRL), true)
	@echo
	@echo "Cleaning iommapd.service from /usr/lib/systemd/system..."
	@if [ -f $(IOMDFILE) ]; then systemctl disable iommapd.service; fi;
	@if [ -f $(IOMDFILE) ]; then rm -rf $(IOMDFILE); fi;
endif
	@echo "Done"


help:
	@echo  ''
	@echo  'Cleaning targets:'
	@echo  '  clean           - remove generated files'
	@echo  '  uninstall       - uninstall driver & remove generated files'
	@echo  'Configuration targets:'
	@echo  '  conf            - generate configuration template file'
	@echo  'Other generic targets:'
	@echo  '  driver          - Build driver (default rule)'
	@echo  '  install         - Build driver and install'
	@echo  '  drvstrt         - Start driver'
	@echo  'Driver packaging:'
	@echo  '  dist            - Build distribution'
	@echo  '  rpm             - Build rpm package'
	@echo  '  tar             - Build tar ball package'
	@echo  ''
	@echo  'Execute "make install" to install the driver'
	@echo  'Execute "make drvstrt" to start the driver'
	@echo  'Execute "make uninstall" to uninstall the driver & remove generated files'
	@echo  ''



