리눅스/커널2012. 10. 3. 00:45

출처: 리눅스 커널 내부구조

리눅스에서 메모리의 최소 할당 단위는 페이지 프레임이라고 알고 있다.  근데 만약 그 이하의 공간이 필요할 때는 어떻게 하는 게 좋을까?  그냥  4kb 던져주는게 좋을까?  말할것도 없이 공간낭비이다.

 

대신 미리 정해진 사이즈의 cache를 가지고 있다가 필요할 때 할당한다면 어떨까?  32byte에서 2의 오더로 128kb 까지 유지해서 말이다.

 

각 cache들은 슬랩들로 구성되고, 슬랩은 다시 객체(Object)들로 구성된다.

 

예를 들어 64byte cache이면,

Object (64byte) --> slab (full/free/partial) --> cache

와 같은 구조로 이루어져 있다.  64byte 공간들이 각각의 객체이고, 이 객체들이 슬랩이 되고, 이 슬랩들이 cache가 되는 것이다.

 

참고로 리눅스는 다양한 크기의 캐시를 효율적으로 관리하기 위해 kmem_cache_t라는 자료 구조를 만들어 두었고, 새로운 캐시를 생성시에 kmem_cache_t라는 구조체로부터 할당 받는다.  이 때 슬랩할당자로부터 할당받는 것이다.

kmem_cache_t 구조체 크기의 객체를 담고 있는 cache의 이름이 cache_cache이다.

당연히 cache_cache는 다른 캐시들보다 먼저 생성되어야 한다(그래야 다른 캐시를 만들 때 할당이 가능하지 않겠는가?)  그 후에 cache_cache를 이용해서 kmem_cache_t를 위한 공간을 할당받아 다양한 캐시를 생성한다.

 

슬랩할당자는 이외에도 외부 인터페이스 함수로 kmalloc(), kfree()를 제공한다.(그래서 kmalloc()를 통해 한번에 할당 받는 최대 크기가 128k라는 걸 눈치 챘을 것이다.)

Posted by code cat
프로그래밍/JAVA2012. 10. 1. 21:20

출처: http://docs.oracle.com/javase/tutorial/java/generics/types.html

 

 

Generics이란?

generics은 class와 interface를 type화 시킬 수 있다.  generics를 사용하면 다음과 같은 이점이 있다.

  • 컴파일 시에 type 체크를 할 수 있다.

컴파일 시에 generic 코드를 체크 함으로써 에러를 미리 방지 할 수 있다.

  • cast를 생략할 수 있다.

List list = new ArrayList();

list.add("hello");

String s = (String) list.get(0);

를 generics을 사용한다면,

 

List<String> list = new ArrayList<String>();

list.add("hello");

String s = list.get(0);

  • generic algorithm을 사용 할 수 있다.

다른 type들로 이루어진 collections에 대한 generic algorithm을 사용할 수 있다.

 

일반적인 Generics  사용법

 

generic class는 다음과 같은 형태이다.

class name<T1, T2, T3, .... Tn> { ... }

 

예제를 통해 보자.

 

generic을 써서 위의 코드를 다시 작성하면,

 

 

보는 바와 같이 Object 대신 type T를 사용할 수 있다.  왜 T냐면.. 보통 다음과 같은 conventions를 따르기 때문이다.

 E

 Element

 K  Key

 N

 Number
 T  Type
 V  Value

 S, U, V

 2nd, 3rd, 4th types

 

 

Generic Type 사용법

 

geneirc Box class를 참조시에 다음과 같이 한다.

Box<Integer> integerBox;

 

위의 경우 Type argument이다. 여기서 Type paramemter 랑 Type argument의 차이점을 보자.

 

Type Parameter and Type Argument Terminology: Many developers use the terms "type parameter" and "type argument" interchangeably, but these terms are not the same. When coding, one provides type arguments in order to create a parameterized type. Therefore, the T in Foo<T> is a type parameter and the String in Foo<String> f is a type argument. This lesson observes this definition when using these terms

 

 

 

 

 

 

 

'프로그래밍 > JAVA' 카테고리의 다른 글

OTA Package Utility  (0) 2013.11.25
Swing desiginer LookAndFeel 종류  (0) 2013.11.19
WindowBuilder Pro for Eclipse 3.7(Indigo) 설치 오류  (0) 2012.08.06
ant 빌드가 안될 때  (0) 2011.10.19
Posted by code cat

init.rc에 oom_adj 값에 대해 찾아보았다.



여기에 사용되는 값은 막 지어낸 게 아니라  linux/include/linux/oom.h 를 참조하는 값이며, 다음과 같이 되어 있다. 


#define OOM_DISABLE     (-17) /* inclusive */

#define OOM_ADJUST_MIN  (-16) 

#define OOM_ADJUST_MAX 15



init 프로세스와 그 child들은 init.rc에서 다음과 같이 정의 되어 있다.

write /proc/1/oom_adj -16

oom_adj를 따로 설정 안 해주는 service들이나 'exec'로 실행되는 바이너리들은 -16을 갖는다.

'안드로이드 > 프레임워크' 카테고리의 다른 글

Bionic libc (2)  (0) 2012.11.08
Bionic libc  (0) 2012.10.30
Dalvik Virtual Machine 와 odex  (0) 2012.08.13
안드로이드 바인더 ipc  (0) 2011.10.23
안드로이드 프레임워크 *Java에서 전처리기 사용하기*  (0) 2011.06.06
Posted by code cat

~/.profile에 

다음과 같이 입력하면 된다.


`echo $- | grep -qs i` && byobu-launcher && exit 0


반대로 자동 실행이 싫으면 위의 라인을 comment 처리하자.

Posted by code cat
프로그래밍/C2012. 9. 25. 09:15

    인라인 어셈블리



    1. #if __LINUX_ARM_ARCH__ >= 6

    2. static inline unsigned long arch_local_irq_save(void)

    3. {

    4. unsigned long flags;

    5. asm volatile(" mrs %0, cpsr    @ arch_local_irq_save\n"

    6. "            cpsid i"

    7. : "=r" (flags) : : "memory", "cc");

    8. return flags;

    9. }


 인라인 어셈블리에 대해서 간단히 짚고 넘어가자. 나중에 보면 이해가 안될거 같으니까.

보통 다음과 같은 문법이다.

__asm__ __volatile__ (asms : output: input: clobber);

ANSI에서는 __asm__만 쓰니까, asm 보단 __asm__을 쓰는게 낫다.  volatile(__volatile__)은 최적화를 진행하지 않는다.  컴파일러가 괜히 머리 쓴다고 사용되지 않는다고 판단되는 변수를 없애는 불상사를 방지한다.

asm은 따옴표로 둘러싸인 어셈블리 코드(여기서는 "mrs ... cpsid i"가 되겠다)이며, %와 같은 형태로 input, output parameter를 사용할 수 있다.  컴파일 후, 파라미터가 치환된 대로 어셈블리 코드로 나타난다.

output은 결과값을 출력하는 변수이다. 

"=r"(flags)이다. =는 쓰기전용이란 뜻이다.

input은 output과 같은 방식으로 사용하고, 인라인 어셈블리 코드에 넘겨주는 parameter를 적는다.

clobber는 asm를 실행 시, 값이 변하는 것을 적어준다.  각 변수는 쉼표로 구분되며 각각을 따옴표로 감싸준다. "memory", "cc"가 되겠다.

이제 실제 코드를 분석해 보면,

mrs %0, cpsr 에서는 "=r" (flags)에서, 레지스터 넘버를 flags로 받은 뒤 나오는 레지스터로 cpsr를 저장시킨다. 그 후 cpsid i를 통해 인터럽트를 disable 시킨다. cpsid i는 arm cortex에서 인터럽트를 disable 시킨다. armv7 전용 명령어로 알고 있었는데, ifdef에서 version 6부터 체크하는 걸 보니, armv6에서도 가능한가 보다.

clobber 영역의 "memory"는 컴파일러에게 어셈브릴 코드가 메모리의 어딘가를 변경한다고 가르쳐 주는 것이다. 만약 이렇게 안해주면 컴파일러는 어셈블리코드에서 메모리의 내뇽을 변경하는 것을 컴파일러는 전혀 알 수 없다. "memory"를 명시해 주면, 컴파일러는 어셈블리 코드를 실행하기 전/후에 레지스터에 저장되어 있는 모든 변수의 값을 갱신하도록 한다. "cc"는 컴파일러에게 어셈블리 명령어가 컨디션 코드 플래그를 읽고 쓴다고 알려준다.  설명이 길어졌다. 결국, cpsr를 저장하고 인터럽트를 disable 시킨다.

'프로그래밍 > C' 카테고리의 다른 글

symbol visibility  (0) 2013.08.07
typedef 와 static 을 동시에 사용 못하는 이유  (0) 2012.11.24
include guard에 대해서  (0) 2012.09.24
구조체 초기화 방법  (0) 2012.08.21
error: expected identifier before numeric constant  (0) 2012.07.03
Posted by code cat
프로그래밍/C2012. 9. 24. 13:58

include guard란 실수로 인해 같은 header 파일이 한번 이상 include되는 걸 막는 방법이다.


아래 예제를 보자.


basic.h


intermediate.h


expert.c


보는 바와 같이 expert.c에서 basic.h를 두번 include하는 결과가 되었다. (라인1에서 한번, 라인 2의 intermediate.h는 결국 basic.h를 include한다)


그래서 이러한 상황을 막기 위해 헤더파일을 정의 할 때 다음과 같이 basic.h에 중복 정의를 막는 매크로를 사용한다.

basic.h  (modified)

 

이러한 예제만 보면 별거 아닌거 가지고 저러나 싶겠지만, 파일 수십가지 수백가지가 되면 의도치않게 중복으로 include하게 된다.

Posted by code cat

내가 모르는 훌륭한 방법이 있을 거라고 보는데, 어쨌든 나는 노가다로 하고 있다.


svn diff -r1000:1001 > svn.r1000.vs.r1001.diff

로 패치 파일을 만든 뒤,

patch -p0 -i ./svn.r1000.vs.r1001.diff

로 패치를 적용하고 git으로 커밋하고 있다.



Posted by code cat

svn up 했더니,

...

어쩌구 저쩌구 잘 업데이트하다가, 마지막에

Tree conflicts: 1 

하고 뜬다.


덴장, 하지만 이럴 땐 다음과 같이 하자.

svn resolve --accept working -R .


Posted by code cat
리눅스/커널2012. 9. 16. 20:44

 

GFP_ATOMIC

메모리가 있으면 할당 없으면 NULL. 휴면 불가능

GFP_KERNEL

메모리 할당이 항상 성공하도록 요구, 메모리가 충분하지 않을 경우는 호출한 프로세스를 멈추고 동적 메모리 할당할 수 있는 상태가 될때까지 대기. 휴면가능.

GFP_USER

유저 메모리를 할당함.  휴면 가능 

GFP_DMA

연속된 물리 메모리를 할당 받을 때 사용

 

'리눅스 > 커널' 카테고리의 다른 글

가상 메모리 관리  (0) 2012.10.03
Slab allocator (슬랩 할당자)  (0) 2012.10.03
include/linux/fs.h 2.6.35 vs 3.0  (0) 2012.09.16
boot memory allocator 의 필요성  (0) 2012.09.04
defunct 프로세스 죽이기  (0) 2012.08.16
Posted by code cat
IT2012. 9. 16. 20:40

출처: http://www.imore.com/big-list-ios-6-features


iCloud sync with OS X Mountain Lion
Messages (with iMessage, pulled from the latest beta), Reminders, Notes
Documents in the Cloud (Pages, Numbers, Keynote, Preview, Text Edit, plus developer SDK)
Mail preferences pushed to iCloud
iCloud Documents API improvements


Siri
    Sports scores (baseball, basketball, football, hockey, soccer) 
    Italian Serie A
    English Premier League
    MLS
    French Ligue 1
    Spanish la Liga
    Dutch Eredivisie
    German Bundesliga
    MLB
    NCAA Football
    NFL
    NBA
    NCAA Basketball
    WNBA
    NHL
    Sport player stats
    Sport team rosters
    Sports league standings
    Sports game schedule
    Updated restaurant searches (type, price, Yelp reviews, distance, map, hours, phone number)
    OpenTable reservations for restaurants
    Movie listings per theatre
    Rotten Tomato moview reviews
    Movie facts
    Movie trailers
    Search by actor/actress
    Launch apps
    Send Tweet
    Update Facebook status
    Listen to notifications
    Eyes Free car integration (in the next year)
    International languages (Canada, Spain, Italy, Switzerland, Korean, Taiwan, Hong Kong, China) and local search (all of the     above plus countries with existing Siri functionality)
    Siri for iPad (new iPad only)


Facebook
    Single sign-on
    Share from Photos, Safari, Maps, App Store, iTunes, Game Center
    Public API for developers
    Contact and Calendar integration


Phone
Reply to incoming calls with message (preset or custom) or save reminder (timed or geofenced)
New dialer layout


Center
Do not disturb toggle with fine-grain phone call exceptions, schedules, or allowing repeat calls
Facebook and Twitter compose buttons


FaceTime
Available over cellular
Apple ID unified with phone number, enabling FaceTime or iMessage answering on iPad or Mac


Safari
iCloud Tabs for Safari on other iOS devices and Macs
Offline Reading List

Photo uploads
Smart app banners link to App Store or launches
Fullscreen video in landscape


Photo Streams
Shared Photo Streams with designated friends, includes comments
Photo Stream pictures in Mac screensaver
Photo Stream now a separate tab, not another album


Mail
VIPs - designated contacts cause notifications, e-mails flagged with stars, separate inbox
Flagged mailbox
Attach photos in-line (finally)
Open password-protected Office docs
Per account signatures
Fun new pull-to-refresh animation
Notifications per mailbox
Long-press compose to open or delete drafts


Passbook
Barcode collection for boarding passes, store cards, coupon, movie tickets
Pops up on lock screen when you arrive
Includes up-to-date-balance
Boarding passes update with gate changes
Synced to iCloud
Cute deletion animation


Guided Access
Disable certain app interactions with a circle
Limit hardware buttons, touch, and motion control access
Single-app mode


Maps
Local search with 100 million business listings with Yelp reviews and pictures
Crowd-sourced traffic data with incident reports
Free turn-by-turn navigation with alternative route offers based on faster ETA
Navigation viewable from lock screen
Siri integration, finds spots along your route
Flyover (3D buildings)
Multitouch rotation, angle change, and zoom
Powered by TomTom
Pinch-out in maps goes to globe view
Report bugs


Game Center
Game Center sync with OS X
Cross-platform turn-based and realtime gaming between iOS and Mac
Issue challenges to friends
Find Facebook friends


Developer SDK
Audio and video sampling during playback
Pass Kit
Rich text on labels, fields, and text views
VoiceOver gestures
Control camera focus and exposure
Remote Web Inspector
CSS filters
Action Sheer
Web Audio API
Crossfade with CSS animation
Game Center in-app experience
Reminders
Video stabilization
Game groups
Bluetooth MAP support
Transit apps (Apple's Maps doesn't have its own, but opening doors to local devs)
In-app Bluetooth pairing
Face detection API
Inter-app audio
Frame drop data
Map Kit
Auto layout
State preservation
Pull to refresh on Table views
In-app purchase hosted content
Read and write image metadata
Collection views
In-app content purchases
Multi-route audio


Other
Location-based reminders for iPad
Autocorrection for every keyboard
Global network proxy for HTTP
Manual reorder of reminders
Lost Mode - send a phone number to lost device which can be called with single tap
Kernel ASLR
Manual location entry for reminders
Custom vibrations for alerts
VoiceOver improvements
App in Safari search results
IPv6 support for Wi-Fi and LTE
HDR improvements
French, German, and Spanish dictionaries
Word highlights for speajk selection
Search all fields in Contacts
New iPad Clock/timer app
Improved keyboard layouts
Made for iPhone hearing aids
Extended functions for China
Baidu
Sina Weibo
Tudou
Youku
Improved text input
Dictionary
Top title bar changes color with app
New iPod app layout
Granular privacy control
iCloud-stored user dictionary
Updated sharing menu with large icons
Music ringtones, alarms
Redesigned App Store and iTunes (can now view App Store screenshots in full screen)
iTunes Match now streams music (rather than just download)
Support for iPhone 3GS and later; iPad 2 and later, iPod touch 4th gen)
Tilt changes reflection on slider buttons
Spotlight now shows which folder apps are in
Government alerts (AMBER and Emergency) in Notifications
More and new Emojis
Music preview banner overlays current screen, plus preview history
Time since last full charge (usage, standby)
Darker camera UI
"New" banner on app icons after installation
Update history in App Store
15 second skip playback controls for podcasts
Hold navigation arrow in Safari for iPhone for history view
"Enhanced" photos now add "-fixed" to file name
Cleared notifications sync across devices
No more pop-up in Safari when there's no internet access available
Share calendar that you created (but not one shared with you) from app
iPhone version of Stocks app loaded on iPad
Downloading doesn't kick you out of App Store anymore
Updating apps doesn't require password anymore
Apple apps have logo in Spotlight search
Wallpaper previews show live reproduction, rather than canned app layout
App Store "installed" buttons now show "open"
Cellular data toggle for FaceTime, iCloud documents, and iTunes
Late night mode in equalizer
Simplified Bluetooth toggle
Episodes viewable by season in Video app

'IT' 카테고리의 다른 글

iPad with Retina display 스펙  (1) 2012.10.24
iPad 미니 스펙  (0) 2012.10.24
아이폰 5 스펙  (0) 2012.09.14
iPhone 5 (아이폰 5) vs 아이폰 4s vs 아이폰4  (0) 2012.09.14
맥북프로 2012년 스펙 (레티나디스플레이 포함)  (0) 2012.06.12
Posted by code cat