카테고리 없음2014. 4. 23. 16:08

ST사의 standard pheripheral library 등을 사용하여 빌드를 하면, 이미지 사이즈가 크게 나온다. 이유는 include 된 소스 코드 중 사용하지 않는 코드도 메모리에 위치하기 때문이다.

사용하지 않는 코드를 제거하여 작은 사이즈의 이미지를 만들기 위한 옵션. 램에서 코드를 돌리고 디버깅하기 위해서는 필수적이다!




저 옵션을 활성화 하면 된다. 이 옵션은 각각의 함수의 섹션을 다르게 지정하여 링크시에 사용하지 않는 함수의 섹션을 날려서 이미지 사이즈를 줄일 수 있다고 한다!


참조는 http://www.keil.com/support/man/docs/armlink/armlink_BABDJCAA.htm 에서.


부연하자면, 섹션을 나누면 어드레스 주소등의 공유를 할 수 없어 코드 사이즈가 조금 늘어나지만, 사용하지 않는 함수를 제거함으로서 빌드후의 이미지 사이즈를 줄일 수 있다고 한다. 상황에 맞게 사용하면 좋겠다.


아마 gcc에도 저 옵션이 있을 것 같다.


Posted by 쿨한넘
카테고리 없음2014. 4. 21. 23:21

74HC595: 8-bit serial-in, serial or parallel-out shift register with output latches; 3-state

이 595를 아두이노의 gpio와 인터페이스하는 코드는,



//
//    8 LEDs control
//
//        each LED is connected to 74HC595's output
//

// Pin connected to ST_CP of 74HC595
int latchPin = 12;
// Pin connected to SH_CP of 74HC595
int clockPin = 13;
// Pin connected to DS of 74HC595
int dataPin = 11;


void LED_out(uint8_t value)
{
	digitalWrite(latchPin, LOW);
	shiftOut(dataPin, clockPin, MSBFIRST, value);
	digitalWrite(latchPin, HIGH);
}


void setup()
{
	// set pins to output so you can control the shift register
	pinMode(latchPin, OUTPUT);
	pinMode(clockPin, OUTPUT);
	pinMode(dataPin, OUTPUT);
}


void loop()
{
	unsigned char value = 0x80;

	while (1) {

		for (value = 0x01; value < 0x80; value <<= 1) {
			LED_out(value);
			delay(500);
		}

		for (value = 0x80; value != 0x00; value >>= 1) {
			LED_out(value);
			delay(500);
		}

		LED_out(0xff);
		delay(1000);

		LED_out(0x00);
		delay(1000);

		LED_out(0xff);
		delay(1000);

		LED_out(0x00);
		delay(1000);
	}
}

코드를 보면 연결은 쉽게 추측할 수 있다.

Q0 ~ Q7까지가 출력으로 LED의 anode에 직접 연결했다.

이때의 출력 파형은,

595의 SHCP (clock)과 DS (data)



SHCP와 STCP


 


ATmega128의 SPI와 74HC595의 연결


atmega128의 신호는

PB0 (pin#10) 는 nSS로, GPIO로 제어. SPI 슬레이브로 128을 설정할 때는 자동으로 PB0는 SPI의 nSS, input으로 셋팅되지만, master일 때는 따로 구동을 해줘야 한다. chip select라 생각하면 된다. 595의 STCP(#12)와 연결한다.

PB1 (pin#11) 은 SCK로, master 설정시 SPI SCK output으로, slave 설정시 SCK input으로 셋팅된다. 595의 SHCP (#11)와 연결한다.

PB2 (pin#12) 는 MOSI 로, master 설정시 output으로, slave 설정시 input으로 셋팅된다. 595의 DS(#14)에 연결한다.

595의 nOE 은 GND에, nMR은 Vcc에 연결한다. Q0 ~ Q7은 출력.

595는 SHCP (SCK) 의 rising edge에서 data (MOSI, DS)가 샘플되므로 (shift), 128의 레지스터 SPCR 의 CPOL 과 CPHA 를 '0' (default) 로 설정한다.



/*
 * spi_74595.c
 *
 * Created: 2014-04-21 오후 9:11:36
 *  Author: Don Quixote
 */ 
#define F_CPU	16000000UL


#include <avr/io.h>
#include <util/delay.h>

#define DD_SS		0	// PB0
#define DD_SCK		1	// PB1, output when SPI master
#define DD_MOSI		2	// PB2, output when SPI master



void SPI_MasterInit(void)
{
	/* Set MOSI and SCK output, all others input */
	DDRB = (1<<DD_MOSI)|(1<<DD_SCK)|(1<<DD_SS);

	/* set nSS to high (normal) */
	PORTB |= 0x1;

	/* set SPI2X: Double SPI Speed Bit */
	SPSR |= 0x01;

	/* Enable SPI, Master, set clock rate fck/16 */
	SPCR = (1<<SPE)|(1<<MSTR);				// fosc / 2
//	SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR1)|(1<<SPR0);		// fosc / 64

}


void SPI_MasterTransmit(uint8_t cData)
{
	/* set nSS to low (select SPI slave) */
	PORTB &= 0xfe;

	/* Start transmission */
	SPDR = cData;

	/* Wait for transmission complete */
	while(!(SPSR & (1<<SPIF)))
	;

	/* set nSS to high */
	PORTB |= 0x01;
}



int main(void)
{
	uint8_t ch;


	SPI_MasterInit();


	while(1) {
		for(ch = 0x01; ch != 0; ch <<= 1) {
			SPI_MasterTransmit(ch);
			_delay_ms(50);
		}

		for(ch = 0x80; ch != 0; ch >>= 1) {
			SPI_MasterTransmit(ch);
			_delay_ms(50);
		}

	}

}


출력파형.

SCK를 fosc / 64 로 설정했을 때.





fosc / 2 로 설정했을 때.






Posted by 쿨한넘
카테고리 없음2014. 2. 7. 13:33

Keil MDK-ARM에서 마이크로컨트롤러의 내부 플래쉬가 아니라 내부 SRAM에 코드를 올리고 실행하기.


xxxx.ini 화일을 하나 만들고 아래와 같이 수정한다.


FUNC void Setup (unsigned int region) {
  region &= 0xFFFF0000;
  SP = _RDWORD(region);			// Setup Stack Pointer
  PC = _RDWORD(region + 4);		// Setup Program Counter
//  _WDWORD(0xE000ED08, region);	// Setup Vector Table Offset Register
}

LOAD "SRAM\\stm32f051r8_flash_test01.axf" INCREMENTAL
Setup(0x20000000); // Get ready to execute image in SRAM or whatever region it is in

//g,main


위 예제는 STM32F051R8 의 내부 SRAM에서 코드를 동작하기 위해 작성했다. 이 프로세서의 내부 SRAM은 0x2000_0000에 위치해있고, 그 크기는 8KB (0x2000)이다.

SRAM 메모리 맵에 맞추어 빌드를 해놓아야 한다.


그리고 프로젝트 옵션에서 아래 그림과 같이 셋팅을 맞추고, 디버깅 시작을 하면 된다.




Posted by 쿨한넘
카테고리 없음2013. 11. 13. 02:25

프로그램 저지 사이트를 돌아다니면서 코딩을 해보면 의외로 시간을 잡아먹는 부분이 입력 처리 부분이다. 내가 C언어를 쉽게 쉽게, 띄엄 띄엄 배워서 그런지 디테일이 영 엉망이라 곤혹스럽다.

관련 이슈를 정리한다.


https://groups.google.com/forum/#!msg/han.comp.lang.c/HmiWd6iVO_E/NkBFztcimHgJ


질문.

아래 소스 중 scanf(" %d %d\n", &a, &b); 여기서요, \n 이 없으면 제대로

작동하는데 \n 만 들어가면 영 이상해집니다. 전 \n 의 역할은 변수를 받은 후

줄바꿈하는 걸로만 생각했는데 아니더라구요.

이 소스에서 \n 역할이 뭔지 좀 알려주세요


void main() {

 int a, b;

   printf("정수 두개 입력해\n");
   scanf("%d %d\n", &a,&b);

   if(a > b) {
    printf("앞에 게 뒤에 것보다 크네\n");
      }
   else if(a < b) {
    printf("뒤에 게 크네\n");
      }
  else {
    printf("앞에 것과 뒤에 게 같다\n");
      }
}


답변

http://www.cppreference.com/stdio_details.html#scanf


scanf 함수의 개념은 "입력 버퍼(stdin)에서 format에서 지정한 대로 읽어들

인다" 입니다. 위의 두개의 차이는 다음과 같습니다.


"%d %d" - stdin에서 숫자, 1자 이상의 공백문자(white-space character), 숫

자를 읽어들인다.

"%d %d\n" - stdin에서 숫자, 1자 이상의 공백문자, 숫자, 1자 이상의 공백문

자를 읽어들인다.


C99의 FCD인 N869 문서의 7.19.6.2.5절을 인용하겠습니다.


A directive composed of white-space character(s) is executed by reading

input up to the first non-white-space character (which remains unread),

or until no more characters can be read.


형식(format) 문자열에 있는 공백문자(white-space)는 그 다음에 공백 문자가

아닌 문자(non-white-space)가 올때까지 입력버퍼(stdin)에서 읽어들이라는

뜻입니다. 즉, "%d %d\n"는 숫자 2개, 1자 이상의 공백문자, 공백문자가 아닌

문자를 받아야만 입력이 완전하게 끝나는 것입니다. 참고로 "%d %d\n""%d

%d ", "%d %d\t"는 같은 뜻을 가집니다.


말이 어렵게 되어버렸는데, 예제로 설명하겠습니다.


scanf("%d %d", &a, &b);

숫자값, 1자 이상의 공백문자, 숫자값이 입력버퍼에 있기를 기대한다.

숫자값, 1자 이상의 공백문자, 숫자값까지 읽어들인다. 그 나머지는 입력 버

퍼(stdin)에 그대로 놔둔다.


실행 결과 - 1 2를 입력했을 경우 형식(format) 문자열과 완벽히 일치한다.

그러므로 a와 b에 읽어들인 값을 저장하고 함수(scanf)를 종료한다.


scanf(%d %d\n", &a, &b);

숫자값, 1자 이상의 공백문자, 숫자값, 1자 이상의 공백문자, 공백문자가 아

닌 문자가 입력버퍼에 있기를 기대한다.

숫자값, 1자 이상의 공백문자, 숫자값, 1자 이상의 공백문자까지 읽어들인다.

그 나머지는 입력 버퍼(stdin)에 그대로 놔둔다.


실행 결과 - 1 2를 입력했을 경우 "%d %d"까지 일치가 되지만 \n 문자 때문에

1자 이상의 공백문자와 그 뒤에 공백문자가 아닌 문자를 기다리게 됩니다. 여

기에 3을 또 입력하게 되면 공백문자까지 읽어들이게 되고 나머지(3)는 그대

로 입력버퍼에 남게 됩니다. 이 남아있는 3은 다음 scanf문이 실행될 때 영향

을 주게 됩니다.


그리고 한가지 더. 다음의 예제 코드를 봐 주십시오.


#include <stdio.h>

int main(void)
{
    int a, b;

    printf("\n>>");


    scanf("%d %d\n", &a, &b);
    printf("[%d,%d]\n>>", a, b);

    scanf("%d %d\n", &a, &b);
    printf("[%d,%d]\n>>", a, b);
    return 0;
}


이 프로그램의 실행 결과는 다음과 같습니다.


$ gcc 3.c -o 3
plsj@localhost: ~
$ ./3

>>1 2    <- 1과 2를 입력한다.
3    <- 숫자 2개가 입력되었는데도 입력을 기다린다. 3을 입력한다.
[1,2]    <- 입력된 숫자 출력
>>4 5    <- 숫자 2개를 또 입력
[3,4]    <- 4 5를 출력하는게 아니라 3과 4를 출력한다.
>>plsj@localhost: ~
$ ./3

>>1 2    <- 1과 2를 입력한다.
a    <- 숫자 2개가 입력되었는데도 입력을 기다린다. 3을 입력한다.
[1,2]    <- 입력받은 값을 출력한다.
>>[1,2]    <- 여기에서 입력을 한번 받아야되는데 받지 않고 입력받은 값을

              또한번 출력한다.
>>plsj@localhost: ~
$



첫번째 실행에서 1 2가 입력되면, "%d %d\n" 중에서 "%d %d"까지 일치가 됩니

다. 그러나 \n이 남아있기 때문에 1자 이상의 공백문자와 공백문자가 아닌 문

자의 입력을 기다리게 됩니다. 여기에 3을 입력하면 3 이전의 공백문자까지

읽어들이게 되어 첫번째 scanf 함수가 끝나게 되고 3은 입력버퍼에 그대로 남

습니다. 그다음의 scanf 함수가 실행되면 입력버퍼에 있는 3을 읽어들이게 되

고 " %d\n"이 남게 됩니다. 여기에 4 5를 입력하게되면 "4 "까지 읽어들이게

되고 5는 그대로 입력버퍼에 남게 됩니다. 즉 a에는 3이, b에는 4가 입력되는

것이죠.


두번째 실행에서도 마찬가지 입니다. 다만 첫번째 scanf 함수가 끝난 후에 3

대신 a가 입력버퍼에 남게 되고, 두번째 scanf 함수가 실행되면 형식(format)

문자열의 %d가 a와 일치가 안되기 때문에 두번째 scanf 함수는 하는일 없이

그대로 끝나게 됩니다. 따라서 1 2가 두번 출력되게 됩니다.


설명이 좀 길어졌습니다. 저는 능력이 없어서 짧고 간단하게 설명할 재주가

없군요-_-;; 양해하시길 바랍니다.

--





http://kldp.org/node/29034

http://kldp.org/node/24757

http://kldp.org/node/28872

======================================================================

지금 상상이 되는 시나리오는gets/scanf를 사용하기 전에 g

지금 상상이 되는 시나리오는

gets/scanf를 사용하기 전에 getchar/scanf로 한 글자를 입력받은 것입니다. (흔히 있는 시나리오죠 :) ) 그 입력 마지막에 엔터를 쳤고, 그 입력을 처리하지 않아 gets에서는 마치 입력을 안받는 것처럼 느끼시는 것 같습니다.

gets는 \n을 보면 입력의 끝인가보다 하고 넘어갔을테고, scanf는 원래 whitespace를 무시하므로 입력을 받은 것 같습니다.

코드로 표현하자면

ch = getchar();
/* 어쩌고 저쩌고 */
gets(buffer);

또는

scanf("%c", &ch);
/* 어쩌고 저쩌고 */
gets(buffer);

이렇게 했을 때 gets가 입력을 못받는 것처럼 느끼시는 듯 합니다.

이럴 때 제가 손쉽게 해결하는 방법은

scanf("%c ", &ch);
/* 어쩌고 저쩌고 */
gets(buffer);

이렇게 하는 것입니다.

문맥상 gets를 쓰긴 했지만, 물론 gets(buffer);는 쓰면 안되고 fgets(buffer, sizeof(buffer), stdin); 등과 같이 바꿔써야 합니다. fgets는 마지막에 \n까지 받아온다는 것을 잊지 마시고.

======================================================================

#include <stdio.h>#include

#include <stdio.h>
#include <string.h>
 
#define NSTR 1 << 7
 
char *safe_gets(char *buf, size_t len)
{
        scanf(" ");
        fgets(buf, len - 1, stdin);
        buf[strlen(buf) - 1] = '\0';
        return buf;
}
 
int main()
{
        char str[NSTR];
        getchar();
        safe_gets(str, NSTR);
        puts(str);
}

매크로로 만들어 쓰셔도 좋습니다.

덧. 다행스럽게도, 빈 입력에도 \n\0 즉, strlen(buf) = 1이 나오기 때문에 저 코드에서 첨자값이 -1이 된다던지 하는 일은 없을 겁니다.

Real programmers /* don't */ comment their code.
If it was hard to write, it should be /* hard to */ read.

=================================================================

Re: fflush( stdin ) ???

ㅡ,.ㅡ;; wrote:
프로그램에서 임의로 삭제하는것이 어떤입력의경우 우리가 원하지 않는 입력까지 같이 들어오는경우가 있습니다. 특히 사용하는 함수에 따라서..
그렇다면.. 새로입력받은경우에 그값을 입력받으려하는데 버퍼에서 오래된
다른값을 넘겨준다면 문제가 되기때문에 일단비우고 새로 받는것입니다.
일반적으로 Text 기반 프로그램작성할때 종종 저렇게 하지요..
"해주면 된다" 라고 생각하시면 될듯합니다...^^;;

저를 포함해 위에서 답변해 주신 분들의 공통적인 의견은

"해서는 안 된다"

입니다. 물론, 입력에 프로그램이 필요로 하지 않은 부적절한 내용이 있어
유의미한 부분이 나올 때까지 무시하는 것 자체가 항상 잘못된 행동은 아니
지만, 그러한 행동을 위해 fflush(stdin); 을 선택하는 것은 많은 경우에
부적절 합니다. 기대한대로 동작하지 않을 여러 가능성은 제 처음 답변에
링크되어 있습니다. 그보다는 지극히 정상적이고 예측 가능한 방법으로 입
력을 처리하는 것이 더 낫습니다. 예를 들어, 현재부터 다음 newline 까지
의 (stdin 으로 오는) 입력을 무시해야 하는 상황이라면,

void throw_all_characters_until_the_next_newline_inclusive_into_the_trash(void)
{
    int c;

    while ((c=getchar()) != EOF && c != '\n');
}

와 같은 함수를 사용하는 것이 좋습니다 - 물론, 함수명은 좀 줄여야 겠지
요. ;-)

그럼...

--
Jun, Woong (woong at gmail.com)
http://www.woong.org

=================================================================

OS-level input buffer..에 존재하는 모든 데이터를 flush시키기

leolo의 아바타

#include <stdio.h>
int main()
{
int c;
while((c = getchar()) != '\0'){
putchar(c);
}
return 0;
}
이렇게 일반적으로 데이터를 입력받아 사용하는데요..

만약에,

c = getchar();
putchar(c);

로 단순히 코딩을 하고 실행시켜서 값을 입력하는데 있어서..
ABCD 를 입력하면 A만 출력이 되겠죠.
여기서, BCD는 OS-level input buffer에 존재한다고 들었는데요.
여기까지의 질문 내용에 문제가 없는지 일단 좀 가르쳐 주세요..

다음으로 OS-level input buffer라는 것이 무엇인지 알려주세요.
대충은 알겠습니다. input이 있으면 output도 있겠죠. 물론, 시스템에 따라
그 사이즈도 다르겠죠.

마지막으로 OS-level input buffer에 들어있는 나머지 데이터를 없에는 
이식성을 가지는 방법은 없는지 알고 싶습니다.
그러니까?
c = getchar();
putchar(c);
요 코드 다음에 어떻게 하라.. 정도로 알려주시면 더욱 감사하겠습니다.

=================================================================

[quote="leolo"]만약에, c = getchar();

leolo wrote:
만약에,

c = getchar(); 
putchar(c); 
마지막으로 OS-level input buffer에 들어있는 나머지 데이터를 없에는 
이식성을 가지는 방법은 없는지 알고 싶습니다.
로 단순히 코딩을 하고 실행시켜서 값을 입력하는데 있어서.. 
ABCD 를 입력하면 A만 출력이 되겠죠. 
여기서, BCD는 OS-level input buffer에 존재한다고 들었는데요.

아직 읽히지 않은 BCD가 존재하는 곳은 *일반적*으로 OS-level input buffer라고 하기보다는,
C Library Buffer라고 하는게 더 정확할 듯 싶습니다..
물론 일반적이지 않게, setvbuf()로 unbuffered로 설정할 수도 있지만요...

예를 드신게, getchar()와 같은 stdio, 즉 Stream I/O인 경우를 물어보셨으니 그에 대해 설명드리면...
Stream I/O는 다음과 같은 buffer 구조를 통해서 실제 데이타를 read/write하게 됩니다..

(Application) <--> (C Library Buffer) <--> (System Buffer) <--> (Device)

말씀하신데로, ABCD를 입력하게되면, "Input device"인 키보드로부터 ABCD가 입력되고, 이 ABCD값은 "System Buffer"를 거쳐,
"C Library Buffer"에 저장이 됩니다... 즉, 실제 getchar()는 "C Library Buffer"에서 읽어드리게 되는겁니다...

여담으로 output에 관련된 것이기는 하지만, fflush(3C)은 "C Library Buffer"의 내용을 "System Buffer"로 flush를 시키는 것이며,
sync(1)과 sync(2), fsync(3C)는 "System Buffer"의 내용을 "Device", 즉 Disk에 flush 시키는 것입니다.
(물론, sync(1)과 sync(2)는 그밖의 작업을 더 수행합니다.)

leolo wrote:
input이 있으면 output도 있겠죠.

output buffer가 input과 분리되어 존재하기보다는 하나의 buffer를 공유해, I/O가 같이 일어날 것으로 생각됩니다..

leolo wrote:
물론, 시스템에 따라 
그 사이즈도 다르겠죠.

*순수한* 버퍼만의 사이즈는 512K(block사이즈)의 배수로, 리눅스와 솔라리스의 경우 8K로, AIX의 경우 4K로 알고 있습니다...

leolo wrote:
마지막으로 OS-level input buffer에 들어있는 나머지 데이터를 없에는 
이식성을 가지는 방법은 없는지 알고 싶습니다.

이식성을 가지는 방법은 없습니다.
즉, C 표준에 input buffer를 clear시키는 방법에 대해서는 언급하고 있지 않습니다.
정 하고 싶으시다면, 위에 적으신 예제처럼, getchar()로 EOF까지 읽은뒤, 혹은 다른 방법으로 읽은 데이타를 버리는 수밖에 없습니다.

--------------------------
Donghyun Jung

=================================================================

[quote="leolo"][quote="eungkyu"]OS레벨이기보단

leolo wrote:
eungkyu wrote:
OS레벨이기보단 C의 standard IO libarary의 버퍼에 들어가겠죠. 물론, OS레벨에도 버퍼가 있긴 하겠지만, 그건 또 다른 문제고.
왜 그 버퍼를 비우려 하시는지는 모르겠지만, 프로그램이 끝나면 알아서 비워집니다 -_-;; 어떤 상황에서 왜 비우려 하시는지..

아래 부분의 내용을 확인하기 위해서 질문 드린 것입니다. 음.. 그렇네요. 라이브러리 버퍼겠죠. 프로그래이 끝나면 당연히 없어지겠죠.
저는 코드에서 버퍼에 남아있는 것을 플러쉬시키고 다시 받기 위해서 질문 드린 것입니다... ^^

standard io가 다루는 것은 stream입니다. stream은 물줄기처럼 밀려오고(입력) 또한 밀려나가는(출력) 것이죠. 물줄기와 현재 처리하는 위치가 있을 뿐이죠. 중간을 뚝 짤라버리는 행위는 스트림 처리에서 매우 이상한 행동입니다. 게다가, 버퍼라는 것은 standard library에서 성능을 위해서 제공하는 것으로서, 그 라이브러리를 사용하는자의 입장에서는 어느정도 transparency하게 내부적으로 제공되는 것입니다.

설사 입력 버퍼를 지우는 함수가 존재한다고 합시다. 지금이야 손으로 입력을 받는 프로그램이라서 그런 식으로 생각해도 말이 되는 듯 합니다. 하지만 상대가 파일이 되면 (progarm < file 이렇게 실행하면) 버퍼의 한계가 불명확해지고 버퍼를 비우면 얼마나 지워질지 짐작하기도 힘듭니다. (프로그램이 제대로 동작하지 않을 수 있다는 뜻입니다) 즉, 버퍼를 비우는 행위는 스트림 처리에서 매우 이상한, 말도 안되는 행동일 뿐더러 standard io library가 애써 만들어놓은 transparency도 깨뜨릴 수 있는 행위입니다. standard io library 내부를 다루는 프로그램이 아니라면, 버퍼를 건드리는 행위는 자제해야 합니다.

개념을 바꿔서 버퍼를 비운다보다는, 쓸데없는 입력을 무시한다로 생각하시면 프로그래밍하기가 편해집니다. 원래 스트림이 그런겁니다.




Posted by 쿨한넘
카테고리 없음2013. 10. 28. 02:51

VirtualBox에 FreeBSD, Xorg 설치 후 해상도가 800 x 600 으로 고정된다.

해결책은 https://forums.virtualbox.org/viewtopic.php?f=2&t=18377

세상은 넓고 내가 모르는 것을 알고 있는 사람도 많다!


1. virtualbox 에 해상도 설정

VBoxManage setextradata FreeBSD10 CustomVideoMode1 1600x1200x24


버추얼박스를 맥에 설치했기 때문에 맥 터미널에서 위 명령을 실행했다.

FreeBSD10은 FreeBSD가 설치된 가상머신의 이름.


2. /etc/X11/xorg.conf 설정


/etc/X11/xorg.conf 의 Section "Monitor" 항목 아래에 다음을 추가한다.


HorizSync     31-80

VertRefresh   30-100



Section "Screen" 에  아래를 추가.


DefaultDepth    24


그리고 Section "Screen" 의 서브섹션을 다음과 같이 수정한다.


SubSection "Display"

                Viewport   0 0

                Depth      24

                Modes      "1600x1200"

EndSubSection



Posted by 쿨한넘
카테고리 없음2013. 10. 17. 13:10

objective-c를 공부하는데 mac os 아니 정확하게는 xcode의 힘은 절대적이다.

그러나 항상 맥을 사용할 수는 없으니 대안을 찾아야 한다.


sudo apt-get install gnustep
sudo apt-get install gnustep-devel
sudo apt-get install gobjc

. /usr/share/GNUstep/Makefiles/GNUstep.sh
gcc `gnustep-config --objc-flags` -lgnustep-base hello.m -o hello


GUI 관련 라이브러리 빼곤 어지간한 것은 있는 듯 하다.

근데 잘 안된다.


GNUstep 가이드를 보면, 다음과 같이 GNUmakefile 이름의 파일을 만들고 make 한다.


include $(GNUSTEP_MAKEFILES)/common.make

TOOL_NAME = LogTest
LogTest_OBJC_FILES = source.m

include $(GNUSTEP_MAKEFILES)/tool.make


LogTest는 생성될 실행 파일의 이름, source.m은 필요한 소스. 이건 된다.

Posted by 쿨한넘

여러 삽질끝에 해답은 딥스위치가 아니었다.

참고 : https://wiki.linaro.org/Boards/MX6QSabreLite


sabre lite 보드는 spi nor 플래쉬에서 부트 이미지를 로드한다. 그래서 SD 카드로 부팅을 하려면 SPI NOR flash에 간단한 로더를 프로그램해야한다고.

첨부 :

iMX6DQ_SPI_to_SD_loader_binaries_rev1.0.zip


0. dip swith를 00으로 set.


1. sd 카드에 이미지 라이트.

sudo dd if=iMX6DQ_SPI_to_uSDHC4.bin of=/dev/sdx

iMX6DQ_SPI_to_uSDHC4.bin는 micro SD에서 부팅을, iMX6DQ_SPI_to_uSDHC3.bin 는 일반 SD 카드에서 부팅을 하기위한 로더이다.


2. SD 카드를 삽입한다.


3. u-boot 프롬프트에서 다음과 같이 한다.

MX6Q SABRELITE U-Boot > mmc dev 1

MX6Q SABRELITE U-Boot > mmc read 0x10800000 0 200

MX6Q SABRELITE U-Boot > sf probe

MX6Q SABRELITE U-Boot > sf erase 0 0x40000

MX6Q SABRELITE U-Boot > sf write 0x10800000 0 0x40000

micro SD인 경우엔 mmc dev 1, 일반 SD인 경우엔 mmc dev 0 을 입력한다.


4. 끝.

u-boot 를 빌드하고 다음과 같이 이미지를 라이트 하고 부팅했다.

sudo dd if=u-boot.imx of=/dev/sdb bs=512 seek=2 && sync && sync



SPI NOR flash 로 u-boot 부트가 안된다면?

freescale의 manufacturing tool로 된단다. 

리나로에서 따로 프로파일을 추가한 manufacturingn tool

MFG_Tool_Profile_for_Linaro.zip



Posted by 쿨한넘
카테고리 없음2013. 8. 28. 16:15




/*
	test.c

	2013. 8. 28.
*/
#include <stdio.h>
#include <stdlib.h>


__attribute__ ((no_instrument_function))
void __cyg_profile_func_enter(void *this, void *callsite)
{
	printf ("__cyg_profile_func_enter\n");
}

__attribute__ ((no_instrument_function))
void __cyg_profile_func_exit(void *this, void *callsite)
{
	printf ("__cyg_profile_func_exit\n");
}

__attribute__ ((constructor))
void myConstructor( void )
{
	printf ("constructor\n");
}

__attribute__ ((destructor))
void myDestructor( void )
{
	printf ("destuctor!\n");
}


void func_a( void )
{
	printf ("func_a\n");
	return;
}

__attribute__ ((no_instrument_function))
void func_b( void )
{
	printf ("func_b\n");
	return;
}


int main()
{
	printf ("main\n");
	func_a();
	func_b();

	return 0;
}


constructor, destructor는 생략해도 된다.

결과는,


dqxt@dons-pleiades ~/study/kernel/instrument_fn $ gcc -o test -finstrument-functions test.c 
dqxt@dons-pleiades ~/study/kernel/instrument_fn $ ./test
__cyg_profile_func_enter
constructor
__cyg_profile_func_exit
__cyg_profile_func_enter
main
__cyg_profile_func_enter
func_a
__cyg_profile_func_exit
func_b
__cyg_profile_func_exit
__cyg_profile_func_enter
destuctor!
__cyg_profile_func_exit
dqxt@dons-pleiades ~/study/kernel/instrument_fn $ 


또 다른 예제.



/*
	test2.c

	2013. 8. 28.
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


static FILE *fp_trace;

__attribute__ ((constructor))
void trace_begin (void)
{
	printf ("constructor.\n");
	fp_trace = fopen("trace.out", "w");
}

__attribute__ ((destructor))
void trace_end (void)
{
	printf ("destructor.\n");
	if (fp_trace != NULL) {
		fclose(fp_trace);
	}
}

__attribute__ ((no_instrument_function))
void __cyg_profile_func_enter (void *func,  void *caller)
{
	printf ("__cyg_profile_func_enter.\n");
	if (fp_trace != NULL) {
		fprintf(fp_trace, "e %p %p %lu\n", func, caller, time(NULL) );
	}
}


__attribute__ ((no_instrument_function))
void __cyg_profile_func_exit (void *func, void *caller)
{
	printf ("__cyg_profile_func_exit.\n");
	if(fp_trace != NULL) {
		fprintf(fp_trace, "x %p %p %lu\n", func, caller, time(NULL));
	}
}

void func_a( void )
{
	printf ("in function_a.\n");
	return;
}

__attribute__ ((no_instrument_function))
void func_b( void )
{
	printf ("in function_b.\n");
	return;
}

int main()
{
	printf ("in main.\n");
	func_a();
	func_b();

	return 0;
}


결과는,


dqxt@dons-pleiades ~/study/kernel/instrument_fn $ gcc -o test2 -finstrument-functions test2.c 
dqxt@dons-pleiades ~/study/kernel/instrument_fn $ ./test2
__cyg_profile_func_enter.
constructor.
__cyg_profile_func_exit.
__cyg_profile_func_enter.
in main.
__cyg_profile_func_enter.
in function_a.
__cyg_profile_func_exit.
in function_b.
__cyg_profile_func_exit.
__cyg_profile_func_enter.
destructor.
__cyg_profile_func_exit.
dqxt@dons-pleiades ~/study/kernel/instrument_fn $ ./readtracelog.sh test2 trace.out 
Exit  trace_begin at 2013-08-28T16:12:39+0900
Enter main at 2013-08-28T16:12:39+0900, called from ?? (??:0)
Enter func_a at 2013-08-28T16:12:39+0900, called from main (??:?)
Exit  func_a at 2013-08-28T16:12:39+0900
Exit  main at 2013-08-28T16:12:39+0900
Enter trace_end at 2013-08-28T16:12:39+0900, called from ?? (??:0)
dqxt@dons-pleiades ~/study/kernel/instrument_fn $ 


readtracelog.sh의 내용은,



#!/bin/sh
if test ! -f "$1"
then
	echo "Error: executable $1 does not exist."
	exit 1
fi

if test ! -f "$2"
then
	echo "Error: trace log $2 does not exist."
	exit 1
fi

EXECUTABLE="$1"
TRACELOG="$2"

while read LINETYPE FADDR CADDR CTIME; do
	FNAME="$(addr2line -f -e ${EXECUTABLE} ${FADDR}|head -1)"
	CDATE="$(date -Iseconds -d @${CTIME})"

	if test "${LINETYPE}" = "e"
	then
		CNAME="$(addr2line -f -e ${EXECUTABLE} ${CADDR}|head -1)"
		CLINE="$(addr2line -s -e ${EXECUTABLE} ${CADDR})"
		echo "Enter ${FNAME} at ${CDATE}, called from ${CNAME} (${CLINE})"
	fi

	if test "${LINETYPE}" = "x"
	then
		echo "Exit  ${FNAME} at ${CDATE}"
	fi

done < "${TRACELOG}"



Posted by 쿨한넘
카테고리 없음2013. 8. 1. 04:21

그렇다.

mac의 dfont 파일을 ttf 들로 나눠준다.

링크는 http://peter.upfold.org.uk/projects/dfontsplitter



dfontsplitter-0.3.1-setup.exe

dfontsplitter-0.4.1-mac.zip


윈도우용, 맥용.

Posted by 쿨한넘
카테고리 없음2013. 7. 29. 11:35

출처 : http://www.cs.vu.nl/~ast/reliable-os/


Preface


Looks like it is microkernel debate time again. Before getting into technical arguments, there are a couple of things I want to say. Many people have said or suggested that Linus and I are enemies or something like that. That is totally false. I met him once. He is a pleasant fellow and very smart. We may disagree on some technical issues, but that doesn't make us enemies. Please don't confuse disagreements about ideas with personal feuds. I have nothing against Linus and have great respect for what he has accomplished.


In the unlikely event that anyone missed it, a couple of years ago Microsoft paid a guy named Ken Brown to write a book saying Linus stole Linux from my MINIX 1 system. I refuted that accusation pretty strongly to clear Linus' good name. I may not entirely agree with the Linux design, but Linux is his baby, not my baby, and I was pretty unhappy when Brown said he plagiarized it from me.


Before getting into the details, I also want to say that my interest is not in microkernels per se. My interest is in building highly reliable (and secure) operating systems and I think microkernels are a good tool for doing that. More below on this.


Engaging mouth


There is supposedly a sign at the Air Force Academy in Colorado that reads: 


     Be sure brain is in gear before engaging mouth


I don't know if it is really there, but I think it is a good idea in any event.


Over the years there have been endless postings on forums such as Slashdot about how microkernels are slow, how microkernels are hard to program, how they aren't in use commercially, and a lot of other nonsense. Virtually all of these postings have come from people who don't have a clue what a microkernel is or what one can do. I think it would raise the level of discussion if people making such postings would first try a microkernel-based operating system and then make postings like "I tried an OS based on a microkernel and I observed X, Y, and Z first hand." Has a lot more credibility.


The easiest way to try one is to go download MINIX 3 and try it. It is free and open source (BSD license) and once you have the CD-ROM image, you can burn it onto a CD-ROM, boot from it, and log in as root. However to actually do anything useful, you need to allocate a disk partition (1 GB will do) and install MINIX 3 on it. Please print and read the setup manual first. Installation takes maybe 10 minutes. Then install all the packages on the CD-ROM, as described in the setup manual. Now start X and you are now able to get some real experience. Try rebuilding the entire operating system as described in the manual. The whole build, kernel + user-mode drivers and all the user-mode servers (125 compilations in all) takes about 5-10 seconds.


Please be aware that MINIX 3 is not your grandfather's MINIX. MINIX 1 was written as an educational tool; it is still widely used in universities as such. Al Woodhull and I even wrote a textbook about it. MINIX 3 is that plus a start at building a highly reliable, self-healing, bloat-free operating system, possibly useful for projects like the $100 laptop to help kids in the third world and maybe embedded systems. MINIX 1 and MINIX 3 are related in the same way as Windows 3.1 and Windows XP are: same first name. Thus even if you used MINIX 1 when you were in college, try MINIX 3; you'll be surprised. It is a minimal but functional UNIX system with X, bash, pdksh, zsh, cc, gcc, perl, python, awk, emacs, vi, pine, ssh, ftp, the GNU tools and over 400 other programs. It is all based on a tiny microkernel and is available right now.


So **PLEASE** no more comments like "If Tanenbaum thinks microkernels are so great, why doesn't he write an OS based on one?" He did. (Actually, he, his students, and his programmers did). It is definitely not as complete or mature as Linux or BSD yet, but it clearly demonstrates that implementing a reliable, self-healing, multiserver UNIX clone in user space based on a small, easy-to-understand microkernel is doable. Don't confuse lack of maturity (we've only been at it for a bit over a year with three people) with issues relating to microkernels. We can and will add more features and port more software over time (your help is very welcome). Over 400,000 visits to the MINIX 3 site have been recorded since it went live at the end of October 2005. Try it yourself and see.


The Paper


Recently, my Ph.D. student Jorrit Herder, my colleague Herbert Bos, and I wrote a paper entitled Can We Make Operating Systems Reliable and Secure? and submitted it to IEEE Computer magazine, the flagship publication of the IEEE Computer Society. It was accepted and published in the May 2006 issue. In this paper we argue that for most computer users, reliability is more important than performance and discuss four current research projects striving to improve operating system reliability. Three of them use microkernels. IEEE put the paper on its Website. Someone then posted a link to it to Slashdot, thus rekindling an ancient discussion about microkernels vs. monolithic systems. While I cheerfully admit to coauthoring the paper, I certainly didn't expect it to reboot the 'Linux is obsolete' debate.


Linus then responded and it looks like we are about to have another little debate. OK, but please, everyone, let's stick to the technical issues.


Linus' Argument


Linus' basic point is that microkernels require distributed algorithms and they are nasty. I agree that distributed algorithms are hell on wheels, although together with Maarten van Steen I wrote a book dealing with them. I have also designed, written and released two distributed systems in the past decade, Amoeba (for LANs) and Globe (For WANs). The problem with distributed algorithms is lack of a common time reference along with possible lost messages and uncertainty as to whether a remote process is dead or merely slow. None of these issues apply to microkernel-based operating systems on a single machine. So while I agree with Linus that distributed algorithms are difficult, that is not germane to the discussion at hand.


Besides, most of the user-space components are drivers, and they have very straightforward interactions with the servers. All character device drivers obey pretty much the same protocol (they read and write byte streams) and all block device drivers obey pretty much the same protocol (they read and write blocks). The number of user-space servers is fairly small: a file server, a process server, a network server, a reincarnation server, and a data store, and a few more. Each has a well-defined job to do and a well-defined interaction with the rest of the system. The data store, for example, provides a publish/subscribe service to allow a loose coupling between servers when that is useful. The number of servers is not likely to grow very much in the future. The complexity is quite manageable. This is not speculation. We have already implemented the system, after all. Go install MINIX 3 and examine the code yourself.


Linus also made the point that shared data structures are a good idea. Here we disagree. If you ever took a course on operating systems, you no doubt remember how much time in the course and space in the textbook was devoted to mutual exclusion and synchronization of cooperating processes. When two or more processes can access the same data structures, you have to be very, very careful not to hang yourself. It is exceedingly hard to get this right, even with semaphores, monitors, mutexes, and all that good stuff.


My view is that you want to avoid shared data structures as much as possible. Systems should be composed of smallish modules that completely hide their internal data structures from everyone else. They should have well-defined 'thin' interfaces that other modules can call to get work done. That's what object-oriented programming is all about--hiding information--not sharing it. I think that hiding information (a la Dave Parnas) is a good idea. It means you can change the data structures, algorithms, and design of any module at will without affecting system correctness, as long as you keep the interface unchanged. Every course on software engineering teaches this. In effect, Linus is saying the past 20 years of work on object-oriented programming is misguided. I don't buy that.


Once you have decided to have each module keep its grubby little paws off other modules' data structures, the next logical step is to put each one in a different address space to have the MMU hardware enforce this rule. When applied to an operating system, you get a microkernel and a collection of user-mode processes communicating using messages and well-defined interfaces and protocols. Makes for a much cleaner and more maintainable design. Naturally, Linus reasons from his experience with a monolithic kernel and has arguably been less involved in microkernels or distributed systems. My own experience is based on designing, implementing, and releasing multiple such operating systems myself. This gives us different perspectives about what is hard and what is not.


For a different take on the whole issue of reliable operating systems, see this piece by Jonathan Shapiro entitled Debunking Linus's Latest.


Are Microkernels for Real?


In a word: yes. There were endless comments on Slashdot Monday (May 8) of the form: "If microkernels are so good, why aren't there any?" Actually there are. Besides MINIX 3, there are:


QNX

Integrity

PikeOS

Symbian

L4Linux

Singularity

K42

Mac OS X

HURD

Coyotos

QNX is widely used in real commercial systems. Cisco's top-of-the-line router uses it, for example, and I can assure you, Cisco cares a **LOT** about performance.


One of the leading operating systems in the military and aerospace markets, where reliability is absolutely critical is Green Hills' Integrity, another microkernel.


PikeOS is another microkernel-based real-time system widely used in defense, aerospace, automotive, and industrial applications.


Symbian is yet another popular microkernel, primarily used in cell phones. It is not a pure microkernel, however, but something of a hybrid, with drivers in the kernel, but the file system, networking, and telephony in user space.


I could go on and on, but clearly in applications where reliability and security are mission critical, designers have often chosen microkernel-based OSes. While Linus may not be personally interested in embedded real-time systems, (where performance, reliability, and security are paramount), these markets are huge and many companies involved think that microkernels are the way to achieve these goals.


Looking at the PC world we find L4Linux, which was written by Hermann Härtig's group at the Technical University of Dresden. It runs all of Linux in user space on top of the L4 microkernel with a performance loss of only a couple of percent. But using the microkernel allowed the TUD people to build new systems such as DROPS (real time) and NIZZA (security) on top of L4 but still have access to full Linux without having to modify it for these new features. In this way, they can experiment with new facilities and still run legacy programs. Other groups are also using the L4 microkernel for operating systems research, such as Wombat, a paravirtualized Linux designed to support legacy applications in embedded systems. Another L4-based OS is TUD-OS and there are more.


Microsoft also has interest in microkernels. It understands the maintenance headache of monolithic kernels like no one else. Windows NT 3.1 was a half-hearted attempt at a microkernel system, but it wasn't done right and the performance wasn't good enough on the hardware of the early 1990s, so it gave up on the idea for a while. But recently, it tried again on modern hardware, resulting in Singularity. Now I know that a lot of people assume that if Microsoft did it, it must be stupid, but the people who drove the Singularity project, Galen Hunt and Jim Larus, are very smart cookies, and they well understand that Windows is a mess and a new approach is needed. Even the people working on Vista see they have a problem and are moving drivers into user space, precisely what I am advocating.


About 10 years ago IBM began developing a new high-performance operating system from scratch for its very large customers. An explicit design goal was to move system functionality from the kernel to servers and application programs, similar to a microkernel. This system, called K42, has now been deployed at the DoE and elsewhere.


Mac OS X is sort of microkernelish. Inside, it consists of Berkeley UNIX riding on top of a modified version of the Mach microkernel. Since all of it runs in kernel mode (to get that little extra bit of performance) it is not a true microkernel, but Carnegie Mellon University had Berkeley UNIX running on Mach in user space years ago, so it probably could be done again, albeit with a small amount of performance loss, as with L4Linux. Work is underway to port the Apple BSD code (Darwin) to L4 to make it a true microkernel system.


Although high on promise and low on execution, GNU HURD is also based on a microkernel. Actually two of them. The first version was based on Mach; the second on L4. A third version will probably be based on yet another microkernel, Coyotos. HURD was designed by Richard Stallman, the author of emacs, gcc, and much other widely used software as well as creator of the GPL and winner of the prestigious MacArthur 'Genius' Award.


Another microkernel system in development is Coyotos, the successor to EROS. Here the focus is more on security than reliability, but the two issues are related in that bloated kernels can lead to problems on both fronts.


And I haven't even discussed hypervisors, such as Xen and Trango, which are quite different from microkernels in many ways, but do share the characteristic of having only a tiny bit of code running in kernel mode, which I believe is the key to building a reliable and secure system.


While MINIX 3, QNX, Integrity, PikeOS, Symbian, L4Linux, Singularity, K42, HURD, Coyotos, and others are an eclectic bunch, clearly I am not alone in seeing something in microkernels. If you are wondering why microkernels aren't even more widely used, well, there is a lot of inertia in the system. Why haven't Linux or Mac OS X replaced Windows? Well, there is a lot of inertia in the system. Most cars in Brazil can run on home-grown ethanol so Brazil uses relatively little oil for vehicle fuel. Why doesn't the U.S. do that and reduce its dependence on the volatile Middle East? Well, there is a lot of inertia in the system. Getting people to change, even to superior practices, is very hard.


What Am I Trying to Prove?


Actually, MINIX 3 and my research generally is **NOT** about microkernels. It is about building highly reliable, self-healing, operating systems. I will consider the job finished when no manufacturer anywhere makes a PC with a reset button. TVs don't have reset buttons. Stereos don't have reset buttons. Cars don't have reset buttons. They are full of software but don't need them. Computers need reset buttons because their software crashes a lot. I know that computer software is different from car software, but users just want them both to work and don't want lectures why they should expect cars to work and computers not to work. I want to build an operating system whose mean time to failure is much longer than the lifetime of the computer so the average user never experiences a crash. MINIX 3 has many specific reliability features. While we are by no means done (e.g. virtual memory is on the agenda for later this year), I think improving reliability is the greatest challenge facing operating systems designers at this moment. The average user does not care about even more features or squeezing the last drop of performance out of the hardware, but cares a lot about having the computer work flawlessly 100% of the time and never crashing. Ask your grandma.


So what do microkernels have to do with this goal? They make it possible to build self-healing systems. That is what I care about and my research is about. Moving most of the OS to a bunch of user processes, one for each driver plus various servers, does not reduce the number of bugs in the code but it greatly reduces the ability of each bug to do serious damage and it also reduces the size of the trusted computing base. In our design, when most drivers fail, the reincarnation server can restart a fresh copy, and optionally save the core image of the dead driver for debugging, log the event, send email to an administrator or developer, etc. The system continues to run, and at the very least can be shut down gracefully without loss of work or data. Some components, such as the reincarnation server itself, the file server, and the process server are critical, and losing them crashes the system, but there is absolutely no reason to allow a faulty audio, printer, or scanner driver to wipe out the system. They should just be restarted and work should continue. This is our goal: systems that can detect and repair their own faults. You can do this easily in a microkernel system. It is much harder in a monolithic kernel, although researchers at the University of Washington have done some good work with Nooks and a group at the University of Karlsruhe has also done interesting work with virtual machine technology.


Linus on Linux


Late update. Linus has come to realize that Linux has become awfully bloated. See here for his comments.


Homework


Before pontificating about what microkernels can and cannot do, go get and try MINIX 3 and be an informed pontificator. It increases your credibility. To learn more about the MINIX 3 design, see the paper in the May IEEE Computer, this paper on modular programming that just appeared in USENIX ;login, or this technical report.


If you have made it this far, thank you for your time.


Andy Tanenbaum, 12 May 2006

Posted by 쿨한넘