๋ณธ๋ฌธ์œผ๋กœ ๊ฑด๋„ˆ๋›ฐ๊ธฐ
ๅฐ้พ™่™พๅฐ้พ™่™พAI
๐Ÿค–

Kernel

Avoid common Linux kernel mistakes โ€” atomic context violations, allocation failures, and locking traps.

ไธ‹่ฝฝ1.2k
ๆ˜Ÿๆ ‡2
็‰ˆๆœฌ1.0.0
ๅผ€ๅ‘ๅทฅๅ…ท
ๅฎ‰ๅ…จ้€š่ฟ‡

ๆŠ€่ƒฝ่ฏดๆ˜Ž


name: Kernel description: Avoid common Linux kernel mistakes โ€” atomic context violations, allocation failures, and locking traps. metadata: {"clawdbot":{"emoji":"๐Ÿง","os":["linux"]}}

Atomic Context Traps

  • spin_lock held = cannot sleep โ€” no kmalloc(GFP_KERNEL), no mutex_lock, no copy_from_user
  • Interrupt can take same spinlock โ€” must use spin_lock_irqsave, not plain spin_lock
  • rcu_read_lock() section cannot sleep โ€” no blocking calls inside RCU read-side
  • might_sleep() annotation โ€” add to functions that may sleep, catches bugs with CONFIG_DEBUG_ATOMIC_SLEEP

Allocation Failures

  • GFP_ATOMIC can return NULL โ€” always check, don't assume success
  • vmalloc memory not physically contiguous โ€” cannot use for DMA
  • kzalloc over kmalloc โ€” uninitialized memory leaks kernel info to userspace
  • Allocation in loop risks OOM โ€” preallocate or use memory pool

User Pointer Handling

  • copy_from_user returns bytes NOT copied โ€” 0 means success, not failure
  • Never use %s with user pointer in printk โ€” kernel crash or info leak
  • User memory can change during syscall โ€” copy to kernel buffer, validate the copy
  • __user annotation is documentation โ€” doesn't enforce anything, you must use copy functions

Memory Ordering

  • READ_ONCE/WRITE_ONCE for lockless shared data โ€” prevents compiler from caching/reordering
  • Spinlock release has implicit barrier โ€” but check-then-act patterns still need care
  • smp_wmb() before publishing pointer โ€” ensures data visible before pointer is

Module Error Paths

  • Init fails midway โ€” must undo everything already done
  • Reverse order cleanup โ€” unregister in opposite order of register
  • goto err_* pattern standard โ€” cleaner than nested ifs
  • Check what's actually initialized โ€” don't free/unregister what wasn't set up

Locking Mistakes

  • Same lock acquired twice = deadlock โ€” even in different functions
  • Inconsistent lock ordering โ€” document order, acquire in same sequence everywhere
  • mutex_trylock returns 1 on success โ€” opposite of pthread_mutex_trylock
  • Reader-writer locks rarely worth it โ€” contention overhead usually exceeds benefit

ๅฆ‚ไฝ•ไฝฟ็”จใ€ŒKernelใ€๏ผŸ

  1. ๆ‰“ๅผ€ๅฐ้พ™่™พAI๏ผˆWeb ๆˆ– iOS App๏ผ‰
  2. ็‚นๅ‡ปไธŠๆ–นใ€Œ็ซ‹ๅณไฝฟ็”จใ€ๆŒ‰้’ฎ๏ผŒๆˆ–ๅœจๅฏน่ฏๆก†ไธญ่พ“ๅ…ฅไปปๅŠกๆ่ฟฐ
  3. ๅฐ้พ™่™พAI ไผš่‡ชๅŠจๅŒน้…ๅนถ่ฐƒ็”จใ€ŒKernelใ€ๆŠ€่ƒฝๅฎŒๆˆไปปๅŠก
  4. ็ป“ๆžœๅณๆ—ถๅ‘ˆ็Žฐ๏ผŒๆ”ฏๆŒ็ปง็ปญๅฏน่ฏไผ˜ๅŒ–

็›ธๅ…ณๆŠ€่ƒฝ