Autocomplete (For Qmake)
QMAKE_CXXFLAGS = -I/usr/src/linux-3.1.8-1-ARCH/include
QMAKE_CFLAGS = -I/usr/src/linux-3.1.8-1-ARCH/include
Debug Options For Kernel:
- Kernel hacking -- [*] Show timing information on printks -- [*] Magic SysRq key -- [*] Debug filesystem -- [*] Kernel debugging -- [*] Detect Soft Lockups -- [ ] Collect scheduler statistics -- [*] Debug slab memory allocations -- [*] Memory leak debugging -- [*] RT Mutex debugging, deadlock detection -- [*] Spinlock debugging -- [*] Sleep-inside-spinlock checking -- [ ] kobject debugging -- [ ] Highmem debugging -- [ ] Compile the kernel with debug info
Mount debugfs
mount -t debugfs none /sys/kernel/debug
Test GPIO
echo 30 > /sys/class/gpio/export
echo in > /sys/class/gpio/gpio30/direction
cat /sys/class/gpio/gpio30/value
cat /sys/kernel/debug/gpio
Disable Peripherals
http://labs.isee.biz/index.php/Mux_instructions
Set sdmmc2_dat5 to gpio137 (mode 4):
# -> root@localhost:/sys/kernel/debug/omap_mux#
cat sdmmc2_dat5
# Result
# name: sdmmc2_dat5.gpio_137 (0x48002166/0x136 = 0x0004), b ah3, t NA
# mode: OMAP_PIN_OUTPUT | OMAP_MUX_MODE4
# signals: sdmmc2_dat5 | sdmmc2_dir_dat1 | cam_global_reset | sdmmc3_dat1 | gpio_137 | hsusb3_tll_stp | mm3_rxdp | safe_mode
# Set sdmmc2_dat5 to gpio137 (mode 4):
echo 0x004 > sdmmc2_dat5
# Check that gpio137 is in user space:
# -> root@localhost:/sys/class/gpio#
ls
# Result: export gpio137 gpio138 gpio139 gpio170 gpio64 gpiochip0 gpiochip128 gpiochip160 gpiochip192 gpiochip32 gpiochip64 gpiochip96 unexport
List iomem and ioports
cat /proc/iomem
cat /proc/ioports
Yazılım bir sanattır. Motosiklet kullanmak da öyle. İkiside incelik ister. Altında bastırdıkları amortisörleri, susturucusuz egzosları ve kaskı kafası yerine koluna takanlardan bahsetmediğim gibi diploma almayı yeterlilik sayan, incelik nezaket ve yaratıcılıktan yoksun, yazılım geliştirmeyi esnaflıkla eşdeğer bir kazanç kapısı gören meslektaşlarımdan da bahsetmiyorum. Etrafındaki insanlara kod yazıyorum hek yapıyorum diye "hava atan" yeniyetmeler de bu yazının ilgi alanına girmiyor. Bohemian Rhapsody'nin içindeki pattern'i ve yaratıcılığı görebilen insanlardan bahsediyorum.
Peki neden yazılım ve motosiklet değil de python ve enduro?
Aslında konunun altında yatan toplumun çizdiği iki düz çizginin arasında gitmektense çizgilerin dışında ilerleyen insanlar. Yaratıcılıklarının farkında olanlar. Python nasıl open source dünyasının bir markası ise kullandığım motosiklet olan Honda-CRF'de enduro dünyasının bir markası. İkisi de ilk başlandığında aksaklıklarla başlar. İkiside bildiğiniz kalıpların dışındadır çünkü.
İlk enduro makinamla araziden inip piste girdiğimizde rampada takla atıp düştükten sonra 1 ay boyunca sağ tarafıma yatarken kemiğim ağrımıştı. Ama o 1 günlük haz 1 ay boyunca mutlu uyuyabilemmi ve tekrar piste gideceğim günü hayal etmemi sağladı. Son düşüşüm oldu. Ne yapmam gerektiğini artık biliyordum.
Pythonla ilk kod yazdığım zamanlarda loop döngülerindeki zaman kaybı yüzüme tokat gibi çarpmıştı. Ama loop'un içini map ettikten, bir kaç optimizasyondan ve pypy ile çalıştırdıktan sonra ARM bir makinada C'ye yakın bir performans elde edince aldığım haz tarif edilemezdi.
Artık biliyordum. Ne hayabusa ne de R1 beni arazide takip edemezlerdi.
Artık biliyordum ne C# ne de senelerce ekmeğini yediğim Java artık beni takip edemezlerdi.
CRF ile artık trafiğin içinde sıkışmış değildim. Önümde yepyeni bir dünya vardı bu sıkış trafikte. Kaldırımlar ve merdivenler :)
Python ile yazılım dünyasının doktrinleri arasında sıkışmış değildim. Her ne kadar python nesne yönelimli bir dil olarak bilinsede esasen alakası yoktur, nesne tabanlı bir dildir ve bu da yazmak istediğiniz tipe göre biçim değiştirmenize olanak sağlar. Bu da yaratıcılığıma kimsenin gem vuramıyacağı anlamına geliyordu :)
Arazide düştükten sonra ben bir ayda kendime gelebilirken , motorumun yamulan gidonunun ve ayak peginin bir klavuz ve mengene yardımıyla 10 dk da düzeltildiğini ve orjinali gibi olduğunu gördüğümde anladım ki herhangi bir sorunda beni yarıyolda bırakmıyacaktı ve düzeltmem dakikalarımı alacaktı.
Django ile sıfırdan ilk blogumu oluşturduğumda(bu oluyor kendileri) eşim köklü bir değişiklik istediğinde bana sadece yarım saat zamana mal olduğunu gördüğümde anladım ki beni yarıyolda bırakmıyacaktı ve düzeltmem dakikalarımı alacaktı.
Arkadaşımın R1'i ile otobanda kalıp, servisin gıkını çıkarmayıp, taşımacıya bir ton para ödeyip kendi parasıyla rezil olmasını izlerken, bir başka arkadaşım dağda kaldığında enduro kullananların bir kurtarma ekibi oluşturduğunu gördüğümde kullandığım motosikletin değerini bir kez daha anladım.
Çalıştığım iş yerleri C# ve benzeri dillerde destek almak için bir ton para ödeyip paralarıyla rezil olurken; sıkıştığımda irc üzerinden insanların yardımcı olmak için bana can attıklarını gördüğümde açık kaynak kod paylaşımcılığının değerini bir kez daha anladım.
Sözün özü Python dünyası da enduro dünyası da paylaşım ve özgürlük üzerine kuruludur. Ama hayatları boyunca ne paylaşmayı ne de gerçek anlamda özgürlüğü tatmamış olanlara anlatması zor oluyor maalesef :)
# aktif olan çözünürlük
v4l2-ctl -V
# Seçili format
v4l2-ctl --list-formats
# Tümü
v4l2-ctl --list-formats-ext
########################################
lsusb
# >> Bus 001 Device 032: ID 046d:089d Logitech, Inc. QuickCam E2500 series
lsusb -s 001:032 -v | egrep "Width|Height"
#>> wWidth 640
#>> wHeight 480
#>> wWidth 1280
#>> wHeight 1024
echo 169 > /sys/class/gpio/export
# echo "in" > /sys/class/gpio/gpio169/direction
echo "out" > /sys/class/gpio/gpio169/direction
echo 0 > /sys/class/gpio/gpio169/value
echo 1 > /sys/class/gpio/gpio169/value
echo 169 > /sys/class/gpio/unexport
# if Kernel configuration ---> Kernel hacking ---> Debug FS enabled
# You can check who uses which gpio
mount -t debugfs none /sys/kernel/debug
cat /sys/kernel/debug/gpio
# pincontrol
# /sys/kernel/debug/pinctrl/
rar a -R -m5 -v10m myarchive.rar compress_directory
a= add
r= recursive
m= compression ratio (1-5)
Results:
Arm - Beagleboard
Calculation Table (in seconds) | Python | PyPy |
---|---|---|
Array Copy | 89.420 | 19.510 |
Float Arithmetic | 77.180 | 0.640 |
Integer Arithmetic | 75.720 | 6.270 |
String Search | 14.860 | 0.640 |
Total | 257.210 | 27.070 |
80x86 64bit (4 core but single thread)
Calculation Table (in seconds) | Python | PyPy |
---|---|---|
Array Copy | 26.906 | 8.053 |
Float Arithmetic | 25.386 | 0.178 |
Integer Arithmetic | 23.494 | 1.988 |
String Search | 4.856 | 0.219 |
Total | 80.642 | 10.438 |
Test Code:
# -*- coding: utf-8 -*-
import time
__author__ = 'ozgur'
__creation_date__ = '4/1/16' '4:11 PM'
TEST_STRING = '''The hierarchy shown above is relative to a PREFIX directory. PREFIX is computed by starting from the directory where the executable resides, and “walking up” the filesystem until we find a directory containing lib_pypy and lib-python/2.7.
The archives (.tar.bz2 or .zip) containing PyPy releases already contain the correct hierarchy, so to run PyPy it’s enough to unpack the archive, and run the bin/pypy executable.
To install PyPy system wide on unix-like systems, it is recommended to put the whole hierarchy alone (e.g. in /opt/pypy2.1) and put a symlink to the pypy executable into /usr/bin or /usr/local/bin
If the executable fails to find suitable libraries, it will report debug: WARNING: library path not found, using compiled-in sys.path and then attempt to continue normally. If the default path is usable, most code will be fine. However, the sys.prefix will be unset and some existing libraries assume beni bul that this is never the case.'''
class StressSuite():
def __init__(self):
pass
@staticmethod
def test_array():
a = []
for y in range(1000000):
txt_arr = "deneme".split()
for item in txt_arr:
a.append(item)
del (a)
@staticmethod
def test_float():
a = 0.5612342
b = 653.324556
c = a + b
d = a * b
e = b / a
f = a - b
@staticmethod
def test_int():
a = 5612342
b = 653324556
c = a + b
d = a * b
e = b / a
f = a - b
@staticmethod
def test_string():
b = TEST_STRING.find("beni bul")
def runtest(self, label, loop, func_exec):
print "Testing : ", label
s_time = time.time()
for x in range(loop):
func_exec()
print "%s exec time : %.3f sn." % (label, (time.time() - s_time))
def run(self):
s_time = time.time()
self.runtest("Array Copy", 100, StressSuite.test_array)
self.runtest("Float Arithmetic", 100000000, StressSuite.test_float)
self.runtest("Integer Arithmetic", 100000000, StressSuite.test_int)
self.runtest("String Search", 10000000, StressSuite.test_string)
print "Total exec time : %.3f sn." % (time.time() - s_time)
if __name__ == '__main__':
ss = StressSuite()
ss.run()
This driver :
1) Creates a character device called kbdozgur
2) Handles an interrupt(keyboard) , buffers it
- send buffered data when kbdozgur opened for read
- prints into dmesg when you put a message in kbdozgur
#include <linux/init.h> // Macros used to mark up functions e.g. __init __exit
#include <linux/module.h> // Core header for loading LKMs into the kernel
#include <linux/device.h> // Header to support the kernel Driver Model
#include <linux/kernel.h> // Contains types, macros, functions for the kernel
#include <linux/fs.h> // Header for the Linux file system support
#include <asm/uaccess.h> // Required for the copy to user function
#include <linux/interrupt.h>
#include <asm/io.h>
#define DEVICE_NAME "kbdozgur" ///< The device will appear at /dev/kbdozgur using this value
#define CLASS_NAME "kbdozgur" ///< The device class -- this is a character device driver
MODULE_AUTHOR("Mehmet Ozgur Bayhan");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Kill all the white men!");
MODULE_VERSION("0.2");
#define BUFFER_SIZE 200
static unsigned char messageFromInterrupt[BUFFER_SIZE]; //buffer that holds interrupt values
static short bufferCounter = 0; //buffer counter for loop
static int majorNumber; ///< Stores the device number -- determined automatically
static char messageFromUser[BUFFER_SIZE] = { 0 }; ///< Memory for the string that is passed from userspace
//static short size_of_message; ///< Used to remember the size of the string stored
static int numberOpens = 0; ///< Counts the number of times the device is opened
static struct class* kbdozgurcharClass = NULL; ///< The device-driver class struct pointer
static struct device* kbdozgurcharDevice = NULL; ///< The device-driver device struct pointer
// The prototype functions for the character driver -- must come before the struct definition
static int dev_open(struct inode *, struct file *);
static int dev_release(struct inode *, struct file *);
static ssize_t dev_read(struct file *, char *, size_t, loff_t *);
static ssize_t dev_write(struct file *, const char *, size_t, loff_t *);
static struct file_operations fops = { .open = dev_open, .read = dev_read, .write = dev_write, .release = dev_release, };
irq_handler_t irq_handler(int irq, void *dev_id, struct pt_regs *regs) {
static unsigned char scancode;
//Read keyboard status
scancode = inb(0x60);
if (scancode == 0x01) {
printk(KERN_INFO "MOB: Inputs are > %s\n", messageFromInterrupt);
bufferCounter = 0;
memset(&messageFromInterrupt[0], 0, sizeof(messageFromInterrupt));
}
else if (scancode == 0x1E) {
messageFromInterrupt[bufferCounter] = 'a';
bufferCounter++;
}
else if (scancode == 0x1F) {
messageFromInterrupt[bufferCounter] = 's';
bufferCounter++;
}
else if (scancode == 0x20) {
messageFromInterrupt[bufferCounter] = 'd';
bufferCounter++;
}
else if (scancode == 0x21) {
messageFromInterrupt[bufferCounter] = 'f';
bufferCounter++;
}
else if (scancode == 0x22) {
messageFromInterrupt[bufferCounter] = 'g';
bufferCounter++;
}
else if (scancode == 0x23) {
messageFromInterrupt[bufferCounter] = 'h';
bufferCounter++;
}
else if (scancode == 0x24) {
messageFromInterrupt[bufferCounter] = 'j';
bufferCounter++;
}
if (bufferCounter >= BUFFER_SIZE) {
bufferCounter = 0;
memset(&messageFromInterrupt[0], 0, sizeof(messageFromInterrupt));
}
return (irq_handler_t) IRQ_HANDLED;
}
static int init_mod(void) {
int result;
/*
*****************************
* Create Character device
*****************************
*/
// Try to dynamically allocate a major number for the device
majorNumber = register_chrdev(0, DEVICE_NAME, &fops);
if (majorNumber < 0) {
printk(KERN_ALERT "MOB: kbdozgurcharClass failed to register a major number\n");
return majorNumber;
}
printk(KERN_INFO "MOB: registered correctly with major number %d\n", majorNumber);
// Register the device class
kbdozgurcharClass = class_create(THIS_MODULE, CLASS_NAME);
if (IS_ERR(kbdozgurcharClass)) { // Check for error and clean up if there is
unregister_chrdev(majorNumber, DEVICE_NAME);
printk(KERN_ALERT "MOB: Failed to register device class\n");
return PTR_ERR(kbdozgurcharClass); // Correct way to return an error on a pointer
}
printk(KERN_INFO "MOB: device class registered correctly\n");
// Register the device driver
kbdozgurcharDevice = device_create(kbdozgurcharClass, NULL, MKDEV(majorNumber, 0), NULL, DEVICE_NAME);
if (IS_ERR(kbdozgurcharDevice)) { // Clean up if there is an error
class_destroy(kbdozgurcharClass); // Repeated code but the alternative is goto statements
unregister_chrdev(majorNumber, DEVICE_NAME);
printk(KERN_ALERT "MOB: Failed to create the device\n");
return PTR_ERR(kbdozgurcharDevice);
}
printk(KERN_INFO "MOB: device class created correctly\n"); // Made it! device was initialized
/*
*****************************
* Bind interrupt
*****************************
*/
// Request IRQ 1, the keyboard IRQ, to go to our irq_handler SA_SHIRQ means we're willing to have othe handlers on this IRQ. SA_INTERRUPT can be used to make the handler into a fast interrupt.
result = request_irq(1, (irq_handler_t) irq_handler, IRQF_SHARED, "kbdozgur", (void *) (irq_handler));
if (result) printk(KERN_INFO "MOB: can't get shared interrupt for keyboard\n");
printk(KERN_INFO "MOB: kbdozgur loaded.\n");
return result;
}
static void exit_mod(void) {
/*
* ****************************
* Destroy Character Device
* ****************************
*/
device_unregister(kbdozgurcharDevice);
device_destroy(kbdozgurcharClass, MKDEV(majorNumber, 0)); // remove the device
class_unregister(kbdozgurcharClass); // unregister the device class
class_destroy(kbdozgurcharClass); // remove the device class
unregister_chrdev(majorNumber, DEVICE_NAME); // unregister the major number
printk(KERN_INFO "MOB: Goodbye from the LKM!\n");
/*
* ****************************
* Free IRQ bind
* ****************************
*/
free_irq(1, (void *) (irq_handler));
printk(KERN_INFO "MOB: kbdozgur unloaded.\n");
}
// Default open function for device
static int dev_open(struct inode *inodep, struct file *filep) {
numberOpens++;
printk(KERN_INFO "MOB: Device has been opened %d time(s)\n", numberOpens);
return 0;
}
/** @brief This function is called whenever device is being read from user space i.e. data is
* being sent from the device to the user. In this case is uses the copy_to_user() function to
* send the buffer string to the user and captures any errors.
* KERNEL SPACE > USER SPACE
* @param filep A pointer to a file object (defined in linux/fs.h)
* @param buffer The pointer to the buffer to which this function writes the data
* @param len The length of the buffer
* @param offset The offset if required
*/
static ssize_t dev_read(struct file *filep, char *buffer, size_t len, loff_t *offset) {
size_t size_requested;
if (len >= bufferCounter) size_requested = bufferCounter;
else size_requested = len;
// if (copy_to_user(buffer, messageFromInterrupt, size_requested)) {
// bufferCounter = bufferCounter - size_requested;
// memset(&messageFromInterrupt[0], 0, sizeof(messageFromInterrupt));
// return -EFAULT;
// }
// else return size_requested;
copy_to_user(buffer, messageFromInterrupt, size_requested);
bufferCounter = bufferCounter - size_requested;
memset(&messageFromInterrupt[0], 0, sizeof(messageFromInterrupt));
return size_requested;
}
/** @brief This function is called whenever the device is being written to from user space i.e.
* data is sent to the device from the user. The data is copied to the messageFromUser[] array in this
* LKM using the sprintf() function along with the length of the string.
* USER SPACE > KERNEL SPACE
* @param filep A pointer to a file object
* @param buffer The buffer to that contains the string to write to the device
* @param len The length of the array of data that is being passed in the const char buffer
* @param offset The offset if required
*/
static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, loff_t *offset) {
short size_of_message;
copy_from_user(messageFromUser, buffer, len);
size_of_message = strlen(messageFromUser); // store the length of the stored message
printk(KERN_INFO "MOB: Received %d characters from the user >> %s", len, messageFromUser);
return len;
}
/** @brief The device release function that is called whenever the device is closed/released by
* the userspace program
* @param inodep A pointer to an inode object (defined in linux/fs.h)
* @param filep A pointer to a file object (defined in linux/fs.h)
*/
static int dev_release(struct inode *inodep, struct file *filep) {
printk(KERN_INFO "MOB: Device successfully closed\n");
return 0;
}
module_init(init_mod);
module_exit(exit_mod);