answer
stringlengths
15
1.25M
#if defined(VGP_ppc64_aix5) #include "pub_core_basics.h" #include "pub_core_vki.h" #include "pub_core_vkiscnums.h" #include "<API key>.h" #include "pub_core_debuglog.h" #include "pub_core_libcassert.h" #include "pub_core_libcprint.h" #include "pub_core_libcproc.h" #include "pub_core_options.h" #include "pub_core_scheduler.h" #include "pub_core_sigframe.h" // For VG_(sigframe_destroy)() #include "pub_core_signals.h" #include "pub_core_syscall.h" #include "pub_core_syswrap.h" #include "pub_core_tooliface.h" #include "priv_types_n_macros.h" #include "priv_syswrap-aix5.h" /* for decls of aix5-common wrappers */ #include "priv_syswrap-main.h" /* XXXXXXXXXXXX these HACKS are copies of stuff in syswrap-linux.c; check for duplication. */ /* HACK: is in syswrap-generic.c, but that doesn't get build on AIX. */ /* Dump out a summary, and a more detailed list, of open file descriptors. */ void VG_(show_open_fds) ( void ) { I_die_here; } static Bool <API key> ( void ) { Int c = VG_(<API key>)(); vg_assert(c >= 1); /* stay sane */ return c == 1; } void VG_(reap_threads)(ThreadId self) { while (!<API key>()) { /* Let other thread(s) run */ VG_(vg_yield)(); VG_(poll_signals)(self); } vg_assert(<API key>()); } void VG_(init_preopened_fds) ( void ) { I_die_here; } // Run a thread from beginning to end and return the thread's // <API key>. static VgSchedReturnCode thread_wrapper(Word /*ThreadId*/ tidW) { VgSchedReturnCode ret; ThreadId tid = (ThreadId)tidW; ThreadState* tst = VG_(get_ThreadState)(tid); VG_(debugLog)(1, "syswrap-aix64", "thread_wrapper(tid=%lld): entry\n", (ULong)tidW); vg_assert(tst->status == VgTs_Init); /* make sure we get the CPU lock before doing anything significant */ VG_(acquire_BigLock)(tid, "thread_wrapper(starting new thread)"); if (0) VG_(printf)("thread tid %d started: stack = %p\n", tid, &tid); VG_TRACK( <API key>, tid ); tst->os_state.lwpid = VG_(gettid)(); tst->os_state.threadgroup = VG_(getpid)(); /* Thread created with all signals blocked; scheduler will set the appropriate mask */ ret = VG_(scheduler)(tid); vg_assert(VG_(is_exiting)(tid)); vg_assert(tst->status == VgTs_Runnable); vg_assert(VG_(is_running_thread)(tid)); VG_(debugLog)(1, "syswrap-aix64", "thread_wrapper(tid=%lld): exit\n", (ULong)tidW); /* Return to caller, still holding the lock. */ return ret; } /* Run a thread all the way to the end, then do appropriate exit actions (this is the <API key> bit). */ static void <API key> ( Word tidW ) { ThreadId tid = (ThreadId)tidW; VgSchedReturnCode src; Int c; VG_(debugLog)(1, "syswrap-aix64", "<API key>(tid=%lld): pre-thread_wrapper\n", (ULong)tidW); /* Run the thread all the way through. */ src = thread_wrapper(tid); VG_(debugLog)(1, "syswrap-aix64", "<API key>(tid=%lld): post-thread_wrapper\n", (ULong)tidW); c = VG_(<API key>)(); vg_assert(c >= 1); /* stay sane */ vg_assert(src == VgSrc_ExitThread || src == VgSrc_ExitProcess || src == VgSrc_FatalSig); if (c == 1 || src == VgSrc_ExitProcess) { VG_(debugLog)(1, "syswrap-aix64", "<API key>(tid=%lld): " "exit process (%d threads remaining)\n", (ULong)tidW, c); /* We are the last one standing. Keep hold of the lock and carry on to show final tool results, then exit the entire system. Use the continuation pointer set at startup in m_main. */ ( * VG_(<API key>) ) (tid, src); } else { ThreadState *tst; VG_(debugLog)(1, "syswrap-aix64", "<API key>(tid=%lld): " "not last one standing\n", (ULong)tidW); /* OK, thread is dead, but others still exist. Just exit. */ vg_assert(c >= 2); tst = VG_(get_ThreadState)(tid); /* This releases the run lock */ VG_(exit_thread)(tid); vg_assert(tst->status == VgTs_Zombie); /* We have to use this sequence to terminate the thread to prevent a subtle race. If VG_(exit_thread)() had left the ThreadState as Empty, then it could have been reallocated, reusing the stack while we're doing these last cleanups. Instead, VG_(exit_thread) leaves it as Zombie to prevent reallocation. We need to make sure we don't touch the stack between marking it Empty and exiting. Hence the assembler. */ { ULong block[4]; vg_assert(sizeof(tst->status == 8)); vg_assert(<API key> != __NR_AIX5_UNKNOWN); block[0] = (ULong)VgTs_Empty; block[1] = (ULong) & (tst->status); block[2] = (ULong) tst->os_state.exitcode; block[3] = <API key>; asm volatile ( "mr 29,%0\n\t" /* r29 = &block[0] */ "ld 20, 0(29)\n\t" /* r20 = VgTs_Empty */ "ld 21, 8(29)\n\t" /* r21 = & (tst->status) */ "ld 22, 16(29)\n\t" /* r22 = tst->os_state.exitcode */ "ld 23, 24(29)\n\t" /* r23 = __NR_exit */ /* after this point we can't safely use the stack. */ "std 20, 0(21)\n\t" /* tst->status = VgTs_Empty */ "mr 2,23\n\t" /* r2 = __NR_exit */ "mr 3,22\n\t" /* set r3 = tst->os_state.exitcode */ /* set up for syscall */ "crorc 6,6,6\n\t" ".long 0x48000005\n\t" /* "bl here+4" */ "mflr 29\n\t" "addi 29,29,16\n\t" "mtlr 29\n\t" "sc\n\t" /* exit(tst->os_state.exitcode) */ : : "b" (&block[0]) : "lr", "memory", "r2", "r3", "r20", "r21", "r22", "r23", "r29" ); } VG_(core_panic)("Thread exit failed?\n"); } /*NOTREACHED*/ vg_assert(0); } static Word <API key> ( void* arg ) { ThreadState* tst = (ThreadState*)arg; ThreadId tid = tst->tid; <API key> ( (Word)tid ); /*NOTREACHED*/ vg_assert(0); } /* Call f(arg1), but first switch stacks, using 'stack' as the new stack. f itself needs to never return. */ __attribute__((noreturn)) static void <API key> ( Addr stack, void (*f_NORETURN)(Word), Word arg1 ) { UWord* fdescr = (UWord*)f_NORETURN; volatile UWord block[5]; block[0] = fdescr[0]; /* nia */ block[1] = stack; block[2] = fdescr[1]; block[3] = arg1; block[4] = fdescr[2]; /* r11 */ __asm__ __volatile__( "mr 4,%0\n\t" /* r4 = block */ "ld 1, 8(4)\n\t" "ld 2, 16(4)\n\t" "ld 3, 24(4)\n\t" "ld 11,32(4)\n\t" "ld 4, 0(4)\n\t" "mtctr 4\n\t" "bctr\n" : /*out*/ : /*in*/ "b"(&block[0]) ); /*NOTREACHED*/ __asm__ __volatile__("trap"); while (1) {} /* convince gcc that this really doesn't return */ } /* Allocate a stack for the main thread, and run it all the way to the end. Although we already have a working VgStack (VG_(interim_stack)) it's better to allocate a new one, so that overflow detection works uniformly for all threads. */ void VG_(<API key>)(ThreadId tid) { Addr sp; VG_(debugLog)(1, "syswrap-aix64", "entering VG_(<API key>)\n"); sp = ML_(allocstack)(tid); /* If we can't even allocate the first thread's stack, we're hosed. Give up. */ vg_assert2(sp != 0, "Cannot allocate main thread's stack."); /* shouldn't be any other threads around yet */ vg_assert( VG_(<API key>)() == 1 ); /* make a stack frame */ sp -= 16; sp &= ~0xF; *(UWord *)sp = 0; <API key>( (Addr)sp, /* stack */ <API key>, /* fn to call */ (Word)tid /* arg to give it */ ); /*NOTREACHED*/ vg_assert(0); } void VG_(cleanup_thread) ( ThreadArchState* arch ) { } #include <sys/thread.h> /* Add prototypes for the wrappers declared here, so that gcc doesn't harass us for not having prototypes. Really this is a kludge -- the right thing to do is to make these wrappers 'static' since they aren't visible outside this file, but that requires even more macro magic. */ #define PRE(name) DEFN_PRE_TEMPLATE(ppc64_aix5, name) #define POST(name) DEFN_POST_TEMPLATE(ppc64_aix5, name) DECL_TEMPLATE(ppc64_aix5, sys__clock_gettime); DECL_TEMPLATE(ppc64_aix5, sys__fp_fpscrx64_); DECL_TEMPLATE(ppc64_aix5, sys_kload); DECL_TEMPLATE(ppc64_aix5, sys_kunload64); DECL_TEMPLATE(ppc64_aix5, sys_thread_setstate); DECL_TEMPLATE(ppc64_aix5, sys_FAKE_SIGRETURN); PRE(sys__clock_gettime) { /* Seems like ARG2 points at a destination buffer? */ /* _clock_gettime (UNDOCUMENTED) ( 0, 0xA, 0x2FF21808 ) */ PRINT("_clock_gettime (UNDOCUMENTED) ( %ld, %#lx, %#lx )", ARG1, ARG2, ARG3 ); PRE_REG_READ3(int, "_clock_gettime", int, arg1, int, arg2, void*, arg3); PRE_MEM_WRITE( "_clock_gettime(dst)", ARG2, sizeof(struct timespec) ); } POST(sys__clock_gettime) { vg_assert(SUCCESS); POST_MEM_WRITE( ARG2, sizeof(struct timespec) ); } PRE(sys__fp_fpscrx64_) { PRINT("_fp_fpscrx64_ (BOGUS HANDLER)"); } PRE(sys_kload) { PRINT("kload (UNDOCUMENTED)( %#lx(%s), %ld, %ld )", ARG1,(Char*)ARG1, ARG2, ARG3 ); PRE_REG_READ3(void*, "kload", char*, name, long, arg2, char*, arg3); } POST(sys_kload) { vg_assert(SUCCESS); if (0) VG_(printf)("kload result = %#lx\n", RES); if (RES) POST_MEM_WRITE( RES, 64 ); ML_(<API key>)(); } PRE(sys_kunload64) { PRINT("kunload64 (UNDOCUMENTED)( %#lx, %ld, %ld, %#lx )", ARG1, ARG2, ARG3, ARG4 ); PRE_REG_READ4(long, "kunload64", void*, arg1, long, arg2, long, arg3, void*, arg4); } POST(sys_kunload64) { vg_assert(SUCCESS); ML_(<API key>)(); } PRE(sys_thread_setstate) { UWord dst_lwpid = (UWord)ARG1; struct tstate* ats_new = (struct tstate*)ARG2; struct tstate* ats_old = (struct tstate*)ARG3; ThreadId dst_tid = VG_INVALID_THREADID; ThreadState* dst_ts = NULL; Int i; /* Arrgh. We MUST retain the lock during this syscall. Reason is that this is sometimes used for asynchronous thread cancellation (nuking other threads). If we don't have the lock during the syscall, then it's possible that the thread we're nuking might get the lock before it gets killed off, and so we can never re-acquire the lock after this syscall, and the system deadlocks. */ /* 10 July 06: above comment is a misdiagnosis. It appears that for thread cancellation (that is, with ->flags == TSTATE_INTR) the target thread is has its PC changed by the the kernel to something else, possibly to pthread_exit(), so that it can run its cancellation handlers and exit. Currently is unknown how the kernel knows what to set the target thread's PC to. I did establish that all the other data passed in the struct is not relevant: when ->flags == TSTATE_INTR, all the other words can be set to 0x0 or 0xFFFFFFFF and the syscall still works. So the address is not passed like that. Also I looked at args to <API key>, which is used when a thread sets its cancellation state, but none of those are code addresses. Also, it's ok for the kernel to simply change the target thread's PC to something else for async thread cancellation, but for deferred cancellation something else is needed, and I can't see how that would work either. Anyway, net result is, target thread ends up not running on the simulator (not dead), which is why it's necessary to hold onto the lock at this point. */ /* 30 July 06: added kludge to intercept attempts to cancel another thread and instead just force that thread to run pthread_exit(PTHREAD_CANCELED). This allows V to keep control. */ PRINT("thread_setstate (BOGUS HANDLER) " "( %ld, %p,%p )", dst_lwpid, ats_new, ats_old); if (1 && VG_(clo_trace_syscalls) && ats_new) ML_(<API key>)((Addr)ats_new, "thread_setstate (NEW)"); /* Intercept and handle ourselves any attempts to cancel another thread (including this one). */ if (ats_new && (!ats_old) && ats_new->flags == TSTATE_INTR) { dst_ts = NULL; if (VG_(clo_trace_syscalls)) VG_(printf)("(INTR for lwpid %ld)", dst_lwpid); dst_tid = VG_INVALID_THREADID; for (i = 0; i < VG_N_THREADS; i++) { dst_ts = VG_(get_ThreadState)(i); if ((dst_ts->status == VgTs_Runnable || dst_ts->status == VgTs_Yielding || dst_ts->status == VgTs_WaitSys) && dst_ts->os_state.lwpid == dst_lwpid) { dst_tid = i; break; } } if (VG_(clo_trace_syscalls)) { if (dst_tid == VG_INVALID_THREADID) VG_(printf)("(== unknown tid)"); else VG_(printf)("(== tid %d)", (Int)dst_tid); } if (dst_tid != VG_INVALID_THREADID) { /* A cancel has been requested for ctid. If the target thread has cancellation enabled, honour it right now. If not, mark the thread as having a cancellation request, so that if it later enables cancellation then the cancellation will take effect. */ vg_assert(dst_ts); if (dst_ts->os_state.cancel_progress == Canc_NoRequest) { if (dst_ts->os_state.cancel_disabled) { if (VG_(clo_trace_syscalls)) VG_(printf)("(target has cancel disabled" "; request lodged)"); dst_ts->os_state.cancel_progress = Canc_Requested; } else { if (VG_(clo_trace_syscalls)) VG_(printf)("(forcing target into pthread_exit)"); dst_ts->os_state.cancel_progress = Canc_Actioned; Bool ok = ML_(<API key>)(dst_tid); if (!ok) { /* now at serious risk of deadlock/livelock. Give up rather than continue. */ ML_(<API key>) (tid, "pthread_cancel(case2-64): " "cannot find pthread_exit; aborting"); SET_STATUS_Success(0); return; } } } SET_STATUS_Success(0); return; } } /* Well, it's not a cancellation request. Maybe it is the initialisation of a previously created thread? */ if (ats_new && !ats_old) { dst_tid = VG_INVALID_THREADID; for (i = 0; i < VG_N_THREADS; i++) { dst_ts = VG_(get_ThreadState)(i); if (dst_ts->status == VgTs_Init && dst_ts->os_state.lwpid == dst_lwpid) { dst_tid = i; break; } } if (dst_tid != VG_INVALID_THREADID) { /* Found the associated child */ if (VG_(clo_trace_syscalls)) VG_(printf)("(initialised child tid %d)", (Int)dst_tid); dst_ts = VG_(get_ThreadState)(dst_tid); UWord* stack = (UWord*)ML_(allocstack)(dst_tid); /* XXX TODO: check allocstack failure */ /* copy the specified child register state into the guest slot (we need that context to run on the simulated CPU, not the real one) and put pointers to our own run-the-simulator function into what we'll hand off to the kernel instead. */ /* The guest thread is to start running whatever context this syscall showed up with. */ dst_ts->arch.vex.guest_GPR0 = ats_new->mst.gpr[0]; dst_ts->arch.vex.guest_GPR1 = ats_new->mst.gpr[1]; dst_ts->arch.vex.guest_GPR2 = ats_new->mst.gpr[2]; /* toc */ dst_ts->arch.vex.guest_GPR3 = ats_new->mst.gpr[3]; /* initarg */ dst_ts->arch.vex.guest_GPR4 = ats_new->mst.gpr[4]; dst_ts->arch.vex.guest_GPR5 = ats_new->mst.gpr[5]; dst_ts->arch.vex.guest_GPR6 = ats_new->mst.gpr[6]; dst_ts->arch.vex.guest_GPR7 = ats_new->mst.gpr[7]; dst_ts->arch.vex.guest_GPR8 = ats_new->mst.gpr[8]; dst_ts->arch.vex.guest_GPR9 = ats_new->mst.gpr[9]; dst_ts->arch.vex.guest_GPR10 = ats_new->mst.gpr[10]; dst_ts->arch.vex.guest_GPR11 = ats_new->mst.gpr[11]; dst_ts->arch.vex.guest_GPR12 = ats_new->mst.gpr[12]; dst_ts->arch.vex.guest_GPR13 = ats_new->mst.gpr[13]; dst_ts->arch.vex.guest_GPR14 = ats_new->mst.gpr[14]; dst_ts->arch.vex.guest_GPR15 = ats_new->mst.gpr[15]; dst_ts->arch.vex.guest_GPR16 = ats_new->mst.gpr[16]; dst_ts->arch.vex.guest_GPR17 = ats_new->mst.gpr[17]; dst_ts->arch.vex.guest_GPR18 = ats_new->mst.gpr[18]; dst_ts->arch.vex.guest_GPR19 = ats_new->mst.gpr[19]; dst_ts->arch.vex.guest_GPR20 = ats_new->mst.gpr[20]; dst_ts->arch.vex.guest_GPR21 = ats_new->mst.gpr[21]; dst_ts->arch.vex.guest_GPR22 = ats_new->mst.gpr[22]; dst_ts->arch.vex.guest_GPR23 = ats_new->mst.gpr[23]; dst_ts->arch.vex.guest_GPR24 = ats_new->mst.gpr[24]; dst_ts->arch.vex.guest_GPR25 = ats_new->mst.gpr[25]; dst_ts->arch.vex.guest_GPR26 = ats_new->mst.gpr[26]; dst_ts->arch.vex.guest_GPR27 = ats_new->mst.gpr[27]; dst_ts->arch.vex.guest_GPR28 = ats_new->mst.gpr[28]; dst_ts->arch.vex.guest_GPR29 = ats_new->mst.gpr[29]; dst_ts->arch.vex.guest_GPR30 = ats_new->mst.gpr[30]; dst_ts->arch.vex.guest_GPR31 = ats_new->mst.gpr[31]; dst_ts->arch.vex.guest_CIA = ats_new->mst.iar; dst_ts->arch.vex.guest_LR = ats_new->mst.lr; dst_ts->arch.vex.guest_CTR = ats_new->mst.ctr; <API key>( ats_new->mst.cr, &dst_ts->arch.vex ); <API key>( ats_new->mst.xer, &dst_ts->arch.vex ); /* Record what seems like the highest legitimate stack address for this thread, so that the stack unwinder works properly. It seems reasonable to use the R1 value supplied here. */ dst_ts-><API key> = dst_ts->arch.vex.guest_GPR1; /* The host thread is to start running <API key> */ UWord* wrapper_fdescr = (UWord*) & <API key>; ats_new->mst.gpr[1] = (UWord)stack; ats_new->mst.gpr[2] = wrapper_fdescr[1]; ats_new->mst.iar = wrapper_fdescr[0]; ats_new->mst.gpr[3] = (UWord)dst_ts; /* Set initial cancellation status for the thread. */ dst_ts->os_state.cancel_async = False; dst_ts->os_state.cancel_disabled = False; dst_ts->os_state.cancel_progress = Canc_NoRequest; } } } POST(sys_thread_setstate) { if (ARG3) POST_MEM_WRITE( ARG3, sizeof(struct tstate) ); if (0 && VG_(clo_trace_syscalls) && ARG3) ML_(<API key>)(ARG3, "thread_setstate (OLD)"); } PRE(sys_FAKE_SIGRETURN) { /* See comments on PRE(sys_rt_sigreturn) in syswrap-amd64-linux.c for an explanation of what follows. */ PRINT("FAKE_SIGRETURN ( )"); vg_assert(VG_(is_valid_tid)(tid)); vg_assert(tid >= 1 && tid < VG_N_THREADS); vg_assert(VG_(is_running_thread)(tid)); /* Remove the signal frame from this thread's (guest) stack, in the process restoring the pre-signal guest state. */ VG_(sigframe_destroy)(tid, True); /* Tell the driver not to update the guest state with the "result", and set a bogus result to keep it happy. */ *flags |= SfNoWriteResult; SET_STATUS_Success(0); /* Check to see if any signals arose as a result of this. */ *flags |= SfPollAfter; } typedef struct { UInt* pSysNo; SyscallTableEntry wrappers; } AIX5SCTabEntry; #undef PLAXY #undef PLAX_ #define PLAXY(sysno, name) \ { & sysno, \ { & WRAPPER_PRE_NAME(ppc64_aix5, name), \ & WRAPPER_POST_NAME(ppc64_aix5, name) }} #define PLAX_(sysno, name) \ { & sysno, \ { & WRAPPER_PRE_NAME(ppc64_aix5, name), \ NULL }} static /* but not const */ AIX5SCTabEntry <API key>[] = { AIXXY(<API key>, sys___libc_sbrk), AIXX_(__NR_AIX5___msleep, sys___msleep), PLAXY(<API key>, sys__clock_gettime), AIXX_(__NR_AIX5__exit, sys__exit), PLAX_(<API key>, sys__fp_fpscrx64_), AIXX_(__NR_AIX5__getpid, sys__getpid), AIXXY(__NR_AIX5__nsleep, sys__nsleep), AIXX_(__NR_AIX5__pause, sys__pause), AIXXY(__NR_AIX5__poll, sys__poll), AIXX_(__NR_AIX5__select, sys__select), AIXX_(__NR_AIX5__sem_wait, sys__sem_wait), AIXXY(<API key>, sys__sigaction), AIXX_(<API key>, sys__thread_self), AIXX_(__NR_AIX5_access, sys_access), AIXX_(__NR_AIX5_accessx, sys_accessx), AIXXY(<API key>, sys_appgetrlimit), AIXXY(<API key>, sys_appgetrusage), AIXX_(<API key>, sys_appsetrlimit), AIXX_(__NR_AIX5_appulimit, sys_appulimit), AIXX_(__NR_AIX5_bind, sys_bind), AIXX_(__NR_AIX5_chdir, sys_chdir), AIXX_(__NR_AIX5_chmod, sys_chmod), AIXX_(__NR_AIX5_chown, sys_chown), AIXX_(__NR_AIX5_close, sys_close), AIXX_(__NR_AIX5_connext, sys_connext), AIXX_(__NR_AIX5_execve, sys_execve), AIXXY(__NR_AIX5_finfo, sys_finfo), AIXXY(__NR_AIX5_fstatfs, sys_fstatfs), AIXXY(__NR_AIX5_fstatx, sys_fstatx), AIXXY(__NR_AIX5_getdirent, sys_getdirent), AIXXY(<API key>, sys_getdirent64), AIXXY(<API key>, sys_getdomainname), AIXX_(__NR_AIX5_getgidx, sys_getgidx), AIXXY(<API key>, sys_gethostname), AIXXY(__NR_AIX5_getpriv, sys_getpriv), AIXXY(__NR_AIX5_getprocs, sys_getprocs), AIXXY(<API key>, sys_getprocs), /* XXX: correct? */ AIXX_(__NR_AIX5_getrpid, sys_getrpid), AIXXY(<API key>, sys_getsockopt), AIXX_(<API key>, sys_gettimerid), AIXX_(__NR_AIX5_getuidx, sys_getuidx), AIXXY(<API key>, sys_incinterval), AIXXY(__NR_AIX5_kfcntl, sys_kfcntl), AIXX_(__NR_AIX5_kfork, sys_kfork), AIXX_(__NR_AIX5_kill, sys_kill), AIXXY(__NR_AIX5_kioctl, sys_kioctl), PLAXY(__NR_AIX5_kload, sys_kload), AIXX_(__NR_AIX5_klseek, sys_klseek), AIXXY(__NR_AIX5_kread, sys_kread), AIXXY(__NR_AIX5_kreadv, sys_kreadv), AIXX_(<API key>, sys_kthread_ctl), AIXX_(__NR_AIX5_ktruncate, sys_ktruncate), PLAXY(__NR_AIX5_kunload64, sys_kunload64), AIXXY(__NR_AIX5_kwaitpid, sys_kwaitpid), AIXX_(__NR_AIX5_kwrite, sys_kwrite), AIXX_(__NR_AIX5_kwritev, sys_kwritev), AIXX_(__NR_AIX5_lseek, sys_lseek), AIXX_(__NR_AIX5_mkdir, sys_mkdir), AIXXY(__NR_AIX5_mmap, sys_mmap), AIXXY(__NR_AIX5_mntctl, sys_mntctl), AIXXY(__NR_AIX5_mprotect, sys_mprotect), AIXXY(__NR_AIX5_munmap, sys_munmap), AIXXY(<API key>, sys_ngetpeername), AIXXY(<API key>, sys_ngetsockname), AIXXY(__NR_AIX5_nrecvfrom, sys_nrecvfrom), AIXX_(__NR_AIX5_nrecvmsg, sys_nrecvmsg), AIXX_(__NR_AIX5_open, sys_open), AIXXY(__NR_AIX5_pipe, sys_pipe), AIXX_(__NR_AIX5_privcheck, sys_privcheck), AIXX_(__NR_AIX5_rename, sys_rename), AIXXY(__NR_AIX5_sbrk, sys_sbrk), AIXXY(__NR_AIX5_sem_init, sys_sem_init), AIXXY(__NR_AIX5_sem_post, sys_sem_post), AIXX_(__NR_AIX5_send, sys_send), AIXX_(__NR_AIX5_setgid, sys_setgid), AIXX_(<API key>, sys_setsockopt), AIXX_(__NR_AIX5_setuid, sys_setuid), AIXXY(__NR_AIX5_shmat, sys_shmat), AIXXY(__NR_AIX5_shmctl, sys_shmctl), AIXXY(__NR_AIX5_shmdt, sys_shmdt), AIXX_(__NR_AIX5_shmget, sys_shmget), AIXX_(__NR_AIX5_shutdown, sys_shutdown), AIXX_(<API key>, sys_sigcleanup), AIXXY(<API key>, sys_sigprocmask), AIXXY(__NR_AIX5_sys_parm, sys_sys_parm), AIXXY(__NR_AIX5_sysconfig, sys_sysconfig), AIXX_(__NR_AIX5_socket, sys_socket), AIXXY(__NR_AIX5_statx, sys_statx), AIXXY(<API key>, sys_thread_create), AIXX_(<API key>, sys_thread_init), AIXX_(<API key>, sys_thread_kill), AIXXY(<API key>, <API key>), AIXX_(<API key>, <API key>), PLAXY(<API key>, sys_thread_setstate), AIXX_(<API key>, <API key>), AIXX_(<API key>, sys_thread_tsleep), AIXX_(<API key>, sys_thread_twakeup), AIXX_(<API key>, sys_thread_unlock), AIXX_(<API key>, <API key>), AIXXY(__NR_AIX5_times, sys_times), AIXXY(__NR_AIX5_uname, sys_uname), AIXX_(__NR_AIX5_unlink, sys_unlink), AIXX_(__NR_AIX5_utimes, sys_utimes), AIXXY(__NR_AIX5_vmgetinfo, sys_vmgetinfo), AIXX_(__NR_AIX5_yield, sys_yield), PLAX_(<API key>, sys_FAKE_SIGRETURN) }; SyscallTableEntry* ML_(<API key>) ( UInt sysno ) { Int i; AIX5SCTabEntry tmp; const Int tab_size = sizeof(<API key>) / sizeof(<API key>[0]); for (i = 0; i < tab_size; i++) if (sysno == *(<API key>[i].pSysNo)) break; vg_assert(i >= 0 && i <= tab_size); if (i == tab_size) return NULL; /* can't find a wrapper */ /* Move found one a bit closer to the front, so as to make future searches cheaper. */ if (i > 0) { tmp = <API key>[i-1]; <API key>[i-1] = <API key>[i]; <API key>[i] = tmp; i } vg_assert(i >= 0 && i < tab_size); return &<API key>[i].wrappers; } #endif // defined(VGP_ppc64_aix5)
.flickr-photo-img, img.flickr-photoset-img, .flickr-wrap, span.flickr-credit { -<API key>: /*variable:flickrstyle_radius*/1em/*variable*/; -moz-border-radius: /*variable:flickrstyle_radius*/1em/*variable*/; border-radius: /*variable:flickrstyle_radius*/1em/*variable*/; }
(function(){tinymce.PluginManager.requireLangPack('codemagic');tinymce.create('tinymce.plugins.CodeMagic',{init:function(ed,url){ed.addCommand('mceCodeMagic',function(){ed.windowManager.open({file:url+'/codemagic.php',width:1200,height:600,inline:1,maximizable:true},{plugin_url:url})});ed.addButton('codemagic',{title:'codemagic.editor_button',cmd:'mceCodeMagic',image:url+'/img/code.png'});ed.onNodeChange.add(function(ed,cm,n,co){cm.setDisabled('link',co&&n.nodeName!='A');cm.setActive('link',n.nodeName=='A'&&!n.name)})},getInfo:function(){return{longname:'CodeMagic - syntax coloring and intendation',author:'Sutulustus',authorurl:'http://www.triad.sk/
/* ScriptData SDName: boss_erekem SD%Complete: 90 SDComment: Timers may need adjustments SDCategory: Violet Hold EndScriptData */ #include "precompiled.h" #include "violet_hold.h" enum { SAY_AGGRO = -1608012, SAY_ADD_DIE_1 = -1608013, SAY_ADD_DIE_2 = -1608014, SAY_DEATH = -1608018, // A few Sound IDs on SLAY, if there _is_ text related, fields -1608015 to -1608017 are free SOUND_ID_SLAY_1 = 14222, SOUND_ID_SLAY_2 = 14223, SOUND_ID_SLAY_3 = 14224, SPELL_BLOODLUST = 54516, SPELL_BREAK_BONDS_H = 59463, SPELL_CHAIN_HEAL = 54481, SPELL_CHAIN_HEAL_H = 59473, SPELL_EARTH_SHIELD = 54479, <API key> = 59471, SPELL_EARTH_SHOCK = 54511, <API key> = 53044, SPELL_STORMSTRIKE = 51876, // Spells of adds SPELL_GUSHING_WOUND = 39215, <API key> = 54463, SPELL_STRIKE = 14516 }; struct boss_erekemAI : public ScriptedAI { boss_erekemAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (<API key>*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } <API key>* m_pInstance; bool m_bIsRegularMode; uint32 m_uiBreakBondsTimer; uint32 m_uiChainHealTimer; uint32 <API key>; uint32 m_uiEarthShockTimer; uint32 <API key>; uint8 m_uiGuardiansDead; void Reset() override { <API key> = 0; <API key> = urand(2000, 3000); m_uiEarthShockTimer = urand(4000, 9000); m_uiChainHealTimer = urand(5000, 15000); m_uiBreakBondsTimer = urand(25000, 30000); m_uiGuardiansDead = 0; } void Aggro(Unit* /*pWho*/) override { DoScriptText(SAY_AGGRO, m_creature); } void JustDied(Unit* /*pKiller*/) override { DoScriptText(SAY_DEATH, m_creature); } void KilledUnit(Unit* /*pVictim*/) override { switch (urand(0, 2)) { case 0: DoPlaySoundToSet(m_creature, SOUND_ID_SLAY_1); break; case 1: DoPlaySoundToSet(m_creature, SOUND_ID_SLAY_2); break; case 2: DoPlaySoundToSet(m_creature, SOUND_ID_SLAY_3); break; } } void GuardianJustDied() { DoScriptText(!m_uiGuardiansDead ? SAY_ADD_DIE_1 : SAY_ADD_DIE_2, m_creature); ++m_uiGuardiansDead; // cast bloodlust if both guards are dead if (m_uiGuardiansDead == 2) DoCastSpellIfCan(m_creature, SPELL_BLOODLUST, <API key>); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (<API key> < uiDiff) { if (DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_EARTH_SHIELD : <API key>, <API key>) == CAST_OK) <API key> = urand(25000, 30000); } else <API key> -= uiDiff; if (m_uiEarthShockTimer < uiDiff) { if (Unit* pTarget = m_creature-><API key>(<API key>, 0)) { if (DoCastSpellIfCan(pTarget, SPELL_EARTH_SHOCK) == CAST_OK) m_uiEarthShockTimer = urand(8000, 13000); } } else m_uiEarthShockTimer -= uiDiff; if (m_uiChainHealTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_CHAIN_HEAL : SPELL_CHAIN_HEAL_H) == CAST_OK) m_uiChainHealTimer = urand(15000, 25000); } else m_uiChainHealTimer -= uiDiff; // Cast Stormstrike only if both guards are down if (<API key> < uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), m_uiGuardiansDead == 2 ? SPELL_STORMSTRIKE : <API key>) == CAST_OK) <API key> = urand(2000, 3000); } else <API key> -= uiDiff; // Break bonds only on heroic if (!m_bIsRegularMode) { if (m_uiBreakBondsTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_BREAK_BONDS_H) == CAST_OK) m_uiBreakBondsTimer = urand(25000, 30000); } else m_uiBreakBondsTimer -= uiDiff; } <API key>(); } }; CreatureAI* GetAI_boss_erekem(Creature* pCreature) { return new boss_erekemAI(pCreature); } struct npc_erekem_guardAI : public ScriptedAI { npc_erekem_guardAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = ((<API key>*)pCreature->GetInstanceData()); Reset(); } <API key>* m_pInstance; uint32 <API key>; uint32 <API key>; uint32 m_uiStrikeTimer; void Reset() override { <API key> = urand(9000, 14000); <API key> = urand(8000, 12000); m_uiStrikeTimer = urand(5000, 7000); } void JustDied(Unit* /*pKiller*/) override { if (!m_pInstance) return; if (Creature* pBoss = m_pInstance-><API key>(m_pInstance->GetData(TYPE_EREKEM) != DONE ? NPC_EREKEM : NPC_ARAKKOA)) { if (!pBoss->isAlive()) return; ((boss_erekemAI*)pBoss->AI())->GuardianJustDied(); } } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (<API key> < uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_GUSHING_WOUND) == CAST_OK) <API key> = urand(25000, 30000); } else <API key> -= uiDiff; if (<API key> < uiDiff) { if (DoCastSpellIfCan(m_creature, <API key>) == CAST_OK) <API key> = urand(10000, 16000); } else <API key> -= uiDiff; if (m_uiStrikeTimer < uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_STRIKE) == CAST_OK) m_uiStrikeTimer = urand(5000, 7000); } else m_uiStrikeTimer -= uiDiff; <API key>(); } }; CreatureAI* <API key>(Creature* pCreature) { return new npc_erekem_guardAI(pCreature); } void AddSC_boss_erekem() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "boss_erekem"; pNewScript->GetAI = &GetAI_boss_erekem; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "npc_erekem_guard"; pNewScript->GetAI = &<API key>; pNewScript->RegisterSelf(); }
<header>ðÒÏÃÅÓÓ</header> ÷ ÜÔÏÍ ÐÏÌÅ ÎÁÈÏÄÉÔÓÑ ËÏÍÁÄÎÁÑ ÓÔÒÏËÁ ÐÒÏÇÒÁÍÍÙ, ËÏÔÏÒÁÑ ÂÕÄÅÔ ×ÙÚ×ÁÎÁ ÄÁÎÎÙÍ ÐÒÏÃÅÓÓÏÍ ÉÎÉÃÉÁÌÉÚÁÃÉÉ (ÎÁÐÒÉÍÅÒ: /etc/init.d/rc, /sbin/getty ...).<p> <hr>
/*! \file GUILabel.h \brief */ #pragma once #include "GUITextLayout.h" #include "GUIInfoTypes.h" #include "GUIFont.h" #include "Geometry.h" class CLabelInfo { public: CLabelInfo() { font = NULL; align = XBFONT_LEFT; offsetX = offsetY = 0; width = 0; angle = 0; scrollSpeed = CScrollInfo::defaultSpeed; scrollSuffix = " | "; }; bool UpdateColors() { bool changed = false; changed |= textColor.Update(); changed |= shadowColor.Update(); changed |= selectedColor.Update(); changed |= disabledColor.Update(); changed |= focusedColor.Update(); return changed; }; CGUIInfoColor textColor; CGUIInfoColor shadowColor; CGUIInfoColor selectedColor; CGUIInfoColor disabledColor; CGUIInfoColor focusedColor; uint32_t align; float offsetX; float offsetY; float width; float angle; CGUIFont *font; int scrollSpeed; CStdString scrollSuffix; }; /*! \ingroup controls, labels \brief Class for rendering text labels. Handles alignment and rendering of text within a control. */ class CGUILabel { public: /*! \brief allowed color categories for labels, as defined by the skin */ enum COLOR { COLOR_TEXT = 0, COLOR_SELECTED, COLOR_FOCUSED, COLOR_DISABLED }; /*! \brief allowed overflow handling techniques for labels, as defined by the skin */ enum OVER_FLOW { OVER_FLOW_TRUNCATE = 0, OVER_FLOW_SCROLL, OVER_FLOW_WRAP }; CGUILabel(float posX, float posY, float width, float height, const CLabelInfo& labelInfo, OVER_FLOW overflow = OVER_FLOW_TRUNCATE); virtual ~CGUILabel(void); /*! \brief Process the label \return bool stating if process caused control to change */ bool Process(unsigned int currentTime); /*! \brief Render the label on screen */ void Render(); /*! \brief Set the maximal extent of the label Sets the maximal size and positioning that the label may render in. Note that <textwidth> can override this, and <textoffsetx> and <textoffsety> may also allow the label to be moved outside this rectangle. */ bool SetMaxRect(float x, float y, float w, float h); bool SetAlign(uint32_t align); /*! \brief Set the text to be displayed in the label Updates the label control and recomputes final position and size \param text CStdString to set as this labels text \sa SetTextW */ bool SetText(const CStdString &label); /*! \brief Set the text to be displayed in the label Updates the label control and recomputes final position and size \param text CStdStringW to set as this labels text \sa SetText */ bool SetTextW(const CStdStringW &label); /*! \brief Set the color to use for the label Sets the color to be used for this label. Takes effect at the next render \param color color to be used for the label */ bool SetColor(COLOR color); /*! \brief Set the final layout of the current text Overrides the calculated layout of the current text, forcing a particular size and position \param rect CRect containing the extents of the current text \sa GetRenderRect, UpdateRenderRect */ void SetRenderRect(const CRect &rect) { m_renderRect = rect; }; /*! \brief Set whether or not this label control should scroll \param scrolling true if this label should scroll. */ bool SetScrolling(bool scrolling); /*! \brief Set this label invalid. Forces an update of the control */ void SetInvalid(); /*! \brief Update this labels colors */ bool UpdateColors(); /*! \brief Returns the precalculated final layout of the current text \return CRect containing the extents of the current text \sa SetRenderRect, UpdateRenderRect */ const CRect &GetRenderRect() const { return m_renderRect; }; /*! \brief Returns the precalculated full width of the current text, regardless of layout \return full width of the current text \sa CalcTextWidth */ float GetTextWidth() const { return m_textLayout.GetTextWidth(); }; /*! \brief Returns the maximal width that this label can render into \return Maximal width that this label can render into. Note that this may differ from the amount given in SetMaxRect as offsets and text width overrides have been taken into account. \sa SetMaxRect */ float GetMaxWidth() const; /*! \brief Calculates the width of some text \param text CStdStringW of text whose width we want \return width of the given text \sa GetTextWidth */ float CalcTextWidth(const CStdStringW &text) const { return m_textLayout.GetTextWidth(text); }; const CLabelInfo& GetLabelInfo() const { return m_label; }; CLabelInfo &GetLabelInfo() { return m_label; }; /*! \brief Check a left aligned and right aligned label for overlap and cut the labels off so that no overlap occurs If a left-aligned label occupies some of the same space on screen as a right-aligned label, then we may be able to correct for this by restricting the width of one or both of them. This routine checks two labels to see whether they satisfy this assumption and, if so, adjusts the render rect of both labels so that they no longer do so. The order of the two labels is not important, but we do assume that the left-aligned label is also the left-most on screen, and that the right-aligned label is the right most on-screen, so that they overlap due to the fact that one or both of the labels are longer than anticipated. In the following diagram, [R...[R R] refers to the maximal allowed and actual space occupied by the right label. Similarly, [L L]...L] refers to the maximal and actual space occupied by the left label. | refers to the central cutting point, i.e. the point that would divide the maximal allowed overlap perfectly in two. There are 3 scenarios to consider: cut [L [R...[R L].|..........L] R] left label ends to the left of the cut -> just crop the left label. [L [R.....[R | L]..L] R] both left and right labels occupy more than the cut allows, so crop both. [L [R..........|.[R L]..L] R] right label ends to the right of the cut -> just crop the right label. \param label1 First label to check \param label2 Second label to check */ static bool <API key>(CGUILabel &label1, CGUILabel &label2); protected: color_t GetColor() const; /*! \brief Computes the final layout of the text Uses the maximal position and width of the text, as well as the text length and alignment to compute the final render rect of the text. \sa GetRenderRect, SetRenderRect */ void UpdateRenderRect(); private: CLabelInfo m_label; CGUITextLayout m_textLayout; bool m_scrolling; OVER_FLOW m_overflowType; bool m_selected; CScrollInfo m_scrollInfo; CRect m_renderRect; ///< actual sizing of text CRect m_maxRect; ///< maximum sizing of text bool m_invalid; ///< if true, the label needs recomputing COLOR m_color; ///< color to render text \sa SetColor, GetColor };
<?php /** * Outputs the RSS2 XML format comment feed using the feed-rss2.php file in * wp-includes folder. This file only sets the feed format and includes the * feed-rss2-comments.php. * * This file is no longer used in WordPress and while it is not deprecated now. * This file will most likely be deprecated or removed in a later version. * * The link for the rss2 comment feed is /index.php?feed=rss2&withcomments=1 * with permalinks off. * * @package WordPress */ if (empty($wp)) { require_once('./wp-load.php'); wp('feed=rss2&withcomments=1'); } require (ABSPATH . WPINC . '/feed-rss2-comments.php'); ?>
<?php namespace eZ\Publish\Core\Persistence\Legacy\Tests\Content; use eZ\Publish\Core\Persistence\Legacy\Tests\TestCase; use eZ\Publish\Core\Persistence\Legacy\Content\StorageRegistry; /** * Test case for StorageRegistry. */ class StorageRegistryTest extends TestCase { /** * @covers eZ\Publish\Core\Persistence\Legacy\Content\StorageRegistry::register */ public function testRegister() { $storage = $this->getStorageMock(); $registry = new StorageRegistry(array('some-type' => $storage)); $this->assertAttributeSame( array( 'some-type' => $storage, ), 'storageMap', $registry ); } /** * @covers eZ\Publish\Core\Persistence\Legacy\Content\StorageRegistry::getStorage */ public function testGetStorage() { $storage = $this->getStorageMock(); $registry = new StorageRegistry(array('some-type' => $storage)); $res = $registry->getStorage('some-type'); $this->assertSame( $storage, $res ); } /** * @covers eZ\Publish\Core\Persistence\Legacy\Content\StorageRegistry::getStorage * @covers eZ\Publish\Core\Persistence\Legacy\Exception\StorageNotFound */ public function testGetNotFound() { $registry = new StorageRegistry(array()); self::assertInstanceOf( 'eZ\\Publish\\Core\\FieldType\\NullStorage', $registry->getStorage('not-found') ); } /** * Returns a mock for Storage. * * @return Storage */ protected function getStorageMock() { return $this->getMock( 'eZ\\Publish\\SPI\\FieldType\\FieldStorage' ); } }
<?php /** * Credits administration panel. * * @package WordPress * @subpackage Administration */ /** WordPress Administration Bootstrap */ require_once __DIR__ . '/admin.php'; require_once __DIR__ . '/includes/credits.php'; $title = __( 'Credits' ); list( $display_version ) = explode( '-', get_bloginfo( 'version' ) ); require_once ABSPATH . 'wp-admin/admin-header.php'; $credits = wp_credits(); ?> <div class="wrap about__container"> <div class="about__header"> <div class="about__header-image"> <img alt="<?php _e( 'Code is Poetry' ); ?>" src="<?php echo admin_url( 'images/about-badge.svg' ); ?>" /> </div> <div class="<API key>"> <div class="about__header-title"> <p> <?php _e( 'WordPress' ); ?> <?php echo $display_version; ?> </p> </div> <div class="about__header-text"> <?php _e( 'Jazz up your stories in an editor that’s cleaner, crisper, and does more to get out of your way.' ); ?> </div> </div> <nav class="<API key> nav-tab-wrapper wp-clearfix" aria-label="<?php esc_attr_e( 'Secondary menu' ); ?>"> <a href="about.php" class="nav-tab"><?php _e( 'What&#8217;s New' ); ?></a> <a href="credits.php" class="nav-tab nav-tab-active" aria-current="page"><?php _e( 'Credits' ); ?></a> <a href="freedoms.php" class="nav-tab"><?php _e( 'Freedoms' ); ?></a> <a href="privacy.php" class="nav-tab"><?php _e( 'Privacy' ); ?></a> </nav> </div> <div class="about__section is-feature"> <div class="column"> <h1><?php _e( 'Credits' ); ?></h1> <?php if ( ! $credits ) : ?> <p> <?php printf( __( 'WordPress is created by a <a href="%1$s">worldwide team</a> of passionate individuals. <a href="%2$s">Get involved in WordPress</a>.' ), __( 'https://wordpress.org/about/' ), __( 'https://make.wordpress.org/' ) ); ?> </p> <?php else : ?> <p> <?php _e( 'WordPress is created by a worldwide team of passionate individuals.' ); ?> </p> <p> <?php printf( __( 'Want to see your name in lights on this page? <a href="%s">Get involved in WordPress</a>.' ), __( 'https://make.wordpress.org/' ) ); ?> </p> <?php endif; ?> </div> </div> <?php if ( ! $credits ) { echo '</div>'; require_once ABSPATH . 'wp-admin/admin-footer.php'; exit; } ?> <hr /> <div class="about__section"> <div class="column <API key>"> <?php <API key>( $credits['groups']['core-developers'] ); ?> <?php <API key>( $credits, 'core-developers' ); ?> <?php <API key>( $credits, '<API key>' ); ?> </div> </div> <hr /> <div class="about__section"> <div class="column"> <?php <API key>( $credits['groups']['props'] ); ?> <?php <API key>( $credits, 'props' ); ?> </div> </div> <hr /> <?php if ( isset( $credits['groups']['translators'] ) || isset( $credits['groups']['validators'] ) ) : ?> <div class="about__section"> <div class="column"> <?php <API key>( $credits['groups']['validators'] ); ?> <?php <API key>( $credits, 'validators' ); ?> <?php <API key>( $credits, 'translators' ); ?> </div> </div> <hr /> <?php endif; ?> <div class="about__section"> <div class="column"> <?php <API key>( $credits['groups']['libraries'] ); ?> <?php <API key>( $credits, 'libraries' ); ?> </div> </div> </div> <?php require_once ABSPATH . 'wp-admin/admin-footer.php'; return; // These are strings returned by the API that we want to be translatable. __( 'Project Leaders' ); /* translators: %s: The current WordPress version number. */ __( 'Core Contributors to WordPress %s' ); __( 'Noteworthy Contributors' ); __( 'Cofounder, Project Lead' ); __( 'Lead Developer' ); __( 'Release Lead' ); __( 'Release Design Lead' ); __( 'Release Deputy' ); __( 'Core Developer' ); __( 'External Libraries' );
#include <linux/init.h> #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/gpio-pxa.h> #include <linux/regulator/machine.h> #include <linux/regulator/max8649.h> #include <linux/regulator/fixed.h> #include <linux/mfd/max8925.h> #include <linux/usb/phy.h> #include <linux/usb/mv_usb2_phy.h> #include <linux/platform_data/mv_usb.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <mach/addr-map.h> #include <mach/mfp-mmp2.h> #include <mach/mmp2.h> #include <mach/irqs.h> #include "common.h" #define BROWNSTONE_NR_IRQS (MMP_NR_IRQS + 40) #define GPIO_5V_ENABLE (89) static unsigned long <API key>[] __initdata = { /* UART1 */ GPIO29_UART1_RXD, GPIO30_UART1_TXD, /* UART3 */ GPIO51_UART3_RXD, GPIO52_UART3_TXD, /* DFI */ GPIO168_DFI_D0, GPIO167_DFI_D1, GPIO166_DFI_D2, GPIO165_DFI_D3, GPIO107_DFI_D4, GPIO106_DFI_D5, GPIO105_DFI_D6, GPIO104_DFI_D7, GPIO111_DFI_D8, GPIO164_DFI_D9, GPIO163_DFI_D10, GPIO162_DFI_D11, GPIO161_DFI_D12, GPIO110_DFI_D13, GPIO109_DFI_D14, GPIO108_DFI_D15, GPIO143_ND_nCS0, GPIO144_ND_nCS1, GPIO147_ND_nWE, GPIO148_ND_nRE, GPIO150_ND_ALE, GPIO149_ND_CLE, GPIO112_ND_RDY0, GPIO160_ND_RDY1, /* PMIC */ PMIC_PMIC_INT | MFP_LPM_EDGE_FALL, /* MMC0 */ GPIO131_MMC1_DAT3 | MFP_PULL_HIGH, GPIO132_MMC1_DAT2 | MFP_PULL_HIGH, GPIO133_MMC1_DAT1 | MFP_PULL_HIGH, GPIO134_MMC1_DAT0 | MFP_PULL_HIGH, GPIO136_MMC1_CMD | MFP_PULL_HIGH, GPIO139_MMC1_CLK, GPIO140_MMC1_CD | MFP_PULL_LOW, GPIO141_MMC1_WP | MFP_PULL_LOW, /* MMC1 */ GPIO37_MMC2_DAT3 | MFP_PULL_HIGH, GPIO38_MMC2_DAT2 | MFP_PULL_HIGH, GPIO39_MMC2_DAT1 | MFP_PULL_HIGH, GPIO40_MMC2_DAT0 | MFP_PULL_HIGH, GPIO41_MMC2_CMD | MFP_PULL_HIGH, GPIO42_MMC2_CLK, /* MMC2 */ GPIO165_MMC3_DAT7 | MFP_PULL_HIGH, GPIO162_MMC3_DAT6 | MFP_PULL_HIGH, GPIO166_MMC3_DAT5 | MFP_PULL_HIGH, GPIO163_MMC3_DAT4 | MFP_PULL_HIGH, GPIO167_MMC3_DAT3 | MFP_PULL_HIGH, GPIO164_MMC3_DAT2 | MFP_PULL_HIGH, GPIO168_MMC3_DAT1 | MFP_PULL_HIGH, GPIO111_MMC3_DAT0 | MFP_PULL_HIGH, GPIO112_MMC3_CMD | MFP_PULL_HIGH, GPIO151_MMC3_CLK, /* 5V regulator */ GPIO89_GPIO, }; static struct <API key> mmp2_gpio_pdata = { .irq_base = MMP_GPIO_TO_IRQ(0), }; static struct <API key> max8649_supply[] = { REGULATOR_SUPPLY("vcc_core", NULL), }; static struct regulator_init_data max8649_init_data = { .constraints = { .name = "vcc_core range", .min_uV = 1150000, .max_uV = 1280000, .always_on = 1, .boot_on = 1, .valid_ops_mask = <API key>, }, .<API key> = 1, .consumer_supplies = &max8649_supply[0], }; static struct <API key> <API key> = { .mode = 2, /* VID1 = 1, VID0 = 0 */ .extclk = 0, .ramp_timing = MAX8649_RAMP_32MV, .regulator = &max8649_init_data, }; static struct <API key> <API key>[] = { REGULATOR_SUPPLY("v_5vp", NULL), }; static struct regulator_init_data <API key> = { .constraints = { .valid_ops_mask = <API key>, }, .<API key> = ARRAY_SIZE(<API key>), .consumer_supplies = <API key>, }; static struct <API key> brownstone_v_5vp = { .supply_name = "v_5vp", .microvolts = 5000000, .gpio = GPIO_5V_ENABLE, .enable_high = 1, .enabled_at_boot = 1, .init_data = &<API key>, }; static struct platform_device <API key> = { .name = "reg-fixed-voltage", .id = 1, .dev = { .platform_data = &brownstone_v_5vp, }, }; static struct <API key> <API key> = { .irq_base = MMP_NR_IRQS, }; static struct i2c_board_info <API key>[] = { [0] = { .type = "max8649", .addr = 0x60, .platform_data = &<API key>, }, [1] = { .type = "max8925", .addr = 0x3c, .irq = IRQ_MMP2_PMIC, .platform_data = &<API key>, }, }; static struct sdhci_pxa_platdata <API key> = { .clk_delay_cycles = 0x1f, }; static struct sdhci_pxa_platdata <API key> = { .clk_delay_cycles = 0x1f, .flags = <API key> | <API key>, }; static struct sram_platdata mmp2_asram_platdata = { .pool_name = "asram", .granularity = SRAM_GRANULARITY, }; static struct sram_platdata mmp2_isram_platdata = { .pool_name = "isram", .granularity = SRAM_GRANULARITY, }; #ifdef CONFIG_USB_SUPPORT #if defined(CONFIG_USB_MV_UDC) || defined(<API key>) static struct <API key> <API key> = { .vbus = NULL, .mode = MV_USB_MODE_OTG, .otg_force_a_bus_req = 1, .set_vbus = NULL, }; #endif #endif static void __init brownstone_init(void) { mfp_config(ARRAY_AND_SIZE(<API key>)); /* on-chip devices */ mmp2_add_uart(1); mmp2_add_uart(3); <API key>(&mmp2_device_gpio, &mmp2_gpio_pdata, sizeof(struct <API key>)); <API key>(&mmp2_device_gpio); mmp2_add_twsi(1, NULL, ARRAY_AND_SIZE(<API key>)); mmp2_add_sdhost(0, &<API key>); /* SD/MMC */ mmp2_add_sdhost(2, &<API key>); /* eMMC */ mmp2_add_asram(&mmp2_asram_platdata); mmp2_add_isram(&mmp2_isram_platdata); /* enable 5v regulator */ <API key>(&<API key>); #ifdef CONFIG_USB_SUPPORT pxa_register_device(&mmp2_device_u2ophy, NULL, 0); #endif #ifdef CONFIG_USB_MV_UDC /* for usb2 phy */ usb_bind_phy(mmp2_device_u2o.drv_name, MV_USB2_PHY_INDEX, mmp2_device_u2ophy.drv_name); #ifdef CONFIG_USB_MV_OTG /* for usb2 otg phy */ usb_bind_phy(mmp2_device_u2o.drv_name, <API key>, mmp2_device_u2ootg.drv_name); #endif pxa_register_device(&mmp2_device_u2o, &<API key>, sizeof(<API key>)); #endif #ifdef <API key> /* for usb2 phy */ usb_bind_phy(mmp2_device_u2oehci.dev_name, MV_USB2_PHY_INDEX, mmp2_device_u2ophy.dev_name); #ifdef CONFIG_USB_MV_OTG /* for usb2 otg phy */ usb_bind_phy(mmp2_device_u2oehci.drv_name, <API key>, mmp2_device_u2ootg.drv_name); #endif pxa_register_device(&mmp2_device_u2oehci, &<API key>, sizeof(<API key>)); #endif #ifdef CONFIG_USB_MV_OTG /* for usb2 phy */ usb_bind_phy(mmp2_device_u2ootg.dev_name, MV_USB2_PHY_INDEX, mmp2_device_u2ophy.dev_name); pxa_register_device(&mmp2_device_u2ootg, &<API key>, sizeof(<API key>)); #endif } MACHINE_START(BROWNSTONE, "Brownstone Development Platform") /* Maintainer: Haojian Zhuang <haojian.zhuang@marvell.com> */ .map_io = mmp_map_io, .nr_irqs = BROWNSTONE_NR_IRQS, .init_irq = mmp2_init_irq, .init_time = mmp2_timer_init, .init_machine = brownstone_init, .restart = mmp_restart, MACHINE_END
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Implementation of the Transmission Control Protocol(TCP). * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Mark Evans, <evansmp@uhura.aston.ac.uk> * Corey Minyard <wf-rch!minyard@relay.EU.net> * Florian La Roche, <flla@stud.uni-sb.de> * Charles Hedrick, <hedrick@klinzhai.rutgers.edu> * Linus Torvalds, <torvalds@cs.helsinki.fi> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Matthew Dillon, <dillon@apollo.west.oic.com> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Jorge Cwik, <jorge@laser.satlink.net> */ /* * Changes: * Pedro Roque : Fast Retransmit/Recovery. * Two receive queues. * Retransmit queue handled by TCP. * Better retransmit timer handling. * New congestion avoidance. * Header prediction. * Variable renaming. * * Eric : Fast Retransmit. * Randy Scott : MSS option defines. * Eric Schenk : Fixes to slow start algorithm. * Eric Schenk : Yet another double ACK bug. * Eric Schenk : Delayed ACK bug fixes. * Eric Schenk : Floyd style fast retrans war avoidance. * David S. Miller : Don't allow zero congestion window. * Eric Schenk : Fix retransmitter so that it sends * next packet on ack of previous packet. * Andi Kleen : Moved open_request checking here * and process RSTs for open_requests. * Andi Kleen : Better prune_queue, and other fixes. * Andrey Savochkin: Fix RTT measurements in the presence of * timestamps. * Andrey Savochkin: Check sequence numbers correctly when * removing SACKs due to in sequence incoming * data segments. * Andi Kleen: Make sure we never ack data there is not * enough room for. Also make this condition * a fatal error if it might still happen. * Andi Kleen: Add tcp_measure_rcv_mss to make * connections with MSS<min(MTU,ann. MSS) * work without delayed acks. * Andi Kleen: Process packets with PSH set in the * fast path. * J Hadi Salim: ECN support * Andrei Gurtov, * Pasi Sarolahti, * Panu Kuhlberg: Experimental audit of TCP (re)transmission * engine. Lots of bugs are found. * Pasi Sarolahti: F-RTO for dealing with spurious RTOs */ #define pr_fmt(fmt) "TCP: " fmt #include <linux/mm.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/sysctl.h> #include <linux/kernel.h> #include <net/dst.h> #include <net/tcp.h> #include <net/inet_common.h> #include <linux/ipsec.h> #include <asm/unaligned.h> #include <net/netdma.h> int <API key> __read_mostly = 1; int <API key> __read_mostly = 1; int sysctl_tcp_sack __read_mostly = 1; int sysctl_tcp_fack __read_mostly = 1; int <API key> __read_mostly = <API key>; EXPORT_SYMBOL(<API key>); int sysctl_tcp_dsack __read_mostly = 1; int sysctl_tcp_app_win __read_mostly = 31; int <API key> __read_mostly = 1; EXPORT_SYMBOL(<API key>); /* rfc5961 challenge ack rate limiting */ int <API key> = 100; int sysctl_tcp_stdurg __read_mostly; int sysctl_tcp_rfc1337 __read_mostly; int <API key> __read_mostly = NR_FILE; int sysctl_tcp_frto __read_mostly = 2; int <API key> __read_mostly; int <API key> __read_mostly = 1; int <API key> __read_mostly = 3; int <API key> __read_mostly = <API key>; #define FLAG_DATA 0x01 /* Incoming frame contained data. */ #define FLAG_WIN_UPDATE 0x02 /* Incoming ACK was a window update. */ #define FLAG_DATA_ACKED 0x04 /* This ACK acknowledged new data. */ #define <API key> 0x08 /* "" "" some of which was retransmitted. */ #define FLAG_SYN_ACKED 0x10 /* This ACK acknowledged SYN. */ #define FLAG_DATA_SACKED 0x20 /* New SACK. */ #define FLAG_ECE 0x40 /* ECE in this ACK */ #define FLAG_SLOWPATH 0x100 /* Do not skip RFC checks for window update.*/ #define <API key> 0x200 /* Never retransmitted data are (s)acked */ #define <API key> 0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */ #define FLAG_DSACKING_ACK 0x800 /* SACK blocks contained D-SACK info */ #define FLAG_SACK_RENEGING 0x2000 /* snd_una advanced to a sacked seq */ #define <API key> 0x4000 /* <API key>() */ #define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED) #define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED) #define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE) #define <API key> (FLAG_ACKED|FLAG_DATA_SACKED) #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH) #define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH)) /* Adapt the MSS value used to make delayed ack decision to the * real world. */ static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb) { struct <API key> *icsk = inet_csk(sk); const unsigned int lss = icsk->icsk_ack.last_seg_size; unsigned int len; icsk->icsk_ack.last_seg_size = 0; /* skb->len may jitter because of SACKs, even if peer * sends good full-sized frames. */ len = skb_shinfo(skb)->gso_size ? : skb->len; if (len >= icsk->icsk_ack.rcv_mss) { icsk->icsk_ack.rcv_mss = len; } else { /* Otherwise, we make more careful check taking into account, * that SACKs block is variable. * * "len" is invariant segment length, including TCP header. */ len += skb->data - <API key>(skb); if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) || /* If PSH is not set, packet should be * full sized, provided peer TCP is not badly broken. * This observation (if it is correct 8)) allows * to handle super-low mtu links fairly. */ (len >= TCP_MIN_MSS + sizeof(struct tcphdr) && !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) { /* Subtract also invariant (if peer is RFC compliant), * tcp header plus fixed timestamp option length. * Resulting "len" is MSS free of SACK jitter. */ len -= tcp_sk(sk)->tcp_header_len; icsk->icsk_ack.last_seg_size = len; if (len == lss) { icsk->icsk_ack.rcv_mss = len; return; } } if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED) icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2; icsk->icsk_ack.pending |= ICSK_ACK_PUSHED; } } static void tcp_incr_quickack(struct sock *sk) { struct <API key> *icsk = inet_csk(sk); unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss); if (quickacks == 0) quickacks = 2; if (quickacks > icsk->icsk_ack.quick) icsk->icsk_ack.quick = min(quickacks, TCP_MAX_QUICKACKS); } static void <API key>(struct sock *sk) { struct <API key> *icsk = inet_csk(sk); tcp_incr_quickack(sk); icsk->icsk_ack.pingpong = 0; icsk->icsk_ack.ato = TCP_ATO_MIN; } /* Send ACKs quickly, if "quick" count is not exhausted * and the session is not interactive. */ static inline bool <API key>(const struct sock *sk) { const struct <API key> *icsk = inet_csk(sk); return icsk->icsk_ack.quick && !icsk->icsk_ack.pingpong; } static inline void TCP_ECN_queue_cwr(struct tcp_sock *tp) { if (tp->ecn_flags & TCP_ECN_OK) tp->ecn_flags |= TCP_ECN_QUEUE_CWR; } static inline void TCP_ECN_accept_cwr(struct tcp_sock *tp, const struct sk_buff *skb) { if (tcp_hdr(skb)->cwr) tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR; } static inline void <API key>(struct tcp_sock *tp) { tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR; } static inline void TCP_ECN_check_ce(struct tcp_sock *tp, const struct sk_buff *skb) { if (!(tp->ecn_flags & TCP_ECN_OK)) return; switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) { case INET_ECN_NOT_ECT: /* Funny extension: if ECT is not set on a segment, * and we already seen ECT on a previous segment, * it is probably a retransmit. */ if (tp->ecn_flags & TCP_ECN_SEEN) <API key>((struct sock *)tp); break; case INET_ECN_CE: if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR)) { /* Better not delay acks, sender can have a very low cwnd */ <API key>((struct sock *)tp); tp->ecn_flags |= TCP_ECN_DEMAND_CWR; } /* fallinto */ default: tp->ecn_flags |= TCP_ECN_SEEN; } } static inline void TCP_ECN_rcv_synack(struct tcp_sock *tp, const struct tcphdr *th) { if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr)) tp->ecn_flags &= ~TCP_ECN_OK; } static inline void TCP_ECN_rcv_syn(struct tcp_sock *tp, const struct tcphdr *th) { if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr)) tp->ecn_flags &= ~TCP_ECN_OK; } static bool <API key>(const struct tcp_sock *tp, const struct tcphdr *th) { if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK)) return true; return false; } /* Buffer size and advertised window tuning. * * 1. Tuning sk->sk_sndbuf, when connection enters established state. */ static void tcp_fixup_sndbuf(struct sock *sk) { int sndmem = SKB_TRUESIZE(tcp_sk(sk)->rx_opt.mss_clamp + MAX_TCP_HEADER); sndmem *= TCP_INIT_CWND; if (sk->sk_sndbuf < sndmem) sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]); } /* 2. Tuning advertised window (window_clamp, rcv_ssthresh) * * All tcp_full_space() is split to two parts: "network" buffer, allocated * forward and advertised in receiver window (tp->rcv_wnd) and * "application buffer", required to isolate scheduling/application * latencies from network. * window_clamp is maximal advertised window. It can be less than * tcp_full_space(), in this case tcp_full_space() - window_clamp * is reserved for "application" buffer. The less window_clamp is * the smoother our behaviour from viewpoint of network, but the lower * throughput and the higher sensitivity of the connection to losses. 8) * * rcv_ssthresh is more strict window_clamp used at "slow start" * phase to predict further behaviour of this connection. * It is used for two goals: * - to enforce header prediction at sender, even when application * requires some significant "application buffer". It is check #1. * - to prevent pruning of receive queue because of misprediction * of receiver window. Check #2. * * The scheme does not work when sender sends good segments opening * window and then starts to feed us spaghetti. But it should work * in common situations. Otherwise, we have to rely on queue collapsing. */ /* Slow part of check#2. */ static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); /* Optimize this! */ int truesize = tcp_win_from_space(skb->truesize) >> 1; int window = tcp_win_from_space(sysctl_tcp_rmem[2]) >> 1; while (tp->rcv_ssthresh <= window) { if (truesize <= skb->len) return 2 * inet_csk(sk)->icsk_ack.rcv_mss; truesize >>= 1; window >>= 1; } return 0; } static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); /* Check #1 */ if (tp->rcv_ssthresh < tp->window_clamp && (int)tp->rcv_ssthresh < tcp_space(sk) && !<API key>(sk)) { int incr; /* Check #2. Increase window, if skb with such overhead * will fit to rcvbuf in future. */ if (tcp_win_from_space(skb->truesize) <= skb->len) incr = 2 * tp->advmss; else incr = __tcp_grow_window(sk, skb); if (incr) { incr = max_t(int, incr, 2 * skb->len); tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr, tp->window_clamp); inet_csk(sk)->icsk_ack.quick |= 1; } } } /* 3. Tuning rcvbuf, when connection enters established state. */ static void tcp_fixup_rcvbuf(struct sock *sk) { u32 mss = tcp_sk(sk)->advmss; u32 icwnd = <API key>; int rcvmem; /* Limit to 10 segments if mss <= 1460, * or 14600/mss segments, with a minimum of two segments. */ if (mss > 1460) icwnd = max_t(u32, (1460 * icwnd) / mss, 2); rcvmem = SKB_TRUESIZE(mss + MAX_TCP_HEADER); while (tcp_win_from_space(rcvmem) < mss) rcvmem += 128; rcvmem *= icwnd; if (sk->sk_rcvbuf < rcvmem) sk->sk_rcvbuf = min(rcvmem, sysctl_tcp_rmem[2]); } /* 4. Try to fixup all. It is made immediately after connection enters * established state. */ void <API key>(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); int maxwin; if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) tcp_fixup_rcvbuf(sk); if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK)) tcp_fixup_sndbuf(sk); tp->rcvq_space.space = tp->rcv_wnd; maxwin = tcp_full_space(sk); if (tp->window_clamp >= maxwin) { tp->window_clamp = maxwin; if (sysctl_tcp_app_win && maxwin > 4 * tp->advmss) tp->window_clamp = max(maxwin - (maxwin >> sysctl_tcp_app_win), 4 * tp->advmss); } /* Force reservation of one segment. */ if (sysctl_tcp_app_win && tp->window_clamp > 2 * tp->advmss && tp->window_clamp + tp->advmss > maxwin) tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss); tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp); tp->snd_cwnd_stamp = tcp_time_stamp; } /* 5. Recalculate window clamp after socket hit its memory bounds. */ static void tcp_clamp_window(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct <API key> *icsk = inet_csk(sk); icsk->icsk_ack.quick = 0; if (sk->sk_rcvbuf < sysctl_tcp_rmem[2] && !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) && !<API key>(sk) && sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) { sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc), sysctl_tcp_rmem[2]); } if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf) tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss); } /* Initialize RCV_MSS value. * RCV_MSS is an our guess about MSS used by the peer. * We haven't any direct information about the MSS. * It's better to underestimate the RCV_MSS rather than overestimate. * Overestimations make us ACKing less frequently than needed. * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss(). */ void <API key>(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache); hint = min(hint, tp->rcv_wnd / 2); hint = min(hint, TCP_MSS_DEFAULT); hint = max(hint, TCP_MIN_MSS); inet_csk(sk)->icsk_ack.rcv_mss = hint; } EXPORT_SYMBOL(<API key>); static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep) { u32 new_sample = tp->rcv_rtt_est.rtt; long m = sample; if (m == 0) m = 1; if (new_sample != 0) { /* If we sample in larger samples in the non-timestamp * case, we could grossly overestimate the RTT especially * with chatty applications or bulk transfer apps which * are stalled on filesystem I/O. * * Also, since we are only going for a minimum in the * non-timestamp case, we do not smooth things out * else with timestamps disabled convergence takes too * long. */ if (!win_dep) { m -= (new_sample >> 3); new_sample += m; } else { m <<= 3; if (m < new_sample) new_sample = m; } } else { /* No previous measure. */ new_sample = m << 3; } if (tp->rcv_rtt_est.rtt != new_sample) tp->rcv_rtt_est.rtt = new_sample; } static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp) { if (tp->rcv_rtt_est.time == 0) goto new_measure; if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq)) return; tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rcv_rtt_est.time, 1); new_measure: tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd; tp->rcv_rtt_est.time = tcp_time_stamp; } static inline void <API key>(struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); if (tp->rx_opt.rcv_tsecr && (TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss)) tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rx_opt.rcv_tsecr, 0); } /* * This function should be called every time data is copied to user space. * It calculates the appropriate TCP receive buffer space. */ void <API key>(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); int time; int space; if (tp->rcvq_space.time == 0) goto new_measure; time = tcp_time_stamp - tp->rcvq_space.time; if (time < (tp->rcv_rtt_est.rtt >> 3) || tp->rcv_rtt_est.rtt == 0) return; space = 2 * (tp->copied_seq - tp->rcvq_space.seq); space = max(tp->rcvq_space.space, space); if (tp->rcvq_space.space != space) { int rcvmem; tp->rcvq_space.space = space; if (<API key> && !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) { int new_clamp = space; /* Receive space grows, normalize in order to * take into account packet headers and sk_buff * structure overhead. */ space /= tp->advmss; if (!space) space = 1; rcvmem = SKB_TRUESIZE(tp->advmss + MAX_TCP_HEADER); while (tcp_win_from_space(rcvmem) < tp->advmss) rcvmem += 128; space *= rcvmem; space = min(space, sysctl_tcp_rmem[2]); if (space > sk->sk_rcvbuf) { sk->sk_rcvbuf = space; /* Make the window clamp follow along. */ tp->window_clamp = new_clamp; } } } new_measure: tp->rcvq_space.seq = tp->copied_seq; tp->rcvq_space.time = tcp_time_stamp; } /* There is something which you must keep in mind when you analyze the * behavior of the tp->ato delayed ack timeout interval. When a * connection starts up, we want to ack as quickly as possible. The * problem is that "good" TCP's do slow start at the beginning of data * transmission. The means that until we send the first few ACK's the * sender will sit on his end and only queue most of his data, because * he can only send snd_cwnd unacked packets at any given time. For * each ACK we send, he increments snd_cwnd and transmits more of his * queue. -DaveM */ static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct <API key> *icsk = inet_csk(sk); u32 now; <API key>(sk); tcp_measure_rcv_mss(sk, skb); tcp_rcv_rtt_measure(tp); now = tcp_time_stamp; if (!icsk->icsk_ack.ato) { /* The _first_ data packet received, initialize * delayed ACK engine. */ tcp_incr_quickack(sk); icsk->icsk_ack.ato = TCP_ATO_MIN; } else { int m = now - icsk->icsk_ack.lrcvtime; if (m <= TCP_ATO_MIN / 2) { /* The fastest case is the first. */ icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2; } else if (m < icsk->icsk_ack.ato) { icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m; if (icsk->icsk_ack.ato > icsk->icsk_rto) icsk->icsk_ack.ato = icsk->icsk_rto; } else if (m > icsk->icsk_rto) { /* Too long gap. Apparently sender failed to * restart window, so that we send ACKs quickly. */ tcp_incr_quickack(sk); sk_mem_reclaim(sk); } } icsk->icsk_ack.lrcvtime = now; TCP_ECN_check_ce(tp, skb); if (skb->len >= 128) tcp_grow_window(sk, skb); } /* Called to compute a smoothed rtt estimate. The data fed to this * routine either comes from timestamps, or from segments that were * known _not_ to have been retransmitted [see Karn/Partridge * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88 * piece by Van Jacobson. * NOTE: the next three routines used to be one big routine. * To save cycles in the RFC 1323 implementation it was better to break * it up into three procedures. -- erics */ static void tcp_rtt_estimator(struct sock *sk, const __u32 mrtt) { struct tcp_sock *tp = tcp_sk(sk); long m = mrtt; /* RTT */ /* The following amusing code comes from Jacobson's * article in SIGCOMM '88. Note that rtt and mdev * are scaled versions of rtt and mean deviation. * This is designed to be as fast as possible * m stands for "measurement". * * On a 1990 paper the rto value is changed to: * RTO = rtt + 4 * mdev * * Funny. This algorithm seems to be very broken. * These formulae increase RTO, when it should be decreased, increase * too slowly, when it should be increased quickly, decrease too quickly * etc. I guess in BSD RTO takes ONE value, so that it is absolutely * does not matter how to _calculate_ it. Seems, it was trap * that VJ failed to avoid. 8) */ if (m == 0) m = 1; if (tp->srtt != 0) { m -= (tp->srtt >> 3); /* m is now error in rtt est */ tp->srtt += m; /* rtt = 7/8 rtt + 1/8 new */ if (m < 0) { m = -m; /* m is now abs(error) */ m -= (tp->mdev >> 2); /* similar update on mdev */ /* This is similar to one of Eifel findings. * Eifel blocks mdev updates when rtt decreases. * This solution is a bit different: we use finer gain * for mdev in this case (alpha*beta). * Like Eifel it also prevents growth of rto, * but also it limits too fast rto decreases, * happening in pure Eifel. */ if (m > 0) m >>= 3; } else { m -= (tp->mdev >> 2); /* similar update on mdev */ } tp->mdev += m; /* mdev = 3/4 mdev + 1/4 new */ if (tp->mdev > tp->mdev_max) { tp->mdev_max = tp->mdev; if (tp->mdev_max > tp->rttvar) tp->rttvar = tp->mdev_max; } if (after(tp->snd_una, tp->rtt_seq)) { if (tp->mdev_max < tp->rttvar) tp->rttvar -= (tp->rttvar - tp->mdev_max) >> 2; tp->rtt_seq = tp->snd_nxt; tp->mdev_max = tcp_rto_min(sk); } } else { /* no previous measure. */ tp->srtt = m << 3; /* take the measured time to be rtt */ tp->mdev = m << 1; /* make sure rto = 3*rtt */ tp->mdev_max = tp->rttvar = max(tp->mdev, tcp_rto_min(sk)); tp->rtt_seq = tp->snd_nxt; } } /* Set the sk_pacing_rate to allow proper sizing of TSO packets. * Note: TCP stack does not yet implement pacing. * FQ packet scheduler can be used to implement cheap but effective * TCP pacing, to smooth the burst on large writes when packets * in flight is significantly lower than cwnd (or rwin) */ static void <API key>(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); u64 rate; /* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */ rate = (u64)tp->mss_cache * 2 * (HZ << 3); rate *= max(tp->snd_cwnd, tp->packets_out); /* Correction for small srtt : minimum srtt being 8 (1 jiffy << 3), * be conservative and assume srtt = 1 (125 us instead of 1.25 ms) * We probably need usec resolution in the future. * Note: This also takes care of possible srtt=0 case, * when tcp_rtt_estimator() was not yet called. */ if (tp->srtt > 8 + 2) do_div(rate, tp->srtt); sk->sk_pacing_rate = min_t(u64, rate, ~0U); } /* Calculate rto without backoff. This is the second half of Van Jacobson's * routine referred to above. */ void tcp_set_rto(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); /* Old crap is replaced with new one. 8) * * More seriously: * 1. If rtt variance happened to be less 50msec, it is hallucination. * It cannot be less due to utterly erratic ACK generation made * at least by solaris and freebsd. "Erratic ACKs" has _nothing_ * to do with delayed acks, because at cwnd>2 true delack timeout * is invisible. Actually, Linux-2.4 also generates erratic * ACKs in some circumstances. */ inet_csk(sk)->icsk_rto = __tcp_set_rto(tp); /* 2. Fixups made earlier cannot be right. * If we do not estimate RTO correctly without them, * all the algo is pure shit and should be replaced * with correct one. It is exactly, which we pretend to do. */ /* NOTE: clamping at TCP_RTO_MIN is not required, current algo * guarantees that rto is higher. */ tcp_bound_rto(sk); } __u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst) { __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0); if (!cwnd) cwnd = TCP_INIT_CWND; return min_t(__u32, cwnd, tp->snd_cwnd_clamp); } /* * Packet counting of FACK is based on in-order assumptions, therefore TCP * disables it when reordering is detected */ void tcp_disable_fack(struct tcp_sock *tp) { /* RFC3517 uses different metric in lost marker => reset on change */ if (tcp_is_fack(tp)) tp->lost_skb_hint = NULL; tp->rx_opt.sack_ok &= ~TCP_FACK_ENABLED; } /* Take a notice that peer is sending D-SACKs */ static void tcp_dsack_seen(struct tcp_sock *tp) { tp->rx_opt.sack_ok |= TCP_DSACK_SEEN; } static void <API key>(struct sock *sk, const int metric, const int ts) { struct tcp_sock *tp = tcp_sk(sk); if (metric > tp->reordering) { int mib_idx; tp->reordering = min(TCP_MAX_REORDERING, metric); /* This exciting event is worth to be remembered. 8) */ if (ts) mib_idx = <API key>; else if (tcp_is_reno(tp)) mib_idx = <API key>; else if (tcp_is_fack(tp)) mib_idx = <API key>; else mib_idx = <API key>; NET_INC_STATS_BH(sock_net(sk), mib_idx); #if FASTRETRANS_DEBUG > 1 pr_debug("Disorder%d %d %u f%u s%u rr%d\n", tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state, tp->reordering, tp->fackets_out, tp->sacked_out, tp->undo_marker ? tp->undo_retrans : 0); #endif tcp_disable_fack(tp); } if (metric > 0) <API key>(tp); } /* This must be called before lost_out is incremented */ static void <API key>(struct tcp_sock *tp, struct sk_buff *skb) { if ((tp->retransmit_skb_hint == NULL) || before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(tp->retransmit_skb_hint)->seq)) tp->retransmit_skb_hint = skb; if (!tp->lost_out || after(TCP_SKB_CB(skb)->end_seq, tp->retransmit_high)) tp->retransmit_high = TCP_SKB_CB(skb)->end_seq; } static void tcp_skb_mark_lost(struct tcp_sock *tp, struct sk_buff *skb) { if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) { <API key>(tp, skb); tp->lost_out += tcp_skb_pcount(skb); TCP_SKB_CB(skb)->sacked |= TCPCB_LOST; } } static void <API key>(struct tcp_sock *tp, struct sk_buff *skb) { <API key>(tp, skb); if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) { tp->lost_out += tcp_skb_pcount(skb); TCP_SKB_CB(skb)->sacked |= TCPCB_LOST; } } static bool <API key>(struct tcp_sock *tp, bool is_dsack, u32 start_seq, u32 end_seq) { /* Too far in future, or reversed (interpretation is ambiguous) */ if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq)) return false; /* Nasty start_seq wrap-around check (see comments above) */ if (!before(start_seq, tp->snd_nxt)) return false; /* In outstanding window? ...This is valid exit for D-SACKs too. * start_seq == snd_una is non-sensical (see comments above) */ if (after(start_seq, tp->snd_una)) return true; if (!is_dsack || !tp->undo_marker) return false; /* ...Then it's D-SACK, and must reside below snd_una completely */ if (after(end_seq, tp->snd_una)) return false; if (!before(start_seq, tp->undo_marker)) return true; /* Too old */ if (!after(end_seq, tp->undo_marker)) return false; /* Undo_marker boundary crossing (overestimates a lot). Known already: * start_seq < undo_marker and end_seq >= undo_marker. */ return !before(start_seq, end_seq - tp->max_window); } /* Check for lost retransmit. This superb idea is borrowed from "ratehalving". * Event "B". Later note: FACK people cheated me again 8), we have to account * for reordering! Ugly, but should help. * * Search retransmitted skbs from write_queue that were sent when snd_nxt was * less than what is now known to be received by the other end (derived from * highest SACK block). Also calculate the lowest snd_nxt among the remaining * retransmitted skbs to avoid some costly processing per ACKs. */ static void <API key>(struct sock *sk) { const struct <API key> *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; int cnt = 0; u32 new_low_seq = tp->snd_nxt; u32 received_upto = <API key>(tp); if (!tcp_is_fack(tp) || !tp->retrans_out || !after(received_upto, tp->lost_retrans_low) || icsk->icsk_ca_state != TCP_CA_Recovery) return; tcp_for_write_queue(skb, sk) { u32 ack_seq = TCP_SKB_CB(skb)->ack_seq; if (skb == tcp_send_head(sk)) break; if (cnt == tp->retrans_out) break; if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) continue; if (!(TCP_SKB_CB(skb)->sacked & <API key>)) continue; /* TODO: We would like to get rid of tcp_is_fack(tp) only * constraint here (see above) but figuring out that at * least tp->reordering SACK blocks reside between ack_seq * and received_upto is not easy task to do cheaply with * the available datastructures. * * Whether FACK should check here for tp->reordering segs * in-between one could argue for either way (it would be * rather simple to implement as we could count fack_count * during the walk and do tp->fackets_out - fack_count). */ if (after(received_upto, ack_seq)) { TCP_SKB_CB(skb)->sacked &= ~<API key>; tp->retrans_out -= tcp_skb_pcount(skb); <API key>(tp, skb); NET_INC_STATS_BH(sock_net(sk), <API key>); } else { if (before(ack_seq, new_low_seq)) new_low_seq = ack_seq; cnt += tcp_skb_pcount(skb); } } if (tp->retrans_out) tp->lost_retrans_low = new_low_seq; } static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb, struct tcp_sack_block_wire *sp, int num_sacks, u32 prior_snd_una) { struct tcp_sock *tp = tcp_sk(sk); u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq); u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq); bool dup_sack = false; if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) { dup_sack = true; tcp_dsack_seen(tp); NET_INC_STATS_BH(sock_net(sk), <API key>); } else if (num_sacks > 1) { u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq); u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq); if (!after(end_seq_0, end_seq_1) && !before(start_seq_0, start_seq_1)) { dup_sack = true; tcp_dsack_seen(tp); NET_INC_STATS_BH(sock_net(sk), <API key>); } } /* D-SACK for already forgotten data... Do dumb counting. */ if (dup_sack && tp->undo_marker && tp->undo_retrans && !after(end_seq_0, prior_snd_una) && after(end_seq_0, tp->undo_marker)) tp->undo_retrans return dup_sack; } struct tcp_sacktag_state { int reord; int fack_count; int flag; }; /* Check if skb is fully within the SACK block. In presence of GSO skbs, * the incoming SACK may not exactly match but we can find smaller MSS * aligned portion of it that matches. Therefore we might need to fragment * which may fail and creates some hassle (caller must handle error case * returns). * * FIXME: this could be merged to shift decision code */ static int <API key>(struct sock *sk, struct sk_buff *skb, u32 start_seq, u32 end_seq) { int err; bool in_sack; unsigned int pkt_len; unsigned int mss; in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) && !before(end_seq, TCP_SKB_CB(skb)->end_seq); if (tcp_skb_pcount(skb) > 1 && !in_sack && after(TCP_SKB_CB(skb)->end_seq, start_seq)) { mss = tcp_skb_mss(skb); in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq); if (!in_sack) { pkt_len = start_seq - TCP_SKB_CB(skb)->seq; if (pkt_len < mss) pkt_len = mss; } else { pkt_len = end_seq - TCP_SKB_CB(skb)->seq; if (pkt_len < mss) return -EINVAL; } /* Round if necessary so that SACKs cover only full MSSes * and/or the remaining small portion (if present) */ if (pkt_len > mss) { unsigned int new_len = (pkt_len / mss) * mss; if (!in_sack && new_len < pkt_len) { new_len += mss; if (new_len > skb->len) return 0; } pkt_len = new_len; } err = tcp_fragment(sk, skb, pkt_len, mss); if (err < 0) return err; } return in_sack; } /* Mark the given newly-SACKed range as such, adjusting counters and hints. */ static u8 tcp_sacktag_one(struct sock *sk, struct tcp_sacktag_state *state, u8 sacked, u32 start_seq, u32 end_seq, bool dup_sack, int pcount) { struct tcp_sock *tp = tcp_sk(sk); int fack_count = state->fack_count; /* Account D-SACK for retransmitted packet. */ if (dup_sack && (sacked & TCPCB_RETRANS)) { if (tp->undo_marker && tp->undo_retrans && after(end_seq, tp->undo_marker)) tp->undo_retrans if (sacked & TCPCB_SACKED_ACKED) state->reord = min(fack_count, state->reord); } /* Nothing to do; acked frame is about to be dropped (was ACKed). */ if (!after(end_seq, tp->snd_una)) return sacked; if (!(sacked & TCPCB_SACKED_ACKED)) { if (sacked & <API key>) { /* If the segment is not tagged as lost, * we do not clear RETRANS, believing * that retransmission is still in flight. */ if (sacked & TCPCB_LOST) { sacked &= ~(TCPCB_LOST|<API key>); tp->lost_out -= pcount; tp->retrans_out -= pcount; } } else { if (!(sacked & TCPCB_RETRANS)) { /* New sack for not retransmitted frame, * which was in hole. It is reordering. */ if (before(start_seq, <API key>(tp))) state->reord = min(fack_count, state->reord); if (!after(end_seq, tp->high_seq)) state->flag |= <API key>; } if (sacked & TCPCB_LOST) { sacked &= ~TCPCB_LOST; tp->lost_out -= pcount; } } sacked |= TCPCB_SACKED_ACKED; state->flag |= FLAG_DATA_SACKED; tp->sacked_out += pcount; fack_count += pcount; /* Lost marker hint past SACKed? Tweak RFC3517 cnt */ if (!tcp_is_fack(tp) && (tp->lost_skb_hint != NULL) && before(start_seq, TCP_SKB_CB(tp->lost_skb_hint)->seq)) tp->lost_cnt_hint += pcount; if (fack_count > tp->fackets_out) tp->fackets_out = fack_count; } /* D-SACK. We can detect redundant retransmission in S|R and plain R * frames and clear it. undo_retrans is decreased above, L|R frames * are accounted above as well. */ if (dup_sack && (sacked & <API key>)) { sacked &= ~<API key>; tp->retrans_out -= pcount; } return sacked; } /* Shift newly-SACKed bytes from this skb to the immediately previous * already-SACKed sk_buff. Mark the newly-SACKed bytes as such. */ static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *skb, struct tcp_sacktag_state *state, unsigned int pcount, int shifted, int mss, bool dup_sack) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *prev = <API key>(sk, skb); u32 start_seq = TCP_SKB_CB(skb)->seq; /* start of newly-SACKed */ u32 end_seq = start_seq + shifted; /* end of newly-SACKed */ BUG_ON(!pcount); /* Adjust counters and hints for the newly sacked sequence * range but discard the return value since prev is already * marked. We must tag the range first because the seq * advancement below implicitly advances * <API key>() when skb is highest_sack. */ tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked, start_seq, end_seq, dup_sack, pcount); if (skb == tp->lost_skb_hint) tp->lost_cnt_hint += pcount; TCP_SKB_CB(prev)->end_seq += shifted; TCP_SKB_CB(skb)->seq += shifted; skb_shinfo(prev)->gso_segs += pcount; BUG_ON(skb_shinfo(skb)->gso_segs < pcount); skb_shinfo(skb)->gso_segs -= pcount; /* When we're adding to gso_segs == 1, gso_size will be zero, * in theory this shouldn't be necessary but as long as DSACK * code can come after this skb later on it's better to keep * setting gso_size to something. */ if (!skb_shinfo(prev)->gso_size) { skb_shinfo(prev)->gso_size = mss; skb_shinfo(prev)->gso_type = sk->sk_gso_type; } /* CHECKME: To clear or not to clear? Mimics normal skb currently */ if (skb_shinfo(skb)->gso_segs <= 1) { skb_shinfo(skb)->gso_size = 0; skb_shinfo(skb)->gso_type = 0; } /* Difference in this won't matter, both ACKed by the same cumul. ACK */ TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS); if (skb->len > 0) { BUG_ON(!tcp_skb_pcount(skb)); NET_INC_STATS_BH(sock_net(sk), <API key>); return false; } /* Whole SKB was eaten :-) */ if (skb == tp->retransmit_skb_hint) tp->retransmit_skb_hint = prev; if (skb == tp->scoreboard_skb_hint) tp->scoreboard_skb_hint = prev; if (skb == tp->lost_skb_hint) { tp->lost_skb_hint = prev; tp->lost_cnt_hint -= tcp_skb_pcount(prev); } TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags; if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) TCP_SKB_CB(prev)->end_seq++; if (skb == tcp_highest_sack(sk)) <API key>(sk, skb); <API key>(skb, sk); sk_wmem_free_skb(sk, skb); NET_INC_STATS_BH(sock_net(sk), <API key>); return true; } /* I wish gso_size would have a bit more sane initialization than * something-or-zero which complicates things */ static int tcp_skb_seglen(const struct sk_buff *skb) { return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb); } /* Shifting pages past head area doesn't work */ static int skb_can_shift(const struct sk_buff *skb) { return !skb_headlen(skb) && skb_is_nonlinear(skb); } /* Try collapsing SACK blocks spanning across multiple skbs to a single * skb. */ static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb, struct tcp_sacktag_state *state, u32 start_seq, u32 end_seq, bool dup_sack) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *prev; int mss; int pcount = 0; int len; int in_sack; if (!sk_can_gso(sk)) goto fallback; /* Normally R but no L won't result in plain S */ if (!dup_sack && (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|<API key>)) == <API key>) goto fallback; if (!skb_can_shift(skb)) goto fallback; /* This frame is about to be dropped (was ACKed). */ if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) goto fallback; /* Can only happen with delayed DSACK + discard craziness */ if (unlikely(skb == <API key>(sk))) goto fallback; prev = <API key>(sk, skb); if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) goto fallback; in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) && !before(end_seq, TCP_SKB_CB(skb)->end_seq); if (in_sack) { len = skb->len; pcount = tcp_skb_pcount(skb); mss = tcp_skb_seglen(skb); /* TODO: Fix DSACKs to not fragment already SACKed and we can * drop this restriction as unnecessary */ if (mss != tcp_skb_seglen(prev)) goto fallback; } else { if (!after(TCP_SKB_CB(skb)->end_seq, start_seq)) goto noop; /* CHECKME: This is non-MSS split case only?, this will * cause skipped skbs due to advancing loop btw, original * has that feature too */ if (tcp_skb_pcount(skb) <= 1) goto noop; in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq); if (!in_sack) { /* TODO: head merge to next could be attempted here * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)), * though it might not be worth of the additional hassle * * ...we can probably just fallback to what was done * previously. We could try merging non-SACKed ones * as well but it probably isn't going to buy off * because later SACKs might again split them, and * it would make skb timestamp tracking considerably * harder problem. */ goto fallback; } len = end_seq - TCP_SKB_CB(skb)->seq; BUG_ON(len < 0); BUG_ON(len > skb->len); /* MSS boundaries should be honoured or else pcount will * severely break even though it makes things bit trickier. * Optimize common case to avoid most of the divides */ mss = tcp_skb_mss(skb); /* TODO: Fix DSACKs to not fragment already SACKed and we can * drop this restriction as unnecessary */ if (mss != tcp_skb_seglen(prev)) goto fallback; if (len == mss) { pcount = 1; } else if (len < mss) { goto noop; } else { pcount = len / mss; len = pcount * mss; } } /* tcp_sacktag_one() won't SACK-tag ranges below snd_una */ if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una)) goto fallback; if (!skb_shift(prev, skb, len)) goto fallback; if (!tcp_shifted_skb(sk, skb, state, pcount, len, mss, dup_sack)) goto out; /* Hole filled allows collapsing with the next as well, this is very * useful when hole on every nth skb pattern happens */ if (prev == <API key>(sk)) goto out; skb = <API key>(sk, prev); if (!skb_can_shift(skb) || (skb == tcp_send_head(sk)) || ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) || (mss != tcp_skb_seglen(skb))) goto out; len = skb->len; if (skb_shift(prev, skb, len)) { pcount += tcp_skb_pcount(skb); tcp_shifted_skb(sk, skb, state, tcp_skb_pcount(skb), len, mss, 0); } out: state->fack_count += pcount; return prev; noop: return skb; fallback: NET_INC_STATS_BH(sock_net(sk), <API key>); return NULL; } static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk, struct tcp_sack_block *next_dup, struct tcp_sacktag_state *state, u32 start_seq, u32 end_seq, bool dup_sack_in) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *tmp; <API key>(skb, sk) { int in_sack = 0; bool dup_sack = dup_sack_in; if (skb == tcp_send_head(sk)) break; /* queue is in-order => we can short-circuit the walk early */ if (!before(TCP_SKB_CB(skb)->seq, end_seq)) break; if ((next_dup != NULL) && before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) { in_sack = <API key>(sk, skb, next_dup->start_seq, next_dup->end_seq); if (in_sack > 0) dup_sack = true; } /* skb reference here is a bit tricky to get right, since * shifting can eat and free both this skb and the next, * so not even _safe variant of the loop is enough. */ if (in_sack <= 0) { tmp = tcp_shift_skb_data(sk, skb, state, start_seq, end_seq, dup_sack); if (tmp != NULL) { if (tmp != skb) { skb = tmp; continue; } in_sack = 0; } else { in_sack = <API key>(sk, skb, start_seq, end_seq); } } if (unlikely(in_sack < 0)) break; if (in_sack) { TCP_SKB_CB(skb)->sacked = tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq, dup_sack, tcp_skb_pcount(skb)); if (!before(TCP_SKB_CB(skb)->seq, <API key>(tp))) <API key>(sk, skb); } state->fack_count += tcp_skb_pcount(skb); } return skb; } /* Avoid all extra work that is being done by sacktag while walking in * a normal way */ static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk, struct tcp_sacktag_state *state, u32 skip_to_seq) { <API key>(skb, sk) { if (skb == tcp_send_head(sk)) break; if (after(TCP_SKB_CB(skb)->end_seq, skip_to_seq)) break; state->fack_count += tcp_skb_pcount(skb); } return skb; } static struct sk_buff *<API key>(struct sk_buff *skb, struct sock *sk, struct tcp_sack_block *next_dup, struct tcp_sacktag_state *state, u32 skip_to_seq) { if (next_dup == NULL) return skb; if (before(next_dup->start_seq, skip_to_seq)) { skb = tcp_sacktag_skip(skb, sk, state, next_dup->start_seq); skb = tcp_sacktag_walk(skb, sk, NULL, state, next_dup->start_seq, next_dup->end_seq, 1); } return skb; } static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache) { return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache); } static int <API key>(struct sock *sk, const struct sk_buff *ack_skb, u32 prior_snd_una) { struct tcp_sock *tp = tcp_sk(sk); const unsigned char *ptr = (<API key>(ack_skb) + TCP_SKB_CB(ack_skb)->sacked); struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2); struct tcp_sack_block sp[TCP_NUM_SACKS]; struct tcp_sack_block *cache; struct tcp_sacktag_state state; struct sk_buff *skb; int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3); int used_sacks; bool found_dup_sack = false; int i, j; int first_sack_index; state.flag = 0; state.reord = tp->packets_out; if (!tp->sacked_out) { if (WARN_ON(tp->fackets_out)) tp->fackets_out = 0; <API key>(sk); } found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire, num_sacks, prior_snd_una); if (found_dup_sack) state.flag |= FLAG_DSACKING_ACK; /* Eliminate too old ACKs, but take into * account more or less fresh ones, they can * contain valid SACK info. */ if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window)) return 0; if (!tp->packets_out) goto out; used_sacks = 0; first_sack_index = 0; for (i = 0; i < num_sacks; i++) { bool dup_sack = !i && found_dup_sack; sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq); sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq); if (!<API key>(tp, dup_sack, sp[used_sacks].start_seq, sp[used_sacks].end_seq)) { int mib_idx; if (dup_sack) { if (!tp->undo_marker) mib_idx = <API key>; else mib_idx = <API key>; } else { /* Don't count olds caused by ACK reordering */ if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) && !after(sp[used_sacks].end_seq, tp->snd_una)) continue; mib_idx = <API key>; } NET_INC_STATS_BH(sock_net(sk), mib_idx); if (i == 0) first_sack_index = -1; continue; } /* Ignore very old stuff early */ if (!after(sp[used_sacks].end_seq, prior_snd_una)) continue; used_sacks++; } /* order SACK blocks to allow in order walk of the retrans queue */ for (i = used_sacks - 1; i > 0; i for (j = 0; j < i; j++) { if (after(sp[j].start_seq, sp[j + 1].start_seq)) { swap(sp[j], sp[j + 1]); /* Track where the first SACK block goes to */ if (j == first_sack_index) first_sack_index = j + 1; } } } skb = <API key>(sk); state.fack_count = 0; i = 0; if (!tp->sacked_out) { /* It's already past, so skip checking against it */ cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache); } else { cache = tp->recv_sack_cache; /* Skip empty blocks in at head of the cache */ while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq && !cache->end_seq) cache++; } while (i < used_sacks) { u32 start_seq = sp[i].start_seq; u32 end_seq = sp[i].end_seq; bool dup_sack = (found_dup_sack && (i == first_sack_index)); struct tcp_sack_block *next_dup = NULL; if (found_dup_sack && ((i + 1) == first_sack_index)) next_dup = &sp[i + 1]; /* Skip too early cached blocks */ while (tcp_sack_cache_ok(tp, cache) && !before(start_seq, cache->end_seq)) cache++; /* Can skip some work by looking recv_sack_cache? */ if (tcp_sack_cache_ok(tp, cache) && !dup_sack && after(end_seq, cache->start_seq)) { /* Head todo? */ if (before(start_seq, cache->start_seq)) { skb = tcp_sacktag_skip(skb, sk, &state, start_seq); skb = tcp_sacktag_walk(skb, sk, next_dup, &state, start_seq, cache->start_seq, dup_sack); } /* Rest of the block already fully processed? */ if (!after(end_seq, cache->end_seq)) goto advance_sp; skb = <API key>(skb, sk, next_dup, &state, cache->end_seq); /* ...tail remains todo... */ if (<API key>(tp) == cache->end_seq) { /* ...but better entrypoint exists! */ skb = tcp_highest_sack(sk); if (skb == NULL) break; state.fack_count = tp->fackets_out; cache++; goto walk; } skb = tcp_sacktag_skip(skb, sk, &state, cache->end_seq); /* Check overlap against next cached too (past this one already) */ cache++; continue; } if (!before(start_seq, <API key>(tp))) { skb = tcp_highest_sack(sk); if (skb == NULL) break; state.fack_count = tp->fackets_out; } skb = tcp_sacktag_skip(skb, sk, &state, start_seq); walk: skb = tcp_sacktag_walk(skb, sk, next_dup, &state, start_seq, end_seq, dup_sack); advance_sp: i++; } /* Clear the head of the cache sack blocks so we can skip it next time */ for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) { tp->recv_sack_cache[i].start_seq = 0; tp->recv_sack_cache[i].end_seq = 0; } for (j = 0; j < used_sacks; j++) tp->recv_sack_cache[i++] = sp[j]; <API key>(sk); tcp_verify_left_out(tp); if ((state.reord < tp->fackets_out) && ((inet_csk(sk)->icsk_ca_state != TCP_CA_Loss) || tp->undo_marker)) <API key>(sk, tp->fackets_out - state.reord, 0); out: #if FASTRETRANS_DEBUG > 0 WARN_ON((int)tp->sacked_out < 0); WARN_ON((int)tp->lost_out < 0); WARN_ON((int)tp->retrans_out < 0); WARN_ON((int)<API key>(tp) < 0); #endif return state.flag; } /* Limits sacked_out so that sum with lost_out isn't ever larger than * packets_out. Returns false if sacked_out adjustement wasn't necessary. */ static bool <API key>(struct tcp_sock *tp) { u32 holes; holes = max(tp->lost_out, 1U); holes = min(holes, tp->packets_out); if ((tp->sacked_out + holes) > tp->packets_out) { tp->sacked_out = tp->packets_out - holes; return true; } return false; } /* If we receive more dupacks than we expected counting segments * in assumption of absent reordering, interpret this as reordering. * The only another reason could be bug in receiver TCP. */ static void <API key>(struct sock *sk, const int addend) { struct tcp_sock *tp = tcp_sk(sk); if (<API key>(tp)) <API key>(sk, tp->packets_out + addend, 0); } /* Emulate SACKs for SACKless connection: account for a new dupack. */ static void tcp_add_reno_sack(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); tp->sacked_out++; <API key>(sk, 0); tcp_verify_left_out(tp); } /* Account for ACK, ACKing some data in Reno Recovery phase. */ static void <API key>(struct sock *sk, int acked) { struct tcp_sock *tp = tcp_sk(sk); if (acked > 0) { /* One ACK acked hole. The rest eat duplicate ACKs. */ if (acked - 1 >= tp->sacked_out) tp->sacked_out = 0; else tp->sacked_out -= acked - 1; } <API key>(sk, acked); tcp_verify_left_out(tp); } static inline void tcp_reset_reno_sack(struct tcp_sock *tp) { tp->sacked_out = 0; } static void <API key>(struct tcp_sock *tp) { tp->retrans_out = 0; tp->lost_out = 0; tp->undo_marker = 0; tp->undo_retrans = 0; } void tcp_clear_retrans(struct tcp_sock *tp) { <API key>(tp); tp->fackets_out = 0; tp->sacked_out = 0; } /* Enter Loss state. If "how" is not zero, forget all SACK information * and reset tags completely, otherwise preserve SACKs. If receiver * dropped its ofo queue, we will know this due to reneging detection. */ void tcp_enter_loss(struct sock *sk, int how) { const struct <API key> *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; bool new_recovery = false; /* Reduce ssthresh if it has not yet been made inside this window. */ if (icsk->icsk_ca_state <= TCP_CA_Disorder || !after(tp->high_seq, tp->snd_una) || (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) { new_recovery = true; tp->prior_ssthresh = <API key>(sk); tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk); tcp_ca_event(sk, CA_EVENT_LOSS); } tp->snd_cwnd = 1; tp->snd_cwnd_cnt = 0; tp->snd_cwnd_stamp = tcp_time_stamp; <API key>(tp); if (tcp_is_reno(tp)) tcp_reset_reno_sack(tp); tp->undo_marker = tp->snd_una; if (how) { tp->sacked_out = 0; tp->fackets_out = 0; } <API key>(tp); tcp_for_write_queue(skb, sk) { if (skb == tcp_send_head(sk)) break; if (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS) tp->undo_marker = 0; TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED; if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || how) { TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED; TCP_SKB_CB(skb)->sacked |= TCPCB_LOST; tp->lost_out += tcp_skb_pcount(skb); tp->retransmit_high = TCP_SKB_CB(skb)->end_seq; } } tcp_verify_left_out(tp); tp->reordering = min_t(unsigned int, tp->reordering, <API key>); tcp_set_ca_state(sk, TCP_CA_Loss); tp->high_seq = tp->snd_nxt; TCP_ECN_queue_cwr(tp); /* F-RTO RFC5682 sec 3.1 step 1: retransmit SND.UNA if no previous * loss recovery is underway except recurring timeout(s) on * the same SND.UNA (sec 3.2). Disable F-RTO on path MTU probing */ tp->frto = sysctl_tcp_frto && (new_recovery || icsk->icsk_retransmits) && !inet_csk(sk)->icsk_mtup.probe_size; } /* If ACK arrived pointing to a remembered SACK, it means that our * remembered SACKs do not reflect real state of receiver i.e. * receiver _host_ is heavily congested (or buggy). * * Do processing similar to RTO timeout. */ static bool <API key>(struct sock *sk, int flag) { if (flag & FLAG_SACK_RENEGING) { struct <API key> *icsk = inet_csk(sk); NET_INC_STATS_BH(sock_net(sk), <API key>); tcp_enter_loss(sk, 1); icsk->icsk_retransmits++; tcp_retransmit_skb(sk, <API key>(sk)); <API key>(sk, ICSK_TIME_RETRANS, icsk->icsk_rto, TCP_RTO_MAX); return true; } return false; } static inline int tcp_fackets_out(const struct tcp_sock *tp) { return tcp_is_reno(tp) ? tp->sacked_out + 1 : tp->fackets_out; } /* Heurestics to calculate number of duplicate ACKs. There's no dupACKs * counter when SACK is enabled (without SACK, sacked_out is used for * that purpose). * * Instead, with FACK TCP uses fackets_out that includes both SACKed * segments up to the highest received SACK block so far and holes in * between them. * * With reordering, holes may still be in flight, so RFC3517 recovery * uses pure sacked_out (total number of SACKed segments) even though * it violates the RFC that uses duplicate ACKs, often these are equal * but when e.g. out-of-window ACKs or packet duplication occurs, * they differ. Since neither occurs due to loss, TCP should really * ignore them. */ static inline int <API key>(const struct tcp_sock *tp) { return tcp_is_fack(tp) ? tp->fackets_out : tp->sacked_out + 1; } static bool <API key>(struct sock *sk, int flag) { struct tcp_sock *tp = tcp_sk(sk); unsigned long delay; /* Delay early retransmit and entering fast recovery for * max(RTT/4, 2msec) unless ack has ECE mark, no RTT samples * available, or RTO is scheduled to fire first. */ if (<API key> < 2 || <API key> > 3 || (flag & FLAG_ECE) || !tp->srtt) return false; delay = max_t(unsigned long, (tp->srtt >> 5), msecs_to_jiffies(2)); if (!time_after(inet_csk(sk)->icsk_timeout, (jiffies + delay))) return false; <API key>(sk, <API key>, delay, TCP_RTO_MAX); return true; } static inline int tcp_skb_timedout(const struct sock *sk, const struct sk_buff *skb) { return tcp_time_stamp - TCP_SKB_CB(skb)->when > inet_csk(sk)->icsk_rto; } static inline int tcp_head_timedout(const struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); return tp->packets_out && tcp_skb_timedout(sk, <API key>(sk)); } /* This function decides, when we should leave Disordered state * and enter Recovery phase, reducing congestion window. * * Main question: may we further continue forward transmission * with the same cwnd? */ static bool tcp_time_to_recover(struct sock *sk, int flag) { struct tcp_sock *tp = tcp_sk(sk); __u32 packets_out; /* Trick#1: The loss is proven. */ if (tp->lost_out) return true; /* Not-A-Trick#2 : Classic rule... */ if (<API key>(tp) > tp->reordering) return true; /* Trick#3 : when we use RFC2988 timer restart, fast * retransmit can be triggered by timeout of queue head. */ if (tcp_is_fack(tp) && tcp_head_timedout(sk)) return true; /* Trick#4: It is still not OK... But will it be useful to delay * recovery more? */ packets_out = tp->packets_out; if (packets_out <= tp->reordering && tp->sacked_out >= max_t(__u32, packets_out/2, <API key>) && !tcp_may_send_now(sk)) { /* We have nothing to send. This connection is limited * either by receiver window or by application. */ return true; } /* If a thin stream is detected, retransmit after first * received dupack. Employ only if SACK is supported in order * to avoid possible corner-case series of spurious retransmissions * Use only if there are no unsent data. */ if ((tp->thin_dupack || <API key>) && tcp_stream_is_thin(tp) && <API key>(tp) > 1 && tcp_is_sack(tp) && !tcp_send_head(sk)) return true; /* Trick#6: TCP early retransmit, per RFC5827. To avoid spurious * retransmissions due to small network reorderings, we implement * Mitigation A.3 in the RFC and delay the retransmission for a short * interval if appropriate. */ if (tp->do_early_retrans && !tp->retrans_out && tp->sacked_out && (tp->packets_out >= (tp->sacked_out + 1) && tp->packets_out < 4) && !tcp_may_send_now(sk)) return !<API key>(sk, flag); return false; } /* New heuristics: it is possible only after we switched to restart timer * each time when something is ACKed. Hence, we can detect timed out packets * during fast retransmit without falling to slow start. * * Usefulness of this as is very questionable, since we should know which of * the segments is the next to timeout which is relatively expensive to find * in general case unless we add some data structure just for that. The * current approach certainly won't find the right one too often and when it * finally does find _something_ it usually marks large part of the window * right away (because a retransmission with a larger timestamp blocks the * loop from advancing). -ij */ static void tcp_timeout_skbs(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; if (!tcp_is_fack(tp) || !tcp_head_timedout(sk)) return; skb = tp->scoreboard_skb_hint; if (tp->scoreboard_skb_hint == NULL) skb = <API key>(sk); <API key>(skb, sk) { if (skb == tcp_send_head(sk)) break; if (!tcp_skb_timedout(sk, skb)) break; tcp_skb_mark_lost(tp, skb); } tp->scoreboard_skb_hint = skb; tcp_verify_left_out(tp); } /* Detect loss in event "A" above by marking head of queue up as lost. * For FACK or non-SACK(Reno) senders, the first "packets" number of segments * are considered lost. For RFC3517 SACK, a segment is considered lost if it * has at least tp->reordering SACKed seqments above it; "packets" refers to * the maximum SACKed segments to pass before reaching this limit. */ static void tcp_mark_head_lost(struct sock *sk, int packets, int mark_head) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; int cnt, oldcnt; int err; unsigned int mss; /* Use SACK to deduce losses of new sequences sent during recovery */ const u32 loss_high = tcp_is_sack(tp) ? tp->snd_nxt : tp->high_seq; WARN_ON(packets > tp->packets_out); if (tp->lost_skb_hint) { skb = tp->lost_skb_hint; cnt = tp->lost_cnt_hint; /* Head already handled? */ if (mark_head && skb != <API key>(sk)) return; } else { skb = <API key>(sk); cnt = 0; } <API key>(skb, sk) { if (skb == tcp_send_head(sk)) break; /* TODO: do this better */ /* this is not the most efficient way to do this... */ tp->lost_skb_hint = skb; tp->lost_cnt_hint = cnt; if (after(TCP_SKB_CB(skb)->end_seq, loss_high)) break; oldcnt = cnt; if (tcp_is_fack(tp) || tcp_is_reno(tp) || (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) cnt += tcp_skb_pcount(skb); if (cnt > packets) { if ((tcp_is_sack(tp) && !tcp_is_fack(tp)) || (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) || (oldcnt >= packets)) break; mss = skb_shinfo(skb)->gso_size; err = tcp_fragment(sk, skb, (packets - oldcnt) * mss, mss); if (err < 0) break; cnt = packets; } tcp_skb_mark_lost(tp, skb); if (mark_head) break; } tcp_verify_left_out(tp); } /* Account newly detected lost packet(s) */ static void <API key>(struct sock *sk, int fast_rexmit) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_is_reno(tp)) { tcp_mark_head_lost(sk, 1, 1); } else if (tcp_is_fack(tp)) { int lost = tp->fackets_out - tp->reordering; if (lost <= 0) lost = 1; tcp_mark_head_lost(sk, lost, 0); } else { int sacked_upto = tp->sacked_out - tp->reordering; if (sacked_upto >= 0) tcp_mark_head_lost(sk, sacked_upto, 0); else if (fast_rexmit) tcp_mark_head_lost(sk, 1, 1); } tcp_timeout_skbs(sk); } /* CWND moderation, preventing bursts due to too big ACKs * in dubious situations. */ static inline void tcp_moderate_cwnd(struct tcp_sock *tp) { tp->snd_cwnd = min(tp->snd_cwnd, <API key>(tp) + tcp_max_burst(tp)); tp->snd_cwnd_stamp = tcp_time_stamp; } /* Nothing was retransmitted or returned timestamp is less * than timestamp of the first retransmission. */ static inline bool tcp_packet_delayed(const struct tcp_sock *tp) { return !tp->retrans_stamp || (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr && before(tp->rx_opt.rcv_tsecr, tp->retrans_stamp)); } /* Undo procedures. */ #if FASTRETRANS_DEBUG > 1 static void DBGUNDO(struct sock *sk, const char *msg) { struct tcp_sock *tp = tcp_sk(sk); struct inet_sock *inet = inet_sk(sk); if (sk->sk_family == AF_INET) { pr_debug("Undo %s %pI4/%u c%u l%u ss%u/%u p%u\n", msg, &inet->inet_daddr, ntohs(inet->inet_dport), tp->snd_cwnd, tcp_left_out(tp), tp->snd_ssthresh, tp->prior_ssthresh, tp->packets_out); } #if IS_ENABLED(CONFIG_IPV6) else if (sk->sk_family == AF_INET6) { struct ipv6_pinfo *np = inet6_sk(sk); pr_debug("Undo %s %pI6/%u c%u l%u ss%u/%u p%u\n", msg, &np->daddr, ntohs(inet->inet_dport), tp->snd_cwnd, tcp_left_out(tp), tp->snd_ssthresh, tp->prior_ssthresh, tp->packets_out); } #endif } #else #define DBGUNDO(x...) do { } while (0) #endif static void tcp_undo_cwr(struct sock *sk, const bool undo_ssthresh) { struct tcp_sock *tp = tcp_sk(sk); if (tp->prior_ssthresh) { const struct <API key> *icsk = inet_csk(sk); if (icsk->icsk_ca_ops->undo_cwnd) tp->snd_cwnd = icsk->icsk_ca_ops->undo_cwnd(sk); else tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh << 1); if (undo_ssthresh && tp->prior_ssthresh > tp->snd_ssthresh) { tp->snd_ssthresh = tp->prior_ssthresh; <API key>(tp); } } else { tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh); } tp->snd_cwnd_stamp = tcp_time_stamp; } static inline bool tcp_may_undo(const struct tcp_sock *tp) { return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp)); } /* People celebrate: "We love our President!" */ static bool <API key>(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_may_undo(tp)) { int mib_idx; /* Happy end! We did not retransmit anything * or our original transmission succeeded. */ DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans"); tcp_undo_cwr(sk, true); if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss) mib_idx = <API key>; else mib_idx = <API key>; NET_INC_STATS_BH(sock_net(sk), mib_idx); tp->undo_marker = 0; } if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) { /* Hold old state until something *above* high_seq * is ACKed. For Reno it is MUST to prevent false * fast retransmits (RFC2582). SACK TCP is safe. */ tcp_moderate_cwnd(tp); return true; } tcp_set_ca_state(sk, TCP_CA_Open); return false; } /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */ static void tcp_try_undo_dsack(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (tp->undo_marker && !tp->undo_retrans) { DBGUNDO(sk, "D-SACK"); tcp_undo_cwr(sk, true); tp->undo_marker = 0; NET_INC_STATS_BH(sock_net(sk), <API key>); } } /* We can clear retrans_stamp when there are no retransmissions in the * window. It would seem that it is trivially available for us in * tp->retrans_out, however, that kind of assumptions doesn't consider * what will happen if errors occur when sending retransmission for the * second time. ...It could the that such segment has only * TCPCB_EVER_RETRANS set at the present time. It seems that checking * the head skb is enough except for some reneging corner cases that * are not worth the effort. * * Main reason for all this complexity is the fact that connection dying * time now depends on the validity of the retrans_stamp, in particular, * that successive retransmissions of a segment must not advance * retrans_stamp under any conditions. */ static bool <API key>(const struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; if (tp->retrans_out) return true; skb = <API key>(sk); if (unlikely(skb && TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS)) return true; return false; } /* Undo during fast recovery after partial ACK. */ static int <API key>(struct sock *sk, int acked) { struct tcp_sock *tp = tcp_sk(sk); /* Partial ACK arrived. Force Hoe's retransmit. */ int failed = tcp_is_reno(tp) || (tcp_fackets_out(tp) > tp->reordering); if (tcp_may_undo(tp)) { /* Plain luck! Hole if filled with delayed * packet, rather than with a retransmit. */ if (!<API key>(sk)) tp->retrans_stamp = 0; <API key>(sk, tcp_fackets_out(tp) + acked, 1); DBGUNDO(sk, "Hoe"); tcp_undo_cwr(sk, false); NET_INC_STATS_BH(sock_net(sk), <API key>); /* So... Do not make Hoe's retransmit yet. * If the first packet was delayed, the rest * ones are most probably delayed as well. */ failed = 0; } return failed; } /* Undo during loss recovery after partial ACK or using F-RTO. */ static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo) { struct tcp_sock *tp = tcp_sk(sk); if (frto_undo || tcp_may_undo(tp)) { struct sk_buff *skb; tcp_for_write_queue(skb, sk) { if (skb == tcp_send_head(sk)) break; TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST; } <API key>(tp); DBGUNDO(sk, "partial loss"); tp->lost_out = 0; tcp_undo_cwr(sk, true); NET_INC_STATS_BH(sock_net(sk), <API key>); if (frto_undo) NET_INC_STATS_BH(sock_net(sk), <API key>); inet_csk(sk)->icsk_retransmits = 0; tp->undo_marker = 0; if (frto_undo || tcp_is_sack(tp)) tcp_set_ca_state(sk, TCP_CA_Open); return true; } return false; } static void <API key>(struct sock *sk, const bool set_ssthresh) { struct tcp_sock *tp = tcp_sk(sk); tp->high_seq = tp->snd_nxt; tp->tlp_high_seq = 0; tp->snd_cwnd_cnt = 0; tp->prior_cwnd = tp->snd_cwnd; tp->prr_delivered = 0; tp->prr_out = 0; if (set_ssthresh) tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk); TCP_ECN_queue_cwr(tp); } static void tcp_cwnd_reduction(struct sock *sk, int newly_acked_sacked, int fast_rexmit) { struct tcp_sock *tp = tcp_sk(sk); int sndcnt = 0; int delta = tp->snd_ssthresh - <API key>(tp); tp->prr_delivered += newly_acked_sacked; if (<API key>(tp) > tp->snd_ssthresh) { u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered + tp->prior_cwnd - 1; sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out; } else { sndcnt = min_t(int, delta, max_t(int, tp->prr_delivered - tp->prr_out, newly_acked_sacked) + 1); } sndcnt = max(sndcnt, (fast_rexmit ? 1 : 0)); tp->snd_cwnd = <API key>(tp) + sndcnt; } static inline void <API key>(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); /* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */ if (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR || (tp->undo_marker && tp->snd_ssthresh < <API key>)) { tp->snd_cwnd = tp->snd_ssthresh; tp->snd_cwnd_stamp = tcp_time_stamp; } tcp_ca_event(sk, <API key>); } /* Enter CWR state. Disable cwnd undo since congestion is proven with ECN */ void tcp_enter_cwr(struct sock *sk, const int set_ssthresh) { struct tcp_sock *tp = tcp_sk(sk); tp->prior_ssthresh = 0; if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) { tp->undo_marker = 0; <API key>(sk, set_ssthresh); tcp_set_ca_state(sk, TCP_CA_CWR); } } static void tcp_try_keep_open(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); int state = TCP_CA_Open; if (tcp_left_out(tp) || <API key>(sk)) state = TCP_CA_Disorder; if (inet_csk(sk)->icsk_ca_state != state) { tcp_set_ca_state(sk, state); tp->high_seq = tp->snd_nxt; } } static void tcp_try_to_open(struct sock *sk, int flag, int newly_acked_sacked) { struct tcp_sock *tp = tcp_sk(sk); tcp_verify_left_out(tp); if (!<API key>(sk)) tp->retrans_stamp = 0; if (flag & FLAG_ECE) tcp_enter_cwr(sk, 1); if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) { tcp_try_keep_open(sk); if (inet_csk(sk)->icsk_ca_state != TCP_CA_Open) tcp_moderate_cwnd(tp); } else { tcp_cwnd_reduction(sk, newly_acked_sacked, 0); } } static void <API key>(struct sock *sk) { struct <API key> *icsk = inet_csk(sk); icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1; icsk->icsk_mtup.probe_size = 0; } static void <API key>(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct <API key> *icsk = inet_csk(sk); /* FIXME: breaks with very large cwnd */ tp->prior_ssthresh = <API key>(sk); tp->snd_cwnd = tp->snd_cwnd * tcp_mss_to_mtu(sk, tp->mss_cache) / icsk->icsk_mtup.probe_size; tp->snd_cwnd_cnt = 0; tp->snd_cwnd_stamp = tcp_time_stamp; tp->snd_ssthresh = <API key>(sk); icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size; icsk->icsk_mtup.probe_size = 0; tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); } /* Do a simple retransmit without using the backoff mechanisms in * tcp_timer. This is used for path mtu discovery. * The socket is already locked here. */ void <API key>(struct sock *sk) { const struct <API key> *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; unsigned int mss = tcp_current_mss(sk); u32 prior_lost = tp->lost_out; tcp_for_write_queue(skb, sk) { if (skb == tcp_send_head(sk)) break; if (tcp_skb_seglen(skb) > mss && !(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) { if (TCP_SKB_CB(skb)->sacked & <API key>) { TCP_SKB_CB(skb)->sacked &= ~<API key>; tp->retrans_out -= tcp_skb_pcount(skb); } <API key>(tp, skb); } } <API key>(tp); if (prior_lost == tp->lost_out) return; if (tcp_is_reno(tp)) <API key>(tp); tcp_verify_left_out(tp); /* Don't muck with the congestion window here. * Reason is that we do not increase amount of _data_ * in network, but units changed and effective * cwnd/ssthresh really reduced now. */ if (icsk->icsk_ca_state != TCP_CA_Loss) { tp->high_seq = tp->snd_nxt; tp->snd_ssthresh = <API key>(sk); tp->prior_ssthresh = 0; tp->undo_marker = 0; tcp_set_ca_state(sk, TCP_CA_Loss); } <API key>(sk); } EXPORT_SYMBOL(<API key>); static void tcp_enter_recovery(struct sock *sk, bool ece_ack) { struct tcp_sock *tp = tcp_sk(sk); int mib_idx; if (tcp_is_reno(tp)) mib_idx = <API key>; else mib_idx = <API key>; NET_INC_STATS_BH(sock_net(sk), mib_idx); tp->prior_ssthresh = 0; tp->undo_marker = tp->snd_una; tp->undo_retrans = tp->retrans_out; if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) { if (!ece_ack) tp->prior_ssthresh = <API key>(sk); <API key>(sk, true); } tcp_set_ca_state(sk, TCP_CA_Recovery); } /* Process an ACK in CA_Loss state. Move to CA_Open if lost data are * recovered or spurious. Otherwise retransmits more on partial ACKs. */ static void tcp_process_loss(struct sock *sk, int flag, bool is_dupack) { struct <API key> *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); bool recovered = !before(tp->snd_una, tp->high_seq); if (tp->frto) { /* F-RTO RFC5682 sec 3.1 (sack enhanced version). */ /* Step 3.b. A timeout is spurious if not all data are * lost, i.e., never-retransmitted data are (s)acked. */ if (tcp_try_undo_loss(sk, flag & <API key>)) return; if (after(tp->snd_nxt, tp->high_seq) && (flag & FLAG_DATA_SACKED || is_dupack)) { tp->frto = 0; /* Loss was real: 2nd part of step 3.a */ } else if (flag & <API key> && !recovered) { tp->high_seq = tp->snd_nxt; <API key>(sk, tcp_current_mss(sk), TCP_NAGLE_OFF); if (after(tp->snd_nxt, tp->high_seq)) return; /* Step 2.b */ tp->frto = 0; } } if (recovered) { /* F-RTO RFC5682 sec 3.1 step 2.a and 1st part of step 3.a */ icsk->icsk_retransmits = 0; <API key>(sk); return; } if (flag & FLAG_DATA_ACKED) icsk->icsk_retransmits = 0; if (tcp_is_reno(tp)) { /* A Reno DUPACK means new data in F-RTO step 2.b above are * delivered. Lower inflight to clock out (re)tranmissions. */ if (after(tp->snd_nxt, tp->high_seq) && is_dupack) tcp_add_reno_sack(sk); else if (flag & <API key>) tcp_reset_reno_sack(tp); } if (tcp_try_undo_loss(sk, false)) return; <API key>(sk); } /* Process an event, which can update packets-in-flight not trivially. * Main goal of this function is to calculate new estimate for left_out, * taking into account both packets sitting in receiver's buffer and * packets lost by network. * * Besides that it does CWND reduction, when packet loss is detected * and changes state of machine. * * It does _not_ decide what to send, it is made in function * <API key>(). */ static void <API key>(struct sock *sk, int pkts_acked, int prior_sacked, int prior_packets, bool is_dupack, int flag) { struct <API key> *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int do_lost = is_dupack || ((flag & FLAG_DATA_SACKED) && (tcp_fackets_out(tp) > tp->reordering)); int newly_acked_sacked = 0; int fast_rexmit = 0; if (WARN_ON(!tp->packets_out && tp->sacked_out)) tp->sacked_out = 0; if (WARN_ON(!tp->sacked_out && tp->fackets_out)) tp->fackets_out = 0; /* Now state machine starts. * A. ECE, hence prohibit cwnd undoing, the reduction is required. */ if (flag & FLAG_ECE) tp->prior_ssthresh = 0; /* B. In all the states check for reneging SACKs. */ if (<API key>(sk, flag)) return; /* C. Check consistency of the current state. */ tcp_verify_left_out(tp); /* D. Check state exit conditions. State can be terminated * when high_seq is ACKed. */ if (icsk->icsk_ca_state == TCP_CA_Open) { WARN_ON(tp->retrans_out != 0); tp->retrans_stamp = 0; } else if (!before(tp->snd_una, tp->high_seq)) { switch (icsk->icsk_ca_state) { case TCP_CA_CWR: /* CWR is to be held something *above* high_seq * is ACKed for CWR bit to reach receiver. */ if (tp->snd_una != tp->high_seq) { <API key>(sk); tcp_set_ca_state(sk, TCP_CA_Open); } break; case TCP_CA_Recovery: if (tcp_is_reno(tp)) tcp_reset_reno_sack(tp); if (<API key>(sk)) return; <API key>(sk); break; } } /* E. Process state. */ switch (icsk->icsk_ca_state) { case TCP_CA_Recovery: if (!(flag & <API key>)) { if (tcp_is_reno(tp) && is_dupack) tcp_add_reno_sack(sk); } else do_lost = <API key>(sk, pkts_acked); newly_acked_sacked = prior_packets - tp->packets_out + tp->sacked_out - prior_sacked; break; case TCP_CA_Loss: tcp_process_loss(sk, flag, is_dupack); if (icsk->icsk_ca_state != TCP_CA_Open) return; /* Fall through to processing in Open state. */ default: if (tcp_is_reno(tp)) { if (flag & <API key>) tcp_reset_reno_sack(tp); if (is_dupack) tcp_add_reno_sack(sk); } newly_acked_sacked = prior_packets - tp->packets_out + tp->sacked_out - prior_sacked; if (icsk->icsk_ca_state <= TCP_CA_Disorder) tcp_try_undo_dsack(sk); if (!tcp_time_to_recover(sk, flag)) { tcp_try_to_open(sk, flag, newly_acked_sacked); return; } /* MTU probe failure: don't reduce cwnd */ if (icsk->icsk_ca_state < TCP_CA_CWR && icsk->icsk_mtup.probe_size && tp->snd_una == tp->mtu_probe.probe_seq_start) { <API key>(sk); /* Restores the reduction we did in tcp_mtup_probe() */ tp->snd_cwnd++; <API key>(sk); return; } /* Otherwise enter Recovery state */ tcp_enter_recovery(sk, (flag & FLAG_ECE)); fast_rexmit = 1; } if (do_lost || (tcp_is_fack(tp) && tcp_head_timedout(sk))) <API key>(sk, fast_rexmit); tcp_cwnd_reduction(sk, newly_acked_sacked, fast_rexmit); <API key>(sk); } void tcp_valid_rtt_meas(struct sock *sk, u32 seq_rtt) { tcp_rtt_estimator(sk, seq_rtt); tcp_set_rto(sk); inet_csk(sk)->icsk_backoff = 0; } EXPORT_SYMBOL(tcp_valid_rtt_meas); /* Read <API key> before mucking * with this code. (Supersedes RFC1323) */ static void tcp_ack_saw_tstamp(struct sock *sk, int flag) { /* RTTM Rule: A TSecr value received in a segment is used to * update the averaged RTT measurement only if the segment * acknowledges some new data, i.e., only if it advances the * left edge of the send window. * * See <API key>, section 3.3. * 1998/04/10 Andrey V. Savochkin <saw@msu.ru> * * Changed: reset backoff as soon as we see the first valid sample. * If we do not, we get strongly overestimated rto. With timestamps * samples are accepted even from very old segments: f.e., when rtt=1 * increases to 8, we retransmit 5 times and after 8 seconds delayed * answer arrives rto becomes 120 seconds! If at least one of segments * in window is lost... Voila. --ANK (010210) */ struct tcp_sock *tp = tcp_sk(sk); tcp_valid_rtt_meas(sk, tcp_time_stamp - tp->rx_opt.rcv_tsecr); } static void tcp_ack_no_tstamp(struct sock *sk, u32 seq_rtt, int flag) { /* We don't have a timestamp. Can only use * packets that are not retransmitted to determine * rtt estimates. Also, we must not reset the * backoff for rto until we get a non-retransmitted * packet. This allows us to deal with a situation * where the network delay has increased suddenly. * I.e. Karn's algorithm. (SIGCOMM '87, p5.) */ if (flag & <API key>) return; tcp_valid_rtt_meas(sk, seq_rtt); } static inline void tcp_ack_update_rtt(struct sock *sk, const int flag, const s32 seq_rtt) { const struct tcp_sock *tp = tcp_sk(sk); /* Note that peer MAY send zero echo. In this case it is ignored. (rfc1323) */ if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr) tcp_ack_saw_tstamp(sk, flag); else if (seq_rtt >= 0) tcp_ack_no_tstamp(sk, seq_rtt, flag); } static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 in_flight) { const struct <API key> *icsk = inet_csk(sk); icsk->icsk_ca_ops->cong_avoid(sk, ack, in_flight); tcp_sk(sk)->snd_cwnd_stamp = tcp_time_stamp; } /* Restart timer after forward progress on connection. * RFC2988 recommends to restart timer to now+rto. */ void tcp_rearm_rto(struct sock *sk) { const struct <API key> *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); /* If the retrans timer is currently being used by Fast Open * for SYN-ACK retrans purpose, stay put. */ if (tp->fastopen_rsk) return; if (!tp->packets_out) { <API key>(sk, ICSK_TIME_RETRANS); } else { u32 rto = inet_csk(sk)->icsk_rto; /* Offset the time elapsed after installing regular RTO */ if (icsk->icsk_pending == <API key> || icsk->icsk_pending == <API key>) { struct sk_buff *skb = <API key>(sk); const u32 rto_time_stamp = TCP_SKB_CB(skb)->when + rto; s32 delta = (s32)(rto_time_stamp - tcp_time_stamp); /* delta may not be positive if the socket is locked * when the retrans timer fires and is rescheduled. */ if (delta > 0) rto = delta; } <API key>(sk, ICSK_TIME_RETRANS, rto, TCP_RTO_MAX); } } /* This function is called when the delayed ER timer fires. TCP enters * fast recovery and performs fast-retransmit. */ void <API key>(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); tcp_rearm_rto(sk); /* Stop if ER is disabled after the delayed ER timer is scheduled */ if (!tp->do_early_retrans) return; tcp_enter_recovery(sk, false); <API key>(sk, 1); <API key>(sk); } /* If we get here, the whole TSO packet has not been acked. */ static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); u32 packets_acked; BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)); packets_acked = tcp_skb_pcount(skb); if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq)) return 0; packets_acked -= tcp_skb_pcount(skb); if (packets_acked) { BUG_ON(tcp_skb_pcount(skb) == 0); BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)); } return packets_acked; } /* Remove acknowledged frames from the retransmission queue. If our packet * is before the ack sequence we can discard it as it's confirmed to have * arrived at the other end. */ static int tcp_clean_rtx_queue(struct sock *sk, int prior_fackets, u32 prior_snd_una) { struct tcp_sock *tp = tcp_sk(sk); const struct <API key> *icsk = inet_csk(sk); struct sk_buff *skb; u32 now = tcp_time_stamp; int fully_acked = true; int flag = 0; u32 pkts_acked = 0; u32 reord = tp->packets_out; u32 prior_sacked = tp->sacked_out; s32 seq_rtt = -1; s32 ca_seq_rtt = -1; ktime_t last_ackt = <API key>(); while ((skb = <API key>(sk)) && skb != tcp_send_head(sk)) { struct tcp_skb_cb *scb = TCP_SKB_CB(skb); u32 acked_pcount; u8 sacked = scb->sacked; /* Determine how many packets and what bytes were acked, tso and else */ if (after(scb->end_seq, tp->snd_una)) { if (tcp_skb_pcount(skb) == 1 || !after(tp->snd_una, scb->seq)) break; acked_pcount = tcp_tso_acked(sk, skb); if (!acked_pcount) break; fully_acked = false; } else { acked_pcount = tcp_skb_pcount(skb); } if (sacked & TCPCB_RETRANS) { if (sacked & <API key>) tp->retrans_out -= acked_pcount; flag |= <API key>; ca_seq_rtt = -1; seq_rtt = -1; } else { ca_seq_rtt = now - scb->when; last_ackt = skb->tstamp; if (seq_rtt < 0) { seq_rtt = ca_seq_rtt; } if (!(sacked & TCPCB_SACKED_ACKED)) reord = min(pkts_acked, reord); if (!after(scb->end_seq, tp->high_seq)) flag |= <API key>; } if (sacked & TCPCB_SACKED_ACKED) tp->sacked_out -= acked_pcount; if (sacked & TCPCB_LOST) tp->lost_out -= acked_pcount; tp->packets_out -= acked_pcount; pkts_acked += acked_pcount; /* Initial outgoing SYN's get put onto the write_queue * just like anything else we transmit. It is not * true data, and if we misinform our callers that * this ACK acks real data, we will erroneously exit * connection startup slow start one packet too * quickly. This is severely frowned upon behavior. */ if (!(scb->tcp_flags & TCPHDR_SYN)) { flag |= FLAG_DATA_ACKED; } else { flag |= FLAG_SYN_ACKED; tp->retrans_stamp = 0; } if (!fully_acked) break; <API key>(skb, sk); sk_wmem_free_skb(sk, skb); tp->scoreboard_skb_hint = NULL; if (skb == tp->retransmit_skb_hint) tp->retransmit_skb_hint = NULL; if (skb == tp->lost_skb_hint) tp->lost_skb_hint = NULL; } if (likely(between(tp->snd_up, prior_snd_una, tp->snd_una))) tp->snd_up = tp->snd_una; if (skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) flag |= FLAG_SACK_RENEGING; if (flag & FLAG_ACKED) { const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops; if (unlikely(icsk->icsk_mtup.probe_size && !after(tp->mtu_probe.probe_seq_end, tp->snd_una))) { <API key>(sk); } tcp_ack_update_rtt(sk, flag, seq_rtt); tcp_rearm_rto(sk); if (tcp_is_reno(tp)) { <API key>(sk, pkts_acked); } else { int delta; /* Non-retransmitted hole got filled? That's reordering */ if (reord < prior_fackets) <API key>(sk, tp->fackets_out - reord, 0); delta = tcp_is_fack(tp) ? pkts_acked : prior_sacked - tp->sacked_out; tp->lost_cnt_hint -= min(tp->lost_cnt_hint, delta); } tp->fackets_out -= min(pkts_acked, tp->fackets_out); if (ca_ops->pkts_acked) { s32 rtt_us = -1; /* Is the ACK triggering packet unambiguous? */ if (!(flag & <API key>)) { /* High resolution needed and available? */ if (ca_ops->flags & TCP_CONG_RTT_STAMP && !ktime_equal(last_ackt, <API key>())) rtt_us = ktime_us_delta(ktime_get_real(), last_ackt); else if (ca_seq_rtt >= 0) rtt_us = jiffies_to_usecs(ca_seq_rtt); } ca_ops->pkts_acked(sk, pkts_acked, rtt_us); } } #if FASTRETRANS_DEBUG > 0 WARN_ON((int)tp->sacked_out < 0); WARN_ON((int)tp->lost_out < 0); WARN_ON((int)tp->retrans_out < 0); if (!tp->packets_out && tcp_is_sack(tp)) { icsk = inet_csk(sk); if (tp->lost_out) { pr_debug("Leak l=%u %d\n", tp->lost_out, icsk->icsk_ca_state); tp->lost_out = 0; } if (tp->sacked_out) { pr_debug("Leak s=%u %d\n", tp->sacked_out, icsk->icsk_ca_state); tp->sacked_out = 0; } if (tp->retrans_out) { pr_debug("Leak r=%u %d\n", tp->retrans_out, icsk->icsk_ca_state); tp->retrans_out = 0; } } #endif return flag; } static void tcp_ack_probe(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); struct <API key> *icsk = inet_csk(sk); /* Was it a usable window open? */ if (!after(TCP_SKB_CB(tcp_send_head(sk))->end_seq, tcp_wnd_end(tp))) { icsk->icsk_backoff = 0; <API key>(sk, ICSK_TIME_PROBE0); /* Socket must be waked up by subsequent tcp_data_snd_check(). * This function is not for random using! */ } else { <API key>(sk, ICSK_TIME_PROBE0, min(icsk->icsk_rto << icsk->icsk_backoff, TCP_RTO_MAX), TCP_RTO_MAX); } } static inline bool tcp_ack_is_dubious(const struct sock *sk, const int flag) { return !(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) || inet_csk(sk)->icsk_ca_state != TCP_CA_Open; } static inline bool tcp_may_raise_cwnd(const struct sock *sk, const int flag) { const struct tcp_sock *tp = tcp_sk(sk); return (!(flag & FLAG_ECE) || tp->snd_cwnd < tp->snd_ssthresh) && !<API key>(sk); } /* Check that window update is acceptable. * The function assumes that snd_una<=ack<=snd_next. */ static inline bool <API key>(const struct tcp_sock *tp, const u32 ack, const u32 ack_seq, const u32 nwin) { return after(ack, tp->snd_una) || after(ack_seq, tp->snd_wl1) || (ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd); } /* Update our send window. * * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2 * and in FreeBSD. NetBSD's one is even worse.) is wrong. */ static int <API key>(struct sock *sk, const struct sk_buff *skb, u32 ack, u32 ack_seq) { struct tcp_sock *tp = tcp_sk(sk); int flag = 0; u32 nwin = ntohs(tcp_hdr(skb)->window); if (likely(!tcp_hdr(skb)->syn)) nwin <<= tp->rx_opt.snd_wscale; if (<API key>(tp, ack, ack_seq, nwin)) { flag |= FLAG_WIN_UPDATE; tcp_update_wl(tp, ack_seq); if (tp->snd_wnd != nwin) { tp->snd_wnd = nwin; /* Note, it is the only place, where * fast path is recovered for sending TCP. */ tp->pred_flags = 0; tcp_fast_path_check(sk); if (nwin > tp->max_window) { tp->max_window = nwin; tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie); } } } tp->snd_una = ack; return flag; } /* RFC 5961 7 [ACK Throttling] */ static void <API key>(struct sock *sk) { /* unprotected vars, we dont care of overwrites */ static u32 challenge_timestamp; static unsigned int challenge_count; u32 now = jiffies / HZ; if (now != challenge_timestamp) { challenge_timestamp = now; challenge_count = 0; } if (++challenge_count <= <API key>) { NET_INC_STATS_BH(sock_net(sk), <API key>); tcp_send_ack(sk); } } static void tcp_store_ts_recent(struct tcp_sock *tp) { tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval; tp->rx_opt.ts_recent_stamp = get_seconds(); } static void <API key>(struct tcp_sock *tp, u32 seq) { if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) { /* PAWS bug workaround wrt. ACK frames, the PAWS discard * extra check below makes sure this can only happen * for pure ACK frames. -DaveM * * Not only, also it occurs for expired timestamps. */ if (tcp_paws_check(&tp->rx_opt, 0)) tcp_store_ts_recent(tp); } } /* This routine deals with acks during a TLP episode. * Ref: loss detection algorithm in <API key>. */ static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag) { struct tcp_sock *tp = tcp_sk(sk); bool is_tlp_dupack = (ack == tp->tlp_high_seq) && !(flag & (<API key> | FLAG_NOT_DUP | FLAG_DATA_SACKED)); /* Mark the end of TLP episode on receiving TLP dupack or when * ack is after tlp_high_seq. */ if (is_tlp_dupack) { tp->tlp_high_seq = 0; return; } if (after(ack, tp->tlp_high_seq)) { tp->tlp_high_seq = 0; /* Don't reduce cwnd if DSACK arrives for TLP retrans. */ if (!(flag & FLAG_DSACKING_ACK)) { <API key>(sk, true); tcp_set_ca_state(sk, TCP_CA_CWR); <API key>(sk); tcp_try_keep_open(sk); NET_INC_STATS_BH(sock_net(sk), <API key>); } } } /* This routine deals with incoming acks, but not outgoing ones. */ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) { struct <API key> *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); u32 prior_snd_una = tp->snd_una; u32 ack_seq = TCP_SKB_CB(skb)->seq; u32 ack = TCP_SKB_CB(skb)->ack_seq; bool is_dupack = false; u32 prior_in_flight, prior_cwnd = tp->snd_cwnd, prior_rtt = tp->srtt; u32 prior_fackets; int prior_packets = tp->packets_out; int prior_sacked = tp->sacked_out; int pkts_acked = 0; int <API key> = 0; /* If the ack is older than previous acks * then we can probably ignore it. */ if (before(ack, prior_snd_una)) { /* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */ if (before(ack, prior_snd_una - tp->max_window)) { <API key>(sk); return -1; } goto old_ack; } /* If the ack includes data we haven't sent yet, discard * this segment (RFC793 Section 3.9). */ if (after(ack, tp->snd_nxt)) goto invalid_ack; if (icsk->icsk_pending == <API key> || icsk->icsk_pending == <API key>) tcp_rearm_rto(sk); if (after(ack, prior_snd_una)) flag |= <API key>; prior_fackets = tp->fackets_out; prior_in_flight = <API key>(tp); /* ts_recent update must be made after we are sure that the packet * is in window. */ if (flag & <API key>) <API key>(tp, TCP_SKB_CB(skb)->seq); if (!(flag & FLAG_SLOWPATH) && after(ack, prior_snd_una)) { /* Window is constant, pure forward advance. * No more checks are required. * Note, we use the fact that SND.UNA>=SND.WL2. */ tcp_update_wl(tp, ack_seq); tp->snd_una = ack; flag |= FLAG_WIN_UPDATE; tcp_ca_event(sk, CA_EVENT_FAST_ACK); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPACKS); } else { if (ack_seq != TCP_SKB_CB(skb)->end_seq) flag |= FLAG_DATA; else NET_INC_STATS_BH(sock_net(sk), <API key>); flag |= <API key>(sk, skb, ack, ack_seq); if (TCP_SKB_CB(skb)->sacked) flag |= <API key>(sk, skb, prior_snd_una); if (<API key>(tp, tcp_hdr(skb))) flag |= FLAG_ECE; tcp_ca_event(sk, CA_EVENT_SLOW_ACK); } /* We passed data and got it acked, remove any soft error * log. Something worked... */ sk->sk_err_soft = 0; icsk->icsk_probes_out = 0; tp->rcv_tstamp = tcp_time_stamp; if (!prior_packets) goto no_queue; /* See if we can take anything off of the retransmit queue. */ <API key> = tp->packets_out; flag |= tcp_clean_rtx_queue(sk, prior_fackets, prior_snd_una); pkts_acked = <API key> - tp->packets_out; if (tcp_ack_is_dubious(sk, flag)) { /* Advance CWND, if state allows this. */ if ((flag & FLAG_DATA_ACKED) && tcp_may_raise_cwnd(sk, flag)) tcp_cong_avoid(sk, ack, prior_in_flight); is_dupack = !(flag & (<API key> | FLAG_NOT_DUP)); <API key>(sk, pkts_acked, prior_sacked, prior_packets, is_dupack, flag); } else { if (flag & FLAG_DATA_ACKED) tcp_cong_avoid(sk, ack, prior_in_flight); } if (tp->tlp_high_seq) tcp_process_tlp_ack(sk, ack, flag); if ((flag & <API key>) || !(flag & FLAG_NOT_DUP)) { struct dst_entry *dst = __sk_dst_get(sk); if (dst) dst_confirm(dst); } if (icsk->icsk_pending == ICSK_TIME_RETRANS) <API key>(sk); if (tp->srtt != prior_rtt || tp->snd_cwnd != prior_cwnd) <API key>(sk); return 1; no_queue: /* If data was DSACKed, see if we can undo a cwnd reduction. */ if (flag & FLAG_DSACKING_ACK) <API key>(sk, pkts_acked, prior_sacked, prior_packets, is_dupack, flag); /* If this ack opens up a zero window, clear backoff. It was * being used to time the probes, and is probably far higher than * it needs to be for normal retransmission. */ if (tcp_send_head(sk)) tcp_ack_probe(sk); if (tp->tlp_high_seq) tcp_process_tlp_ack(sk, ack, flag); return 1; invalid_ack: SOCK_DEBUG(sk, "Ack %u after %u:%u\n", ack, tp->snd_una, tp->snd_nxt); return -1; old_ack: /* If data was SACKed, tag it and see if we should send more data. * If data was DSACKed, see if we can undo a cwnd reduction. */ if (TCP_SKB_CB(skb)->sacked) { flag |= <API key>(sk, skb, prior_snd_una); <API key>(sk, pkts_acked, prior_sacked, prior_packets, is_dupack, flag); } SOCK_DEBUG(sk, "Ack %u before %u:%u\n", ack, tp->snd_una, tp->snd_nxt); return 0; } /* Look for tcp options. Normally only called on SYN and SYNACK packets. * But, this can also be called on packets in the established flow when * the fast version below fails. */ void tcp_parse_options(const struct sk_buff *skb, struct <API key> *opt_rx, int estab, struct tcp_fastopen_cookie *foc) { const unsigned char *ptr; const struct tcphdr *th = tcp_hdr(skb); int length = (th->doff * 4) - sizeof(struct tcphdr); ptr = (const unsigned char *)(th + 1); opt_rx->saw_tstamp = 0; while (length > 0) { int opcode = *ptr++; int opsize; switch (opcode) { case TCPOPT_EOL: return; case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */ length continue; default: opsize = *ptr++; if (opsize < 2) /* "silly options" */ return; if (opsize > length) return; /* don't parse partial options */ switch (opcode) { case TCPOPT_MSS: if (opsize == TCPOLEN_MSS && th->syn && !estab) { u16 in_mss = get_unaligned_be16(ptr); if (in_mss) { if (opt_rx->user_mss && opt_rx->user_mss < in_mss) in_mss = opt_rx->user_mss; opt_rx->mss_clamp = in_mss; } } break; case TCPOPT_WINDOW: if (opsize == TCPOLEN_WINDOW && th->syn && !estab && <API key>) { __u8 snd_wscale = *(__u8 *)ptr; opt_rx->wscale_ok = 1; if (snd_wscale > 14) { <API key>("%s: Illegal window scaling value %d >14 received\n", __func__, snd_wscale); snd_wscale = 14; } opt_rx->snd_wscale = snd_wscale; } break; case TCPOPT_TIMESTAMP: if ((opsize == TCPOLEN_TIMESTAMP) && ((estab && opt_rx->tstamp_ok) || (!estab && <API key>))) { opt_rx->saw_tstamp = 1; opt_rx->rcv_tsval = get_unaligned_be32(ptr); opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4); } break; case TCPOPT_SACK_PERM: if (opsize == TCPOLEN_SACK_PERM && th->syn && !estab && sysctl_tcp_sack) { opt_rx->sack_ok = TCP_SACK_SEEN; tcp_sack_reset(opt_rx); } break; case TCPOPT_SACK: if ((opsize >= (TCPOLEN_SACK_BASE + <API key>)) && !((opsize - TCPOLEN_SACK_BASE) % <API key>) && opt_rx->sack_ok) { TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th; } break; #ifdef CONFIG_TCP_MD5SIG case TCPOPT_MD5SIG: /* * The MD5 Hash has already been * checked (see tcp_v{4,6}_do_rcv()). */ break; #endif case TCPOPT_EXP: /* Fast Open option shares code 254 using a * 16 bits magic number. It's valid only in * SYN or SYN-ACK with an even size. */ if (opsize < <API key> || get_unaligned_be16(ptr) != <API key> || foc == NULL || !th->syn || (opsize & 1)) break; foc->len = opsize - <API key>; if (foc->len >= <API key> && foc->len <= <API key>) memcpy(foc->val, ptr + 2, foc->len); else if (foc->len != 0) foc->len = -1; break; } ptr += opsize-2; length -= opsize; } } } EXPORT_SYMBOL(tcp_parse_options); static bool <API key>(struct tcp_sock *tp, const struct tcphdr *th) { const __be32 *ptr = (const __be32 *)(th + 1); if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) { tp->rx_opt.saw_tstamp = 1; ++ptr; tp->rx_opt.rcv_tsval = ntohl(*ptr); ++ptr; if (*ptr) tp->rx_opt.rcv_tsecr = ntohl(*ptr) - tp->tsoffset; else tp->rx_opt.rcv_tsecr = 0; return true; } return false; } /* Fast parse options. This hopes to only see timestamps. * If it is wrong it falls back on tcp_parse_options(). */ static bool <API key>(const struct sk_buff *skb, const struct tcphdr *th, struct tcp_sock *tp) { /* In the spirit of fast parsing, compare doff directly to constant * values. Because equality is used, short doff can be ignored here. */ if (th->doff == (sizeof(*th) / 4)) { tp->rx_opt.saw_tstamp = 0; return false; } else if (tp->rx_opt.tstamp_ok && th->doff == ((sizeof(*th) + <API key>) / 4)) { if (<API key>(tp, th)) return true; } tcp_parse_options(skb, &tp->rx_opt, 1, NULL); if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr) tp->rx_opt.rcv_tsecr -= tp->tsoffset; return true; } #ifdef CONFIG_TCP_MD5SIG /* * Parse MD5 Signature option */ const u8 *<API key>(const struct tcphdr *th) { int length = (th->doff << 2) - sizeof(*th); const u8 *ptr = (const u8 *)(th + 1); /* If the TCP option is too short, we can short cut */ if (length < TCPOLEN_MD5SIG) return NULL; while (length > 0) { int opcode = *ptr++; int opsize; switch(opcode) { case TCPOPT_EOL: return NULL; case TCPOPT_NOP: length continue; default: opsize = *ptr++; if (opsize < 2 || opsize > length) return NULL; if (opcode == TCPOPT_MD5SIG) return opsize == TCPOLEN_MD5SIG ? ptr : NULL; } ptr += opsize - 2; length -= opsize; } return NULL; } EXPORT_SYMBOL(<API key>); #endif /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM * * It is not fatal. If this ACK does _not_ change critical state (seqs, window) * it can pass through stack. So, the following predicate verifies that * this segment is not used for anything but congestion avoidance or * fast retransmit. Moreover, we even are able to eliminate most of such * second order effects, if we apply some small "replay" window (~RTO) * to timestamp space. * * All these measures still do not guarantee that we reject wrapped ACKs * on networks with high bandwidth, when sequence space is recycled fastly, * but it guarantees that such events will be very rare and do not affect * connection seriously. This doesn't look nice, but alas, PAWS is really * buggy extension. * * [ Later note. Even worse! It is buggy for segments _with_ data. RFC * states that events when retransmit arrives after original data are rare. * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is * the biggest problem on large power networks even with minor reordering. * OK, let's give it small replay window. If peer clock is even 1hz, it is safe * up to bandwidth of 18Gigabit/sec. 8) ] */ static int tcp_disordered_ack(const struct sock *sk, const struct sk_buff *skb) { const struct tcp_sock *tp = tcp_sk(sk); const struct tcphdr *th = tcp_hdr(skb); u32 seq = TCP_SKB_CB(skb)->seq; u32 ack = TCP_SKB_CB(skb)->ack_seq; return (/* 1. Pure ACK with correct sequence number. */ (th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) && /* 2. ... and duplicate ACK. */ ack == tp->snd_una && /* 3. ... and does not update window. */ !<API key>(tp, ack, seq, ntohs(th->window) << tp->rx_opt.snd_wscale) && /* 4. ... and sits in replay window. */ (s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) <= (inet_csk(sk)->icsk_rto * 1024) / HZ); } static inline bool tcp_paws_discard(const struct sock *sk, const struct sk_buff *skb) { const struct tcp_sock *tp = tcp_sk(sk); return !tcp_paws_check(&tp->rx_opt, TCP_PAWS_WINDOW) && !tcp_disordered_ack(sk, skb); } /* Check segment sequence number for validity. * * Segment controls are considered valid, if the segment * fits to the window after truncation to the window. Acceptability * of data (and SYN, FIN, of course) is checked separately. * See tcp_data_queue(), for example. * * Also, controls (RST is main one) are accepted using RCV.WUP instead * of RCV.NXT. Peer still did not advance his SND.UNA when we * delayed ACK, so that hisSND.UNA<=ourRCV.WUP. * (borrowed from freebsd) */ static inline bool tcp_sequence(const struct tcp_sock *tp, u32 seq, u32 end_seq) { return !before(end_seq, tp->rcv_wup) && !after(seq, tp->rcv_nxt + tcp_receive_window(tp)); } /* When we get a reset we do this. */ void tcp_reset(struct sock *sk) { /* We want the right error as BSD sees it (and indeed as we do). */ switch (sk->sk_state) { case TCP_SYN_SENT: sk->sk_err = ECONNREFUSED; break; case TCP_CLOSE_WAIT: sk->sk_err = EPIPE; break; case TCP_CLOSE: return; default: sk->sk_err = ECONNRESET; } /* This barrier is coupled with smp_rmb() in tcp_poll() */ smp_wmb(); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_error_report(sk); tcp_done(sk); } /* * Process the FIN bit. This now behaves as it is supposed to work * and the FIN takes effect when it is validly part of sequence * space. Not before when we get holes. * * If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT * (and thence onto LAST-ACK and finally, CLOSE, we never enter * TIME-WAIT) * * If we are in FINWAIT-1, a received FIN indicates simultaneous * close and we go into CLOSING (and later onto TIME-WAIT) * * If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT. */ static void tcp_fin(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); <API key>(sk); sk->sk_shutdown |= RCV_SHUTDOWN; sock_set_flag(sk, SOCK_DONE); switch (sk->sk_state) { case TCP_SYN_RECV: case TCP_ESTABLISHED: /* Move to CLOSE_WAIT */ tcp_set_state(sk, TCP_CLOSE_WAIT); inet_csk(sk)->icsk_ack.pingpong = 1; break; case TCP_CLOSE_WAIT: case TCP_CLOSING: /* Received a retransmission of the FIN, do * nothing. */ break; case TCP_LAST_ACK: /* RFC793: Remain in the LAST-ACK state. */ break; case TCP_FIN_WAIT1: /* This case occurs when a simultaneous close * happens, we must ack the received FIN and * enter the CLOSING state. */ tcp_send_ack(sk); tcp_set_state(sk, TCP_CLOSING); break; case TCP_FIN_WAIT2: /* Received a FIN -- send ACK and enter TIME_WAIT. */ tcp_send_ack(sk); tcp_time_wait(sk, TCP_TIME_WAIT, 0); break; default: /* Only TCP_LISTEN and TCP_CLOSE are left, in these * cases we should never reach this piece of code. */ pr_err("%s: Impossible, sk->sk_state=%d\n", __func__, sk->sk_state); break; } /* It _is_ possible, that we have something out-of-order _after_ FIN. * Probably, we should reset in this case. For now drop them. */ __skb_queue_purge(&tp->out_of_order_queue); if (tcp_is_sack(tp)) tcp_sack_reset(&tp->rx_opt); sk_mem_reclaim(sk); if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); /* Do not send POLL_HUP for half duplex close. */ if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE) sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP); else sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); } } static inline bool tcp_sack_extend(struct tcp_sack_block *sp, u32 seq, u32 end_seq) { if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) { if (before(seq, sp->start_seq)) sp->start_seq = seq; if (after(end_seq, sp->end_seq)) sp->end_seq = end_seq; return true; } return false; } static void tcp_dsack_set(struct sock *sk, u32 seq, u32 end_seq) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_is_sack(tp) && sysctl_tcp_dsack) { int mib_idx; if (before(seq, tp->rcv_nxt)) mib_idx = <API key>; else mib_idx = <API key>; NET_INC_STATS_BH(sock_net(sk), mib_idx); tp->rx_opt.dsack = 1; tp->duplicate_sack[0].start_seq = seq; tp->duplicate_sack[0].end_seq = end_seq; } } static void tcp_dsack_extend(struct sock *sk, u32 seq, u32 end_seq) { struct tcp_sock *tp = tcp_sk(sk); if (!tp->rx_opt.dsack) tcp_dsack_set(sk, seq, end_seq); else tcp_sack_extend(tp->duplicate_sack, seq, end_seq); } static void tcp_send_dupack(struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) { NET_INC_STATS_BH(sock_net(sk), <API key>); <API key>(sk); if (tcp_is_sack(tp) && sysctl_tcp_dsack) { u32 end_seq = TCP_SKB_CB(skb)->end_seq; if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) end_seq = tp->rcv_nxt; tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, end_seq); } } tcp_send_ack(sk); } /* These routines update the SACK block as out-of-order packets arrive or * in-order packets close up the sequence space. */ static void <API key>(struct tcp_sock *tp) { int this_sack; struct tcp_sack_block *sp = &tp->selective_acks[0]; struct tcp_sack_block *swalk = sp + 1; /* See if the recent change to the first SACK eats into * or hits the sequence space of other SACK blocks, if so coalesce. */ for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) { if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) { int i; /* Zap SWALK, by moving every further SACK up by one slot. * Decrease num_sacks. */ tp->rx_opt.num_sacks for (i = this_sack; i < tp->rx_opt.num_sacks; i++) sp[i] = sp[i + 1]; continue; } this_sack++, swalk++; } } static void <API key>(struct sock *sk, u32 seq, u32 end_seq) { struct tcp_sock *tp = tcp_sk(sk); struct tcp_sack_block *sp = &tp->selective_acks[0]; int cur_sacks = tp->rx_opt.num_sacks; int this_sack; if (!cur_sacks) goto new_sack; for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) { if (tcp_sack_extend(sp, seq, end_seq)) { /* Rotate this_sack to the first one. */ for (; this_sack > 0; this_sack swap(*sp, *(sp - 1)); if (cur_sacks > 1) <API key>(tp); return; } } /* Could not find an adjacent existing SACK, build a new one, * put it at the front, and shift everyone else down. We * always know there is at least one SACK present already here. * * If the sack array is full, forget about the last one. */ if (this_sack >= TCP_NUM_SACKS) { this_sack tp->rx_opt.num_sacks sp } for (; this_sack > 0; this_sack *sp = *(sp - 1); new_sack: /* Build the new head SACK, and we're done. */ sp->start_seq = seq; sp->end_seq = end_seq; tp->rx_opt.num_sacks++; } /* RCV.NXT advances, some SACKs should be eaten. */ static void tcp_sack_remove(struct tcp_sock *tp) { struct tcp_sack_block *sp = &tp->selective_acks[0]; int num_sacks = tp->rx_opt.num_sacks; int this_sack; /* Empty ofo queue, hence, all the SACKs are eaten. Clear. */ if (skb_queue_empty(&tp->out_of_order_queue)) { tp->rx_opt.num_sacks = 0; return; } for (this_sack = 0; this_sack < num_sacks;) { /* Check if the start of the sack is covered by RCV.NXT. */ if (!before(tp->rcv_nxt, sp->start_seq)) { int i; /* RCV.NXT must cover all the block! */ WARN_ON(before(tp->rcv_nxt, sp->end_seq)); /* Zap this SACK, by moving forward any other SACKS. */ for (i=this_sack+1; i < num_sacks; i++) tp->selective_acks[i-1] = tp->selective_acks[i]; num_sacks continue; } this_sack++; sp++; } tp->rx_opt.num_sacks = num_sacks; } /* This one checks to see if we can put data from the * out_of_order queue into the receive_queue. */ static void tcp_ofo_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); __u32 dsack_high = tp->rcv_nxt; struct sk_buff *skb; while ((skb = skb_peek(&tp->out_of_order_queue)) != NULL) { if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) break; if (before(TCP_SKB_CB(skb)->seq, dsack_high)) { __u32 dsack = dsack_high; if (before(TCP_SKB_CB(skb)->end_seq, dsack_high)) dsack_high = TCP_SKB_CB(skb)->end_seq; tcp_dsack_extend(sk, TCP_SKB_CB(skb)->seq, dsack); } if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) { SOCK_DEBUG(sk, "ofo packet was already received\n"); __skb_unlink(skb, &tp->out_of_order_queue); __kfree_skb(skb); continue; } SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n", tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); __skb_unlink(skb, &tp->out_of_order_queue); __skb_queue_tail(&sk->sk_receive_queue, skb); tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq; if (tcp_hdr(skb)->fin) tcp_fin(sk); } } static bool tcp_prune_ofo_queue(struct sock *sk); static int tcp_prune_queue(struct sock *sk); static int <API key>(struct sock *sk, struct sk_buff *skb, unsigned int size) { if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf || !sk_rmem_schedule(sk, skb, size)) { if (tcp_prune_queue(sk) < 0) return -1; if (!sk_rmem_schedule(sk, skb, size)) { if (!tcp_prune_ofo_queue(sk)) return -1; if (!sk_rmem_schedule(sk, skb, size)) return -1; } } return 0; } /** * tcp_try_coalesce - try to merge skb to prior one * @sk: socket * @to: prior buffer * @from: buffer to add in queue * @fragstolen: pointer to boolean * * Before queueing skb @from after @to, try to merge them * to reduce overall memory use and queue lengths, if cost is small. * Packets in ofo or receive queues can stay a long time. * Better try to coalesce them right now to avoid future collapses. * Returns true if caller should free @from instead of queueing it */ static bool tcp_try_coalesce(struct sock *sk, struct sk_buff *to, struct sk_buff *from, bool *fragstolen) { int delta; *fragstolen = false; if (tcp_hdr(from)->fin) return false; /* Its possible this segment overlaps with prior segment in queue */ if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq) return false; if (!skb_try_coalesce(to, from, fragstolen, &delta)) return false; atomic_add(delta, &sk->sk_rmem_alloc); sk_mem_charge(sk, delta); NET_INC_STATS_BH(sock_net(sk), <API key>); TCP_SKB_CB(to)->end_seq = TCP_SKB_CB(from)->end_seq; TCP_SKB_CB(to)->ack_seq = TCP_SKB_CB(from)->ack_seq; return true; } static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb1; u32 seq, end_seq; TCP_ECN_check_ce(tp, skb); if (unlikely(<API key>(sk, skb, skb->truesize))) { NET_INC_STATS_BH(sock_net(sk), <API key>); __kfree_skb(skb); return; } /* Disable header prediction. */ tp->pred_flags = 0; <API key>(sk); NET_INC_STATS_BH(sock_net(sk), <API key>); SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n", tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); skb1 = skb_peek_tail(&tp->out_of_order_queue); if (!skb1) { /* Initial out of order segment, build 1 SACK. */ if (tcp_is_sack(tp)) { tp->rx_opt.num_sacks = 1; tp->selective_acks[0].start_seq = TCP_SKB_CB(skb)->seq; tp->selective_acks[0].end_seq = TCP_SKB_CB(skb)->end_seq; } __skb_queue_head(&tp->out_of_order_queue, skb); goto end; } seq = TCP_SKB_CB(skb)->seq; end_seq = TCP_SKB_CB(skb)->end_seq; if (seq == TCP_SKB_CB(skb1)->end_seq) { bool fragstolen; if (!tcp_try_coalesce(sk, skb1, skb, &fragstolen)) { __skb_queue_after(&tp->out_of_order_queue, skb1, skb); } else { kfree_skb_partial(skb, fragstolen); skb = NULL; } if (!tp->rx_opt.num_sacks || tp->selective_acks[0].end_seq != seq) goto add_sack; /* Common case: data arrive in order after hole. */ tp->selective_acks[0].end_seq = end_seq; goto end; } /* Find place to insert this segment. */ while (1) { if (!after(TCP_SKB_CB(skb1)->seq, seq)) break; if (skb_queue_is_first(&tp->out_of_order_queue, skb1)) { skb1 = NULL; break; } skb1 = skb_queue_prev(&tp->out_of_order_queue, skb1); } /* Do skb overlap to previous one? */ if (skb1 && before(seq, TCP_SKB_CB(skb1)->end_seq)) { if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) { /* All the bits are present. Drop. */ NET_INC_STATS_BH(sock_net(sk), <API key>); __kfree_skb(skb); skb = NULL; tcp_dsack_set(sk, seq, end_seq); goto add_sack; } if (after(seq, TCP_SKB_CB(skb1)->seq)) { /* Partial overlap. */ tcp_dsack_set(sk, seq, TCP_SKB_CB(skb1)->end_seq); } else { if (skb_queue_is_first(&tp->out_of_order_queue, skb1)) skb1 = NULL; else skb1 = skb_queue_prev( &tp->out_of_order_queue, skb1); } } if (!skb1) __skb_queue_head(&tp->out_of_order_queue, skb); else __skb_queue_after(&tp->out_of_order_queue, skb1, skb); /* And clean segments covered by new one as whole. */ while (!skb_queue_is_last(&tp->out_of_order_queue, skb)) { skb1 = skb_queue_next(&tp->out_of_order_queue, skb); if (!after(end_seq, TCP_SKB_CB(skb1)->seq)) break; if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) { tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq, end_seq); break; } __skb_unlink(skb1, &tp->out_of_order_queue); tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq, TCP_SKB_CB(skb1)->end_seq); NET_INC_STATS_BH(sock_net(sk), <API key>); __kfree_skb(skb1); } add_sack: if (tcp_is_sack(tp)) <API key>(sk, seq, end_seq); end: if (skb) skb_set_owner_r(skb, sk); } static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, int hdrlen, bool *fragstolen) { int eaten; struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue); __skb_pull(skb, hdrlen); eaten = (tail && tcp_try_coalesce(sk, tail, skb, fragstolen)) ? 1 : 0; tcp_sk(sk)->rcv_nxt = TCP_SKB_CB(skb)->end_seq; if (!eaten) { __skb_queue_tail(&sk->sk_receive_queue, skb); skb_set_owner_r(skb, sk); } return eaten; } int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size) { struct sk_buff *skb = NULL; struct tcphdr *th; bool fragstolen; if (size == 0) return 0; skb = alloc_skb(size + sizeof(*th), sk->sk_allocation); if (!skb) goto err; if (<API key>(sk, skb, size + sizeof(*th))) goto err_free; th = (struct tcphdr *)skb_put(skb, sizeof(*th)); <API key>(skb); memset(th, 0, sizeof(*th)); if (memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size)) goto err_free; TCP_SKB_CB(skb)->seq = tcp_sk(sk)->rcv_nxt; TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size; TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1; if (tcp_queue_rcv(sk, skb, sizeof(*th), &fragstolen)) { WARN_ON_ONCE(fragstolen); /* should not happen */ __kfree_skb(skb); } return size; err_free: kfree_skb(skb); err: return -ENOMEM; } static void tcp_data_queue(struct sock *sk, struct sk_buff *skb) { const struct tcphdr *th = tcp_hdr(skb); struct tcp_sock *tp = tcp_sk(sk); int eaten = -1; bool fragstolen = false; if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) goto drop; skb_dst_drop(skb); __skb_pull(skb, th->doff * 4); TCP_ECN_accept_cwr(tp, skb); tp->rx_opt.dsack = 0; /* Queue data for delivery to the user. * Packets in sequence go to the receive queue. * Out of sequence packets to the out_of_order_queue. */ if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) { if (tcp_receive_window(tp) == 0) goto out_of_window; /* Ok. In sequence. In window. */ if (tp->ucopy.task == current && tp->copied_seq == tp->rcv_nxt && tp->ucopy.len && sock_owned_by_user(sk) && !tp->urg_data) { int chunk = min_t(unsigned int, skb->len, tp->ucopy.len); __set_current_state(TASK_RUNNING); local_bh_enable(); if (!<API key>(skb, 0, tp->ucopy.iov, chunk)) { tp->ucopy.len -= chunk; tp->copied_seq += chunk; eaten = (chunk == skb->len); <API key>(sk); } local_bh_disable(); } if (eaten <= 0) { queue_and_out: if (eaten < 0 && <API key>(sk, skb, skb->truesize)) goto drop; eaten = tcp_queue_rcv(sk, skb, 0, &fragstolen); } tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq; if (skb->len) tcp_event_data_recv(sk, skb); if (th->fin) tcp_fin(sk); if (!skb_queue_empty(&tp->out_of_order_queue)) { tcp_ofo_queue(sk); /* RFC2581. 4.2. SHOULD send immediate ACK, when * gap in queue is filled. */ if (skb_queue_empty(&tp->out_of_order_queue)) inet_csk(sk)->icsk_ack.pingpong = 0; } if (tp->rx_opt.num_sacks) tcp_sack_remove(tp); tcp_fast_path_check(sk); if (eaten > 0) kfree_skb_partial(skb, fragstolen); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, 0); return; } if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) { /* A retransmit, 2nd most common case. Force an immediate ack. */ NET_INC_STATS_BH(sock_net(sk), <API key>); tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); out_of_window: <API key>(sk); <API key>(sk); drop: __kfree_skb(skb); return; } /* Out of window. F.e. zero window probe. */ if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt + tcp_receive_window(tp))) goto out_of_window; <API key>(sk); if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) { /* Partial packet, seq < rcv_next < end_seq */ SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n", tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, tp->rcv_nxt); /* If window is closed, drop tail of packet. But after * remembering D-SACK for its head made in previous line. */ if (!tcp_receive_window(tp)) goto out_of_window; goto queue_and_out; } tcp_data_queue_ofo(sk, skb); } static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb, struct sk_buff_head *list) { struct sk_buff *next = NULL; if (!skb_queue_is_last(list, skb)) next = skb_queue_next(list, skb); __skb_unlink(skb, list); __kfree_skb(skb); NET_INC_STATS_BH(sock_net(sk), <API key>); return next; } /* Collapse contiguous sequence of skbs head..tail with * sequence numbers start..end. * * If tail is NULL, this means until the end of the list. * * Segments with FIN/SYN are not collapsed (only because this * simplifies code) */ static void tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct sk_buff *head, struct sk_buff *tail, u32 start, u32 end) { struct sk_buff *skb, *n; bool end_of_skbs; /* First, check that queue is collapsible and find * the point where collapsing can be useful. */ skb = head; restart: end_of_skbs = true; <API key>(list, skb, n) { if (skb == tail) break; /* No new bits? It is possible on ofo queue. */ if (!before(start, TCP_SKB_CB(skb)->end_seq)) { skb = tcp_collapse_one(sk, skb, list); if (!skb) break; goto restart; } /* The first skb to collapse is: * - not SYN/FIN and * - bloated or contains data before "start" or * overlaps to the next one. */ if (!tcp_hdr(skb)->syn && !tcp_hdr(skb)->fin && (tcp_win_from_space(skb->truesize) > skb->len || before(TCP_SKB_CB(skb)->seq, start))) { end_of_skbs = false; break; } if (!skb_queue_is_last(list, skb)) { struct sk_buff *next = skb_queue_next(list, skb); if (next != tail && TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(next)->seq) { end_of_skbs = false; break; } } /* Decided to skip this, advance start seq. */ start = TCP_SKB_CB(skb)->end_seq; } if (end_of_skbs || tcp_hdr(skb)->syn || tcp_hdr(skb)->fin) return; while (before(start, end)) { struct sk_buff *nskb; unsigned int header = skb_headroom(skb); int copy = SKB_MAX_ORDER(header, 0); /* Too big header? This can happen with IPv6. */ if (copy < 0) return; if (end - start < copy) copy = end - start; nskb = alloc_skb(copy + header, GFP_ATOMIC); if (!nskb) return; skb_set_mac_header(nskb, skb_mac_header(skb) - skb->head); <API key>(nskb, (skb_network_header(skb) - skb->head)); <API key>(nskb, (<API key>(skb) - skb->head)); skb_reserve(nskb, header); memcpy(nskb->head, skb->head, header); memcpy(nskb->cb, skb->cb, sizeof(skb->cb)); TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start; __skb_queue_before(list, skb, nskb); skb_set_owner_r(nskb, sk); /* Copy data, releasing collapsed skbs. */ while (copy > 0) { int offset = start - TCP_SKB_CB(skb)->seq; int size = TCP_SKB_CB(skb)->end_seq - start; BUG_ON(offset < 0); if (size > 0) { size = min(copy, size); if (skb_copy_bits(skb, offset, skb_put(nskb, size), size)) BUG(); TCP_SKB_CB(nskb)->end_seq += size; copy -= size; start += size; } if (!before(start, TCP_SKB_CB(skb)->end_seq)) { skb = tcp_collapse_one(sk, skb, list); if (!skb || skb == tail || tcp_hdr(skb)->syn || tcp_hdr(skb)->fin) return; } } } } /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs * and tcp_collapse() them until all the queue is collapsed. */ static void <API key>(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb = skb_peek(&tp->out_of_order_queue); struct sk_buff *head; u32 start, end; if (skb == NULL) return; start = TCP_SKB_CB(skb)->seq; end = TCP_SKB_CB(skb)->end_seq; head = skb; for (;;) { struct sk_buff *next = NULL; if (!skb_queue_is_last(&tp->out_of_order_queue, skb)) next = skb_queue_next(&tp->out_of_order_queue, skb); skb = next; /* Segment is terminated when we see gap or when * we are at the end of all the queue. */ if (!skb || after(TCP_SKB_CB(skb)->seq, end) || before(TCP_SKB_CB(skb)->end_seq, start)) { tcp_collapse(sk, &tp->out_of_order_queue, head, skb, start, end); head = skb; if (!skb) break; /* Start new segment */ start = TCP_SKB_CB(skb)->seq; end = TCP_SKB_CB(skb)->end_seq; } else { if (before(TCP_SKB_CB(skb)->seq, start)) start = TCP_SKB_CB(skb)->seq; if (after(TCP_SKB_CB(skb)->end_seq, end)) end = TCP_SKB_CB(skb)->end_seq; } } } /* * Purge the out-of-order queue. * Return true if queue was pruned. */ static bool tcp_prune_ofo_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); bool res = false; if (!skb_queue_empty(&tp->out_of_order_queue)) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_OFOPRUNED); __skb_queue_purge(&tp->out_of_order_queue); /* Reset SACK state. A conforming SACK implementation will * do the same at a timeout based retransmit. When a connection * is in a sad state like this, we care only about integrity * of the connection not performance. */ if (tp->rx_opt.sack_ok) tcp_sack_reset(&tp->rx_opt); sk_mem_reclaim(sk); res = true; } return res; } /* Reduce allocated memory if we can, trying to get * the socket within its memory limits again. * * Return less than zero if we should start dropping frames * until the socket owning process reads some of the data * to stabilize the situation. */ static int tcp_prune_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq); NET_INC_STATS_BH(sock_net(sk), <API key>); if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) tcp_clamp_window(sk); else if (<API key>(sk)) tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss); <API key>(sk); if (!skb_queue_empty(&sk->sk_receive_queue)) tcp_collapse(sk, &sk->sk_receive_queue, skb_peek(&sk->sk_receive_queue), NULL, tp->copied_seq, tp->rcv_nxt); sk_mem_reclaim(sk); if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) return 0; /* Collapsing did not help, destructive actions follow. * This must not ever occur. */ tcp_prune_ofo_queue(sk); if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) return 0; /* If we are really being abused, tell the caller to silently * drop receive data on the floor. It will get retransmitted * and hopefully then we'll have sufficient space. */ NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_RCVPRUNED); /* Massive buffer overcommit. */ tp->pred_flags = 0; return -1; } /* RFC2861, slow part. Adjust cwnd, after it was not full during one rto. * As additional protections, we do not touch cwnd in retransmission phases, * and if application hit its sndbuf limit recently. */ void <API key>(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (inet_csk(sk)->icsk_ca_state == TCP_CA_Open && sk->sk_socket && !test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { /* Limited by application or receiver window. */ u32 init_win = tcp_init_cwnd(tp, __sk_dst_get(sk)); u32 win_used = max(tp->snd_cwnd_used, init_win); if (win_used < tp->snd_cwnd) { tp->snd_ssthresh = <API key>(sk); tp->snd_cwnd = (tp->snd_cwnd + win_used) >> 1; } tp->snd_cwnd_used = 0; } tp->snd_cwnd_stamp = tcp_time_stamp; } static bool <API key>(const struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); /* If the user specified a specific send buffer setting, do * not modify it. */ if (sk->sk_userlocks & SOCK_SNDBUF_LOCK) return false; /* If we are under global TCP memory pressure, do not expand. */ if (<API key>(sk)) return false; /* If we are under soft global TCP memory pressure, do not expand. */ if (sk_memory_allocated(sk) >= sk_prot_mem_limits(sk, 0)) return false; /* If we filled the congestion window, do not expand. */ if (tp->packets_out >= tp->snd_cwnd) return false; return true; } /* When incoming ACK allowed to free some skb from write_queue, * we remember this event in flag SOCK_QUEUE_SHRUNK and wake up socket * on the exit from tcp input handler. * * PROBLEM: sndbuf expansion does not work well with largesend. */ static void tcp_new_space(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (<API key>(sk)) { int sndmem = SKB_TRUESIZE(max_t(u32, tp->rx_opt.mss_clamp, tp->mss_cache) + MAX_TCP_HEADER); int demanded = max_t(unsigned int, tp->snd_cwnd, tp->reordering + 1); sndmem *= 2 * demanded; if (sndmem > sk->sk_sndbuf) sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]); tp->snd_cwnd_stamp = tcp_time_stamp; } sk->sk_write_space(sk); } static void tcp_check_space(struct sock *sk) { if (sock_flag(sk, SOCK_QUEUE_SHRUNK)) { sock_reset_flag(sk, SOCK_QUEUE_SHRUNK); if (sk->sk_socket && test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) tcp_new_space(sk); } } static inline void tcp_data_snd_check(struct sock *sk) { <API key>(sk); tcp_check_space(sk); } /* * Check if sending an ack is needed. */ static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible) { struct tcp_sock *tp = tcp_sk(sk); /* More than one full frame received... */ if (((tp->rcv_nxt - tp->rcv_wup) > (inet_csk(sk)->icsk_ack.rcv_mss) * <API key> && /* ... and right edge of window advances far enough. * (tcp_recvmsg() will send ACK otherwise). Or... */ __tcp_select_window(sk) >= tp->rcv_wnd) || /* We ACK each frame or... */ <API key>(sk) || /* We have out of order data. */ (ofo_possible && skb_peek(&tp->out_of_order_queue))) { /* Then ack it now */ tcp_send_ack(sk); } else { /* Else, send delayed ack. */ <API key>(sk); } } static inline void tcp_ack_snd_check(struct sock *sk) { if (!<API key>(sk)) { /* We sent a data segment already. */ return; } __tcp_ack_snd_check(sk, 1); } /* * This routine is only called when we have urgent data * signaled. Its the 'slow' part of tcp_urg. It could be * moved inline now as tcp_urg is only called from one * place. We handle URGent data wrong. We have to - as * BSD still doesn't use the correction from RFC961. * For 1003.1g we should support a new option TCP_STDURG to permit * either form (or just set the sysctl tcp_stdurg). */ static void tcp_check_urg(struct sock *sk, const struct tcphdr *th) { struct tcp_sock *tp = tcp_sk(sk); u32 ptr = ntohs(th->urg_ptr); if (ptr && !sysctl_tcp_stdurg) ptr ptr += ntohl(th->seq); /* Ignore urgent data that we've already seen and read. */ if (after(tp->copied_seq, ptr)) return; /* Do not replay urg ptr. * * NOTE: interesting situation not covered by specs. * Misbehaving sender may send urg ptr, pointing to segment, * which we already have in ofo queue. We are not able to fetch * such data and will stay in TCP_URG_NOTYET until will be eaten * by recvmsg(). Seems, we are not obliged to handle such wicked * situations. But it is worth to think about possibility of some * DoSes using some hypothetical application level deadlock. */ if (before(ptr, tp->rcv_nxt)) return; /* Do we already have a newer (or duplicate) urgent pointer? */ if (tp->urg_data && !after(ptr, tp->urg_seq)) return; /* Tell the world about our new urgent pointer. */ sk_send_sigurg(sk); /* We may be adding urgent data when the last byte read was * urgent. To do this requires some care. We cannot just ignore * tp->copied_seq since we would read the last urgent byte again * as data, nor can we alter copied_seq until this data arrives * or we break the semantics of SIOCATMARK (and thus sockatmark()) * * NOTE. Double Dutch. Rendering to plain English: author of comment * above did something sort of send("A", MSG_OOB); send("B", MSG_OOB); * and expect that both A and B disappear from stream. This is _wrong_. * Though this happens in BSD with high probability, this is occasional. * Any application relying on this is buggy. Note also, that fix "works" * only in this artificial test. Insert some normal data between A and B and we will * decline of BSD again. Verdict: it is better to remove to trap * buggy users. */ if (tp->urg_seq == tp->copied_seq && tp->urg_data && !sock_flag(sk, SOCK_URGINLINE) && tp->copied_seq != tp->rcv_nxt) { struct sk_buff *skb = skb_peek(&sk->sk_receive_queue); tp->copied_seq++; if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) { __skb_unlink(skb, &sk->sk_receive_queue); __kfree_skb(skb); } } tp->urg_data = TCP_URG_NOTYET; tp->urg_seq = ptr; /* Disable header prediction. */ tp->pred_flags = 0; } /* This is the 'fast' part of urgent handling. */ static void tcp_urg(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th) { struct tcp_sock *tp = tcp_sk(sk); /* Check if we get a new urgent pointer - normally not. */ if (th->urg) tcp_check_urg(sk, th); /* Do we wait for any urgent data? - normally not... */ if (tp->urg_data == TCP_URG_NOTYET) { u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) - th->syn; /* Is the urgent pointer pointing into this packet? */ if (ptr < skb->len) { u8 tmp; if (skb_copy_bits(skb, ptr, &tmp, 1)) BUG(); tp->urg_data = TCP_URG_VALID | tmp; if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, 0); } } } static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen) { struct tcp_sock *tp = tcp_sk(sk); int chunk = skb->len - hlen; int err; local_bh_enable(); if (<API key>(skb)) err = <API key>(skb, hlen, tp->ucopy.iov, chunk); else err = <API key>(skb, hlen, tp->ucopy.iov); if (!err) { tp->ucopy.len -= chunk; tp->copied_seq += chunk; <API key>(sk); } local_bh_disable(); return err; } static __sum16 <API key>(struct sock *sk, struct sk_buff *skb) { __sum16 result; if (sock_owned_by_user(sk)) { local_bh_enable(); result = <API key>(skb); local_bh_disable(); } else { result = <API key>(skb); } return result; } static inline bool <API key>(struct sock *sk, struct sk_buff *skb) { return !<API key>(skb) && <API key>(sk, skb); } #ifdef CONFIG_NET_DMA static bool <API key>(struct sock *sk, struct sk_buff *skb, int hlen) { struct tcp_sock *tp = tcp_sk(sk); int chunk = skb->len - hlen; int dma_cookie; bool copied_early = false; if (tp->ucopy.wakeup) return false; if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list) tp->ucopy.dma_chan = <API key>(); if (tp->ucopy.dma_chan && <API key>(skb)) { dma_cookie = <API key>(tp->ucopy.dma_chan, skb, hlen, tp->ucopy.iov, chunk, tp->ucopy.pinned_list); if (dma_cookie < 0) goto out; tp->ucopy.dma_cookie = dma_cookie; copied_early = true; tp->ucopy.len -= chunk; tp->copied_seq += chunk; <API key>(sk); if ((tp->ucopy.len == 0) || (tcp_flag_word(tcp_hdr(skb)) & TCP_FLAG_PSH) || (atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1))) { tp->ucopy.wakeup = 1; sk->sk_data_ready(sk, 0); } } else if (chunk > 0) { tp->ucopy.wakeup = 1; sk->sk_data_ready(sk, 0); } out: return copied_early; } #endif /* CONFIG_NET_DMA */ /* Does PAWS and seqno based validation of an incoming segment, flags will * play significant role here. */ static bool <API key>(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, int syn_inerr) { struct tcp_sock *tp = tcp_sk(sk); /* RFC1323: H1. Apply PAWS check first. */ if (<API key>(skb, th, tp) && tp->rx_opt.saw_tstamp && tcp_paws_discard(sk, skb)) { if (!th->rst) { NET_INC_STATS_BH(sock_net(sk), <API key>); tcp_send_dupack(sk, skb); goto discard; } /* Reset is accepted even if it did not pass PAWS. */ } /* Step 1: check sequence number */ if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) { /* RFC793, page 37: "In all states except SYN-SENT, all reset * (RST) segments are validated by checking their SEQ-fields." * And page 69: "If an incoming segment is not acceptable, * an acknowledgment should be sent in reply (unless the RST * bit is set, if so drop the segment and return)". */ if (!th->rst) { if (th->syn) goto syn_challenge; tcp_send_dupack(sk, skb); } goto discard; } /* Step 2: check RST bit */ if (th->rst) { /* RFC 5961 3.2 : * If sequence number exactly matches RCV.NXT, then * RESET the connection * else * Send a challenge ACK */ if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) tcp_reset(sk); else <API key>(sk); goto discard; } /* step 3: check security and precedence [ignored] */ /* step 4: Check for a SYN * RFC 5691 4.2 : Send a challenge ack */ if (th->syn) { syn_challenge: if (syn_inerr) TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS); NET_INC_STATS_BH(sock_net(sk), <API key>); <API key>(sk); goto discard; } return true; discard: __kfree_skb(skb); return false; } /* * TCP receive function for the ESTABLISHED state. * * It is split into a fast path and a slow path. The fast path is * disabled when: * - A zero window was announced from us - zero window probing * is only handled properly in the slow path. * - Out of order segments arrived. * - Urgent data is expected. * - There is no buffer space left * - Unexpected TCP flags/window values/header lengths are received * (detected by checking the TCP header against pred_flags) * - Data is sent in both directions. Fast path only supports pure senders * or pure receivers (this means either the sequence number or the ack * value must stay constant) * - Unexpected TCP option. * * When these conditions are not satisfied it drops into a standard * receive procedure patterned after RFC793 to handle all cases. * The first three cases are guaranteed by proper pred_flags setting, * the rest is checked inline. Fast processing is turned on in * tcp_data_queue when everything is OK. */ int tcp_rcv_established(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, unsigned int len) { struct tcp_sock *tp = tcp_sk(sk); if (unlikely(sk->sk_rx_dst == NULL)) inet_csk(sk)->icsk_af_ops->sk_rx_dst_set(sk, skb); /* * Header prediction. * The code loosely follows the one in the famous * "30 instruction TCP receive" Van Jacobson mail. * * Van's trick is to deposit buffers into socket queue * on a device interrupt, to call tcp_recv function * on the receive process context and checksum and copy * the buffer to user space. smart... * * Our current scheme is not silly either but we take the * extra cost of the net_bh soft interrupt processing... * We do checksum and copy also but from device to kernel. */ tp->rx_opt.saw_tstamp = 0; /* pred_flags is 0xS?10 << 16 + snd_wnd * if header_prediction is to be made * 'S' will always be tp->tcp_header_len >> 2 * '?' will be 0 for the fast path, otherwise pred_flags is 0 to * turn it off (when there are holes in the receive * space for instance) * PSH flag is ignored. */ if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags && TCP_SKB_CB(skb)->seq == tp->rcv_nxt && !after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) { int tcp_header_len = tp->tcp_header_len; /* Timestamp header prediction: tcp_header_len * is automatically equal to th->doff*4 due to pred_flags * match. */ /* Check timestamp */ if (tcp_header_len == sizeof(struct tcphdr) + <API key>) { /* No? Slow path! */ if (!<API key>(tp, th)) goto slow_path; /* If PAWS failed, check it more carefully in slow path */ if ((s32)(tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent) < 0) goto slow_path; /* DO NOT update ts_recent here, if checksum fails * and timestamp was corrupted part, it will result * in a hung connection since we will drop all * future packets due to the PAWS test. */ } if (len <= tcp_header_len) { /* Bulk data transfer: sender */ if (len == tcp_header_len) { /* Predicted packet is in window by definition. * seq == rcv_nxt and rcv_wup <= rcv_nxt. * Hence, check seq<=rcv_wup reduces to: */ if (tcp_header_len == (sizeof(struct tcphdr) + <API key>) && tp->rcv_nxt == tp->rcv_wup) tcp_store_ts_recent(tp); /* We know that such packets are checksummed * on entry. */ tcp_ack(sk, skb, 0); __kfree_skb(skb); tcp_data_snd_check(sk); return 0; } else { /* Header too small */ TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS); goto discard; } } else { int eaten = 0; int copied_early = 0; bool fragstolen = false; if (tp->copied_seq == tp->rcv_nxt && len - tcp_header_len <= tp->ucopy.len) { #ifdef CONFIG_NET_DMA if (tp->ucopy.task == current && sock_owned_by_user(sk) && <API key>(sk, skb, tcp_header_len)) { copied_early = 1; eaten = 1; } #endif if (tp->ucopy.task == current && sock_owned_by_user(sk) && !copied_early) { __set_current_state(TASK_RUNNING); if (!tcp_copy_to_iovec(sk, skb, tcp_header_len)) eaten = 1; } if (eaten) { /* Predicted packet is in window by definition. * seq == rcv_nxt and rcv_wup <= rcv_nxt. * Hence, check seq<=rcv_wup reduces to: */ if (tcp_header_len == (sizeof(struct tcphdr) + <API key>) && tp->rcv_nxt == tp->rcv_wup) tcp_store_ts_recent(tp); <API key>(sk, skb); __skb_pull(skb, tcp_header_len); tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq; NET_INC_STATS_BH(sock_net(sk), <API key>); } if (copied_early) tcp_cleanup_rbuf(sk, skb->len); } if (!eaten) { if (<API key>(sk, skb)) goto csum_error; if ((int)skb->truesize > sk->sk_forward_alloc) goto step5; /* Predicted packet is in window by definition. * seq == rcv_nxt and rcv_wup <= rcv_nxt. * Hence, check seq<=rcv_wup reduces to: */ if (tcp_header_len == (sizeof(struct tcphdr) + <API key>) && tp->rcv_nxt == tp->rcv_wup) tcp_store_ts_recent(tp); <API key>(sk, skb); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPHITS); /* Bulk data transfer: receiver */ eaten = tcp_queue_rcv(sk, skb, tcp_header_len, &fragstolen); } tcp_event_data_recv(sk, skb); if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) { /* Well, only one small jumplet in fast path... */ tcp_ack(sk, skb, FLAG_DATA); tcp_data_snd_check(sk); if (!<API key>(sk)) goto no_ack; } if (!copied_early || tp->rcv_nxt != tp->rcv_wup) __tcp_ack_snd_check(sk, 0); no_ack: #ifdef CONFIG_NET_DMA if (copied_early) __skb_queue_tail(&sk->sk_async_wait_queue, skb); else #endif if (eaten) kfree_skb_partial(skb, fragstolen); sk->sk_data_ready(sk, 0); return 0; } } slow_path: if (len < (th->doff << 2) || <API key>(sk, skb)) goto csum_error; if (!th->ack && !th->rst && !th->syn) goto discard; /* * Standard slow path. */ if (!<API key>(sk, skb, th, 1)) return 0; step5: if (tcp_ack(sk, skb, FLAG_SLOWPATH | <API key>) < 0) goto discard; <API key>(sk, skb); /* Process urgent data. */ tcp_urg(sk, skb, th); /* step 7: process the segment text */ tcp_data_queue(sk, skb); tcp_data_snd_check(sk); tcp_ack_snd_check(sk); return 0; csum_error: TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_CSUMERRORS); TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS); discard: __kfree_skb(skb); return 0; } EXPORT_SYMBOL(tcp_rcv_established); void tcp_finish_connect(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct <API key> *icsk = inet_csk(sk); tcp_set_state(sk, TCP_ESTABLISHED); if (skb != NULL) { icsk->icsk_af_ops->sk_rx_dst_set(sk, skb); <API key>(sk, skb); } /* Make sure socket is routed, for correct metrics. */ icsk->icsk_af_ops->rebuild_header(sk); tcp_init_metrics(sk); <API key>(sk); /* Prevent spurious tcp_cwnd_restart() on first data * packet. */ tp->lsndtime = tcp_time_stamp; <API key>(sk); if (sock_flag(sk, SOCK_KEEPOPEN)) <API key>(sk, keepalive_time_when(tp)); if (!tp->rx_opt.snd_wscale) __tcp_fast_path_on(tp, tp->snd_wnd); else tp->pred_flags = 0; if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); } } static bool <API key>(struct sock *sk, struct sk_buff *synack, struct tcp_fastopen_cookie *cookie) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *data = tp->syn_data ? <API key>(sk) : NULL; u16 mss = tp->rx_opt.mss_clamp; bool syn_drop; if (mss == tp->rx_opt.user_mss) { struct <API key> opt; /* Get original SYNACK MSS value if user MSS sets mss_clamp */ tcp_clear_options(&opt); opt.user_mss = opt.mss_clamp = 0; tcp_parse_options(synack, &opt, 0, NULL); mss = opt.mss_clamp; } if (!tp->syn_fastopen) /* Ignore an unsolicited cookie */ cookie->len = -1; /* The SYN-ACK neither has cookie nor acknowledges the data. Presumably * the remote receives only the retransmitted (regular) SYNs: either * the original SYN-data or the corresponding SYN-ACK is lost. */ syn_drop = (cookie->len <= 0 && data && tp->total_retrans); <API key>(sk, mss, cookie, syn_drop); if (data) { /* Retransmit unacked data in SYN */ <API key>(data, sk) { if (data == tcp_send_head(sk) || <API key>(sk, data)) break; } tcp_rearm_rto(sk); return true; } tp->syn_data_acked = tp->syn_data; return false; } static int <API key>(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, unsigned int len) { struct <API key> *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct tcp_fastopen_cookie foc = { .len = -1 }; int saved_clamp = tp->rx_opt.mss_clamp; tcp_parse_options(skb, &tp->rx_opt, 0, &foc); if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr) tp->rx_opt.rcv_tsecr -= tp->tsoffset; if (th->ack) { /* rfc793: * "If the state is SYN-SENT then * first check the ACK bit * If the ACK bit is set * If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send * a reset (unless the RST bit is set, if so drop * the segment and return)" */ if (!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_una) || after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) goto reset_and_undo; if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr && !between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp, tcp_time_stamp)) { NET_INC_STATS_BH(sock_net(sk), <API key>); goto reset_and_undo; } /* Now ACK is acceptable. * * "If the RST bit is set * If the ACK was acceptable then signal the user "error: * connection reset", drop the segment, enter CLOSED state, * delete TCB, and return." */ if (th->rst) { tcp_reset(sk); goto discard; } /* rfc793: * "fifth, if neither of the SYN or RST bits is set then * drop the segment and return." * * See note below! * --ANK(990513) */ if (!th->syn) goto discard_and_undo; /* rfc793: * "If the SYN bit is on ... * are acceptable then ... * (our SYN has been ACKed), change the connection * state to ESTABLISHED..." */ TCP_ECN_rcv_synack(tp, th); tcp_init_wl(tp, TCP_SKB_CB(skb)->seq); tcp_ack(sk, skb, FLAG_SLOWPATH); /* Ok.. it's good. Set up sequence numbers and * move to established. */ tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1; tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1; /* RFC1323: The window in SYN & SYN/ACK segments is * never scaled. */ tp->snd_wnd = ntohs(th->window); if (!tp->rx_opt.wscale_ok) { tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0; tp->window_clamp = min(tp->window_clamp, 65535U); } if (tp->rx_opt.saw_tstamp) { tp->rx_opt.tstamp_ok = 1; tp->tcp_header_len = sizeof(struct tcphdr) + <API key>; tp->advmss -= <API key>; tcp_store_ts_recent(tp); } else { tp->tcp_header_len = sizeof(struct tcphdr); } if (tcp_is_sack(tp) && sysctl_tcp_fack) tcp_enable_fack(tp); tcp_mtup_init(sk); tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); <API key>(sk); /* Remember, tcp_poll() does not lock socket! * Change state from SYN-SENT only after copied_seq * is initialized. */ tp->copied_seq = tp->rcv_nxt; smp_mb(); tcp_finish_connect(sk, skb); if ((tp->syn_fastopen || tp->syn_data) && <API key>(sk, skb, &foc)) return -1; if (sk->sk_write_pending || icsk->icsk_accept_queue.rskq_defer_accept || icsk->icsk_ack.pingpong) { /* Save one ACK. Data will be ready after * several ticks, if write_pending is set. * * It may be deleted, but with this feature tcpdumps * look so _wonderfully_ clever, that I was not able * to stand against the temptation 8) --ANK */ <API key>(sk); icsk->icsk_ack.lrcvtime = tcp_time_stamp; <API key>(sk); <API key>(sk, ICSK_TIME_DACK, TCP_DELACK_MAX, TCP_RTO_MAX); discard: __kfree_skb(skb); return 0; } else { tcp_send_ack(sk); } return -1; } /* No ACK in the segment */ if (th->rst) { /* rfc793: * "If the RST bit is set * * Otherwise (no ACK) drop the segment and return." */ goto discard_and_undo; } /* PAWS check. */ if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp && tcp_paws_reject(&tp->rx_opt, 0)) goto discard_and_undo; if (th->syn) { /* We see SYN without ACK. It is attempt of * simultaneous connect with crossed SYNs. * Particularly, it can be connect to self. */ tcp_set_state(sk, TCP_SYN_RECV); if (tp->rx_opt.saw_tstamp) { tp->rx_opt.tstamp_ok = 1; tcp_store_ts_recent(tp); tp->tcp_header_len = sizeof(struct tcphdr) + <API key>; } else { tp->tcp_header_len = sizeof(struct tcphdr); } tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1; tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1; /* RFC1323: The window in SYN & SYN/ACK segments is * never scaled. */ tp->snd_wnd = ntohs(th->window); tp->snd_wl1 = TCP_SKB_CB(skb)->seq; tp->max_window = tp->snd_wnd; TCP_ECN_rcv_syn(tp, th); tcp_mtup_init(sk); tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); <API key>(sk); tcp_send_synack(sk); #if 0 /* Note, we could accept data and URG from this segment. * There are no obstacles to make this (except that we must * either change tcp_recvmsg() to prevent it from returning data * before 3WHS completes per RFC793, or employ TCP Fast Open). * * However, if we ignore data in ACKless segments sometimes, * we have no reasons to accept it sometimes. * Also, seems the code doing it in step6 of <API key> * is not flawless. So, discard packet for sanity. * Uncomment this return to process the data. */ return -1; #else goto discard; #endif } /* "fifth, if neither of the SYN or RST bits is set then * drop the segment and return." */ discard_and_undo: tcp_clear_options(&tp->rx_opt); tp->rx_opt.mss_clamp = saved_clamp; goto discard; reset_and_undo: tcp_clear_options(&tp->rx_opt); tp->rx_opt.mss_clamp = saved_clamp; return 1; } /* * This function implements the receiving procedure of RFC 793 for * all states except ESTABLISHED and TIME_WAIT. * It's called from both tcp_v4_rcv and tcp_v6_rcv and should be * address independent. */ int <API key>(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, unsigned int len) { struct tcp_sock *tp = tcp_sk(sk); struct <API key> *icsk = inet_csk(sk); struct request_sock *req; int queued = 0; tp->rx_opt.saw_tstamp = 0; switch (sk->sk_state) { case TCP_CLOSE: goto discard; case TCP_LISTEN: if (th->ack) return 1; if (th->rst) goto discard; if (th->syn) { if (th->fin) goto discard; if (icsk->icsk_af_ops->conn_request(sk, skb) < 0) return 1; /* Now we have several options: In theory there is * nothing else in the frame. KA9Q has an option to * send data with the syn, BSD accepts data with the * syn up to the [to be] advertised window and * Solaris 2.1 gives you a protocol error. For now * we just ignore it, that fits the spec precisely * and avoids incompatibilities. It would be nice in * future to drop through and process the data. * * Now that TTCP is starting to be used we ought to * queue this data. * But, this leaves one open to an easy denial of * service attack, and SYN cookies can't defend * against this problem. So, we drop the data * in the interest of security over speed unless * it's still in use. */ kfree_skb(skb); return 0; } goto discard; case TCP_SYN_SENT: queued = <API key>(sk, skb, th, len); if (queued >= 0) return queued; /* Do step6 onward by hand. */ tcp_urg(sk, skb, th); __kfree_skb(skb); tcp_data_snd_check(sk); return 0; } req = tp->fastopen_rsk; if (req != NULL) { WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV && sk->sk_state != TCP_FIN_WAIT1); if (tcp_check_req(sk, skb, req, NULL, true) == NULL) goto discard; } if (!th->ack && !th->rst && !th->syn) goto discard; if (!<API key>(sk, skb, th, 0)) return 0; /* step 5: check the ACK field */ if (true) { int acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH | <API key>) > 0; switch (sk->sk_state) { case TCP_SYN_RECV: if (acceptable) { /* Once we leave TCP_SYN_RECV, we no longer * need req so release it. */ if (req) { tcp_synack_rtt_meas(sk, req); tp->total_retrans = req->num_retrans; <API key>(sk, req, false); } else { /* Make sure socket is routed, for * correct metrics. */ icsk->icsk_af_ops->rebuild_header(sk); <API key>(sk); tcp_mtup_init(sk); <API key>(sk); tp->copied_seq = tp->rcv_nxt; } smp_mb(); tcp_set_state(sk, TCP_ESTABLISHED); sk->sk_state_change(sk); /* Note, that this wakeup is only for marginal * crossed SYN case. Passively open sockets * are not waked up, because sk->sk_sleep == * NULL and sk->sk_socket == NULL. */ if (sk->sk_socket) sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); tp->snd_una = TCP_SKB_CB(skb)->ack_seq; tp->snd_wnd = ntohs(th->window) << tp->rx_opt.snd_wscale; tcp_init_wl(tp, TCP_SKB_CB(skb)->seq); if (tp->rx_opt.tstamp_ok) tp->advmss -= <API key>; if (req) { /* Re-arm the timer because data may * have been sent out. This is similar * to the regular data transmission case * when new data has just been ack'ed. * * (TFO) - we could try to be more * aggressive and retranmitting any data * sooner based on when they were sent * out. */ tcp_rearm_rto(sk); } else tcp_init_metrics(sk); <API key>(sk); /* Prevent spurious tcp_cwnd_restart() on * first data packet. */ tp->lsndtime = tcp_time_stamp; <API key>(sk); tcp_fast_path_on(tp); } else { return 1; } break; case TCP_FIN_WAIT1: /* If we enter the TCP_FIN_WAIT1 state and we are a * Fast Open socket and this is the first acceptable * ACK we have received, this would have acknowledged * our SYNACK so stop the SYNACK timer. */ if (req != NULL) { /* Return RST if ack_seq is invalid. * Note that RFC793 only says to generate a * DUPACK for it but for TCP Fast Open it seems * better to treat this case like TCP_SYN_RECV * above. */ if (!acceptable) return 1; /* We no longer need the request sock. */ <API key>(sk, req, false); tcp_rearm_rto(sk); } if (tp->snd_una == tp->write_seq) { struct dst_entry *dst; tcp_set_state(sk, TCP_FIN_WAIT2); sk->sk_shutdown |= SEND_SHUTDOWN; dst = __sk_dst_get(sk); if (dst) dst_confirm(dst); if (!sock_flag(sk, SOCK_DEAD)) /* Wake up lingering close() */ sk->sk_state_change(sk); else { int tmo; if (tp->linger2 < 0 || (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) { tcp_done(sk); NET_INC_STATS_BH(sock_net(sk), <API key>); return 1; } tmo = tcp_fin_time(sk); if (tmo > TCP_TIMEWAIT_LEN) { <API key>(sk, tmo - TCP_TIMEWAIT_LEN); } else if (th->fin || sock_owned_by_user(sk)) { /* Bad case. We could lose such FIN otherwise. * It is not a big problem, but it looks confusing * and not so rare event. We still can lose it now, * if it spins in bh_lock_sock(), but it is really * marginal case. */ <API key>(sk, tmo); } else { tcp_time_wait(sk, TCP_FIN_WAIT2, tmo); goto discard; } } } break; case TCP_CLOSING: if (tp->snd_una == tp->write_seq) { tcp_time_wait(sk, TCP_TIME_WAIT, 0); goto discard; } break; case TCP_LAST_ACK: if (tp->snd_una == tp->write_seq) { tcp_update_metrics(sk); tcp_done(sk); goto discard; } break; } } /* step 6: check the URG bit */ tcp_urg(sk, skb, th); /* step 7: process the segment text */ switch (sk->sk_state) { case TCP_CLOSE_WAIT: case TCP_CLOSING: case TCP_LAST_ACK: if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) break; case TCP_FIN_WAIT1: case TCP_FIN_WAIT2: /* RFC 793 says to queue data in these states, * RFC 1122 says we MUST send a reset. * BSD 4.4 also does reset. */ if (sk->sk_shutdown & RCV_SHUTDOWN) { if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) { NET_INC_STATS_BH(sock_net(sk), <API key>); tcp_reset(sk); return 1; } } /* Fall through */ case TCP_ESTABLISHED: tcp_data_queue(sk, skb); queued = 1; break; } /* tcp_data could move socket to TIME-WAIT */ if (sk->sk_state != TCP_CLOSE) { tcp_data_snd_check(sk); tcp_ack_snd_check(sk); } if (!queued) { discard: __kfree_skb(skb); } return 0; } EXPORT_SYMBOL(<API key>);
from Source import Source from Components.Element import cached from Components.SystemInfo import SystemInfo from enigma import eServiceReference StreamServiceList = [] class StreamService(Source): def __init__(self, navcore): Source.__init__(self) self.ref = None self.__service = None self.navcore = navcore def serviceEvent(self, event): pass @cached def getService(self): return self.__service service = property(getService) def handleCommand(self, cmd): print "[StreamService] handle command", cmd self.ref = eServiceReference(cmd) def recordEvent(self, service, event): if service is self.__service: return print "[StreamService] RECORD event for us:", service self.changed((self.CHANGED_ALL, )) def execBegin(self): if self.ref is None: print "[StreamService] has no service ref set" return print "[StreamService]e execBegin", self.ref.toString() if SystemInfo["<API key>"]: from Screens.InfoBar import InfoBar if InfoBar.instance and hasattr(InfoBar.instance.session, 'pipshown') and InfoBar.instance.session.pipshown: hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP() print "[StreamService] try to disable pip before start stream" if hasattr(InfoBar.instance.session, 'pip'): del InfoBar.instance.session.pip InfoBar.instance.session.pipshown = False self.__service = self.navcore.recordService(self.ref) self.navcore.record_event.append(self.recordEvent) if self.__service is not None: if self.__service.__deref__() not in StreamServiceList: StreamServiceList.append(self.__service.__deref__()) self.__service.prepareStreaming() self.__service.start() def execEnd(self): print "[StreamService] execEnd", self.ref.toString() self.navcore.record_event.remove(self.recordEvent) if self.__service is not None: if self.__service.__deref__() in StreamServiceList: StreamServiceList.remove(self.__service.__deref__()) self.navcore.stopRecordService(self.__service) self.__service = None self.ref = None
<?php /** * Template Name: Wide Page Template * * Description: A page template that provides a key component of WordPress as a CMS * by meeting the need for a carefully crafted introductory page. The front page template * in Twenty Twelve consists of a page content area for adding text, images, video -- * anything you'd like -- followed by front-page-only widgets in one or two columns. * * @package WordPress * @subpackage Plum_Tree * @since Plum Tree 0.1 */ get_header(); ?> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php if ( (get_option('<API key>') != '') && (get_option('<API key>') != '#fff') ) { $spacer_bg = 'style="background:'.get_option('<API key>').';"'; } elseif ( get_option('<API key>') != '' ) { $spacer_bg = 'style="background: url('.get_option('<API key>').') repeat;"'; } else { $spacer_bg = 'style="background: url('.<API key>().'/assets/spacer-'.get_option('<API key>').'.png) repeat;"'; } ?> <div class="spacer" <?php echo $spacer_bg; ?> <API key>="0.5"> <div class="container-fluid"> <div class="row-fluid"> <h1 class="spacer-title" data-stellar-ratio="0.93"><?php the_title(); ?></h1> </div> </div> </div> <section id="content" role="main" class="site-content"><!-- Main content --> <div class="entry-content"> <?php the_content(); ?> </div><!-- .entry-content --> <?php endwhile; ?> <?php endif; ?> </section><!-- Main content --> <?php get_footer(); ?>
<html lang="en"> <head> <title>Context management - Debugging with GDB</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Debugging with GDB"> <meta name="generator" content="makeinfo 4.13"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="<API key>.html#<API key>" title="GDB/MI General Design"> <link rel="next" href="<API key>.html#<API key>" title="Asynchronous and non-stop modes"> <link href="http: <! Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being ``Free Software'' and ``Free Software Needs Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover Texts as in (a) below. (a) The FSF's Back-Cover Text is: ``You are free to copy and modify this GNU Manual. Buying copies from GNU Press supports the FSF in developing GNU and promoting software freedom.'' <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><! pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> <link rel="stylesheet" type="text/css" href="../cs.css"> </head> <body> <div class="node"> <a name="Context-management"></a> <p> Next:&nbsp;<a rel="next" accesskey="n" href="<API key>.html#<API key>">Asynchronous and non-stop modes</a>, Up:&nbsp;<a rel="up" accesskey="u" href="<API key>.html#<API key>">GDB/MI General Design</a> <hr> </div> <h4 class="subsection">27.1.1 Context management</h4> <p>In most cases when <span class="sc">gdb</span> accesses the target, this access is done in context of a specific thread and frame (see <a href="Frames.html#Frames">Frames</a>). Often, even when accessing global data, the target requires that a thread be specified. The CLI interface maintains the selected thread and frame, and supplies them to target on each command. This is convenient, because a command line user would not want to specify that information explicitly on each command, and because user interacts with <span class="sc">gdb</span> via a single terminal, so no confusion is possible as to what thread and frame are the current ones. <p>In the case of MI, the concept of selected thread and frame is less useful. First, a frontend can easily remember this information itself. Second, a graphical frontend can have more than one window, each one used for debugging a different thread, and the frontend might want to access additional threads for internal purposes. This increases the risk that by relying on implicitly selected thread, the frontend may be operating on a wrong one. Therefore, each MI command should explicitly specify which thread and frame to operate on. To make it possible, each MI command accepts the &lsquo;<samp><span class="samp">--thread</span></samp>&rsquo; and &lsquo;<samp><span class="samp">--frame</span></samp>&rsquo; options, the value to each is <span class="sc">gdb</span> identifier for thread and frame to operate on. <p>Usually, each top-level window in a frontend allows the user to select a thread and a frame, and remembers the user selection for further operations. However, in some cases <span class="sc">gdb</span> may suggest that the current thread be changed. For example, when stopping on a breakpoint it is reasonable to switch to the thread where breakpoint is hit. For another example, if the user issues the CLI &lsquo;<samp><span class="samp">thread</span></samp>&rsquo; command via the frontend, it is desirable to change the frontend's selected thread to the one specified by user. <span class="sc">gdb</span> communicates the suggestion to change current thread using the &lsquo;<samp><span class="samp">=thread-selected</span></samp>&rsquo; notification. No such notification is available for the selected frame at the moment. <p>Note that historically, MI shares the selected thread with CLI, so frontends used the <code>-thread-select</code> to execute commands in the right context. However, getting this to work right is cumbersome. The simplest way is for frontend to emit <code>-thread-select</code> command before every command. This doubles the number of commands that need to be sent. The alternative approach is to suppress <code>-thread-select</code> if the selected thread in <span class="sc">gdb</span> is supposed to be identical to the thread the frontend wants to operate on. However, getting this optimization right can be tricky. In particular, if the frontend sends several commands to <span class="sc">gdb</span>, and one of the commands changes the selected thread, then the behaviour of subsequent commands will change. So, a frontend should either wait for response from such problematic commands, or explicitly add <code>-thread-select</code> for all subsequent commands. No frontend is known to do this exactly right, so it is suggested to just always pass the &lsquo;<samp><span class="samp">--thread</span></samp>&rsquo; and &lsquo;<samp><span class="samp">--frame</span></samp>&rsquo; options. </body></html>
int main() { if(true) {return 1;} else if(true) {return 1;} else {return 1;} }
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} # FIXME: Add more, better examples EXAMPLES = r''' - <API key>: host: apic username: admin <API key> dst_group: '{{ dst_group }}' description: '{{ descr }}' tenant: '{{ tenant }}' ''' from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec from ansible.module_utils.basic import AnsibleModule def main(): argument_spec = aci_argument_spec() argument_spec.update( dst_group=dict(type='str', required=False, aliases=['name']), # Not required for querying all objects tenant=dict(type='str', required=False, aliases=['tenant_name']), # Not required for querying all objects description=dict(type='str', aliases=['descr']), state=dict(type='str', default='present', choices=['absent', 'present', 'query']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['dst_group', 'tenant']], ['state', 'present', ['dst_group', 'tenant']], ], ) dst_group = module.params['dst_group'] description = module.params['description'] state = module.params['state'] tenant = module.params['tenant'] aci = ACIModule(module) aci.construct_url( root_class=dict( aci_class='fvTenant', aci_rn='tn-{0}'.format(tenant), filter_target='eq(fvTenant.name, "{0}")'.format(tenant), module_object=tenant, ), subclass_1=dict( aci_class='spanDestGrp', aci_rn='destgrp-{0}'.format(dst_group), filter_target='eq(spanDestGrp.name, "{0}")'.format(dst_group), module_object=dst_group, ), ) aci.get_existing() if state == 'present': aci.payload( aci_class='spanDestGrp', class_config=dict( name=dst_group, descr=description, ), ) aci.get_diff(aci_class='spanDestGrp') aci.post_config() elif state == 'absent': aci.delete_config() aci.exit_json() if __name__ == "__main__": main()
#ifndef _TCOD_ZIP_H #define _TCOD_ZIP_H typedef void *TCOD_zip_t; TCODLIB_API TCOD_zip_t TCOD_zip_new(); TCODLIB_API void TCOD_zip_delete(TCOD_zip_t zip); /* output interface */ TCODLIB_API void TCOD_zip_put_char(TCOD_zip_t zip, char val); TCODLIB_API void TCOD_zip_put_int(TCOD_zip_t zip, int val); TCODLIB_API void TCOD_zip_put_float(TCOD_zip_t zip, float val); TCODLIB_API void TCOD_zip_put_string(TCOD_zip_t zip, const char *val); TCODLIB_API void TCOD_zip_put_color(TCOD_zip_t zip, const TCOD_color_t val); TCODLIB_API void TCOD_zip_put_image(TCOD_zip_t zip, const TCOD_image_t val); TCODLIB_API void <API key>(TCOD_zip_t zip, const TCOD_console_t val); TCODLIB_API void TCOD_zip_put_data(TCOD_zip_t zip, int nbBytes, const void *data); TCODLIB_API uint32 <API key>(TCOD_zip_t zip); TCODLIB_API int <API key>(TCOD_zip_t zip, const char *filename); /* input interface */ TCODLIB_API int <API key>(TCOD_zip_t zip, const char *filename); TCODLIB_API char TCOD_zip_get_char(TCOD_zip_t zip); TCODLIB_API int TCOD_zip_get_int(TCOD_zip_t zip); TCODLIB_API float TCOD_zip_get_float(TCOD_zip_t zip); TCODLIB_API const char *TCOD_zip_get_string(TCOD_zip_t zip); TCODLIB_API TCOD_color_t TCOD_zip_get_color(TCOD_zip_t zip); TCODLIB_API TCOD_image_t TCOD_zip_get_image(TCOD_zip_t zip); TCODLIB_API TCOD_console_t <API key>(TCOD_zip_t zip); TCODLIB_API int TCOD_zip_get_data(TCOD_zip_t zip, int nbBytes, void *data); TCODLIB_API uint32 <API key>(TCOD_zip_t zip); TCODLIB_API void TCOD_zip_skip_bytes(TCOD_zip_t zip, uint32 nbBytes); #endif
Clazz.declarePackage ("JSV.common"); Clazz.load (["java.lang.Enum", "JSV.source.JDXDataObject", "JU.Lst"], "JSV.common.Spectrum", ["java.lang.Boolean", "$.Double", "java.util.Hashtable", "JU.PT", "JSV.common.Coordinate", "$.Parameters", "$.PeakInfo", "JSV.source.<API key>", "JU.Logger"], function () { c$ = Clazz.decorateAsClass (function () { this.subSpectra = null; this.peakList = null; this.piUnitsX = null; this.piUnitsY = null; this.selectedPeak = null; this.highlightedPeak = null; this.specShift = 0; this.<API key> = 0; this.$isForcedSubset = false; this.id = ""; this.convertedSpectrum = null; this.userYFactor = 1; this.<API key> = false; this.fillColor = null; Clazz.instantialize (this, arguments); }, JSV.common, "Spectrum", JSV.source.JDXDataObject); Clazz.prepareFields (c$, function () { this.peakList = new JU.Lst (); }); Clazz.overrideMethod (c$, "finalize", function () { System.out.println ("JDXSpectrum " + this + " finalized " + this.title); }); Clazz.defineMethod (c$, "dispose", function () { }); Clazz.defineMethod (c$, "isForcedSubset", function () { return this.$isForcedSubset; }); Clazz.defineMethod (c$, "setId", function (id) { this.id = id; }, "~S"); Clazz.makeConstructor (c$, function () { Clazz.superConstructor (this, JSV.common.Spectrum, []); this.headerTable = new JU.Lst (); this.xyCoords = new Array (0); this.parent = this; }); Clazz.defineMethod (c$, "copy", function () { var newSpectrum = new JSV.common.Spectrum (); this.copyTo (newSpectrum); newSpectrum.setPeakList (this.peakList, this.piUnitsX, null); newSpectrum.fillColor = this.fillColor; return newSpectrum; }); Clazz.defineMethod (c$, "getXYCoords", function () { return this.<API key> ().xyCoords; }); Clazz.defineMethod (c$, "getPeakList", function () { return this.peakList; }); Clazz.defineMethod (c$, "setPeakList", function (list, piUnitsX, piUnitsY) { this.peakList = list; this.piUnitsX = piUnitsX; this.piUnitsY = piUnitsY; for (var i = list.size (); --i >= 0; ) this.peakList.get (i).spectrum = this; if (JU.Logger.debugging) JU.Logger.info ("Spectrum " + this.getTitle () + " peaks: " + list.size ()); return list.size (); }, "JU.Lst,~S,~S"); Clazz.defineMethod (c$, "<API key>", function (filePath, index, atomKey) { if (this.peakList != null && this.peakList.size () > 0 && (atomKey == null || this.sourceID.equals (index))) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkFileIndex (filePath, index, atomKey)) { System.out.println ("selecting peak by FileIndex " + this + " " + this.peakList.get (i)); return (this.selectedPeak = this.peakList.get (i)); } return null; }, "~S,~S,~S"); Clazz.defineMethod (c$, "<API key>", function (filePath, type, model) { if (this.peakList != null && this.peakList.size () > 0) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkFileTypeModel (filePath, type, model)) { System.out.println ("selecting peak byFilePathTypeModel " + this + " " + this.peakList.get (i)); return (this.selectedPeak = this.peakList.get (i)); } return null; }, "~S,~S,~S"); Clazz.defineMethod (c$, "<API key>", function (type, model) { if (type.equals ("ID")) return (this.sourceID.equalsIgnoreCase (model)); if (this.peakList != null && this.peakList.size () > 0) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkTypeModel (type, model)) return true; return false; }, "~S,~S"); Clazz.defineMethod (c$, "setSelectedPeak", function (peak) { this.selectedPeak = peak; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "setHighlightedPeak", function (peak) { this.highlightedPeak = peak; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "getSelectedPeak", function () { return this.selectedPeak; }); Clazz.defineMethod (c$, "<API key>", function () { if (this.peakList != null) for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).autoSelectOnLoad ()) return this.peakList.get (i); return null; }); Clazz.defineMethod (c$, "<API key>", function (xPixel, coord) { this.selectedPeak = this.findPeakByCoord (xPixel, coord); return (this.selectedPeak == null ? this.getBasePeakInfo () : this.selectedPeak); }, "~N,JSV.common.Coordinate"); Clazz.defineMethod (c$, "findPeakByCoord", function (xPixel, coord) { if (coord != null && this.peakList != null && this.peakList.size () > 0) { var xVal = coord.getXVal (); var iBest = -1; var dBest = 1e100; for (var i = 0; i < this.peakList.size (); i++) { var d = this.peakList.get (i).checkRange (xPixel, xVal); if (d < dBest) { dBest = d; iBest = i; }} if (iBest >= 0) return this.peakList.get (iBest); }return null; }, "~N,JSV.common.Coordinate"); Clazz.defineMethod (c$, "getPeakTitle", function () { return (this.selectedPeak != null ? this.selectedPeak.getTitle () : this.highlightedPeak != null ? this.highlightedPeak.getTitle () : this.getTitleLabel ()); }); Clazz.defineMethod (c$, "getTitleLabel", function () { var type = (this.peakList == null || this.peakList.size () == 0 ? this.<API key> () : this.peakList.get (0).getType ()); if (type != null && type.startsWith ("NMR")) { if (this.nucleusY != null && !this.nucleusY.equals ("?")) { type = "2D" + type; } else { type = this.nucleusX + type; }}return (type != null && type.length > 0 ? type + " " : "") + this.getTitle (); }); Clazz.defineMethod (c$, "setNextPeak", function (coord, istep) { if (this.peakList == null || this.peakList.size () == 0) return -1; var x0 = coord.getXVal () + istep * 0.000001; var ipt1 = -1; var ipt2 = -1; var dmin1 = 1.<API key> * istep; var dmin2 = 0; for (var i = this.peakList.size (); --i >= 0; ) { var x = this.peakList.get (i).getX (); if (istep > 0) { if (x > x0 && x < dmin1) { ipt1 = i; dmin1 = x; } else if (x < x0 && x - x0 < dmin2) { ipt2 = i; dmin2 = x - x0; }} else { if (x < x0 && x > dmin1) { ipt1 = i; dmin1 = x; } else if (x > x0 && x - x0 > dmin2) { ipt2 = i; dmin2 = x - x0; }}} if (ipt1 < 0) { if (ipt2 < 0) return -1; ipt1 = ipt2; }return ipt1; }, "JSV.common.Coordinate,~N"); Clazz.defineMethod (c$, "getPercentYValueAt", function (x) { if (!this.isContinuous ()) return NaN; return this.getYValueAt (x); }, "~N"); Clazz.defineMethod (c$, "getYValueAt", function (x) { return JSV.common.Coordinate.getYValueAt (this.xyCoords, x); }, "~N"); Clazz.defineMethod (c$, "setUserYFactor", function (userYFactor) { this.userYFactor = userYFactor; }, "~N"); Clazz.defineMethod (c$, "getUserYFactor", function () { return this.userYFactor; }); Clazz.defineMethod (c$, "<API key>", function () { return this.convertedSpectrum; }); Clazz.defineMethod (c$, "<API key>", function (spectrum) { this.convertedSpectrum = spectrum; }, "JSV.common.Spectrum"); c$.taConvert = Clazz.defineMethod (c$, "taConvert", function (spectrum, mode) { if (!spectrum.isContinuous ()) return spectrum; switch (mode) { case JSV.common.Spectrum.IRMode.NO_CONVERT: return spectrum; case JSV.common.Spectrum.IRMode.TO_ABS: if (!spectrum.isTransmittance ()) return spectrum; break; case JSV.common.Spectrum.IRMode.TO_TRANS: if (!spectrum.isAbsorbance ()) return spectrum; break; case JSV.common.Spectrum.IRMode.TOGGLE: break; } var spec = spectrum.<API key> (); return (spec != null ? spec : spectrum.isAbsorbance () ? JSV.common.Spectrum.toT (spectrum) : JSV.common.Spectrum.toA (spectrum)); }, "JSV.common.Spectrum,JSV.common.Spectrum.IRMode"); c$.toT = Clazz.defineMethod (c$, "toT", function (spectrum) { if (!spectrum.isAbsorbance ()) return null; var xyCoords = spectrum.getXYCoords (); var newXYCoords = new Array (xyCoords.length); if (!JSV.common.Coordinate.isYInRange (xyCoords, 0, 4.0)) xyCoords = JSV.common.Coordinate.normalise (xyCoords, 0, 4.0); for (var i = 0; i < xyCoords.length; i++) newXYCoords[i] = new JSV.common.Coordinate ().set (xyCoords[i].getXVal (), JSV.common.Spectrum.toTransmittance (xyCoords[i].getYVal ())); return JSV.common.Spectrum.newSpectrum (spectrum, newXYCoords, "TRANSMITTANCE"); }, "JSV.common.Spectrum"); c$.toA = Clazz.defineMethod (c$, "toA", function (spectrum) { if (!spectrum.isTransmittance ()) return null; var xyCoords = spectrum.getXYCoords (); var newXYCoords = new Array (xyCoords.length); var isPercent = JSV.common.Coordinate.isYInRange (xyCoords, -2, 2); for (var i = 0; i < xyCoords.length; i++) newXYCoords[i] = new JSV.common.Coordinate ().set (xyCoords[i].getXVal (), JSV.common.Spectrum.toAbsorbance (xyCoords[i].getYVal (), isPercent)); return JSV.common.Spectrum.newSpectrum (spectrum, newXYCoords, "ABSORBANCE"); }, "JSV.common.Spectrum"); c$.newSpectrum = Clazz.defineMethod (c$, "newSpectrum", function (spectrum, newXYCoords, units) { var specNew = spectrum.copy (); specNew.setOrigin ("JSpecView Converted"); specNew.setOwner ("JSpecView Generated"); specNew.setXYCoords (newXYCoords); specNew.setYUnits (units); spectrum.<API key> (specNew); specNew.<API key> (spectrum); return specNew; }, "JSV.common.Spectrum,~A,~S"); c$.toAbsorbance = Clazz.defineMethod (c$, "toAbsorbance", function (x, isPercent) { return (Math.min (4.0, isPercent ? 2 - JSV.common.Spectrum.log10 (x) : -JSV.common.Spectrum.log10 (x))); }, "~N,~B"); c$.toTransmittance = Clazz.defineMethod (c$, "toTransmittance", function (x) { return (x <= 0 ? 1 : Math.pow (10, -x)); }, "~N"); c$.log10 = Clazz.defineMethod (c$, "log10", function (value) { return Math.log (value) / Math.log (10); }, "~N"); c$.process = Clazz.defineMethod (c$, "process", function (specs, irMode) { if (irMode === JSV.common.Spectrum.IRMode.TO_ABS || irMode === JSV.common.Spectrum.IRMode.TO_TRANS) for (var i = 0; i < specs.size (); i++) specs.set (i, JSV.common.Spectrum.taConvert (specs.get (i), irMode)); return true; }, "JU.Lst,JSV.common.Spectrum.IRMode"); Clazz.defineMethod (c$, "getSubSpectra", function () { return this.subSpectra; }); Clazz.defineMethod (c$, "<API key>", function () { return (this.subSpectra == null ? this : this.subSpectra.get (this.<API key>)); }); Clazz.defineMethod (c$, "advanceSubSpectrum", function (dir) { return this.<API key> (this.<API key> + dir); }, "~N"); Clazz.defineMethod (c$, "<API key>", function (n) { return (this.<API key> = JSV.common.Coordinate.intoRange (n, 0, this.subSpectra.size () - 1)); }, "~N"); Clazz.defineMethod (c$, "addSubSpectrum", function (spectrum, forceSub) { if (!forceSub && (this.numDim < 2 || this.blockID != spectrum.blockID) || !JSV.common.Spectrum.allowSubSpec (this, spectrum)) return false; this.$isForcedSubset = forceSub; if (this.subSpectra == null) { this.subSpectra = new JU.Lst (); this.addSubSpectrum (this, true); }this.subSpectra.addLast (spectrum); spectrum.parent = this; return true; }, "JSV.common.Spectrum,~B"); Clazz.defineMethod (c$, "getSubIndex", function () { return (this.subSpectra == null ? -1 : this.<API key>); }); Clazz.defineMethod (c$, "<API key>", function (leftToRight) { this.<API key> = leftToRight; }, "~B"); Clazz.defineMethod (c$, "<API key>", function () { return this.<API key>; }); Clazz.defineMethod (c$, "getInfo", function (key) { var info = new java.util.Hashtable (); if ("id".equalsIgnoreCase (key)) { info.put (key, this.id); return info; }info.put ("id", this.id); JSV.common.Parameters.putInfo (key, info, "specShift", Double.$valueOf (this.specShift)); var justHeader = ("header".equals (key)); if (!justHeader && key != null) { for (var i = this.headerTable.size (); --i >= 0; ) { var entry = this.headerTable.get (i); if (entry[0].equalsIgnoreCase (key) || entry[2].equalsIgnoreCase (key)) { info.put (key, entry[1]); return info; }} }var head = new java.util.Hashtable (); var list = this.<API key> (); for (var i = 0; i < list.length; i++) { var label = JSV.source.<API key>.cleanLabel (list[i][0]); if (key != null && !justHeader && !label.equals (key)) continue; var val = JSV.common.Spectrum.fixInfoValue (list[i][1]); if (key == null) { var data = new java.util.Hashtable (); data.put ("value", val); data.put ("index", Integer.$valueOf (i + 1)); info.put (label, data); } else { info.put (label, val); }} if (head.size () > 0) info.put ("header", head); if (!justHeader) { JSV.common.Parameters.putInfo (key, info, "titleLabel", this.getTitleLabel ()); JSV.common.Parameters.putInfo (key, info, "type", this.getDataType ()); JSV.common.Parameters.putInfo (key, info, "isHZToPPM", Boolean.$valueOf (this.$isHZtoPPM)); JSV.common.Parameters.putInfo (key, info, "subSpectrumCount", Integer.$valueOf (this.subSpectra == null ? 0 : this.subSpectra.size ())); }return info; }, "~S"); c$.fixInfoValue = Clazz.defineMethod (c$, "fixInfoValue", function (info) { try { return (Integer.$valueOf (info)); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } try { return (Double.$valueOf (info)); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } return info; }, "~S"); Clazz.overrideMethod (c$, "toString", function () { return this.getTitleLabel (); }); Clazz.defineMethod (c$, "<API key>", function (pi) { for (var i = 0; i < this.peakList.size (); i++) if (this.peakList.get (i).checkTypeMatch (pi)) return this.peakList.get (i); return null; }, "JSV.common.PeakInfo"); Clazz.defineMethod (c$, "getBasePeakInfo", function () { return (this.peakList.size () == 0 ? new JSV.common.PeakInfo () : new JSV.common.PeakInfo (" baseModel=\"\" " + this.peakList.get (0))); }); Clazz.defineMethod (c$, "getAxisLabel", function (isX) { var units = (isX ? this.piUnitsX : this.piUnitsY); if (units == null) units = (isX ? this.xLabel : this.yLabel); if (units == null) units = (isX ? this.xUnits : this.yUnits); return (units == null ? "" : units.equalsIgnoreCase ("WAVENUMBERS") ? "1/cm" : units.equalsIgnoreCase ("nanometers") ? "nm" : units); }, "~B"); Clazz.defineMethod (c$, "findXForPeakNearest", function (x) { return JSV.common.Coordinate.findXForPeakNearest (this.xyCoords, x, this.isInverted ()); }, "~N"); Clazz.defineMethod (c$, "addSpecShift", function (dx) { if (dx != 0) { this.specShift += dx; JSV.common.Coordinate.shiftX (this.xyCoords, dx); if (this.subSpectra != null) for (var i = this.subSpectra.size (); --i >= 0; ) { var spec = this.subSpectra.get (i); if (spec !== this && spec !== this.parent) spec.addSpecShift (dx); } }return this.specShift; }, "~N"); c$.allowSubSpec = Clazz.defineMethod (c$, "allowSubSpec", function (s1, s2) { return (s1.is1D () == s2.is1D () && s1.xUnits.equalsIgnoreCase (s2.xUnits) && s1.isHNMR () == s2.isHNMR ()); }, "JSV.common.Spectrum,JSV.common.Spectrum"); c$.<API key> = Clazz.defineMethod (c$, "<API key>", function (s1, s2, isSubspecCheck, isLinkCheck) { var isNMR1 = s1.isNMR (); if (isNMR1 != s2.isNMR () || s1.isContinuous () != s2.isContinuous () || !isLinkCheck && !JSV.common.Spectrum.areUnitsCompatible (s1.xUnits, s2.xUnits)) return false; if (isSubspecCheck) { if (s1.is1D () != s2.is1D ()) return false; } else if (isLinkCheck) { if (!isNMR1) return true; } else if (!s1.is1D () || !s2.is1D ()) { return false; }return (!isNMR1 || s2.is1D () && s1.parent.nucleusX.equals (s2.parent.nucleusX)); }, "JSV.common.Spectrum,JSV.common.Spectrum,~B,~B"); c$.areUnitsCompatible = Clazz.defineMethod (c$, "areUnitsCompatible", function (u1, u2) { if (u1.equalsIgnoreCase (u2)) return true; u1 = u1.toUpperCase (); u2 = u2.toUpperCase (); return (u1.equals ("HZ") && u2.equals ("PPM") || u1.equals ("PPM") && u2.equals ("HZ")); }, "~S,~S"); c$.areLinkableX = Clazz.defineMethod (c$, "areLinkableX", function (s1, s2) { return (s1.isNMR () && s2.isNMR () && s1.nucleusX.equals (s2.nucleusX)); }, "JSV.common.Spectrum,JSV.common.Spectrum"); c$.areLinkableY = Clazz.defineMethod (c$, "areLinkableY", function (s1, s2) { return (s1.isNMR () && s2.isNMR () && s1.nucleusX.equals (s2.nucleusY)); }, "JSV.common.Spectrum,JSV.common.Spectrum"); Clazz.defineMethod (c$, "setNHydrogens", function (nH) { this.nH = nH; }, "~N"); Clazz.defineMethod (c$, "getPeakWidth", function () { var w = this.getLastX () - this.getFirstX (); return (w / 100); }); Clazz.defineMethod (c$, "setSimulated", function (filePath) { this.isSimulation = true; var s = this.sourceID; if (s.length == 0) s = JU.PT.rep (filePath, "http://SIMULATION/", ""); if (s.indexOf ("MOL=") >= 0) s = ""; this.title = "SIMULATED " + JU.PT.rep (s, "$", ""); }, "~S"); Clazz.defineMethod (c$, "setFillColor", function (color) { this.fillColor = color; if (this.convertedSpectrum != null) this.convertedSpectrum.fillColor = color; }, "javajs.api.GenericColor"); Clazz.pu$h(self.c$); c$ = Clazz.declareType (JSV.common.Spectrum, "IRMode", Enum); c$.getMode = Clazz.defineMethod (c$, "getMode", function (a) { switch (a == null ? 'I' : a.toUpperCase ().charAt (0)) { case 'A': return JSV.common.Spectrum.IRMode.TO_ABS; case 'T': return (a.equalsIgnoreCase ("TOGGLE") ? JSV.common.Spectrum.IRMode.TOGGLE : JSV.common.Spectrum.IRMode.TO_TRANS); case 'N': return JSV.common.Spectrum.IRMode.NO_CONVERT; default: return JSV.common.Spectrum.IRMode.TOGGLE; } }, "~S"); Clazz.defineEnumConstant (c$, "NO_CONVERT", 0, []); Clazz.defineEnumConstant (c$, "TO_TRANS", 1, []); Clazz.defineEnumConstant (c$, "TO_ABS", 2, []); Clazz.defineEnumConstant (c$, "TOGGLE", 3, []); c$ = Clazz.p0p (); Clazz.defineStatics (c$, "MAXABS", 4); });
;; XSTORMY16 Machine description template ;; Copyright (C) 1997, 1998, 1999, 2001, 2002 Free Software Foundation, Inc. ;; Contributed by Red Hat, Inc. ;; This file is part of GNU CC. ;; GNU CC is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 2, or (at your option) ;; any later version. ;; GNU CC is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU CC; see the file COPYING. If not, write to ;; the Free Software Foundation, 59 Temple Place - Suite 330, ;; Boston, MA 02111-1307, USA. ;;- See file "rtl.def" for documentation on define_insn, match_*, et. al. ;; :::::::::::::::::::: ;; :: ;; :: Attributes ;; :: ;; :::::::::::::::::::: ; Categorize branches for the conditional in the length attribute. (define_attr "branch_class" "notdirectbranch,br12,bcc12,bcc8p2,bcc8p4" (const_string "notdirectbranch")) ; The length of an instruction, used for branch shortening. (define_attr "length" "" (cond [(eq_attr "branch_class" "br12") (if_then_else (and (ge (minus (match_dup 0) (pc)) (const_int -2046)) (lt (minus (match_dup 0) (pc)) (const_int 2048))) (const_int 2) (const_int 4)) (eq_attr "branch_class" "bcc12") (if_then_else (and (ge (minus (match_dup 0) (pc)) (const_int -2044)) (lt (minus (match_dup 0) (pc)) (const_int 2048))) (const_int 4) (const_int 8)) (eq_attr "branch_class" "bcc8p2") (if_then_else (and (ge (minus (match_dup 0) (pc)) (const_int -124)) (lt (minus (match_dup 0) (pc)) (const_int 128))) (const_int 4) (const_int 8)) (eq_attr "branch_class" "bcc8p4") (if_then_else (and (ge (minus (match_dup 0) (pc)) (const_int -122)) (lt (minus (match_dup 0) (pc)) (const_int 128))) (const_int 6) (const_int 10))] (const_int 2))) ; The operand which determines the setting of Rpsw. ; The numbers indicate the operand number, ; 'clobber' indicates it is changed in some unspecified way ; 'nop' means it is not changed. (define_attr "psw_operand" "clobber,nop,0,1,2,3,4" (const_string "0")) (<API key> [(set_attr "length" "4") (set_attr "psw_operand" "clobber")]) ;; :::::::::::::::::::: ;; :: ;; :: Moves ;; :: ;; :::::::::::::::::::: ;; push/pop qi and hi are here as separate insns rather than part of ;; the movqi/hi patterns because we need to ensure that reload isn't ;; passed anything it can't cope with. Without these patterns, we ;; might end up with ;; (set (mem (post_inc (sp))) mem (post_inc (reg))) ;; If, in this example, reg needs reloading, reload will read reg from ;; the stack , adjust sp, and store reg back at what is now the wrong ;; offset. By using separate patterns for push and pop we ensure that ;; insns like this one are never generated. (define_insn "pushqi" [(set (mem:QI (post_inc (reg:HI 15))) (match_operand:QI 0 "register_operand" "r"))] "" "push %0" [(set_attr "psw_operand" "nop") (set_attr "length" "2")]) (define_insn "popqi" [(set (match_operand:QI 0 "register_operand" "=r") (mem:QI (pre_dec (reg:HI 15))))] "" "pop %0" [(set_attr "psw_operand" "nop") (set_attr "length" "2")]) (define_expand "movqi" [(set (match_operand:QI 0 "<API key>" "") (match_operand:QI 1 "general_operand" ""))] "" "{ <API key> (QImode, operands[0], operands[1]); DONE; }") (define_insn "*movqi_internal" [(set (match_operand:QI 0 "<API key>" "=r,m,e,e,T,r,S") (match_operand:QI 1 "general_operand" "r,e,m,i,i,i,i"))] "" "@ mov %0,%1 mov.b %0,%1 mov.b %0,%1 mov %0,%1 mov Rx,%1 mov %0,%1 mov.b %0,%1" [(<API key> "length" [(const_int 2) (if_then_else (match_operand:QI 0 "<API key>" "") (const_int 2) (const_int 4)) (if_then_else (match_operand:QI 1 "<API key>" "") (const_int 2) (const_int 4)) (const_int 2) (const_int 2) (const_int 4) (const_int 4)]) (set_attr "psw_operand" "0,0,0,0,nop,0,nop")]) (define_insn "pushhi" [(set (mem:HI (post_inc (reg:HI 15))) (match_operand:HI 0 "register_operand" "r"))] "" "push %0" [(set_attr "psw_operand" "nop") (set_attr "length" "2")]) (define_insn "pophi" [(set (match_operand:HI 0 "register_operand" "=r") (mem:HI (pre_dec (reg:HI 15))))] "" "pop %0" [(set_attr "psw_operand" "nop") (set_attr "length" "2")]) (define_expand "movhi" [(set (match_operand:HI 0 "<API key>" "") (match_operand:HI 1 "general_operand" ""))] "" "{ <API key> (HImode, operands[0], operands[1]); DONE; }") (define_insn "*movhi_internal" [(set (match_operand:HI 0 "<API key>" "=r,m,e,e,T,r,S") (match_operand:HI 1 "general_operand" "r,e,m,L,L,i,i"))] "" "@ mov %0,%1 mov.w %0,%1 mov.w %0,%1 mov.w %0,%1 mov.w Rx,%1 mov.w %0,%1 mov.w %0,%1" [(<API key> "length" [(const_int 2) (if_then_else (match_operand:QI 0 "<API key>" "") (const_int 2) (const_int 4)) (if_then_else (match_operand:QI 1 "<API key>" "") (const_int 2) (const_int 4)) (const_int 2) (const_int 2) (const_int 4) (const_int 4)]) (set_attr "psw_operand" "0,0,0,0,nop,0,nop")]) (define_expand "movsi" [(set (match_operand:SI 0 "<API key>" "") (match_operand:SI 1 "general_operand" ""))] "" "{ <API key> (SImode, operands[0], operands[1]); DONE; }") (<API key> "*movsi_internal" [(set (match_operand:SI 0 "<API key>" "=r,Q,r,m,e,&e,e,r,S") (match_operand:SI 1 "general_operand" "r,r,R,e,o, V,L,i,i"))] "" " "reload_completed" [(pc)] "{ <API key> (SImode, operands[0], operands[1]); DONE; }" [(<API key> "length" [(const_int 4) (const_int 4) (const_int 4) (if_then_else (match_operand:QI 0 "<API key>" "") (const_int 6) (const_int 8)) (if_then_else (match_operand:QI 1 "<API key>" "") (const_int 6) (const_int 8)) (if_then_else (match_operand:QI 1 "<API key>" "") (const_int 6) (const_int 8)) (const_int 4) (const_int 8) (const_int 8)])]) ;; :::::::::::::::::::: ;; :: ;; :: Conversions ;; :: ;; :::::::::::::::::::: (define_insn "extendqihi2" [(set (match_operand:HI 0 "register_operand" "=r") (sign_extend:HI (match_operand:QI 1 "register_operand" "0")))] "" "cbw %0") (define_insn "zero_extendqihi2" [(set (match_operand:HI 0 "register_operand" "=e,r") (zero_extend:HI (match_operand:QI 1 "<API key>" "m,0")))] "" "@ mov.b %0, %1 shl %0,#8\n\tshr %0,#8" [(set_attr "psw_operand" "nop,0") (<API key> "length" [(const_int 2) (const_int 4)])]) ;; :::::::::::::::::::: ;; :: ;; :: Bit field extraction ;; :: ;; :::::::::::::::::::: ;; Extract an unsigned bit field ;(define_insn "extzv" ; [(set (match_operand:SI 0 "register_operand" "=r") ; (zero_extract:SI (match_operand:SI 1 "register_operand" "r") ; (match_operand:SI 2 "const_int_operand" "n") ; (match_operand:SI 3 "const_int_operand" "n")))] ; "" ; "extzv %0,%1,%2,%3" ; [(set_attr "length" "4")]) ;; Insert a bit field ;(define_insn "insv" ; [(set (zero_extract:SI (match_operand:SI 0 "register_operand" "+r") ; (match_operand:SI 1 "const_int_operand" "n") ; (match_operand:SI 2 "const_int_operand" "n")) ; (match_operand:SI 3 "nonmemory_operand" "ri"))] ; "" ; "insv %0,%1,%2,%3" ; [(set_attr "length" "4")]) ;; :::::::::::::::::::: ;; :: ;; :: 16 bit Integer arithmetic ;; :: ;; :::::::::::::::::::: ;; Addition ; Operand 3 is marked earlyclobber because that helps reload ; to generate better code---this pattern will never need the ; carry register as an input, and some output reloads or input ; reloads might need to use it. In fact, without the '&' reload ; will fail in some cases. (define_insn "addhi3" [(set (match_operand:HI 0 "register_operand" "=r,r,T,T,r,r,r") (plus:HI (match_operand:HI 1 "register_operand" "%0,0,0,0,0,0,0") (match_operand:HI 2 "nonmemory_operand" "O,P,L,M,Ir,N,i"))) (clobber (match_scratch:BI 3 "=X,X,&y,&y,&y,&y,&y"))] "" "@ inc %0,%o2 dec %0,%O2 add Rx,%2 sub Rx, add %0,%2 sub %0, add %0,%2" [(set_attr "length" "2,2,2,2,2,2,4")]) ; Reload can generate addition operations. The <API key> ; macro causes it to allocate the carry register; this pattern ; shows it how to place the register in RTL to make the addition work. (define_expand "reload_inhi" [(parallel [(set (match_operand:HI 0 "register_operand" "=r") (match_operand:HI 1 "<API key>" "")) (clobber (match_operand:BI 2 "" "=&y"))])] "" "if (! rtx_equal_p (operands[0], XEXP (operands[1], 0))) { emit_insn (gen_rtx_SET (VOIDmode, operands[0], XEXP (operands[1], 0))); operands[1] = gen_rtx_PLUS (GET_MODE (operands[1]), operands[0], XEXP (operands[1], 1)); } ") (define_insn "addchi4" [(set (match_operand:HI 0 "register_operand" "=T,r,r") (plus:HI (match_operand:HI 1 "register_operand" "%0,0,0") (match_operand:HI 2 "nonmemory_operand" "L,Ir,i"))) (set (match_operand:BI 3 "register_operand" "=y,y,y") (truncate:BI (lshiftrt:SI (plus:SI (zero_extend:SI (match_dup 1)) (zero_extend:SI (match_dup 2))) (const_int 16))))] "" "@ add Rx,%2 add %0,%2 add %0,%2" [(set_attr "length" "2,2,4")]) (define_insn "addchi5" [(set (match_operand:HI 0 "register_operand" "=T,r,r") (plus:HI (plus:HI (match_operand:HI 1 "register_operand" "%0,0,0") (zero_extend:HI (match_operand:BI 3 "register_operand" "y,y,y"))) (match_operand:HI 2 "nonmemory_operand" "L,Ir,i"))) (set (match_operand:BI 4 "register_operand" "=y,y,y") (truncate:BI (lshiftrt:SI (plus:SI (plus:SI (zero_extend:SI (match_dup 1)) (zero_extend:SI (match_dup 3))) (zero_extend:SI (match_dup 2))) (const_int 16))))] "" "@ adc Rx,%2 adc %0,%2 adc %0,%2" [(set_attr "length" "2,2,4")]) ;; Subtraction ; Operand 3 is marked earlyclobber because that helps reload ; to generate better code---this pattern will never need the ; carry register as an input, and some output reloads or input ; reloads might need to use it. In fact, without the '&' reload ; will fail in some cases. (define_insn "subhi3" [(set (match_operand:HI 0 "register_operand" "=r,r,T,T,r,r,r") (minus:HI (match_operand:HI 1 "register_operand" "0,0,0,0,0,0,0") (match_operand:HI 2 "nonmemory_operand" "O,P,L,M,rI,M,i"))) (clobber (match_scratch:BI 3 "=X,X,&y,&y,&y,&y,&y"))] "" "@ dec %0,%o2 inc %0,%O2 sub Rx,%2 add Rx, sub %0,%2 add %0, sub %0,%2" [(set_attr "length" "2,2,2,2,2,2,4")]) (define_insn "subchi4" [(set (match_operand:HI 0 "register_operand" "=T,r,r") (minus:HI (match_operand:HI 1 "register_operand" "0,0,0") (match_operand:HI 2 "nonmemory_operand" "L,Ir,i"))) (set (match_operand:BI 3 "register_operand" "=y,y,y") (truncate:BI (lshiftrt:SI (minus:SI (zero_extend:SI (match_dup 1)) (zero_extend:SI (match_dup 2))) (const_int 16))))] "" "@ sub Rx,%2 sub %0,%2 sub %0,%2" [(set_attr "length" "2,2,4")]) (define_insn "subchi5" [(set (match_operand:HI 0 "register_operand" "=T,r,r") (minus:HI (minus:HI (match_operand:HI 1 "register_operand" "0,0,0") (zero_extend:HI (match_operand:BI 3 "register_operand" "y,y,y"))) (match_operand:HI 2 "nonmemory_operand" "L,Ir,i"))) (set (match_operand:BI 4 "register_operand" "=y,y,y") (truncate:BI (lshiftrt:SI (minus:SI (minus:SI (zero_extend:SI (match_dup 1)) (zero_extend:SI (match_dup 3))) (zero_extend:SI (match_dup 2))) (const_int 16))))] "" "@ sbc Rx,%2 sbc %0,%2 sbc %0,%2" [(set_attr "length" "2,2,4")]) ; Basic multiplication (define_insn "mulhi3" [(set (match_operand:HI 0 "register_operand" "=a") (mult:HI (match_operand:HI 1 "register_operand" "%a") (match_operand:HI 2 "register_operand" "c"))) (clobber (match_scratch:HI 3 "=b")) ] "" "mul" [(set_attr "psw_operand" "nop")]) ;; Unsigned multiplication producing 64 bit results from 32 bit inputs ; The constraint on operand 0 is 't' because it is actually two regs ; long, and both regs must match the constraint. (define_insn "umulhisi3" [(set (match_operand:SI 0 "register_operand" "=t") (mult:SI (zero_extend:SI (match_operand:HI 1 "register_operand" "%a")) (zero_extend:SI (match_operand:HI 2 "register_operand" "c")))) ] "" "mul" [(set_attr "psw_operand" "nop")]) ;; Unsigned division giving both quotient and remainder (define_insn "udivmodhi4" [(set (match_operand:HI 0 "register_operand" "=a") (udiv:HI (match_operand:HI 1 "register_operand" "a") (match_operand:HI 2 "register_operand" "c"))) (set (match_operand:HI 3 "register_operand" "=b") (umod:HI (match_dup 1) (match_dup 2)))] "" "div" [(set_attr "psw_operand" "nop")]) ;; Negation (define_expand "neghi2" [(set (match_operand:HI 0 "register_operand" "") (not:HI (match_operand:HI 1 "register_operand" ""))) (parallel [(set (match_dup 0) (plus:HI (match_dup 0) (const_int 1))) (clobber (match_scratch:BI 3 ""))])] "" "") ;; :::::::::::::::::::: ;; :: ;; :: 16 bit Integer Shifts and Rotates ;; :: ;; :::::::::::::::::::: ;; Arithmetic Shift Left (define_insn "ashlhi3" [(set (match_operand:HI 0 "register_operand" "=r") (ashift:HI (match_operand:HI 1 "register_operand" "0") (match_operand:HI 2 "nonmemory_operand" "ri"))) (clobber (match_scratch:BI 3 "=y"))] "" "shl %0,%2") ;; Arithmetic Shift Right (define_insn "ashrhi3" [(set (match_operand:HI 0 "register_operand" "=r") (ashiftrt:HI (match_operand:HI 1 "register_operand" "0") (match_operand:HI 2 "nonmemory_operand" "ri"))) (clobber (match_scratch:BI 3 "=y"))] "" "asr %0,%2") ;; Logical Shift Right (define_insn "lshrhi3" [(set (match_operand:HI 0 "register_operand" "=r") (lshiftrt:HI (match_operand:HI 1 "register_operand" "0") (match_operand:HI 2 "nonmemory_operand" "ri"))) (clobber (match_scratch:BI 3 "=y"))] "" "shr %0,%2") ;; :::::::::::::::::::: ;; :: ;; :: 16 Bit Integer Logical operations ;; :: ;; :::::::::::::::::::: ;; Logical AND, 16 bit integers (define_insn "andhi3" [(set (match_operand:HI 0 "register_operand" "=T,r,r,r") (and:HI (match_operand:HI 1 "register_operand" "%0,0,0,0") (match_operand:HI 2 "nonmemory_operand" "L,r,K,i")))] "" "@ and Rx,%2 and %0,%2 clr1 %0,%B2 and %0,%2" [(set_attr "length" "2,2,2,4")]) ;; Inclusive OR, 16 bit integers (define_insn "iorhi3" [(set (match_operand:HI 0 "register_operand" "=T,r,r,r") (ior:HI (match_operand:HI 1 "register_operand" "%0,0,0,0") (match_operand:HI 2 "nonmemory_operand" "L,r,J,i")))] "" "@ or Rx,%2 or %0,%2 set1 %0,%B2 or %0,%2" [(set_attr "length" "2,2,2,4")]) ;; Exclusive OR, 16 bit integers (define_insn "xorhi3" [(set (match_operand:HI 0 "register_operand" "=T,r,r") (xor:HI (match_operand:HI 1 "register_operand" "%0,0,0") (match_operand:HI 2 "nonmemory_operand" "L,r,i")))] "" "@ xor Rx,%2 xor %0,%2 xor %0,%2" [(set_attr "length" "2,2,4")]) ;; One's complement, 16 bit integers (define_insn "one_cmplhi2" [(set (match_operand:HI 0 "register_operand" "=r") (not:HI (match_operand:HI 1 "register_operand" "0")))] "" "not %0") ;; :::::::::::::::::::: ;; :: ;; :: 32 bit Integer arithmetic ;; :: ;; :::::::::::::::::::: ;; Addition (<API key> "addsi3" [(set (match_operand:SI 0 "register_operand" "=r") (plus:SI (match_operand:SI 1 "register_operand" "%0") (match_operand:SI 2 "nonmemory_operand" "ri"))) (clobber (match_scratch:BI 3 "=y"))] "" " "reload_completed" [(pc)] "{ <API key> (SImode, PLUS, operands[0], operands[1], operands[2], operands[3]); DONE; } " [(set_attr "length" "4")]) ;; Subtraction (<API key> "subsi3" [(set (match_operand:SI 0 "register_operand" "=r") (minus:SI (match_operand:SI 1 "register_operand" "0") (match_operand:SI 2 "nonmemory_operand" "ri"))) (clobber (match_scratch:BI 3 "=y"))] "" " "reload_completed" [(pc)] "{ <API key> (SImode, MINUS, operands[0], operands[1], operands[2], operands[3]); DONE; } " [(set_attr "length" "4")]) (define_expand "negsi2" [(set (match_operand:SI 0 "register_operand" "") (neg:SI (match_operand:SI 1 "register_operand" "")))] "" "{ <API key> (SImode, NEG, operands[0], const0_rtx, operands[1], gen_reg_rtx (BImode)); DONE; }") ;; :::::::::::::::::::: ;; :: ;; :: 32 bit Integer Shifts and Rotates ;; :: ;; :::::::::::::::::::: ;; Arithmetic Shift Left (define_expand "ashlsi3" [(parallel [(set (match_operand:SI 0 "register_operand" "") (ashift:SI (match_operand:SI 1 "register_operand" "") (match_operand:SI 2 "const_int_operand" ""))) (clobber (match_dup 3)) (clobber (match_dup 4))])] "" " if (! const_int_operand (operands[2], SImode)) FAIL; operands[3] = gen_reg_rtx (BImode); operands[4] = gen_reg_rtx (HImode); ") ;; Arithmetic Shift Right (define_expand "ashrsi3" [(parallel [(set (match_operand:SI 0 "register_operand" "") (ashiftrt:SI (match_operand:SI 1 "register_operand" "") (match_operand:SI 2 "const_int_operand" ""))) (clobber (match_dup 3)) (clobber (match_dup 4))])] "" " if (! const_int_operand (operands[2], SImode)) FAIL; operands[3] = gen_reg_rtx (BImode); operands[4] = gen_reg_rtx (HImode); ") ;; Logical Shift Right (define_expand "lshrsi3" [(parallel [(set (match_operand:SI 0 "register_operand" "") (lshiftrt:SI (match_operand:SI 1 "register_operand" "") (match_operand:SI 2 "const_int_operand" ""))) (clobber (match_dup 3)) (clobber (match_dup 4))])] "" " if (! const_int_operand (operands[2], SImode)) FAIL; operands[3] = gen_reg_rtx (BImode); operands[4] = gen_reg_rtx (HImode); ") (define_insn "*shiftsi" [(set (match_operand:SI 0 "register_operand" "=r,r") (match_operator:SI 5 "shift_operator" [(match_operand:SI 1 "register_operand" "0,0") (match_operand:SI 2 "const_int_operand" "U,n")])) (clobber (match_operand:BI 3 "register_operand" "=y,y")) (clobber (match_operand:HI 4 "" "=X,r"))] "" "* return <API key> (SImode, GET_CODE (operands[5]), operands[0], operands[2], operands[4]);" [(set_attr "length" "6,10") (set_attr "psw_operand" "clobber,clobber")]) ;; :::::::::::::::::::: ;; :: ;; :: Comparisons ;; :: ;; :::::::::::::::::::: ;; Note, we store the operands in the comparison insns, and use them later ;; when generating the branch or scc operation. ;; First the routines called by the machine independent part of the compiler (define_expand "cmphi" [(set (cc0) (compare (match_operand:HI 0 "register_operand" "") (match_operand:HI 1 "nonmemory_operand" "")))] "" " { <API key> = operands[0]; <API key> = operands[1]; DONE; }") ; There are no real SImode comparisons, but some can be emulated ; by performing a SImode subtract and looking at the condition flags. (define_expand "cmpsi" [(set (cc0) (compare (match_operand:SI 0 "register_operand" "") (match_operand:SI 1 "nonmemory_operand" "")))] "" " { <API key> = operands[0]; <API key> = operands[1]; DONE; }") ;; :::::::::::::::::::: ;; :: ;; :: Branches ;; :: ;; :::::::::::::::::::: (define_expand "beq" [(use (match_operand 0 "" ""))] "" "{ <API key> (EQ, operands[0]); DONE; }") (define_expand "bne" [(use (match_operand 0 "" ""))] "" "{ <API key> (NE, operands[0]); DONE; }") (define_expand "bge" [(use (match_operand 0 "" ""))] "" "{ <API key> (GE, operands[0]); DONE; }") (define_expand "bgt" [(use (match_operand 0 "" ""))] "" "{ <API key> (GT, operands[0]); DONE; }") (define_expand "ble" [(use (match_operand 0 "" ""))] "" "{ <API key> (LE, operands[0]); DONE; }") (define_expand "blt" [(use (match_operand 0 "" ""))] "" "{ <API key> (LT, operands[0]); DONE; }") (define_expand "bgeu" [(use (match_operand 0 "" ""))] "" "{ <API key> (GEU, operands[0]); DONE; }") (define_expand "bgtu" [(use (match_operand 0 "" ""))] "" "{ <API key> (GTU, operands[0]); DONE; }") (define_expand "bleu" [(use (match_operand 0 "" ""))] "" "{ <API key> (LEU, operands[0]); DONE; }") (define_expand "bltu" [(use (match_operand 0 "" ""))] "" "{ <API key> (LTU, operands[0]); DONE; }") (define_insn "*cbranchhi" [(set (pc) (if_then_else (match_operator:HI 1 "comparison_operator" [(match_operand:HI 2 "nonmemory_operand" "r,e,L") (match_operand:HI 3 "nonmemory_operand" "r,L,e")]) (label_ref (match_operand 0 "" "")) (pc))) (clobber (match_operand:BI 4 "" "=&y,&y,&y"))] "" "* { return <API key> (operands[1], \"%l0\", 0, insn); }" [(set_attr "branch_class" "bcc12") (set_attr "psw_operand" "0,0,1")]) (define_insn "*cbranchhi_neg" [(set (pc) (if_then_else (match_operator:HI 1 "comparison_operator" [(match_operand:HI 2 "nonmemory_operand" "r,e,L") (match_operand:HI 3 "nonmemory_operand" "r,L,e")]) (pc) (label_ref (match_operand 0 "" "")))) (clobber (match_operand:BI 4 "" "=&y,&y,&y"))] "" "* { return <API key> (operands[1], \"%l0\", 1, insn); }" [(set_attr "branch_class" "bcc12") (set_attr "psw_operand" "0,0,1")]) (define_insn "*eqbranchsi" [(set (pc) (if_then_else (match_operator:SI 1 "equality_operator" [(match_operand:SI 2 "register_operand" "+r") (const_int 0)]) (label_ref (match_operand 0 "" "")) (pc))) ;; Although I would greatly like the 'match_dup' in the following line ;; to actually be a register constraint, there is (at the time of writing) no ;; way for reload to insert an output reload on the edges out of a branch. ;; If reload is fixed to use insert_insn_on_edge, this can be changed. (clobber (match_dup 2))] "" "* { return <API key> (operands[1], \"%l0\", 0, insn); }" [(set_attr "branch_class" "bcc8p2") (set_attr "psw_operand" "clobber")]) (<API key> "*ineqbranchsi" [(set (pc) (if_then_else (match_operator:SI 1 "<API key>" [(match_operand:SI 2 "register_operand" "+r") (match_operand:SI 3 "nonmemory_operand" "ri")]) (label_ref (match_operand 0 "" "")) (pc))) ;; Although I would greatly like the 'match_dup' in the following line ;; to actually be a register constraint, there is (at the time of writing) no ;; way for reload to insert an output reload on the edges out of a branch. ;; If reload is fixed to use insert_insn_on_edge, this can be changed, ;; preferably to a 'minus' operand that explains the actual operation, like: ; (set (match_operand 5 "register_operand" "=2") ; (minus:SI (match_operand 6 "register_operand" "2") ; (match_operand 7 "register_operand" "3"))) (clobber (match_dup 2)) (clobber (match_operand:BI 4 "" "=&y"))] "" " "reload_completed" [(pc)] "{ <API key> (SImode, operands[0], operands[1], operands[2], operands[4]); DONE; }" [(set_attr "length" "8")]) (define_insn "*ineqbranch_1" [(set (pc) (if_then_else (match_operator:HI 5 "<API key>" [(minus:HI (match_operand:HI 1 "register_operand" "T,r,r") (zero_extend:HI (match_operand:BI 4 "register_operand" "y,y,y"))) (match_operand:HI 3 "nonmemory_operand" "L,Ir,i")]) (label_ref (match_operand 0 "" "")) (pc))) (set (match_operand:HI 2 "register_operand" "=2,2,2") (minus:HI (minus:HI (match_dup 1) (zero_extend:HI (match_dup 4))) (match_dup 3))) (clobber (match_operand:BI 6 "" "=y,y,y"))] "" "* { return <API key> (operands[5], \"%l0\", 0, insn); }" [(set_attr "branch_class" "bcc8p2,bcc8p2,bcc8p4") (set_attr "psw_operand" "2,2,2")]) ;; :::::::::::::::::::: ;; :: ;; :: Call and branch instructions ;; :: ;; :::::::::::::::::::: ;; Subroutine call instruction returning no value. Operand 0 is the function ;; to call; operand 1 is the number of bytes of arguments pushed (in mode ;; `SImode', except it is normally a `const_int'); operand 2 is the number of ;; registers used as operands. ;; On most machines, operand 2 is not actually stored into the RTL pattern. It ;; is supplied for the sake of some RISC machines which need to put this ;; information into the assembler code; they can put it in the RTL instead of ;; operand 1. (define_expand "call" [(call (match_operand:HI 0 "memory_operand" "m") (match_operand 1 "" "")) (use (match_operand 2 "immediate_operand" ""))] "" "<API key> (NULL_RTX, operands[0], operands[1]); DONE;") ;; Subroutine call instruction returning a value. Operand 0 is the hard ;; register in which the value is returned. There are three more operands, the ;; same as the three operands of the `call' instruction (but with numbers ;; increased by one). ;; Subroutines that return `BLKmode' objects use the `call' insn. (define_expand "call_value" [(set (match_operand 0 "register_operand" "=r") (call (match_operand:HI 1 "memory_operand" "m") (match_operand:SI 2 "" ""))) (use (match_operand 3 "immediate_operand" ""))] "" "<API key> (operands[0], operands[1], operands[2]); DONE;") (define_insn "*call_internal" [(call (mem:HI (match_operand:HI 0 "nonmemory_operand" "i,r")) (match_operand 1 "" "")) (use (match_operand:HI 2 "nonmemory_operand" "X,z"))] "" "@ callf %C0 call %2,%0" [(set_attr "length" "4,2") (set_attr "psw_operand" "clobber")]) (define_insn "*call_value_internal" [(set (match_operand 3 "register_operand" "=r,r") (call (mem:HI (match_operand:HI 0 "nonmemory_operand" "i,r")) (match_operand 1 "" ""))) (use (match_operand:HI 2 "nonmemory_operand" "X,z"))] "" "@ callf %C0 call %2,%0" [(set_attr "length" "4,2") (set_attr "psw_operand" "clobber")]) ;; Subroutine return (define_expand "return" [(return)] "direct_return()" "") (define_insn "return_internal" [(return)] "" "ret" [(set_attr "psw_operand" "nop")]) (define_insn "<API key>" [(return) (unspec_volatile [(const_int 0)] 1)] "" "iret" [(set_attr "psw_operand" "clobber")]) ;; Normal unconditional jump (define_insn "jump" [(set (pc) (label_ref (match_operand 0 "" "")))] "" "* { return <API key> (NULL_RTX, \"%l0\", 0, insn); }" [(set_attr "branch_class" "br12") (set_attr "psw_operand" "nop")]) ;; Indirect jump through a register (define_expand "indirect_jump" [(set (match_dup 1) (const_int 0)) (parallel [(set (pc) (match_operand:HI 0 "register_operand" "r")) (use (match_dup 1))])] "" "operands[1] = gen_reg_rtx (HImode);") (define_insn "" [(set (pc) (match_operand:HI 0 "register_operand" "r")) (use (match_operand:HI 1 "register_operand" "z"))] "" "jmp %1,%0" [(set_attr "length" "4") (set_attr "psw_operand" "nop")]) ;; Table-based switch statements. (define_expand "casesi" [(use (match_operand:SI 0 "register_operand" "")) (use (match_operand:SI 1 "immediate_operand" "")) (use (match_operand:SI 2 "immediate_operand" "")) (use (label_ref (match_operand 3 "" ""))) (use (label_ref (match_operand 4 "" "")))] "" " { <API key> (operands[0], operands[1], operands[2], operands[3], operands[4]); DONE; }") (define_insn "tablejump_pcrel" [(set (pc) (mem:HI (plus:HI (pc) (match_operand:HI 0 "register_operand" "r")))) (use (label_ref:SI (match_operand 1 "" "")))] "" "br %0" [(set_attr "psw_operand" "nop")]) ;; :::::::::::::::::::: ;; :: ;; :: Prologue and Epilogue instructions ;; :: ;; :::::::::::::::::::: ;; Called after register allocation to add any instructions needed for ;; the prologue. Using a prologue insn is favored compared to putting ;; all of the instructions in the <API key> macro, ;; since it allows the scheduler to intermix instructions with the ;; saves of the caller saved registers. In some cases, it might be ;; necessary to emit a barrier instruction as the last insn to prevent ;; such scheduling. (define_expand "prologue" [(const_int 1)] "" " { <API key> (); DONE; }") ;; Called after register allocation to add any instructions needed for ;; the epilogue. Using an epilogue insn is favored compared to putting ;; all of the instructions in the <API key> macro, ;; since it allows the scheduler to intermix instructions with the ;; restires of the caller saved registers. In some cases, it might be ;; necessary to emit a barrier instruction as the first insn to ;; prevent such scheduling. (define_expand "epilogue" [(const_int 2)] "" " { <API key> (); DONE; }") ;; :::::::::::::::::::: ;; :: ;; :: Miscellaneous instructions ;; :: ;; :::::::::::::::::::: ;; No operation, needed in case the user uses -g but not -O. (define_insn "nop" [(const_int 0)] "" "nop" [(set_attr "psw_operand" "nop")]) ;; Pseudo instruction that prevents the scheduler from moving code above this ;; point. (define_insn "blockage" [(unspec_volatile [(const_int 0)] 0)] "" "" [(set_attr "length" "0") (set_attr "psw_operand" "nop")])
#include "gmp.h" #include "gmp-impl.h" void mpq_div (mpq_ptr quot, mpq_srcptr op1, mpq_srcptr op2) { mpz_t gcd1, gcd2; mpz_t tmp1, tmp2; mpz_t numtmp; mp_size_t op1_num_size; mp_size_t op1_den_size; mp_size_t op2_num_size; mp_size_t op2_den_size; mp_size_t alloc; TMP_DECL; op2_num_size = ABSIZ(NUM(op2)); if (UNLIKELY (op2_num_size == 0)) DIVIDE_BY_ZERO; op1_num_size = ABSIZ(NUM(op1)); if (op1_num_size == 0) { /* We special case this to simplify allocation logic; gcd(0,x) = x is a singular case for the allocations. */ SIZ(NUM(quot)) = 0; PTR(DEN(quot))[0] = 1; SIZ(DEN(quot)) = 1; return; } op2_den_size = SIZ(DEN(op2)); op1_den_size = SIZ(DEN(op1)); TMP_MARK; alloc = MIN (op1_num_size, op2_num_size); MPZ_TMP_INIT (gcd1, alloc); alloc = MIN (op1_den_size, op2_den_size); MPZ_TMP_INIT (gcd2, alloc); alloc = MAX (op1_num_size, op2_num_size); MPZ_TMP_INIT (tmp1, alloc); alloc = MAX (op1_den_size, op2_den_size); MPZ_TMP_INIT (tmp2, alloc); alloc = op1_num_size + op2_den_size; MPZ_TMP_INIT (numtmp, alloc); /* QUOT might be identical to either operand, so don't store the result there until we are finished with the input operands. We can overwrite the numerator of QUOT when we are finished with the numerators of OP1 and OP2. */ mpz_gcd (gcd1, NUM(op1), NUM(op2)); mpz_gcd (gcd2, DEN(op2), DEN(op1)); mpz_divexact_gcd (tmp1, NUM(op1), gcd1); mpz_divexact_gcd (tmp2, DEN(op2), gcd2); mpz_mul (numtmp, tmp1, tmp2); mpz_divexact_gcd (tmp1, NUM(op2), gcd1); mpz_divexact_gcd (tmp2, DEN(op1), gcd2); mpz_mul (DEN(quot), tmp1, tmp2); /* We needed to go via NUMTMP to take care of QUOT being the same as OP2. Now move NUMTMP to QUOT->_mp_num. */ mpz_set (NUM(quot), numtmp); /* Keep the denominator positive. */ if (SIZ(DEN(quot)) < 0) { SIZ(DEN(quot)) = -SIZ(DEN(quot)); SIZ(NUM(quot)) = -SIZ(NUM(quot)); } TMP_FREE; }
#ifndef <API key> #define <API key> #include "Particle.h" class SimulationSample { public: Particle particle; int ParticleID; int PositionX, PositionY; float AirPressure; float AirTemperature; float AirVelocityX; float AirVelocityY; int WallType; float Gravity; float GravityVelocityX; float GravityVelocityY; int NumParts; bool isMouseInSim; SimulationSample() : PositionX(0), PositionY(0), ParticleID(0), particle(), AirPressure(0), AirVelocityX(0), AirVelocityY(0), WallType(0), Gravity(0), GravityVelocityX(0), GravityVelocityY(0), AirTemperature(0), NumParts(0), isMouseInSim(true) {} }; #endif
s = new ShardingTest( "diffservers1" , 2 ); assert.eq( 2 , s.config.shards.count() , "server count wrong" ); assert.eq( 2 , s._connections[0].getDB( "config" ).shards.count() , "where are servers!" ); assert.eq( 0 , s._connections[1].getDB( "config" ).shards.count() , "shouldn't be here" ); test1 = s.getDB( "test1" ).foo; test1.save( { a : 1 } ); test1.save( { a : 2 } ); test1.save( { a : 3 } ); assert( 3 , test1.count() ); assert( ! s.admin.runCommand( { addshard: "sdd$%" } ).ok , "bad hostname" ); assert( ! s.admin.runCommand( { addshard: "127.0.0.1:43415" } ).ok , "host not up" ); assert( ! s.admin.runCommand( { addshard: "10.0.0.1:43415" } ).ok , "allowed shard in IP when config is localhost" ); s.stop();
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 4 -*- // IndexHash.h: Rcpp R/C++ interface class library -- hashing utility, inspired // from Simon's fastmatch package // This file is part of Rcpp. // Rcpp is free software: you can redistribute it and/or modify it // (at your option) any later version. // Rcpp is distributed in the hope that it will be useful, but // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #ifndef <API key> #define <API key> #if ( defined(HASH_PROFILE) && defined(__APPLE__) ) // only mac version for now #include <mach/mach_time.h> #define ABSOLUTE_TIME mach_absolute_time #define RCPP_PROFILE_TIC start = ABSOLUTE_TIME() ; #define RCPP_PROFILE_TOC end = ABSOLUTE_TIME() ; #define RCPP_PROFILE_RECORD(name) profile_data[#name] = end - start ; #else #define RCPP_PROFILE_TIC #define RCPP_PROFILE_TOC #define RCPP_PROFILE_RECORD(name) #endif #define RCPP_USE_CACHE_HASH namespace Rcpp{ namespace sugar{ #ifndef RCPP_HASH #define RCPP_HASH(X) (3141592653U * ((unsigned int)(X)) >> (32 - k)) #endif template <int RTYPE> class IndexHash { public: typedef typename traits::storage_type<RTYPE>::type STORAGE ; typedef Vector<RTYPE> VECTOR ; IndexHash( SEXP table ) : n(Rf_length(table)), m(2), k(1), src( (STORAGE*)dataptr(table) ), size_(0) , data() #ifdef HASH_PROFILE , profile_data() #endif { RCPP_PROFILE_TIC int desired = n*2 ; while( m < desired ){ m *= 2 ; k++ ; } #ifdef RCPP_USE_CACHE_HASH data = get_cache(m) ; #else data.resize( m ) ; #endif RCPP_PROFILE_TOC RCPP_PROFILE_RECORD(ctor_body) } inline IndexHash& fill(){ RCPP_PROFILE_TIC for( int i=0; i<n; i++) add_value(i) ; RCPP_PROFILE_TOC RCPP_PROFILE_RECORD(fill) return *this ; } inline LogicalVector <API key>() { LogicalVector result = no_init(n) ; int* res = LOGICAL(result) ; for( int i=0; i<n; i++) res[i] = ! add_value(i) ; return result ; } template <typename T> inline SEXP lookup(const T& vec) const { return lookup__impl(vec, vec.size() ) ; } // use the pointers for actual (non sugar expression vectors) inline SEXP lookup(const VECTOR& vec) const { return lookup__impl(vec.begin(), vec.size() ) ; } inline bool contains(STORAGE val) const { return get_index(val) != NA_INTEGER ; } inline int size() const { return size_ ; } // keys, in the order they appear in the data inline Vector<RTYPE> keys() const{ Vector<RTYPE> res = no_init(size_) ; for( int i=0, j=0; j<size_; i++){ if( data[i] ) res[j++] = src[data[i]-1] ; } return res ; } int n, m, k ; STORAGE* src ; int size_ ; #ifdef RCPP_USE_CACHE_HASH int* data ; #else std::vector<int> data ; #endif #ifdef HASH_PROFILE mutable std::map<std::string,int> profile_data ; mutable uint64_t start ; mutable uint64_t end ; #endif template <typename T> SEXP lookup__impl(const T& vec, int n_) const { RCPP_PROFILE_TIC SEXP res = Rf_allocVector(INTSXP, n_) ; RCPP_PROFILE_TOC RCPP_PROFILE_RECORD(allocVector) int *v = INTEGER(res) ; RCPP_PROFILE_TIC for( int i=0; i<n_; i++) v[i] = get_index( vec[i] ) ; RCPP_PROFILE_TOC RCPP_PROFILE_RECORD(lookup) return res ; } SEXP get_profile_data(){ #ifdef HASH_PROFILE return wrap( profile_data ) ; #else return R_NilValue ; #endif } inline bool not_equal(const STORAGE& lhs, const STORAGE& rhs) { return ! internal::NAEquals<STORAGE>()(lhs, rhs); } bool add_value(int i){ RCPP_DEBUG_2( "%s::add_value(%d)", DEMANGLE(IndexHash), i ) STORAGE val = src[i++] ; int addr = get_addr(val) ; while (data[addr] && not_equal( src[data[addr] - 1], val)) { addr++; if (addr == m) { addr = 0; } } if (!data[addr]){ data[addr] = i ; size_++ ; return true ; } return false; } /* NOTE: we are returning a 1-based index ! */ inline int get_index(STORAGE value) const { int addr = get_addr(value) ; while (data[addr]) { if (src[data[addr] - 1] == value) return data[addr]; addr++; if (addr == m) addr = 0; } return NA_INTEGER; } // defined below int get_addr(STORAGE value) const ; } ; template <> inline int IndexHash<INTSXP>::get_addr(int value) const { return RCPP_HASH(value) ; } template <> inline int IndexHash<REALSXP>::get_addr(double val) const { int addr; union dint_u { double d; unsigned int u[2]; }; union dint_u val_u; /* double is a bit tricky - we nave to normalize 0.0, NA and NaN */ if (val == 0.0) val = 0.0; if (internal::Rcpp_IsNA(val)) val = NA_REAL; else if (internal::Rcpp_IsNaN(val)) val = R_NaN; val_u.d = val; addr = RCPP_HASH(val_u.u[0] + val_u.u[1]); return addr ; } template <> inline int IndexHash<STRSXP>::get_addr(SEXP value) const { intptr_t val = (intptr_t) value; int addr; #if (defined _LP64) || (defined __LP64__) || (defined WIN64) addr = RCPP_HASH((val & 0xffffffff) ^ (val >> 32)); #else addr = RCPP_HASH(val); #endif return addr ; } } // sugar } // Rcpp #endif
<?php return array( 'group_exists' => 'குழு ஏற்கனவே உள்ளது!', 'group_not_found' => 'குழு [: id] இல்லை.', 'group_name_required' => 'பெயர் புலம் தேவை', 'success' => array( 'create' => 'குழு வெற்றிகரமாக உருவாக்கப்பட்டது.', 'update' => 'குழு வெற்றிகரமாக புதுப்பிக்கப்பட்டது.', 'delete' => 'குழு வெற்றிகரமாக நீக்கப்பட்டது.', ), 'delete' => array( 'confirm' => 'இந்த குழுவையை நிச்சயமாக நீக்க விரும்புகிறீர்களா?', 'create' => 'குழுவை உருவாக்கும் ஒரு சிக்கல் இருந்தது. தயவு செய்து மீண்டும் முயற்சிக்கவும்.', 'update' => 'குழுவை புதுப்பிப்பதில் சிக்கல் ஏற்பட்டது. தயவு செய்து மீண்டும் முயற்சிக்கவும்.', 'delete' => 'குழுவை நீக்குவதில் ஒரு சிக்கல் இருந்தது. தயவு செய்து மீண்டும் முயற்சிக்கவும்.', ), );
# -*- coding: utf-8 -*- from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" <API key> = fields.Char(string='Authorization Code') google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI', help="The URL to generate the authorization code from Google") @api.depends('<API key>') def _compute_drive_uri(self): google_drive_uri = self.env['google.service'].<API key>('drive', scope=self.env['google.drive.config'].get_google_scope()) for config in self: config.google_drive_uri = google_drive_uri @api.model def get_values(self): res = super(ResConfigSettings, self).get_values() res.update( <API key>=self.env['ir.config_parameter'].sudo().get_param('<API key>'), ) return res def set_values(self): super(ResConfigSettings, self).set_values() params = self.env['ir.config_parameter'].sudo() authorization_code = self.<API key> refresh_token = False if authorization_code and authorization_code != params.get_param('<API key>'): refresh_token = self.env['google.service'].<API key>('drive', authorization_code) params.set_param('<API key>', authorization_code) params.set_param('<API key>', refresh_token)
#Track Items Using Barcode A barcode is a value decoded into vertical spaced lines. Barcode scanners are the input medium, like Keyboard. When it scans a barcode, the data appears in the computer screens at the point of a cursor. To enable barcode feature in ERPNext go to: `Setup > Customize > Features Setup` Check "Item Barcode". <img alt="Material Transfer" class="screenshot" src="{{docs_base_url}}/assets/img/articles/<API key>.png"> Now a new field "Barcode" will be appear in Item master. Enter barcode while creating a new item. <img alt="Material Transfer" class="screenshot" src="{{docs_base_url}}/assets/img/articles/barcode-item-master.png"> Once barcode field is updated in item master, items can be fetched using barcode. This feature will be availble in Delivery Note, Sales Invoice and Purchase Receipt transactions only. <img alt="Material Transfer" class="screenshot" src="{{docs_base_url}}/assets/img/articles/<API key>.gif"> <!-- markdown -->
#include <config.h> #include "ref.h" #include <stdlib.h> int ref_make_ref(void *ptrptr, size_t size, size_t ref_ofs) { *(void**) ptrptr = calloc(1, size); if (*(void **)ptrptr == NULL) { return -1; } else { void *ptr = *(void **)ptrptr; *((ref_t *) ((char*) ptr + ref_ofs)) = 1; return 0; } } /* * Local variables: * indent-tabs-mode: nil * c-indent-level: 4 * c-basic-offset: 4 * tab-width: 4 * End: */
// @(#)root/ged:$Id$ #ifndef ROOT_TAxisEditor #define ROOT_TAxisEditor // TAxisEditor // // Implements GUI for axis attributes. // #ifndef ROOT_TGedFrame #include "TGedFrame.h" #endif class TAxis; class TGLabel; class TGComboBox; class TGNumberEntry; class TGTextEntry; class TGCheckButton; class TGColorSelect; class TGFontTypeComboBox; class TAxisEditor : public TGedFrame { protected: TAxis *fAxis; // axis object TGColorSelect *fAxisColor; // color selection widget TGCheckButton *fLogAxis; // logarithmic check box TGNumberEntry *fTickLength; // tick length number entry TGNumberEntry *fDiv1; // primary axis division number entry TGNumberEntry *fDiv2; // secondary axis division number entry TGNumberEntry *fDiv3; // tertiary axis division number entry TGCheckButton *fOptimize; // tick optimization check box TGCheckButton *fTicksBoth; // check box setting ticks on both axis sides TGCheckButton *fMoreLog; // more logarithmic labels check box Int_t fTicksFlag; // positive/negative ticks' flag TGTextEntry *fTitle; // axis title input field TGColorSelect *fTitleColor; // color selection widget TGFontTypeComboBox *fTitleFont; // title font combo box Int_t fTitlePrec; // font precision level TGNumberEntry *fTitleSize; // title size number entry TGNumberEntry *fTitleOffset; // title offset number entry TGCheckButton *fCentered; // check button for centered title TGCheckButton *fRotated; // check button for rotated title TGColorSelect *fLabelColor; // color selection widget TGFontTypeComboBox *fLabelFont; // label font combo box Int_t fLabelPrec; // font precision level TGNumberEntry *fLabelSize; // label size number entry TGNumberEntry *fLabelOffset; // label offset number entry TGCheckButton *fNoExponent; // check box for No exponent choice TGCheckButton *fDecimal; // decimal part check box virtual void <API key>(); public: TAxisEditor(const TGWindow *p = 0, Int_t width = 140, Int_t height = 30, UInt_t options = kChildFrame, Pixel_t back = <API key>()); virtual ~TAxisEditor(); virtual void SetModel(TObject* obj); // slots related to axis attributes virtual void DoTickLength(); virtual void DoAxisColor(Pixel_t color); virtual void DoTicks(); virtual void DoDivisions(); virtual void DoLogAxis(); virtual void DoMoreLog(); // slots related to axis title attributes virtual void DoTitleColor(Pixel_t color); virtual void DoTitle(const char *text); virtual void DoTitleSize(); virtual void DoTitleFont(Int_t font); virtual void DoTitleOffset(); virtual void DoTitleCentered(); virtual void DoTitleRotated(); // slots related to axis labels attributes virtual void DoLabelColor(Pixel_t color); virtual void DoLabelSize(); virtual void DoLabelFont(Int_t font); virtual void DoLabelOffset(); virtual void DoNoExponent(); virtual void DoDecimal(Bool_t on); ClassDef(TAxisEditor,0) // axis editor }; #endif
package org.fenixedu.academic.ui.faces.components.util; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import org.apache.struts.util.MessageResources; import org.fenixedu.academic.domain.Exam; import org.fenixedu.academic.domain.ExecutionCourse; import org.fenixedu.academic.domain.Project; import org.fenixedu.academic.domain.WrittenEvaluation; import org.fenixedu.academic.domain.WrittenTest; import org.fenixedu.academic.util.Bundle; import org.fenixedu.academic.util.DateFormatUtil; public class CalendarLink { private Calendar objectOccurrence; private String objectLinkLabel; private Map<String, String> linkParameters = new HashMap<String, String>(); private boolean asLink; public CalendarLink(boolean asLink) { setAsLink(asLink); } public CalendarLink() { this(true); } public CalendarLink(final ExecutionCourse executionCourse, final WrittenEvaluation writtenEvaluation, final Locale locale) { setObjectOccurrence(writtenEvaluation.getDay()); setObjectLinkLabel(<API key>(executionCourse, writtenEvaluation, locale)); } public CalendarLink(final ExecutionCourse executionCourse, final Project project, final Date date, final String tail, final Locale locale) { setObjectOccurrence(date); setObjectLinkLabel(<API key>(executionCourse, project, date, tail, locale)); } public void setObjectOccurrence(Calendar objectOccurrence) { this.objectOccurrence = objectOccurrence; } public void setObjectOccurrence(Date objectOccurrence) { final Calendar calendar = Calendar.getInstance(); calendar.setTime(objectOccurrence); this.objectOccurrence = calendar; } public Calendar getObjectOccurrence() { return this.objectOccurrence; } public void setObjectLinkLabel(String objectLinkLabel) { this.objectLinkLabel = objectLinkLabel; } public String getObjectLinkLabel() { return this.objectLinkLabel; } public void setLinkParameters(Map<String, String> linkParameters) { this.linkParameters = linkParameters; } public String giveLink(String editLinkPage) { final StringBuilder linkParameters = new StringBuilder(); linkParameters.append(editLinkPage); if (this.linkParameters != null && !this.linkParameters.isEmpty()) { linkParameters.append(editLinkPage.indexOf('?') > 0 ? '&' : '?'); for (final Iterator<Entry<String, String>> iterator = this.linkParameters.entrySet().iterator(); iterator.hasNext();) { final Entry<String, String> entry = iterator.next(); linkParameters.append(entry.getKey()); linkParameters.append('='); linkParameters.append(entry.getValue()); if (iterator.hasNext()) { linkParameters.append('&'); } } } return linkParameters.toString(); } public void addLinkParameter(final String key, final String value) { linkParameters.put(key, value); } private static final MessageResources messages = MessageResources.getMessageResources(Bundle.DEGREE); private String <API key>(final ExecutionCourse executionCourse, final WrittenEvaluation writtenEvaluation, final Locale locale) { final StringBuilder stringBuilder = new StringBuilder(); if (writtenEvaluation instanceof WrittenTest) { stringBuilder.append(messages.getMessage(locale, "label.evaluation.shortname.test")); } else if (writtenEvaluation instanceof Exam) { stringBuilder.append(messages.getMessage(locale, "label.evaluation.shortname.exam")); } stringBuilder.append(" "); stringBuilder.append(executionCourse.getSigla()); stringBuilder.append(" ("); stringBuilder.append(DateFormatUtil.format("HH:mm", writtenEvaluation.getBeginningDate())); stringBuilder.append("-"); stringBuilder.append(DateFormatUtil.format("HH:mm", writtenEvaluation.getEndDate())); stringBuilder.append(")"); return stringBuilder.toString(); } private String <API key>(final ExecutionCourse executionCourse, final Project project, final Date time, final String tail, final Locale locale) { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(messages.getMessage(locale, "label.evaluation.shortname.project")); stringBuilder.append(" "); stringBuilder.append(executionCourse.getSigla()); stringBuilder.append(" ("); stringBuilder.append(DateFormatUtil.format("HH:mm", time)); stringBuilder.append(") "); stringBuilder.append(tail); return stringBuilder.toString(); } public boolean isAsLink() { return asLink; } public void setAsLink(boolean asLink) { this.asLink = asLink; } }
// personal includes ".h" #include "EUTELESCOPE.h" #include "EUTelBaseDetector.h" #include "EUTelTLUDetector.h" // system includes <> #include <iostream> #include <iomanip> #include <vector> #include <string> using namespace std; using namespace eutelescope; EUTelTLUDetector::EUTelTLUDetector() : EUTelBaseDetector() { _name = "TLU"; // nothing else to do ! } void EUTelTLUDetector::setAndMask(unsigned short value) { _andMask = value; } void EUTelTLUDetector::setOrMask(unsigned short value) { _orMask = value; } void EUTelTLUDetector::setVetoMask(unsigned short value) { _vetoMask = value; } void EUTelTLUDetector::setDUTMask(unsigned short value) { _dutMask = value; } void EUTelTLUDetector::setFirmwareID(unsigned short value) { _firmwareID = value; } void EUTelTLUDetector::setTimeInterval(short value) { _timeInterval = value; } void EUTelTLUDetector::print(ostream &os) const { size_t w = 35; os << resetiosflags(ios::right) << setiosflags(ios::left) << setfill('.') << setw(w) << setiosflags(ios::left) << "Detector name " << resetiosflags(ios::left) << " " << _name << endl << setw(w) << setiosflags(ios::left) << "AndMask " << resetiosflags(ios::left) << " 0x" << to_hex(_andMask, 2) << endl << setw(w) << setiosflags(ios::left) << "OrMask " << resetiosflags(ios::left) << " 0x" << to_hex(_orMask, 2) << endl << setw(w) << setiosflags(ios::left) << "VetoMask " << resetiosflags(ios::left) << " 0x" << to_hex(_vetoMask, 2) << endl << setw(w) << setiosflags(ios::left) << "DUTMask " << resetiosflags(ios::left) << " 0x" << to_hex(_dutMask, 2) << endl << setw(w) << setiosflags(ios::left) << "FirmwareID " << resetiosflags(ios::left) << " " << _firmwareID << endl << setw(w) << setiosflags(ios::left) << "TimeInterval " << resetiosflags(ios::left) << " " << _timeInterval << setfill(' ') << endl; }
package uk.co.alt236.bluetoothlelib.device.beacon.ibeacon; public class IBeaconConstants { public static final byte[] <API key> = {0x4C, 0x00, 0x02, 0x15}; }
#include "chrome/browser/autocomplete/autocomplete_match.h" #include "base/basictypes.h" #include "testing/gtest/include/gtest/gtest.h" TEST(<API key>, MoreRelevant) { struct RelevantCases { int r1; int r2; bool expected_result; } cases[] = { { 10, 0, true }, { 10, -5, true }, { -5, 10, false }, { 0, 10, false }, { -10, -5, false }, { -5, -10, true }, }; AutocompleteMatch m1(NULL, 0, false, AutocompleteMatch::URL_WHAT_YOU_TYPED); AutocompleteMatch m2(NULL, 0, false, AutocompleteMatch::URL_WHAT_YOU_TYPED); for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) { m1.relevance = cases[i].r1; m2.relevance = cases[i].r2; EXPECT_EQ(cases[i].expected_result, AutocompleteMatch::MoreRelevant(m1, m2)); } } TEST(<API key>, <API key>) { // Merging two empty vectors should result in an empty vector. EXPECT_EQ(std::string(), AutocompleteMatch::<API key>( AutocompleteMatch::<API key>( AutocompleteMatch::<API key>(), AutocompleteMatch::<API key>()))); // If one vector is empty and the other is "trivial" but non-empty (i.e. (0, // NONE)), the non-empty vector should be returned. EXPECT_EQ("0,0", AutocompleteMatch::<API key>( AutocompleteMatch::<API key>( AutocompleteMatch::<API key>("0,0"), AutocompleteMatch::<API key>()))); EXPECT_EQ("0,0", AutocompleteMatch::<API key>( AutocompleteMatch::<API key>( AutocompleteMatch::<API key>(), AutocompleteMatch::<API key>("0,0")))); // Ditto if the one-entry vector is non-trivial. EXPECT_EQ("0,1", AutocompleteMatch::<API key>( AutocompleteMatch::<API key>( AutocompleteMatch::<API key>("0,1"), AutocompleteMatch::<API key>()))); EXPECT_EQ("0,1", AutocompleteMatch::<API key>( AutocompleteMatch::<API key>( AutocompleteMatch::<API key>(), AutocompleteMatch::<API key>("0,1")))); // Merge an unstyled one-entry vector with a styled one-entry vector. EXPECT_EQ("0,1", AutocompleteMatch::<API key>( AutocompleteMatch::<API key>( AutocompleteMatch::<API key>("0,0"), AutocompleteMatch::<API key>("0,1")))); // Test simple cases of overlap. EXPECT_EQ("0,3," "1,2", AutocompleteMatch::<API key>( AutocompleteMatch::<API key>( AutocompleteMatch::<API key>("0,1," "1,0"), AutocompleteMatch::<API key>("0,2")))); EXPECT_EQ("0,3," "1,2", AutocompleteMatch::<API key>( AutocompleteMatch::<API key>( AutocompleteMatch::<API key>("0,2"), AutocompleteMatch::<API key>("0,1," "1,0")))); // Test the case where both vectors have classifications at the same // positions. EXPECT_EQ("0,3", AutocompleteMatch::<API key>( AutocompleteMatch::<API key>( AutocompleteMatch::<API key>("0,1," "1,2"), AutocompleteMatch::<API key>("0,2," "1,1")))); // Test an arbitrary complicated case. EXPECT_EQ("0,2," "1,0," "2,1," "4,3," "5,7," "6,3," "7,7," "15,1," "17,0", AutocompleteMatch::<API key>( AutocompleteMatch::<API key>( AutocompleteMatch::<API key>( "0,0," "2,1," "4,3," "7,7," "10,6," "15,0"), AutocompleteMatch::<API key>( "0,2," "1,0," "5,7," "6,1," "17,0")))); }
// This is a generated file. Not intended for manual editing. package com.intellij.sh.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.intellij.sh.ShTypes.*; import com.intellij.sh.psi.*; public class <API key> extends ShExpressionImpl implements ShUnaryExpression { public <API key>(ASTNode node) { super(node); } @Override public void accept(@NotNull ShVisitor visitor) { visitor.<API key>(this); } @Override public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof ShVisitor) accept((ShVisitor)visitor); else super.accept(visitor); } @Override @Nullable public ShExpression getExpression() { return findChildByClass(ShExpression.class); } @Override @Nullable public PsiElement getMinus() { return findChildByType(MINUS); } @Override @Nullable public PsiElement getPlus() { return findChildByType(PLUS); } }
package com.intellij.execution.configurations; /** * Configuration of such type can't be manually added or removed by the user; the template entry is hidden. */ public interface <API key> { }
package grpc import ( "net" "testing" "time" "golang.org/x/net/context" "google.golang.org/grpc/credentials" ) const tlsDir = "testdata/" func TestDialTimeout(t *testing.T) { conn, err := Dial("Non-Existent.Server:80", WithTimeout(time.Millisecond), WithBlock(), WithInsecure()) if err == nil { conn.Close() } if err != context.DeadlineExceeded { t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) } } func TestTLSDialTimeout(t *testing.T) { creds, err := credentials.<API key>(tlsDir+"ca.pem", "x.test.youtube.com") if err != nil { t.Fatalf("Failed to create credentials %v", err) } conn, err := Dial("Non-Existent.Server:80", <API key>(creds), WithTimeout(time.Millisecond), WithBlock()) if err == nil { conn.Close() } if err != context.DeadlineExceeded { t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) } } func <API key>(t *testing.T) { overwriteServerName := "over.write.server.name" creds, err := credentials.<API key>(tlsDir+"ca.pem", overwriteServerName) if err != nil { t.Fatalf("Failed to create credentials %v", err) } conn, err := Dial("Non-Existent.Server:80", <API key>(creds)) if err != nil { t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) } conn.Close() if conn.authority != overwriteServerName { t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) } } func <API key>(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() if _, err := DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure()); err != context.Canceled { t.Fatalf("DialContext(%v, _) = _, %v, want _, %v", ctx, err, context.Canceled) } } // blockingBalancer mimics the behavior of balancers whose initialization takes a long time. // In this test, reading from blockingBalancer.Notify() blocks forever. type blockingBalancer struct { ch chan []Address } func newBlockingBalancer() Balancer { return &blockingBalancer{ch: make(chan []Address)} } func (b *blockingBalancer) Start(target string, config BalancerConfig) error { return nil } func (b *blockingBalancer) Up(addr Address) func(error) { return nil } func (b *blockingBalancer) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) { return Address{}, nil, nil } func (b *blockingBalancer) Notify() <-chan []Address { return b.ch } func (b *blockingBalancer) Close() error { close(b.ch) return nil } func <API key>(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) dialDone := make(chan struct{}) go func() { DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure(), WithBalancer(newBlockingBalancer())) close(dialDone) }() cancel() <-dialDone } // <API key> always requires transport security. type <API key> struct{} func (c <API key>) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { return nil, nil } func (c <API key>) <API key>() bool { return true } func <API key>(t *testing.T) { tlsCreds, err := credentials.<API key>(tlsDir+"ca.pem", "x.test.youtube.com") if err != nil { t.Fatalf("Failed to create authenticator %v", err) } // Two conflicting credential configurations if _, err := Dial("Non-Existent.Server:80", <API key>(tlsCreds), WithBlock(), WithInsecure()); err != <API key> { t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, <API key>) } // security info on insecure connection if _, err := Dial("Non-Existent.Server:80", <API key>(<API key>{}), WithBlock(), WithInsecure()); err != <API key> { t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, <API key>) } } func <API key>(t *testing.T) { <API key>(t, &<API key>) } func <API key>(t *testing.T) { b := BackoffConfig{MaxDelay: <API key>.MaxDelay / 2} expected := b setDefaults(&expected) // defaults should be set <API key>(t, &expected, WithBackoffConfig(b)) } func <API key>(t *testing.T) { md := <API key>.MaxDelay / 2 expected := BackoffConfig{MaxDelay: md} setDefaults(&expected) <API key>(t, &expected, WithBackoffMaxDelay(md)) } func <API key>(t *testing.T, expected *BackoffConfig, opts ...DialOption) { opts = append(opts, WithInsecure()) conn, err := Dial("foo:80", opts...) if err != nil { t.Fatalf("unexpected error dialing connection: %v", err) } if conn.dopts.bs == nil { t.Fatalf("backoff config not set") } actual, ok := conn.dopts.bs.(BackoffConfig) if !ok { t.Fatalf("unexpected type of backoff config: %#v", conn.dopts.bs) } if actual != *expected { t.Fatalf("unexpected backoff config on connection: %v, want %v", actual, expected) } conn.Close() } type testErr struct { temp bool } func (e *testErr) Error() string { return "test error" } func (e *testErr) Temporary() bool { return e.temp } var nonTemporaryError = &testErr{false} func <API key>(addr string, timeout time.Duration) (net.Conn, error) { return nil, nonTemporaryError } func <API key>(t *testing.T) { ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(<API key>), WithBlock(), <API key>(true)); err != nonTemporaryError { t.Fatalf("Dial(%q) = %v, want %v", "", err, nonTemporaryError) } // Without <API key>, gRPC will retry to connect, and dial should exit with time out error. if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(<API key>), WithBlock()); err != context.DeadlineExceeded { t.Fatalf("Dial(%q) = %v, want %v", "", err, context.DeadlineExceeded) } }
package main import ( "fmt" "os" "path/filepath" "github.com/karrick/godirwalk" "github.com/pkg/errors" ) func main() { if len(os.Args) < 2 { fmt.Fprintf(os.Stderr, "usage: %s dir1 [dir2 [dir3...]]\n", filepath.Base(os.Args[0])) os.Exit(2) } scratchBuffer := make([]byte, 64*1024) // allocate once and re-use each time var count, total int var err error for _, arg := range os.Args[1:] { count, err = <API key>(arg, scratchBuffer) total += count if err != nil { break } } fmt.Fprintf(os.Stderr, "Removed %d empty directories\n", total) if err != nil { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) os.Exit(1) } } func <API key>(osDirname string, scratchBuffer []byte) (int, error) { var count int err := godirwalk.Walk(osDirname, &godirwalk.Options{ Unsorted: true, ScratchBuffer: scratchBuffer, Callback: func(_ string, _ *godirwalk.Dirent) error { // no-op while diving in; all the fun happens in <API key> return nil }, <API key>: func(osPathname string, _ *godirwalk.Dirent) error { deChildren, err := godirwalk.ReadDirents(osPathname, scratchBuffer) if err != nil { return errors.Wrap(err, "cannot ReadDirents") } // NOTE: ReadDirents skips "." and ".." if len(deChildren) > 0 { return nil // this directory has children; no additional work here } if osPathname == osDirname { return nil // do not remove provided root directory } err = os.Remove(osPathname) if err == nil { count++ } return err }, }) return count, err }
// "Replace 'collect(toUnmodifiableList())' with 'toList()'" "true" import java.util.List; import java.util.stream.*; class X { void test(Stream<String> stream) { List<String> list = stream.collect<caret>(Collectors.toUnmodifiableList()); } }
package org.jetbrains.plugins.groovy.lang.psi.impl.synthetic; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil; import org.jetbrains.plugins.groovy.transformations.<API key>; public class GrTraitField extends GrLightField implements PsiMirrorElement { private static final Logger LOG = Logger.getInstance(GrTraitField.class); private final PsiField myField; public GrTraitField(@NotNull GrField field, GrTypeDefinition clazz, PsiSubstitutor substitutor, @Nullable <API key> context) { super(clazz, getNewNameForField(field), substitutor.substitute(field.getType()), field); GrLightModifierList modifierList = getModifierList(); for (String modifier : PsiModifier.MODIFIERS) { boolean hasModifierProperty; GrModifierList fieldModifierList = field.getModifierList(); if (context == null || fieldModifierList == null) { hasModifierProperty = field.hasModifierProperty(modifier); } else { hasModifierProperty = context.hasModifierProperty(fieldModifierList, modifier); } if (hasModifierProperty) { modifierList.addModifier(modifier); } } modifierList.copyAnnotations(field.getModifierList()); myField = field; } @NotNull private static String getNewNameForField(@NotNull PsiField field) { PsiClass containingClass = field.getContainingClass(); LOG.assertTrue(containingClass != null); return GrTraitUtil.getTraitFieldPrefix(containingClass) + field.getName(); } @NotNull @Override public PsiField getPrototype() { return myField; } }
// .NAME <API key> - triangulate any type of dataset // .SECTION Description // <API key> generates n-dimensional simplices from any input // dataset. That is, 3D cells are converted to tetrahedral meshes, 2D cells // to triangles, and so on. The triangulation is guaranteed to be compatible. // This filter uses simple 1D and 2D triangulation techniques for cells // that are of topological dimension 2 or less. For 3D cells--due to the // issue of face compatibility across quadrilateral faces (which way to // orient the diagonal?)--a fancier ordered Delaunay triangulation is used. // This approach produces templates on the fly for triangulating the // cells. The templates are then used to do the actual triangulation. // .SECTION See Also // <API key> vtkTriangleFilter #ifndef <API key> #define <API key> #include "<API key>.h" // For export macro #include "<API key>.h" class <API key>; class <API key> <API key> : public <API key> { public: static <API key> *New(); vtkTypeMacro(<API key>,<API key>); void PrintSelf(ostream& os, vtkIndent indent); // Description: // When On this filter will cull all 1D and 2D cells from the output. // The default is Off. vtkSetMacro(TetrahedraOnly, int); vtkGetMacro(TetrahedraOnly, int); vtkBooleanMacro(TetrahedraOnly, int); protected: <API key>(); ~<API key>(); // Usual data generation method virtual int RequestData(vtkInformation *, <API key> **, <API key> *); virtual int <API key>(int port, vtkInformation *info); // Used to triangulate 3D cells <API key> *Triangulator; // Different execute methods depending on whether input is structured or not void StructuredExecute(vtkDataSet *, vtkUnstructuredGrid *); void UnstructuredExecute(vtkDataSet *, vtkUnstructuredGrid *); int TetrahedraOnly; private: <API key>(const <API key>&); // Not implemented. void operator=(const <API key>&); // Not implemented. }; #endif
// This source file is part of the Swift.org open source project #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILModule.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" using namespace swift; namespace { class <API key> : public SILModuleTransform { void run() override { for (auto &Fn : *getModule()) { unsigned Count = 0; llvm::outs() << "@" << Fn.getName() << "\n"; for (auto &BB : Fn) { for (auto &I : BB) { llvm::outs() << "Inst #: " << Count++ << "\n " << I; llvm::outs() << " Mem Behavior: " << I.getMemoryBehavior() << "\n"; llvm::outs() << " Release Behavior: " << I.<API key>() << "\n"; } } } } llvm::StringRef getName() override { return "<API key>"; } }; } // end anonymous namespace SILTransform *swift::<API key>() { return new <API key>(); }
#include "chrome/browser/ui/views/apps/<API key>.h" #include "apps/ui/views/<API key>.h" #include "ash/ash_constants.h" #include "ash/frame/<API key>.h" #include "ash/screen_util.h" #include "ash/shell.h" #include "ash/wm/<API key>.h" #include "ash/wm/panels/panel_frame_view.h" #include "ash/wm/window_properties.h" #include "ash/wm/window_state.h" #include "ash/wm/<API key>.h" #include "ash/wm/<API key>.h" #include "chrome/browser/ui/ash/ash_util.h" #include "chrome/browser/ui/ash/multi_user/<API key>.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/views/apps/<API key>.h" #include "chrome/browser/ui/views/apps/<API key>.h" #include "chrome/browser/web_applications/web_app.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" #include "ui/base/hit_test.h" #include "ui/base/models/simple_menu_model.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/widget/widget.h" #if defined(OS_CHROMEOS) #include "ash/shell_window_ids.h" #endif #if defined(OS_LINUX) #include "chrome/browser/<API key>.h" #endif using extensions::AppWindow; namespace { // This class handles a user's fullscreen request (Shift+F4/F4). class <API key> : public ash::wm::WindowStateDelegate, public ash::wm::WindowStateObserver, public aura::WindowObserver { public: <API key>(AppWindow* app_window, extensions::NativeAppWindow* native_app_window) : app_window_(app_window), window_state_( ash::wm::GetWindowState(native_app_window->GetNativeWindow())) { // Add a window state observer to exit fullscreen properly in case // fullscreen is exited without going through AppWindow::Restore(). This // is the case when exiting immersive fullscreen via the "Restore" window // control. window_state_->AddObserver(this); window_state_->window()->AddObserver(this); } ~<API key>() override { if (window_state_) { window_state_->RemoveObserver(this); window_state_->window()->RemoveObserver(this); } } private: // Overridden from ash::wm::WindowStateDelegate. bool ToggleFullscreen(ash::wm::WindowState* window_state) override { // Windows which cannot be maximized should not be fullscreened. DCHECK(window_state->IsFullscreen() || window_state->CanMaximize()); if (window_state->IsFullscreen()) app_window_->Restore(); else if (window_state->CanMaximize()) app_window_->OSFullscreen(); return true; } // Overridden from ash::wm::WindowStateDelegate. bool RestoreAlwaysOnTop(ash::wm::WindowState* window_state) override { app_window_->RestoreAlwaysOnTop(); return true; } // Overridden from ash::wm::WindowStateObserver: void <API key>(ash::wm::WindowState* window_state, ash::wm::WindowStateType old_type) override { // Since the window state might get set by a window manager, it is possible // to come here before the application set its |BaseWindow|. if (!window_state->IsFullscreen() && !window_state->IsMinimized() && app_window_->GetBaseWindow() && app_window_->GetBaseWindow()-><API key>()) { app_window_->Restore(); // Usually <API key>() is called when the window bounds are // changed as a result of a state type change. Because the change in state // type has already occurred, we need to call <API key>() // explicitly. app_window_-><API key>(); } } // Overridden from aura::WindowObserver: void OnWindowDestroying(aura::Window* window) override { window_state_->RemoveObserver(this); window_state_->window()->RemoveObserver(this); window_state_ = NULL; } // Not owned. AppWindow* app_window_; ash::wm::WindowState* window_state_; <API key>(<API key>); }; } // namespace <API key>::<API key>() { } <API key>::~<API key>() { } void <API key>::InitializeWindow( AppWindow* app_window, const AppWindow::CreateParams& create_params) { <API key>::InitializeWindow(app_window, create_params); // Restore docked state on ash desktop and ignore it elsewhere. if (create_params.state == ui::SHOW_STATE_DOCKED && chrome::<API key>(widget()->GetNativeWindow()) == chrome::<API key>) { widget()->GetNativeWindow()->SetProperty(aura::client::kShowStateKey, create_params.state); } } void <API key>::OnBeforeWidgetInit( const AppWindow::CreateParams& create_params, views::Widget::InitParams* init_params, views::Widget* widget) { #if defined(OS_LINUX) && !defined(OS_CHROMEOS) std::string app_name = web_app::<API key>( app_window()->extension_id()); // Set up a custom WM_CLASS for app windows. This allows task switchers in // X11 environments to distinguish them from main browser windows. init_params->wm_class_name = web_app::<API key>(app_name); init_params->wm_class_class = <API key>::GetProgramClassName(); const char kX11WindowRoleApp[] = "app"; init_params->wm_role_name = std::string(kX11WindowRoleApp); #endif <API key>::OnBeforeWidgetInit(create_params, init_params, widget); #if defined(OS_CHROMEOS) if (create_params.is_ime_window) { // Puts ime windows into ime window container. init_params->parent = ash::Shell::GetContainer(ash::Shell::<API key>(), ash::<API key>); } #endif } void <API key>::<API key>( bool use_default_bounds, views::Widget::InitParams* init_params, views::Widget* widget) { <API key>::<API key>(use_default_bounds, init_params, widget); if (ash::Shell::HasInstance() && use_default_bounds) { // Open a new panel on the target root. init_params->bounds = ash::ScreenUtil::ConvertRectToScreen( ash::Shell::GetTargetRootWindow(), gfx::Rect(GetPreferredSize())); } } views::NonClientFrameView* <API key>::<API key>() { apps::AppWindowFrameView* frame = new apps::AppWindowFrameView(widget(), this, HasFrameColor(), ActiveFrameColor(), InactiveFrameColor()); frame->Init(); // For Aura windows on the Ash desktop the sizes are different and the user // can resize the window from slightly outside the bounds as well. if (chrome::IsNativeWindowInAsh(widget()->GetNativeWindow())) { frame->SetResizeSizes(ash::<API key>, ash::<API key>, ash::<API key>); } #if !defined(OS_CHROMEOS) // For non-Ash windows, install an easy resize window targeter, which ensures // that the root window (not the app) receives mouse events on the edges. if (chrome::<API key>(widget()->GetNativeWindow()) != chrome::<API key>) { aura::Window* window = widget()->GetNativeWindow(); int resize_inside = frame-><API key>(); gfx::Insets inset(resize_inside, resize_inside, resize_inside, resize_inside); // Add the <API key> on the window, not its root // window. The root window does not have a delegate, which is needed to // handle the event in Linux. window->SetEventTargeter(scoped_ptr<ui::EventTargeter>( new <API key>(window, inset, this))); } #endif return frame; } gfx::Rect <API key>::GetRestoredBounds() const { gfx::Rect* bounds = widget()->GetNativeWindow()->GetProperty(ash::<API key>); if (bounds && !bounds->IsEmpty()) return *bounds; return <API key>::GetRestoredBounds(); } ui::WindowShowState <API key>::GetRestoredState() const { // Use <API key> in case a window is minimized/hidden. ui::WindowShowState restore_state = widget()->GetNativeWindow()->GetProperty( aura::client::<API key>); if (widget()->GetNativeWindow()->GetProperty( ash::<API key>)) { // If an override is given, we use that restore state (after filtering). restore_state = widget()->GetNativeWindow()->GetProperty( ash::<API key>); } else { // Otherwise first normal states are checked. if (IsMaximized()) return ui::<API key>; if (IsFullscreen()) { if (<API key>.get() && <API key>->IsEnabled()) { // Restore windows which were previously in immersive fullscreen to // maximized. Restoring the window to a different fullscreen type // makes for a bad experience. return ui::<API key>; } return ui::<API key>; } if (widget()->GetNativeWindow()->GetProperty( aura::client::kShowStateKey) == ui::SHOW_STATE_DOCKED || widget()->GetNativeWindow()->GetProperty( aura::client::<API key>) == ui::SHOW_STATE_DOCKED) { return ui::SHOW_STATE_DOCKED; } } // Whitelist states to return so that invalid and transient states // are not saved and used to restore windows when they are recreated. switch (restore_state) { case ui::SHOW_STATE_NORMAL: case ui::<API key>: case ui::<API key>: return restore_state; case ui::SHOW_STATE_DEFAULT: case ui::<API key>: case ui::SHOW_STATE_INACTIVE: case ui::SHOW_STATE_DOCKED: case ui::SHOW_STATE_END: return ui::SHOW_STATE_NORMAL; } return ui::SHOW_STATE_NORMAL; } bool <API key>::IsAlwaysOnTop() const { return app_window()-><API key>() ? ash::wm::GetWindowState(widget()->GetNativeWindow()) ->panel_attached() : widget()->IsAlwaysOnTop(); } void <API key>::<API key>( views::View* source, const gfx::Point& p, ui::MenuSourceType source_type) { #if defined(OS_CHROMEOS) scoped_ptr<ui::MenuModel> model = <API key>(app_window()->GetNativeWindow()); if (!model.get()) return; // Only show context menu if point is in caption. gfx::Point <API key>(p); views::View::<API key>(widget()->non_client_view(), &<API key>); int hit_test = widget()->non_client_view()->NonClientHitTest(<API key>); if (hit_test == HTCAPTION) { menu_runner_.reset(new views::MenuRunner( model.get(), views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU)); if (menu_runner_->RunMenuAt(source->GetWidget(), NULL, gfx::Rect(p, gfx::Size(0, 0)), views::MENU_ANCHOR_TOPLEFT, source_type) == views::MenuRunner::MENU_DELETED) { return; } } #endif } views::NonClientFrameView* <API key>::<API key>( views::Widget* widget) { if (chrome::IsNativeViewInAsh(widget->GetNativeView())) { // Set the delegate now because CustomFrameViewAsh sets the // WindowStateDelegate if one is not already set. ash::wm::GetWindowState(GetNativeWindow()) ->SetDelegate( scoped_ptr<ash::wm::WindowStateDelegate>( new <API key>(app_window(), this)).Pass()); if (IsFrameless()) return <API key>(); if (app_window()-><API key>()) { views::NonClientFrameView* frame_view = new ash::PanelFrameView(widget, ash::PanelFrameView::FRAME_ASH); frame_view-><API key>(this); return frame_view; } ash::CustomFrameViewAsh* custom_frame_view = new ash::CustomFrameViewAsh(widget); // Non-frameless app windows can be put into immersive fullscreen. <API key>.reset( new ash::<API key>()); custom_frame_view-><API key>( <API key>.get()); custom_frame_view->GetHeaderView()-><API key>(this); if (HasFrameColor()) { custom_frame_view->SetFrameColors(ActiveFrameColor(), InactiveFrameColor()); } return custom_frame_view; } return <API key>::<API key>(widget); } void <API key>::SetFullscreen(int fullscreen_types) { <API key>::SetFullscreen(fullscreen_types); if (<API key>.get()) { // |<API key>| should only be set if immersive // fullscreen is the fullscreen type used by the OS. <API key>->SetEnabled( ash::<API key>::<API key>, (fullscreen_types & AppWindow::FULLSCREEN_TYPE_OS) != 0); // Autohide the shelf instead of hiding the shelf completely when only in // OS fullscreen. ash::wm::WindowState* window_state = ash::wm::GetWindowState(widget()->GetNativeWindow()); window_state-><API key>(fullscreen_types != AppWindow::FULLSCREEN_TYPE_OS); DCHECK(ash::Shell::HasInstance()); ash::Shell::GetInstance()-><API key>(); } } void <API key>::UpdateShape(scoped_ptr<SkRegion> region) { bool had_shape = !!shape(); <API key>::UpdateShape(region.Pass()); aura::Window* native_window = widget()->GetNativeWindow(); if (shape() && !had_shape) { native_window->SetEventTargeter(scoped_ptr<ui::EventTargeter>( new <API key>(native_window, this))); } else if (!shape() && had_shape) { native_window->SetEventTargeter(scoped_ptr<ui::EventTargeter>()); } }
<header>Program zewnętrzny używany zamiast doręczania do skrzynki pocztowej</header> <center><tt>mailbox_command</tt></center> <hr> Ten parametr określa fakultatywne zewnętrzne polecenie wykorzystywane zamiast doręczania do skrzynki pocztowej. Polecenie będzie uruchamiane z&nbsp;prawami odbiorcy i&nbsp;z&nbsp;prawidłowymi ustawieniami <tt>HOME</tt>, <tt>SHELL</tt> i&nbsp;<tt>LOGNAME</tt> w&nbsp;środowisku. Wyjątek: doręczanie dla <tt>root</tt>-a odbywa się jako <tt>$default_user</tt>. <p> Inne interesujące zmienne środowiska: <tt>USER</tt> (nazwa użytkownika będącego odbiorcą), <tt>EXTENSION</tt> (rozszerzenie adresu), <tt>DOMAIN</tt> (domenowa część adresu), i&nbsp;<tt>LOCAL</tt> (lokalna część adresu). <p> W&nbsp;odróżnieniu od innych parametrów konfiguracyjnych Postfiksa, ta opcja nie jest poddana podstawianiu parametrów. Ma to na celu ułatwienie podawania składni powłoki (patrz poniższy przykład). <p> Unikaj metaznaków powłoki, gdyż zmuszą one Postfiksa do uruchomienia kosztownego procesu powłoki. Sam <tt>procmail</tt> jest dostatecznie kosztowny. <p> JEŚLI KORZYSTASZ Z&nbsp;TEJ OPCJI DLA DORĘCZANIA POCZTY W&nbsp;CAŁYM SYSTEMIE, MUSISZ USTAWIĆ ALIAS PRZEKIEROWUJĄCY POCZTĘ DO ROOT-A DO ZWYKŁEGO UŻYTKOWNIKA. <p> Przykłady: <ul> <li><tt>/gdzies/tam/procmail</tt> <li><tt>/gdzies/tam/procmail -a "$EXTENSION"</tt> </ul> <hr>
#ifndef <API key> #define <API key> #include <jni.h> #include <string> #include "base/android/scoped_java_ref.h" #include "base/at_exit.h" #include "net/url_request/<API key>.h" #include "remoting/base/auto_thread.h" #include "remoting/client/jni/<API key>.h" #include "remoting/protocol/connection_to_host.h" template<typename T> struct <API key>; namespace remoting { bool RegisterJni(JNIEnv* env); // Houses the global resources on which the Chromoting components run // (e.g. message loops and task runners). Proxies outgoing JNI calls from its // <API key> member to Java. All its methods should be invoked // exclusively from the UI thread unless otherwise noted. class <API key> { public: // This class is instantiated at process initialization and persists until // we close. Its components are reused across |<API key>|s. static <API key>* GetInstance(); scoped_refptr<<API key>> ui_task_runner() { return ui_task_runner_; } scoped_refptr<<API key>> network_task_runner() { return <API key>; } scoped_refptr<<API key>> display_task_runner() { return <API key>; } scoped_refptr<net::<API key>> url_requester() { return url_requester_; } // Initiates a connection with the specified host. Only call when a host // connection is active (i.e. between a call to Connect() and the // corresponding call to Disconnect()). To skip the attempt at pair-based // authentication, leave |pairing_id| and |pairing_secret| as empty strings. void ConnectToHost(const char* username, const char* auth_token, const char* host_jid, const char* host_id, const char* host_pubkey, const char* pairing_id, const char* pairing_secret, const char* capabilities); // Terminates any ongoing connection attempt and cleans up by nullifying // |session_|. This is a no-op unless |session| is currently non-null. void DisconnectFromHost(); // Returns the client for the currently-active session. Do not call if // |session| is null. scoped_refptr<<API key>> session() { DCHECK(session_.get()); return session_; } // Notifies Java code of the current connection status. Call on UI thread. void OnConnectionState(protocol::ConnectionToHost::State state, protocol::ErrorCode error); // Pops up a dialog box asking the user to enter a PIN. Call on UI thread. void Display<API key>(bool pairing_supported); // Saves new pairing credentials to permanent storage. Call on UI thread. void <API key>(const std::string& host, const std::string& id, const std::string& secret); // Pops up a third party login page to fetch token required for // authentication. Call on UI thread. void <API key>(const GURL& token_url, const std::string& client_id, const std::string& scope); // Pass on the set of negotiated capabilities to the client. void SetCapabilities(const std::string& capabilities); // Passes on the deconstructed ExtensionMessage to the client to handle // appropriately. void <API key>(const std::string& type, const std::string& message); // Creates a new Bitmap object to store a video frame. base::android::ScopedJavaLocalRef<jobject> NewBitmap( webrtc::DesktopSize size); // Updates video frame bitmap. |bitmap| must be an instance of // android.graphics.Bitmap. Call on the display thread. void UpdateFrameBitmap(jobject bitmap); // Updates cursor shape. Call on display thread. void UpdateCursorShape(const protocol::CursorShapeInfo& cursor_shape); // Draws the latest image buffer onto the canvas. Call on the display thread. void RedrawCanvas(); private: <API key>(); // Forces a DisconnectFromHost() in case there is any active or failed // connection, then proceeds to tear down the Chromium dependencies on which // all sessions depended. Because destruction only occurs at application exit // after all connections have terminated, it is safe to make unretained // cross-thread calls on the class. virtual ~<API key>(); // Detaches JVM from the current thread, then signals. Doesn't own |waiter|. void <API key>(base::WaitableEvent* waiter); // Used by the Chromium libraries to clean up the base and net libraries' JNI // bindings. It must persist for the lifetime of the singleton. scoped_ptr<base::AtExitManager> at_exit_manager_; // Chromium code's connection to the Java message loop. scoped_ptr<base::MessageLoopForUI> ui_loop_; // References to native threads. scoped_refptr<<API key>> ui_task_runner_; scoped_refptr<<API key>> <API key>; scoped_refptr<<API key>> <API key>; scoped_refptr<net::<API key>> url_requester_; // Contains all connection-specific state. scoped_refptr<<API key>> session_; friend struct <API key><<API key>>; <API key>(<API key>); }; } // namespace remoting #endif
#ifndef <API key> #define <API key> #include <string> #include "base/strings/string16.h" #include "base/time/time.h" #include "components/autofill/core/browser/form_group.h" namespace autofill { class AutofillType; // This class is an interface for the primary data models that back Autofill. // The information in objects of this class is managed by the // PersonalDataManager. class AutofillDataModel : public FormGroup { public: AutofillDataModel(const std::string& guid, const std::string& origin); ~AutofillDataModel() override; // Returns true if the data in this model was entered directly by the user, // rather than automatically aggregated. bool IsVerified() const; // Called to update |use_count_| and |use_date_| when this data model is // the subject of user interaction (usually, when it's used to fill a form). void RecordUse(); std::string guid() const { return guid_; } void set_guid(const std::string& guid) { guid_ = guid; } std::string origin() const { return origin_; } void set_origin(const std::string& origin) { origin_ = origin; } size_t use_count() const { return use_count_; } void set_use_count(size_t count) { use_count_ = count; } const base::Time& use_date() const { return use_date_; } void set_use_date(const base::Time& time) { use_date_ = time; } const base::Time& modification_date() const { return modification_date_; } // This should only be called from database code. void <API key>(const base::Time& time) { modification_date_ = time; } private: // A globally unique ID for this object. std::string guid_; // The origin of this data. This should be // (a) a web URL for the domain of the form from which the data was // (b) some other non-empty string, which cannot be interpreted as a web // URL, identifying the origin for non-aggregated data, or std::string origin_; // The number of times this model has been used. size_t use_count_; // The last time the model was used. base::Time use_date_; // The last time data in the model was modified. base::Time modification_date_; }; } // namespace autofill #endif // <API key>
using FluentNHibernate.Conventions; using FluentNHibernate.Conventions.Instances; namespace Examples.<API key> { <summary> This is a convention that will be applied to all entities in your application. What this particular convention does is to specify that many-to-one, one-to-many, and many-to-many relationships will all have their Cascade option set to All. </summary> class CascadeConvention : <API key>, IHasManyConvention, <API key> { public void Apply(IManyToOneInstance instance) { instance.Cascade.All(); } public void Apply(<API key> instance) { instance.Cascade.All(); } public void Apply(<API key> instance) { instance.Cascade.All(); } } }
from SimpleCV import Camera, Image, Color, <API key>, ROI, Display import matplotlib.pyplot as plt cam = Camera(1) tct = <API key>() img = cam.getImage() roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img) tct.train(cam,roi=roi,maxFrames=250,pkWndw=20) # Matplot Lib example plotting plotc = {'r':'r','g':'g','b':'b','i':'m','h':'y'} for key in tct.data.keys(): plt.plot(tct.data[key],plotc[key]) for pt in tct.peaks[key]: plt.plot(pt[0],pt[1],'r*') for pt in tct.valleys[key]: plt.plot(pt[0],pt[1],'b*') plt.grid() plt.show() disp = Display((800,600)) while disp.isNotDone(): img = cam.getImage() result = tct.recognize(img) plt.plot(tct._rtData,'r-') plt.grid() plt.savefig('temp.png') plt.clf() plotImg = Image('temp.png') roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img) roi.draw(width=3) img.drawText(str(result),20,20,color=Color.RED,fontsize=32) img = img.applyLayers() img = img.blit(plotImg.resize(w=img.width,h=img.height),pos=(0,0),alpha=0.5) img.save(disp)
This is the go portion of a [benchmarking test suite](https: > High performance, extensible, minimalist Go web framework ## Test URLs - http://localhost:8080/json - http://localhost:8080/db - http://localhost:8080/queries/:n[1-500] - http://localhost:8080/fortunes - http://localhost:8080/updates/:n[1-500] - http://localhost:8080/plaintext
#ifndef <API key> #define <API key> #include "chrome/browser/ui/browser_navigator.h" #include "content/public/common/referrer.h" #include "third_party/WebKit/public/web/WebWindowFeatures.h" #include "ui/base/<API key>.h" #include "url/gurl.h" namespace content { class WebContents; } // namespace content class BlockedWindowParams { public: BlockedWindowParams(const GURL& target_url, const content::Referrer& referrer, <API key> disposition, const blink::WebWindowFeatures& features, bool user_gesture, bool opener_suppressed, int render_process_id, int <API key>); chrome::NavigateParams <API key>( content::WebContents* web_contents) const; blink::WebWindowFeatures features() const { return features_; } int <API key>() const { return <API key>; } int render_process_id() const { return render_process_id_; } const GURL& target_url() const { return target_url_; } private: GURL target_url_; content::Referrer referrer_; <API key> disposition_; blink::WebWindowFeatures features_; bool user_gesture_; bool opener_suppressed_; int render_process_id_; int <API key>; }; #endif // <API key>
#include "src/base/bits.h" #include "src/base/<API key>.h" #include "src/compiler/js-graph.h" #include "src/compiler/<API key>.h" #include "src/compiler/typer.h" #include "test/unittests/compiler/graph-unittest.h" #include "test/unittests/compiler/node-test-utils.h" #include "testing/gmock-support.h" using testing::AllOf; using testing::BitEq; using testing::Capture; using testing::CaptureEq; namespace v8 { namespace internal { namespace compiler { class <API key> : public TypedGraphTest { public: explicit <API key>(int num_parameters = 2) : TypedGraphTest(num_parameters), machine_(zone()) {} protected: Reduction Reduce(Node* node) { JSOperatorBuilder javascript(zone()); JSGraph jsgraph(isolate(), graph(), common(), &javascript, &machine_); <API key> reducer(&jsgraph); return reducer.Reduce(node); } Matcher<Node*> IsTruncatingDiv(const Matcher<Node*>& dividend_matcher, const int32_t divisor) { base::<API key><uint32_t> const mag = base::<API key>(bit_cast<uint32_t>(divisor)); int32_t const multiplier = bit_cast<int32_t>(mag.multiplier); int32_t const shift = bit_cast<int32_t>(mag.shift); Matcher<Node*> quotient_matcher = IsInt32MulHigh(dividend_matcher, IsInt32Constant(multiplier)); if (divisor > 0 && multiplier < 0) { quotient_matcher = IsInt32Add(quotient_matcher, dividend_matcher); } else if (divisor < 0 && multiplier > 0) { quotient_matcher = IsInt32Sub(quotient_matcher, dividend_matcher); } if (shift) { quotient_matcher = IsWord32Sar(quotient_matcher, IsInt32Constant(shift)); } return IsInt32Add(quotient_matcher, IsWord32Shr(dividend_matcher, IsInt32Constant(31))); } <API key>* machine() { return &machine_; } private: <API key> machine_; }; template <typename T> class <API key> : public <API key>, public ::testing::WithParamInterface<T> { public: explicit <API key>(int num_parameters = 2) : <API key>(num_parameters) {} ~<API key>() OVERRIDE {} }; namespace { const float kFloat32Values[] = { -std::numeric_limits<float>::infinity(), -2.70497e+38f, -1.4698e+37f, -1.22813e+35f, -1.20555e+35f, -1.34584e+34f, -1.0079e+32f, -6.49364e+26f, -3.06077e+25f, -1.46821e+25f, -1.17658e+23f, -1.9617e+22f, -2.7357e+20f, -1.48708e+13f, -1.89633e+12f, -4.66622e+11f, -2.22581e+11f, -1.45381e+10f, -1.3956e+09f, -1.32951e+09f, -1.30721e+09f, -1.19756e+09f, -9.26822e+08f, -6.35647e+08f, -4.00037e+08f, -1.81227e+08f, -5.09256e+07f, -964300.0f, -192446.0f, -28455.0f, -27194.0f, -26401.0f, -20575.0f, -17069.0f, -9167.0f, -960.178f, -113.0f, -62.0f, -15.0f, -7.0f, -0.0256635f, -4.60374e-07f, -3.63759e-10f, -4.30175e-14f, -5.27385e-15f, -1.48084e-15f, -1.05755e-19f, -3.2995e-21f, -1.67354e-23f, -1.11885e-23f, -1.78506e-30f, -5.07594e-31f, -3.65799e-31f, -1.43718e-34f, -1.27126e-38f, -0.0f, 0.0f, 1.17549e-38f, 1.56657e-37f, 4.08512e-29f, 3.31357e-28f, 6.25073e-22f, 4.1723e-13f, 1.44343e-09f, 5.27004e-08f, 9.48298e-08f, 5.57888e-07f, 4.89988e-05f, 0.244326f, 12.4895f, 19.0f, 47.0f, 106.0f, 538.324f, 564.536f, 819.124f, 7048.0f, 12611.0f, 19878.0f, 20309.0f, 797056.0f, 1.77219e+09f, 1.51116e+11f, 4.18193e+13f, 3.59167e+16f, 3.38211e+19f, 2.67488e+20f, 1.78831e+21f, 9.20914e+21f, 8.35654e+23f, 1.4495e+24f, 5.94015e+25f, 4.43608e+30f, 2.44502e+33f, 2.61152e+33f, 1.38178e+37f, 1.71306e+37f, 3.31899e+38f, 3.40282e+38f, std::numeric_limits<float>::infinity()}; const double kFloat64Values[] = { -V8_INFINITY, -4.23878e+275, -5.82632e+265, -6.60355e+220, -6.26172e+212, -2.56222e+211, -4.82408e+201, -1.84106e+157, -1.63662e+127, -1.55772e+100, -1.67813e+72, -2.3382e+55, -3.179e+30, -1.441e+09, -1.0647e+09, -7.99361e+08, -5.77375e+08, -2.20984e+08, -32757, -13171, -9970, -3984, -107, -105, -92, -77, -61, -0.000208163, -1.86685e-06, -1.17296e-10, -9.26358e-11, -5.08004e-60, -1.74753e-65, -1.06561e-71, -5.67879e-79, -5.78459e-130, -2.90989e-171, -7.15489e-243, -3.76242e-252, -1.05639e-263, -4.40497e-267, -2.19666e-273, -4.9998e-276, -5.59821e-278, -2.03855e-282, -5.99335e-283, -7.17554e-284, -3.11744e-309, -0.0, 0.0, 2.22507e-308, 1.30127e-270, 7.62898e-260, 4.00313e-249, 3.16829e-233, 1.85244e-228, 2.03544e-129, 1.35126e-110, 1.01182e-106, 5.26333e-94, 1.35292e-90, 2.85394e-83, 1.78323e-77, 5.4967e-57, 1.03207e-25, 4.57401e-25, 1.58738e-05, 2, 125, 2310, 9636, 14802, 17168, 28945, 29305, 4.81336e+07, 1.41207e+08, 4.65962e+08, 1.40499e+09, 2.12648e+09, 8.80006e+30, 1.4446e+45, 1.12164e+54, 2.48188e+89, 6.71121e+102, 3.074e+112, 4.9699e+152, 5.58383e+166, 4.30654e+172, 7.08824e+185, 9.6586e+214, 2.028e+223, 6.63277e+243, 1.56192e+261, 1.23202e+269, 5.72883e+289, 8.5798e+290, 1.40256e+294, 1.79769e+308, V8_INFINITY}; const int32_t kInt32Values[] = { std::numeric_limits<int32_t>::min(), -1914954528, -1698749618, -1578693386, -1577976073, -1573998034, -1529085059, -1499540537, -1299205097, -1090814845, -938186388, -806828902, -750927650, -520676892, -513661538, -453036354, -433622833, -282638793, -28375, -27788, -22770, -18806, -14173, -11956, -11200, -10212, -8160, -3751, -2758, -1522, -121, -120, -118, -117, -106, -84, -80, -74, -59, -52, -48, -39, -35, -17, -11, -10, -9, -7, -5, 0, 9, 12, 17, 23, 29, 31, 33, 35, 40, 47, 55, 56, 62, 64, 67, 68, 69, 74, 79, 84, 89, 90, 97, 104, 118, 124, 126, 127, 7278, 17787, 24136, 24202, 25570, 26680, 30242, 32399, 420886487, 642166225, 821912648, 822577803, 851385718, 1212241078, 1411419304, 1589626102, 1596437184, 1876245816, 1954730266, 2008792749, 2045320228, std::numeric_limits<int32_t>::max()}; const int64_t kInt64Values[] = { std::numeric_limits<int64_t>::min(), V8_INT64_C(-8974392461363618006), V8_INT64_C(-8874367046689588135), V8_INT64_C(-8269197512118230839), V8_INT64_C(-8146091527100606733), V8_INT64_C(-7550917981466150848), V8_INT64_C(-7216590251577894337), V8_INT64_C(-6464086891160048440), V8_INT64_C(-6365616494908257190), V8_INT64_C(-6305630541365849726), V8_INT64_C(-5982222642272245453), V8_INT64_C(-5510103099058504169), V8_INT64_C(-5496838675802432701), V8_INT64_C(-4047626578868642657), V8_INT64_C(-4033755046900164544), V8_INT64_C(-3554299241457877041), V8_INT64_C(-2482258764588614470), V8_INT64_C(-1688515425526875335), V8_INT64_C(-924784137176548532), V8_INT64_C(-725316567157391307), V8_INT64_C(-439022654781092241), V8_INT64_C(-105545757668917080), V8_INT64_C(-2088319373), V8_INT64_C(-2073699916), V8_INT64_C(-1844949911), V8_INT64_C(-1831090548), V8_INT64_C(-1756711933), V8_INT64_C(-1559409497), V8_INT64_C(-1281179700), V8_INT64_C(-1211513985), V8_INT64_C(-1182371520), V8_INT64_C(-785934753), V8_INT64_C(-767480697), V8_INT64_C(-705745662), V8_INT64_C(-514362436), V8_INT64_C(-459916580), V8_INT64_C(-312328082), V8_INT64_C(-302949707), V8_INT64_C(-285499304), V8_INT64_C(-125701262), V8_INT64_C(-95139843), V8_INT64_C(-32768), V8_INT64_C(-27542), V8_INT64_C(-23600), V8_INT64_C(-18582), V8_INT64_C(-17770), V8_INT64_C(-9086), V8_INT64_C(-9010), V8_INT64_C(-8244), V8_INT64_C(-2890), V8_INT64_C(-103), V8_INT64_C(-34), V8_INT64_C(-27), V8_INT64_C(-25), V8_INT64_C(-9), V8_INT64_C(-7), V8_INT64_C(0), V8_INT64_C(2), V8_INT64_C(38), V8_INT64_C(58), V8_INT64_C(65), V8_INT64_C(93), V8_INT64_C(111), V8_INT64_C(1003), V8_INT64_C(1267), V8_INT64_C(12797), V8_INT64_C(23122), V8_INT64_C(28200), V8_INT64_C(30888), V8_INT64_C(42648848), V8_INT64_C(116836693), V8_INT64_C(263003643), V8_INT64_C(571039860), V8_INT64_C(1079398689), V8_INT64_C(1145196402), V8_INT64_C(1184846321), V8_INT64_C(1758281648), V8_INT64_C(1859991374), V8_INT64_C(1960251588), V8_INT64_C(2042443199), V8_INT64_C(296220586027987448), V8_INT64_C(1015494173071134726), V8_INT64_C(1151237951914455318), V8_INT64_C(1331941174616854174), V8_INT64_C(2022020418667972654), V8_INT64_C(2450251424374977035), V8_INT64_C(3668393562685561486), V8_INT64_C(4858229301215502171), V8_INT64_C(4919426235170669383), V8_INT64_C(5034286595330341762), V8_INT64_C(5055797915536941182), V8_INT64_C(6072389716149252074), V8_INT64_C(6185309910199801210), V8_INT64_C(6297328311011094138), V8_INT64_C(6932372858072165827), V8_INT64_C(8483640924987737210), V8_INT64_C(8663764179455849203), V8_INT64_C(8877197042645298254), V8_INT64_C(8901543506779157333), std::numeric_limits<int64_t>::max()}; const uint32_t kUint32Values[] = { 0x00000000, 0x00000001, 0xffffffff, 0x1b09788b, 0x04c5fce8, 0xcc0de5bf, 0x273a798e, 0x187937a3, 0xece3af83, 0x5495a16b, 0x0b668ecc, 0x11223344, 0x0000009e, 0x00000043, 0x0000af73, 0x0000116b, 0x00658ecc, 0x002b3b4c, 0x88776655, 0x70000000, 0x07200000, 0x7fffffff, 0x56123761, 0x7fffff00, 0x761c4761, 0x80000000, 0x88888888, 0xa0000000, 0xdddddddd, 0xe0000000, 0xeeeeeeee, 0xfffffffd, 0xf0000000, 0x007fffff, 0x003fffff, 0x001fffff, 0x000fffff, 0x0007ffff, 0x0003ffff, 0x0001ffff, 0x0000ffff, 0x00007fff, 0x00003fff, 0x00001fff, 0x00000fff, 0x000007ff, 0x000003ff, 0x000001ff}; struct <API key> { const Operator* (<API key>::*constructor)(); const char* constructor_name; }; std::ostream& operator<<(std::ostream& os, <API key> const& cbop) { return os << cbop.constructor_name; } const <API key> <API key>[] = { #define OPCODE(Opcode) \ { &<API key>::Opcode, #Opcode } \ , <API key>(OPCODE) #undef OPCODE }; } // namespace // Unary operators namespace { struct UnaryOperator { const Operator* (<API key>::*constructor)(); const char* constructor_name; }; std::ostream& operator<<(std::ostream& os, const UnaryOperator& unop) { return os << unop.constructor_name; } static const UnaryOperator kUnaryOperators[] = { {&<API key>::<API key>, "<API key>"}, {&<API key>::<API key>, "<API key>"}, {&<API key>::<API key>, "<API key>"}, {&<API key>::<API key>, "<API key>"}, {&<API key>::ChangeInt32ToInt64, "ChangeInt32ToInt64"}, {&<API key>::<API key>, "<API key>"}, {&<API key>::<API key>, "<API key>"}, {&<API key>::<API key>, "<API key>"}}; } // namespace typedef <API key><UnaryOperator> <API key>; TEST_P(<API key>, Parameter) { const UnaryOperator unop = GetParam(); Reduction reduction = Reduce(graph()->NewNode((machine()->*unop.constructor)(), Parameter(0))); EXPECT_FALSE(reduction.Changed()); } <API key>(<API key>, <API key>, ::testing::ValuesIn(kUnaryOperators)); // <API key> TEST_F(<API key>, <API key>) { TRACED_FOREACH(float, x, kFloat32Values) { Reduction reduction = Reduce(graph()->NewNode( machine()-><API key>(), Float32Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsFloat64Constant(BitEq<double>(x))); } } // <API key> TEST_F(<API key>, <API key>) { Node* value = Parameter(0); Reduction reduction = Reduce(graph()->NewNode( machine()-><API key>(), graph()->NewNode(machine()-><API key>(), value))); ASSERT_TRUE(reduction.Changed()); EXPECT_EQ(value, reduction.replacement()); } TEST_F(<API key>, <API key>) { TRACED_FOREACH(int32_t, x, kInt32Values) { Reduction reduction = Reduce(graph()->NewNode( machine()-><API key>(), Float64Constant(FastI2D(x)))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt32Constant(x)); } } // <API key> TEST_F(<API key>, <API key>) { Node* value = Parameter(0); Reduction reduction = Reduce(graph()->NewNode( machine()-><API key>(), graph()->NewNode(machine()-><API key>(), value))); ASSERT_TRUE(reduction.Changed()); EXPECT_EQ(value, reduction.replacement()); } TEST_F(<API key>, <API key>) { TRACED_FOREACH(uint32_t, x, kUint32Values) { Reduction reduction = Reduce(graph()->NewNode( machine()-><API key>(), Float64Constant(FastUI2D(x)))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt32Constant(bit_cast<int32_t>(x))); } } // <API key> TEST_F(<API key>, <API key>) { TRACED_FOREACH(int32_t, x, kInt32Values) { Reduction reduction = Reduce( graph()->NewNode(machine()-><API key>(), Int32Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsFloat64Constant(BitEq(FastI2D(x)))); } } // ChangeInt32ToInt64 TEST_F(<API key>, <API key>) { TRACED_FOREACH(int32_t, x, kInt32Values) { Reduction reduction = Reduce( graph()->NewNode(machine()->ChangeInt32ToInt64(), Int32Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt64Constant(x)); } } // <API key> TEST_F(<API key>, <API key>) { TRACED_FOREACH(uint32_t, x, kUint32Values) { Reduction reduction = Reduce(graph()->NewNode(machine()-><API key>(), Int32Constant(bit_cast<int32_t>(x)))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsFloat64Constant(BitEq(FastUI2D(x)))); } } // <API key> TEST_F(<API key>, <API key>) { TRACED_FOREACH(uint32_t, x, kUint32Values) { Reduction reduction = Reduce(graph()->NewNode(machine()-><API key>(), Int32Constant(bit_cast<int32_t>(x)))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt64Constant(bit_cast<int64_t>(static_cast<uint64_t>(x)))); } } // <API key> TEST_F(<API key>, <API key>) { Node* value = Parameter(0); Reduction reduction = Reduce(graph()->NewNode( machine()-><API key>(), graph()->NewNode(machine()-><API key>(), value))); ASSERT_TRUE(reduction.Changed()); EXPECT_EQ(value, reduction.replacement()); } TEST_F(<API key>, <API key>) { TRACED_FOREACH(double, x, kFloat64Values) { Reduction reduction = Reduce(graph()->NewNode( machine()-><API key>(), Float64Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsFloat32Constant(BitEq(DoubleToFloat32(x)))); } } // <API key> TEST_F(<API key>, <API key>) { Node* value = Parameter(0); Reduction reduction = Reduce(graph()->NewNode( machine()-><API key>(), graph()->NewNode(machine()-><API key>(), value))); ASSERT_TRUE(reduction.Changed()); EXPECT_EQ(value, reduction.replacement()); } TEST_F(<API key>, <API key>) { TRACED_FOREACH(double, x, kFloat64Values) { Reduction reduction = Reduce(graph()->NewNode( machine()-><API key>(), Float64Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt32Constant(DoubleToInt32(x))); } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); Node* const merge = graph()->start(); Reduction reduction = Reduce(graph()->NewNode( machine()-><API key>(), graph()->NewNode(common()->Phi(kMachFloat64, 2), p0, p1, merge))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsPhi(kMachInt32, <API key>(p0), <API key>(p1), merge)); } // <API key> TEST_F(<API key>, <API key>) { Node* value = Parameter(0); Reduction reduction = Reduce(graph()->NewNode( machine()-><API key>(), graph()->NewNode(machine()->ChangeInt32ToInt64(), value))); ASSERT_TRUE(reduction.Changed()); EXPECT_EQ(value, reduction.replacement()); } TEST_F(<API key>, <API key>) { TRACED_FOREACH(int64_t, x, kInt64Values) { Reduction reduction = Reduce( graph()->NewNode(machine()-><API key>(), Int64Constant(x))); ASSERT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt32Constant(bit_cast<int32_t>( static_cast<uint32_t>(bit_cast<uint64_t>(x))))); } } // Word32And TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); TRACED_FORRANGE(int32_t, l, 1, 31) { TRACED_FORRANGE(int32_t, k, 1, l) { // (x << L) & (-1 << K) => x << L Reduction const r1 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Word32Shl(), p0, Int32Constant(l)), Int32Constant(-1 << k))); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), IsWord32Shl(p0, IsInt32Constant(l))); // (-1 << K) & (x << L) => x << L Reduction const r2 = Reduce(graph()->NewNode( machine()->Word32And(), Int32Constant(-1 << k), graph()->NewNode(machine()->Word32Shl(), p0, Int32Constant(l)))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), IsWord32Shl(p0, IsInt32Constant(l))); } } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); TRACED_FOREACH(int32_t, k, kInt32Values) { TRACED_FOREACH(int32_t, l, kInt32Values) { if (k == 0 || k == -1 || l == 0 || l == -1) continue; // (x & K) & L => x & (K & L) Reduction const r1 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Word32And(), p0, Int32Constant(k)), Int32Constant(l))); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), (k & l) ? IsWord32And(p0, IsInt32Constant(k & l)) : IsInt32Constant(0)); // (K & x) & L => x & (K & L) Reduction const r2 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Word32And(), Int32Constant(k), p0), Int32Constant(l))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), (k & l) ? IsWord32And(p0, IsInt32Constant(k & l)) : IsInt32Constant(0)); } } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); TRACED_FORRANGE(int32_t, l, 1, 31) { TRACED_FOREACH(int32_t, k, kInt32Values) { if ((k << l) == 0) continue; // (x + (K << L)) & (-1 << L) => (x & (-1 << L)) + (K << L) Reduction const r = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), p0, Int32Constant(k << l)), Int32Constant(-1 << l))); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), IsInt32Constant(k << l))); } Node* s1 = graph()->NewNode(machine()->Word32Shl(), p1, Int32Constant(l)); // (y << L + x) & (-1 << L) => (x & (-1 << L)) + y << L Reduction const r1 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), s1, p0), Int32Constant(-1 << l))); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), s1)); // (x + y << L) & (-1 << L) => (x & (-1 << L)) + y << L Reduction const r2 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), p0, s1), Int32Constant(-1 << l))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), s1)); } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); TRACED_FORRANGE(int32_t, l, 1, 31) { TRACED_FOREACH(int32_t, k, kInt32Values) { if ((k << l) == 0) continue; // (x * (K << L)) & (-1 << L) => x * (K << L) Reduction const r1 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Mul(), p0, Int32Constant(k << l)), Int32Constant(-1 << l))); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), IsInt32Mul(p0, IsInt32Constant(k << l))); // ((K << L) * x) & (-1 << L) => x * (K << L) Reduction const r2 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Mul(), Int32Constant(k << l), p0), Int32Constant(-1 << l))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), IsInt32Mul(p0, IsInt32Constant(k << l))); } } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); TRACED_FORRANGE(int32_t, l, 1, 31) { TRACED_FOREACH(int32_t, k, kInt32Values) { if ((k << l) == 0) continue; // (y * (K << L) + x) & (-1 << L) => (x & (-1 << L)) + y * (K << L) Reduction const r1 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), graph()->NewNode(machine()->Int32Mul(), p1, Int32Constant(k << l)), p0), Int32Constant(-1 << l))); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), IsInt32Mul(p1, IsInt32Constant(k << l)))); // (x + y * (K << L)) & (-1 << L) => (x & (-1 << L)) + y * (K << L) Reduction const r2 = Reduce(graph()->NewNode( machine()->Word32And(), graph()->NewNode(machine()->Int32Add(), p0, graph()->NewNode(machine()->Int32Mul(), p1, Int32Constant(k << l))), Int32Constant(-1 << l))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), IsInt32Mul(p1, IsInt32Constant(k << l)))); } } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); TRACED_FOREACH(<API key>, cbop, <API key>) { Node* cmp = graph()->NewNode((machine()->*cbop.constructor)(), p0, p1); // cmp & 1 => cmp Reduction const r1 = Reduce(graph()->NewNode(machine()->Word32And(), cmp, Int32Constant(1))); ASSERT_TRUE(r1.Changed()); EXPECT_EQ(cmp, r1.replacement()); // 1 & cmp => cmp Reduction const r2 = Reduce(graph()->NewNode(machine()->Word32And(), Int32Constant(1), cmp)); ASSERT_TRUE(r2.Changed()); EXPECT_EQ(cmp, r2.replacement()); } } // Word32Xor TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); // (x ^ -1) ^ -1 => x Reduction r1 = Reduce(graph()->NewNode( machine()->Word32Xor(), graph()->NewNode(machine()->Word32Xor(), p0, Int32Constant(-1)), Int32Constant(-1))); ASSERT_TRUE(r1.Changed()); EXPECT_EQ(r1.replacement(), p0); // -1 ^ (x ^ -1) => x Reduction r2 = Reduce(graph()->NewNode( machine()->Word32Xor(), Int32Constant(-1), graph()->NewNode(machine()->Word32Xor(), p0, Int32Constant(-1)))); ASSERT_TRUE(r2.Changed()); EXPECT_EQ(r2.replacement(), p0); // (-1 ^ x) ^ -1 => x Reduction r3 = Reduce(graph()->NewNode( machine()->Word32Xor(), graph()->NewNode(machine()->Word32Xor(), Int32Constant(-1), p0), Int32Constant(-1))); ASSERT_TRUE(r3.Changed()); EXPECT_EQ(r3.replacement(), p0); // -1 ^ (-1 ^ x) => x Reduction r4 = Reduce(graph()->NewNode( machine()->Word32Xor(), Int32Constant(-1), graph()->NewNode(machine()->Word32Xor(), Int32Constant(-1), p0))); ASSERT_TRUE(r4.Changed()); EXPECT_EQ(r4.replacement(), p0); } // Word32Ror TEST_F(<API key>, <API key>) { Node* value = Parameter(0); Node* shift = Parameter(1); Node* sub = graph()->NewNode(machine()->Int32Sub(), Int32Constant(32), shift); // Testing rotate left. Node* shl_l = graph()->NewNode(machine()->Word32Shl(), value, shift); Node* shr_l = graph()->NewNode(machine()->Word32Shr(), value, sub); // (x << y) | (x >>> (32 - y)) => x ror (32 - y) Node* node1 = graph()->NewNode(machine()->Word32Or(), shl_l, shr_l); Reduction reduction1 = Reduce(node1); EXPECT_TRUE(reduction1.Changed()); EXPECT_EQ(reduction1.replacement(), node1); EXPECT_THAT(reduction1.replacement(), IsWord32Ror(value, sub)); // (x >>> (32 - y)) | (x << y) => x ror (32 - y) Node* node2 = graph()->NewNode(machine()->Word32Or(), shr_l, shl_l); Reduction reduction2 = Reduce(node2); EXPECT_TRUE(reduction2.Changed()); EXPECT_EQ(reduction2.replacement(), node2); EXPECT_THAT(reduction2.replacement(), IsWord32Ror(value, sub)); // Testing rotate right. Node* shl_r = graph()->NewNode(machine()->Word32Shl(), value, sub); Node* shr_r = graph()->NewNode(machine()->Word32Shr(), value, shift); // (x << (32 - y)) | (x >>> y) => x ror y Node* node3 = graph()->NewNode(machine()->Word32Or(), shl_r, shr_r); Reduction reduction3 = Reduce(node3); EXPECT_TRUE(reduction3.Changed()); EXPECT_EQ(reduction3.replacement(), node3); EXPECT_THAT(reduction3.replacement(), IsWord32Ror(value, shift)); // (x >>> y) | (x << (32 - y)) => x ror y Node* node4 = graph()->NewNode(machine()->Word32Or(), shr_r, shl_r); Reduction reduction4 = Reduce(node4); EXPECT_TRUE(reduction4.Changed()); EXPECT_EQ(reduction4.replacement(), node4); EXPECT_THAT(reduction4.replacement(), IsWord32Ror(value, shift)); } TEST_F(<API key>, <API key>) { Node* value = Parameter(0); TRACED_FORRANGE(int32_t, k, 0, 31) { Node* shl = graph()->NewNode(machine()->Word32Shl(), value, Int32Constant(k)); Node* shr = graph()->NewNode(machine()->Word32Shr(), value, Int32Constant(32 - k)); // (x << K) | (x >>> ((32 - K) - y)) => x ror (32 - K) Node* node1 = graph()->NewNode(machine()->Word32Or(), shl, shr); Reduction reduction1 = Reduce(node1); EXPECT_TRUE(reduction1.Changed()); EXPECT_EQ(reduction1.replacement(), node1); EXPECT_THAT(reduction1.replacement(), IsWord32Ror(value, IsInt32Constant(32 - k))); // (x >>> (32 - K)) | (x << K) => x ror (32 - K) Node* node2 = graph()->NewNode(machine()->Word32Or(), shr, shl); Reduction reduction2 = Reduce(node2); EXPECT_TRUE(reduction2.Changed()); EXPECT_EQ(reduction2.replacement(), node2); EXPECT_THAT(reduction2.replacement(), IsWord32Ror(value, IsInt32Constant(32 - k))); } } TEST_F(<API key>, <API key>) { Node* value = Parameter(0); Node* node = graph()->NewNode(machine()->Word32Ror(), value, Int32Constant(0)); Reduction reduction = Reduce(node); EXPECT_TRUE(reduction.Changed()); EXPECT_EQ(reduction.replacement(), value); } TEST_F(<API key>, <API key>) { TRACED_FOREACH(int32_t, x, kUint32Values) { TRACED_FORRANGE(int32_t, y, 0, 31) { Node* node = graph()->NewNode(machine()->Word32Ror(), Int32Constant(x), Int32Constant(y)); Reduction reduction = Reduce(node); EXPECT_TRUE(reduction.Changed()); EXPECT_THAT(reduction.replacement(), IsInt32Constant(base::bits::RotateRight32(x, y))); } } } // Word32Sar TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); TRACED_FOREACH(<API key>, cbop, <API key>) { Node* cmp = graph()->NewNode((machine()->*cbop.constructor)(), p0, p1); // cmp << 31 >> 31 => 0 - cmp Reduction const r = Reduce(graph()->NewNode( machine()->Word32Sar(), graph()->NewNode(machine()->Word32Shl(), cmp, Int32Constant(31)), Int32Constant(31))); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Sub(IsInt32Constant(0), cmp)); } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); { Node* const l = graph()->NewNode(machine()->Load(kMachInt8), p0, p1, graph()->start(), graph()->start()); Reduction const r = Reduce(graph()->NewNode( machine()->Word32Sar(), graph()->NewNode(machine()->Word32Shl(), l, Int32Constant(24)), Int32Constant(24))); ASSERT_TRUE(r.Changed()); EXPECT_EQ(l, r.replacement()); } { Node* const l = graph()->NewNode(machine()->Load(kMachInt16), p0, p1, graph()->start(), graph()->start()); Reduction const r = Reduce(graph()->NewNode( machine()->Word32Sar(), graph()->NewNode(machine()->Word32Shl(), l, Int32Constant(16)), Int32Constant(16))); ASSERT_TRUE(r.Changed()); EXPECT_EQ(l, r.replacement()); } } // Word32Shl TEST_F(<API key>, <API key>) { Node* p0 = Parameter(0); Node* node = graph()->NewNode(machine()->Word32Shl(), p0, Int32Constant(0)); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_EQ(p0, r.replacement()); } TEST_F(<API key>, <API key>) { Node* p0 = Parameter(0); TRACED_FORRANGE(int32_t, x, 1, 31) { Node* node = graph()->NewNode( machine()->Word32Shl(), graph()->NewNode(machine()->Word32Sar(), p0, Int32Constant(x)), Int32Constant(x)); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); int32_t m = bit_cast<int32_t>(~((1U << x) - 1U)); EXPECT_THAT(r.replacement(), IsWord32And(p0, IsInt32Constant(m))); } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); TRACED_FOREACH(int32_t, k, kInt32Values) { TRACED_FORRANGE(int32_t, l, 1, 31) { if ((k << l) == 0) continue; // (x + (K << L)) >> L << L => (x & (-1 << L)) + (K << L) Reduction const r = Reduce(graph()->NewNode( machine()->Word32Shl(), graph()->NewNode(machine()->Word32Sar(), graph()->NewNode(machine()->Int32Add(), p0, Int32Constant(k << l)), Int32Constant(l)), Int32Constant(l))); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Add(IsWord32And(p0, IsInt32Constant(-1 << l)), IsInt32Constant(k << l))); } } } TEST_F(<API key>, <API key>) { Node* p0 = Parameter(0); TRACED_FORRANGE(int32_t, x, 1, 31) { Node* node = graph()->NewNode( machine()->Word32Shl(), graph()->NewNode(machine()->Word32Shr(), p0, Int32Constant(x)), Int32Constant(x)); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); int32_t m = bit_cast<int32_t>(~((1U << x) - 1U)); EXPECT_THAT(r.replacement(), IsWord32And(p0, IsInt32Constant(m))); } } // Int32Sub TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); TRACED_FOREACH(int32_t, k, kInt32Values) { Reduction const r = Reduce(graph()->NewNode(machine()->Int32Sub(), p0, Int32Constant(k))); ASSERT_TRUE(r.Changed()); if (k == 0) { EXPECT_EQ(p0, r.replacement()); } else { EXPECT_THAT(r.replacement(), IsInt32Add(p0, IsInt32Constant(-k))); } } } // Int32Div TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(0), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_EQ(r.replacement(), p0); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(-1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Sub(IsInt32Constant(0), p0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(2), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsWord32Sar(IsInt32Add(IsWord32Shr(p0, IsInt32Constant(31)), p0), IsInt32Constant(1))); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(-2), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsInt32Sub( IsInt32Constant(0), IsWord32Sar(IsInt32Add(IsWord32Shr(p0, IsInt32Constant(31)), p0), IsInt32Constant(1)))); } TRACED_FORRANGE(int32_t, shift, 2, 30) { Reduction const r = Reduce(graph()->NewNode(machine()->Int32Div(), p0, Int32Constant(1 << shift), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsWord32Sar(IsInt32Add(IsWord32Shr(IsWord32Sar(p0, IsInt32Constant(31)), IsInt32Constant(32 - shift)), p0), IsInt32Constant(shift))); } TRACED_FORRANGE(int32_t, shift, 2, 31) { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Uint32Constant(bit_cast<uint32_t, int32_t>(-1) << shift), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsInt32Sub( IsInt32Constant(0), IsWord32Sar( IsInt32Add(IsWord32Shr(IsWord32Sar(p0, IsInt32Constant(31)), IsInt32Constant(32 - shift)), p0), IsInt32Constant(shift)))); } TRACED_FOREACH(int32_t, divisor, kInt32Values) { if (divisor < 0) { if (base::bits::IsPowerOfTwo32(-divisor)) continue; Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Sub(IsInt32Constant(0), IsTruncatingDiv(p0, -divisor))); } else if (divisor > 0) { if (base::bits::IsPowerOfTwo32(divisor)) continue; Reduction const r = Reduce(graph()->NewNode( machine()->Int32Div(), p0, Int32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsTruncatingDiv(p0, divisor)); } } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); Reduction const r = Reduce(graph()->NewNode(machine()->Int32Div(), p0, p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsWord32Equal(IsWord32Equal(p0, IsInt32Constant(0)), IsInt32Constant(0))); } // Uint32Div TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Div(), Int32Constant(0), p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Div(), p0, Int32Constant(0), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Div(), p0, Int32Constant(1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_EQ(r.replacement(), p0); } TRACED_FOREACH(uint32_t, dividend, kUint32Values) { TRACED_FOREACH(uint32_t, divisor, kUint32Values) { Reduction const r = Reduce( graph()->NewNode(machine()->Uint32Div(), Uint32Constant(dividend), Uint32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(bit_cast<int32_t>( base::bits::UnsignedDiv32(dividend, divisor)))); } } TRACED_FORRANGE(uint32_t, shift, 1, 31) { Reduction const r = Reduce(graph()->NewNode(machine()->Uint32Div(), p0, Uint32Constant(1u << shift), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsWord32Shr(p0, IsInt32Constant(bit_cast<int32_t>(shift)))); } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); Reduction const r = Reduce( graph()->NewNode(machine()->Uint32Div(), p0, p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsWord32Equal(IsWord32Equal(p0, IsInt32Constant(0)), IsInt32Constant(0))); } // Int32Mod TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), Int32Constant(0), p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), p0, Int32Constant(0), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), p0, Int32Constant(1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), p0, Int32Constant(-1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } TRACED_FOREACH(int32_t, dividend, kInt32Values) { TRACED_FOREACH(int32_t, divisor, kInt32Values) { Reduction const r = Reduce( graph()->NewNode(machine()->Int32Mod(), Int32Constant(dividend), Int32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(base::bits::SignedMod32(dividend, divisor))); } } TRACED_FORRANGE(int32_t, shift, 1, 30) { Reduction const r = Reduce(graph()->NewNode(machine()->Int32Mod(), p0, Int32Constant(1 << shift), graph()->start())); int32_t const mask = (1 << shift) - 1; ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsSelect(kMachInt32, IsInt32LessThan(p0, IsInt32Constant(0)), IsInt32Sub(IsInt32Constant(0), IsWord32And(IsInt32Sub(IsInt32Constant(0), p0), IsInt32Constant(mask))), IsWord32And(p0, IsInt32Constant(mask)))); } TRACED_FORRANGE(int32_t, shift, 1, 31) { Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), p0, Uint32Constant(bit_cast<uint32_t, int32_t>(-1) << shift), graph()->start())); int32_t const mask = bit_cast<int32_t, uint32_t>((1U << shift) - 1); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsSelect(kMachInt32, IsInt32LessThan(p0, IsInt32Constant(0)), IsInt32Sub(IsInt32Constant(0), IsWord32And(IsInt32Sub(IsInt32Constant(0), p0), IsInt32Constant(mask))), IsWord32And(p0, IsInt32Constant(mask)))); } TRACED_FOREACH(int32_t, divisor, kInt32Values) { if (divisor == 0 || base::bits::IsPowerOfTwo32(Abs(divisor))) continue; Reduction const r = Reduce(graph()->NewNode( machine()->Int32Mod(), p0, Int32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Sub(p0, IsInt32Mul(IsTruncatingDiv(p0, Abs(divisor)), IsInt32Constant(Abs(divisor))))); } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); Reduction const r = Reduce(graph()->NewNode(machine()->Int32Mod(), p0, p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } // Uint32Mod TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Mod(), p0, Int32Constant(0), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Mod(), Int32Constant(0), p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } { Reduction const r = Reduce(graph()->NewNode( machine()->Uint32Mod(), p0, Int32Constant(1), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } TRACED_FOREACH(uint32_t, dividend, kUint32Values) { TRACED_FOREACH(uint32_t, divisor, kUint32Values) { Reduction const r = Reduce( graph()->NewNode(machine()->Uint32Mod(), Uint32Constant(dividend), Uint32Constant(divisor), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(bit_cast<int32_t>( base::bits::UnsignedMod32(dividend, divisor)))); } } TRACED_FORRANGE(uint32_t, shift, 1, 31) { Reduction const r = Reduce(graph()->NewNode(machine()->Uint32Mod(), p0, Uint32Constant(1u << shift), graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsWord32And(p0, IsInt32Constant( bit_cast<int32_t>((1u << shift) - 1u)))); } } TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); Reduction const r = Reduce( graph()->NewNode(machine()->Uint32Mod(), p0, p0, graph()->start())); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); } // Int32Add TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); Node* const p1 = Parameter(1); Reduction const r1 = Reduce(graph()->NewNode( machine()->Int32Add(), graph()->NewNode(machine()->Int32Sub(), Int32Constant(0), p0), p1)); ASSERT_TRUE(r1.Changed()); EXPECT_THAT(r1.replacement(), IsInt32Sub(p1, p0)); Reduction const r2 = Reduce(graph()->NewNode( machine()->Int32Add(), p0, graph()->NewNode(machine()->Int32Sub(), Int32Constant(0), p1))); ASSERT_TRUE(r2.Changed()); EXPECT_THAT(r2.replacement(), IsInt32Sub(p0, p1)); } // <API key> TEST_F(<API key>, <API key>) { Node* p0 = Parameter(0); { Node* add = graph()->NewNode(machine()-><API key>(), Int32Constant(0), p0); Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); r = Reduce(graph()->NewNode(common()->Projection(0), add)); ASSERT_TRUE(r.Changed()); EXPECT_EQ(p0, r.replacement()); } { Node* add = graph()->NewNode(machine()-><API key>(), p0, Int32Constant(0)); Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); r = Reduce(graph()->NewNode(common()->Projection(0), add)); ASSERT_TRUE(r.Changed()); EXPECT_EQ(p0, r.replacement()); } } TEST_F(<API key>, <API key>) { TRACED_FOREACH(int32_t, x, kInt32Values) { TRACED_FOREACH(int32_t, y, kInt32Values) { int32_t z; Node* add = graph()->NewNode(machine()-><API key>(), Int32Constant(x), Int32Constant(y)); Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(base::bits::SignedAddOverflow32(x, y, &z))); r = Reduce(graph()->NewNode(common()->Projection(0), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(z)); } } } // <API key> TEST_F(<API key>, <API key>) { Node* p0 = Parameter(0); Node* add = graph()->NewNode(machine()-><API key>(), p0, Int32Constant(0)); Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(0)); r = Reduce(graph()->NewNode(common()->Projection(0), add)); ASSERT_TRUE(r.Changed()); EXPECT_EQ(p0, r.replacement()); } TEST_F(<API key>, <API key>) { TRACED_FOREACH(int32_t, x, kInt32Values) { TRACED_FOREACH(int32_t, y, kInt32Values) { int32_t z; Node* add = graph()->NewNode(machine()-><API key>(), Int32Constant(x), Int32Constant(y)); Reduction r = Reduce(graph()->NewNode(common()->Projection(1), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(base::bits::SignedSubOverflow32(x, y, &z))); r = Reduce(graph()->NewNode(common()->Projection(0), add)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsInt32Constant(z)); } } } // Uint32LessThan TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); TRACED_FORRANGE(uint32_t, shift, 1, 3) { const uint32_t limit = (kMaxInt >> shift) - 1; Node* const node = graph()->NewNode( machine()->Uint32LessThan(), graph()->NewNode(machine()->Word32Sar(), p0, Uint32Constant(shift)), Uint32Constant(limit)); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsUint32LessThan( p0, IsInt32Constant(bit_cast<int32_t>(limit << shift)))); } } // Float64Mul TEST_F(<API key>, <API key>) { Node* const p0 = Parameter(0); { Reduction r = Reduce( graph()->NewNode(machine()->Float64Mul(), p0, Float64Constant(-1.0))); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsFloat64Sub(IsFloat64Constant(BitEq(-0.0)), p0)); } { Reduction r = Reduce( graph()->NewNode(machine()->Float64Mul(), Float64Constant(-1.0), p0)); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsFloat64Sub(IsFloat64Constant(BitEq(-0.0)), p0)); } } // <API key> TEST_F(<API key>, <API key>) { TRACED_FOREACH(double, x, kFloat64Values) { TRACED_FOREACH(uint32_t, y, kUint32Values) { Reduction const r = Reduce(graph()->NewNode(machine()-><API key>(), Float64Constant(x), Uint32Constant(y))); ASSERT_TRUE(r.Changed()); EXPECT_THAT( r.replacement(), IsFloat64Constant(BitEq(bit_cast<double>( (bit_cast<uint64_t>(x) & V8_UINT64_C(0xFFFFFFFF00000000)) | y)))); } } } // <API key> TEST_F(<API key>, <API key>) { TRACED_FOREACH(double, x, kFloat64Values) { TRACED_FOREACH(uint32_t, y, kUint32Values) { Reduction const r = Reduce(graph()->NewNode(machine()-><API key>(), Float64Constant(x), Uint32Constant(y))); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsFloat64Constant(BitEq(bit_cast<double>( (bit_cast<uint64_t>(x) & V8_UINT64_C(0xFFFFFFFF)) | (static_cast<uint64_t>(y) << 32))))); } } } // Store TEST_F(<API key>, <API key>) { const StoreRepresentation rep(kRepWord8, kNoWriteBarrier); Node* const base = Parameter(0); Node* const index = Parameter(1); Node* const value = Parameter(2); Node* const effect = graph()->start(); Node* const control = graph()->start(); TRACED_FOREACH(uint32_t, x, kUint32Values) { Node* const node = graph()->NewNode(machine()->Store(rep), base, index, graph()->NewNode(machine()->Word32And(), value, Uint32Constant(x | 0xffu)), effect, control); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsStore(rep, base, index, value, effect, control)); } } TEST_F(<API key>, <API key>) { const StoreRepresentation rep(kRepWord8, kNoWriteBarrier); Node* const base = Parameter(0); Node* const index = Parameter(1); Node* const value = Parameter(2); Node* const effect = graph()->start(); Node* const control = graph()->start(); TRACED_FORRANGE(int32_t, x, 1, 24) { Node* const node = graph()->NewNode( machine()->Store(rep), base, index, graph()->NewNode( machine()->Word32Sar(), graph()->NewNode(machine()->Word32Shl(), value, Int32Constant(x)), Int32Constant(x)), effect, control); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsStore(rep, base, index, value, effect, control)); } } TEST_F(<API key>, <API key>) { const StoreRepresentation rep(kRepWord16, kNoWriteBarrier); Node* const base = Parameter(0); Node* const index = Parameter(1); Node* const value = Parameter(2); Node* const effect = graph()->start(); Node* const control = graph()->start(); TRACED_FOREACH(uint32_t, x, kUint32Values) { Node* const node = graph()->NewNode(machine()->Store(rep), base, index, graph()->NewNode(machine()->Word32And(), value, Uint32Constant(x | 0xffffu)), effect, control); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsStore(rep, base, index, value, effect, control)); } } TEST_F(<API key>, <API key>) { const StoreRepresentation rep(kRepWord16, kNoWriteBarrier); Node* const base = Parameter(0); Node* const index = Parameter(1); Node* const value = Parameter(2); Node* const effect = graph()->start(); Node* const control = graph()->start(); TRACED_FORRANGE(int32_t, x, 1, 16) { Node* const node = graph()->NewNode( machine()->Store(rep), base, index, graph()->NewNode( machine()->Word32Sar(), graph()->NewNode(machine()->Word32Shl(), value, Int32Constant(x)), Int32Constant(x)), effect, control); Reduction r = Reduce(node); ASSERT_TRUE(r.Changed()); EXPECT_THAT(r.replacement(), IsStore(rep, base, index, value, effect, control)); } } } // namespace compiler } // namespace internal } // namespace v8
#ifndef <API key> #define <API key> #include "include/core/SkTypes.h" // Opaque handle to a resource. Users should always use the macro below to create a specific // template instantiation of GrResourceHandle. template <typename kind> class GrResourceHandle { public: GrResourceHandle(int value) : fValue(value) { SkASSERT(this->isValid()); } GrResourceHandle() : fValue(<API key>) {} bool operator==(const GrResourceHandle& other) const { return other.fValue == fValue; } bool isValid() const { return <API key> != fValue; } int toIndex() const { SkASSERT(this->isValid()); return fValue; } private: static const int <API key> = -1; int fValue; }; // Creates a type "name", which is a specfic template instantiation of GrResourceHandle. #define <API key>(name) \ struct name##Kind {}; \ using name = GrResourceHandle<name##Kind>; #endif
require 'rubygems' require 'rubygems/user_interaction' require 'uri' # RemoteFetcher handles the details of fetching gems and gem information from # a remote source. class Gem::RemoteFetcher
namespace std { template<typename T> class allocator { public: void in_base(); }; template<typename T, typename Alloc = std::allocator<T> > class vector : Alloc { public: void foo(); void stop(); }; template<typename Alloc> class vector<bool, Alloc>; } void f() { std::vector<int> v; v.foo(); // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:18:8 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s // CHECK-CC1: allocator<<#typename T#>> // CHECK-CC1-NEXT: vector<<#typename T#>{#, <#typename Alloc#>#}> // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:19:5 %s -o - | FileCheck -check-prefix=CHECK-CC2 %s // CHECK-CC2: foo // CHECK-CC2: in_base // CHECK-CC2: stop } template <typename> struct X; template <typename T> struct X<T*> { X(double); }; X<int*> x(42); // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:32:11 %s -o - | FileCheck -check-prefix=CHECK-CONSTRUCTOR %s // CHECK-CONSTRUCTOR: OVERLOAD: X(<#double#>) // (rather than X<type-parameter-0-0 *>(<#double#>)
# CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 2.8 # Relative path conversion top directories. SET(<API key> "/home/alexander/projects/natural_editor") SET(<API key> "/home/alexander/projects/natural_editor/build") # Force unix paths in dependencies. SET(<API key> 1) # The C and CXX include file regular expressions for this directory. SET(<API key> "^.*$") SET(<API key> "^$") SET(<API key> ${<API key>}) SET(<API key> ${<API key>})
// RECESS // RULE: .js prefixes should not be styled 'use strict' var util = require('../util') , RULE = { type: 'noJSPrefix' , exp: /^\.js\-/ , message: '.js prefixes should not be styled' } // validation method module.exports = function (def, data) { // default validation to true var isValid = true // return if no selector to validate if (!def.selectors) return isValid // loop over selectors def.selectors.forEach(function (selector) { // loop over selector entities selector.elements.forEach(function (element) { var extract // continue to next element if .js- prefix not styled if (!RULE.exp.test(element.value)) return // calculate line number for the extract extract = util.getLine(element.index - element.value.length, data) extract = util.padLine(extract) // highlight invalid styling of .js- prefix extract += element.value.replace(RULE.exp, '.js-'.magenta) // set invalid flag to false isValid = false // set error object on defintion token util.throwError(def, { type: RULE.type , message: RULE.message , extract: extract }) }) }) // return valid state return isValid }
Refinery::Application.configure do # Settings specified here will take precedence over those in config/environment.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.<API key> = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.<API key> = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Print deprecation notices to the stderr config.active_support.deprecation = :stderr end
#if !defined(<API key>) #define <API key> #include <string> #include <boost/mpl/bool.hpp> #include <boost/mpl/identity.hpp> namespace boost { namespace spirit { namespace x3 { namespace traits { // Determine if T is a character type template <typename T> struct is_char : mpl::false_ {}; template <typename T> struct is_char<T const> : is_char<T> {}; template <> struct is_char<char> : mpl::true_ {}; template <> struct is_char<wchar_t> : mpl::true_ {}; // Determine if T is a string template <typename T> struct is_string : mpl::false_ {}; template <typename T> struct is_string<T const> : is_string<T> {}; template <> struct is_string<char const*> : mpl::true_ {}; template <> struct is_string<wchar_t const*> : mpl::true_ {}; template <> struct is_string<char*> : mpl::true_ {}; template <> struct is_string<wchar_t*> : mpl::true_ {}; template <std::size_t N> struct is_string<char[N]> : mpl::true_ {}; template <std::size_t N> struct is_string<wchar_t[N]> : mpl::true_ {}; template <std::size_t N> struct is_string<char const[N]> : mpl::true_ {}; template <std::size_t N> struct is_string<wchar_t const[N]> : mpl::true_ {}; template <std::size_t N> struct is_string<char(&)[N]> : mpl::true_ {}; template <std::size_t N> struct is_string<wchar_t(&)[N]> : mpl::true_ {}; template <std::size_t N> struct is_string<char const(&)[N]> : mpl::true_ {}; template <std::size_t N> struct is_string<wchar_t const(&)[N]> : mpl::true_ {}; template <typename T, typename Traits, typename Allocator> struct is_string<std::basic_string<T, Traits, Allocator> > : mpl::true_ {}; // Get the underlying char type of a string template <typename T> struct char_type_of; template <typename T> struct char_type_of<T const> : char_type_of<T> {}; template <> struct char_type_of<char> : mpl::identity<char> {}; template <> struct char_type_of<wchar_t> : mpl::identity<wchar_t> {}; template <> struct char_type_of<char const*> : mpl::identity<char const> {}; template <> struct char_type_of<wchar_t const*> : mpl::identity<wchar_t const> {}; template <> struct char_type_of<char*> : mpl::identity<char> {}; template <> struct char_type_of<wchar_t*> : mpl::identity<wchar_t> {}; template <std::size_t N> struct char_type_of<char[N]> : mpl::identity<char> {}; template <std::size_t N> struct char_type_of<wchar_t[N]> : mpl::identity<wchar_t> {}; template <std::size_t N> struct char_type_of<char const[N]> : mpl::identity<char const> {}; template <std::size_t N> struct char_type_of<wchar_t const[N]> : mpl::identity<wchar_t const> {}; template <std::size_t N> struct char_type_of<char(&)[N]> : mpl::identity<char> {}; template <std::size_t N> struct char_type_of<wchar_t(&)[N]> : mpl::identity<wchar_t> {}; template <std::size_t N> struct char_type_of<char const(&)[N]> : mpl::identity<char const> {}; template <std::size_t N> struct char_type_of<wchar_t const(&)[N]> : mpl::identity<wchar_t const> {}; template <typename T, typename Traits, typename Allocator> struct char_type_of<std::basic_string<T, Traits, Allocator> > : mpl::identity<T> {}; // Get the C string from a string template <typename String> struct extract_c_string; template <typename String> struct extract_c_string { typedef typename char_type_of<String>::type char_type; template <typename T> static T const* call (T* str) { return (T const*)str; } template <typename T> static T const* call (T const* str) { return str; } }; // Forwarder that strips const template <typename T> struct extract_c_string<T const> { typedef typename extract_c_string<T>::char_type char_type; static typename extract_c_string<T>::char_type const* call (T const str) { return extract_c_string<T>::call(str); } }; // Forwarder that strips references template <typename T> struct extract_c_string<T&> { typedef typename extract_c_string<T>::char_type char_type; static typename extract_c_string<T>::char_type const* call (T& str) { return extract_c_string<T>::call(str); } }; // Forwarder that strips const references template <typename T> struct extract_c_string<T const&> { typedef typename extract_c_string<T>::char_type char_type; static typename extract_c_string<T>::char_type const* call (T const& str) { return extract_c_string<T>::call(str); } }; template <typename T, typename Traits, typename Allocator> struct extract_c_string<std::basic_string<T, Traits, Allocator> > { typedef T char_type; typedef std::basic_string<T, Traits, Allocator> string; static T const* call (string const& str) { return str.c_str(); } }; template <typename T> typename extract_c_string<T*>::char_type const* get_c_string(T* str) { return extract_c_string<T*>::call(str); } template <typename T> typename extract_c_string<T const*>::char_type const* get_c_string(T const* str) { return extract_c_string<T const*>::call(str); } template <typename String> typename extract_c_string<String>::char_type const* get_c_string(String& str) { return extract_c_string<String>::call(str); } template <typename String> typename extract_c_string<String>::char_type const* get_c_string(String const& str) { return extract_c_string<String>::call(str); } // Get the begin/end iterators from a string // Implementation for C-style strings. template <typename T> inline T const* get_string_begin(T const* str) { return str; } template <typename T> inline T* get_string_begin(T* str) { return str; } template <typename T> inline T const* get_string_end(T const* str) { T const* last = str; while (*last) last++; return last; } template <typename T> inline T* get_string_end(T* str) { T* last = str; while (*last) last++; return last; } // Implementation for containers (includes basic_string). template <typename T, typename Str> inline typename Str::const_iterator get_string_begin(Str const& str) { return str.begin(); } template <typename T, typename Str> inline typename Str::iterator get_string_begin(Str& str) { return str.begin(); } template <typename T, typename Str> inline typename Str::const_iterator get_string_end(Str const& str) { return str.end(); } template <typename T, typename Str> inline typename Str::iterator get_string_end(Str& str) { return str.end(); } }}}} #endif
module.exports.twitter = function twitter(username) { // Creates the canonical twitter URL without the '@' return 'https://twitter.com/' + username.replace(/^@/, ''); }; module.exports.facebook = function facebook(username) { // Handles a starting slash, this shouldn't happen, but just in case return 'https: };
# CentOS CentOS Linux is a community-supported distribution derived from sources freely provided to the public by [Red Hat](ftp://ftp.redhat.com/pub/redhat/linux/enterprise/) for Red Hat Enterprise Linux (RHEL). As such, CentOS Linux aims to be functionally compatible with RHEL. The CentOS Project mainly changes packages to remove upstream vendor branding and artwork. CentOS Linux is no-cost and free to redistribute. Each CentOS Linux version is maintained for up to 10 years (by means of security updates -- the duration of the support interval by Red Hat has varied over time with respect to Sources released). A new CentOS Linux version is released approximately every 2 years and each CentOS Linux version is periodically updated (roughly every 6 months) to support newer hardware. This results in a secure, low-maintenance, reliable, predictable, and reproducible Linux environment. > [wiki.centos.org](https://wiki.centos.org/FrontPage) %%LOGO%% # CentOS image documentation The `%%IMAGE%%:latest` tag is always the most recent version currently available. ## Rolling builds The CentOS Project offers regularly updated images for all active releases. These images will be updated monthly or as needed for emergency fixes. These rolling updates are tagged with the major version number only. For example: `docker pull %%IMAGE%%:6` or `docker pull %%IMAGE%%:7` ## Minor tags Additionally, images with minor version tags that correspond to install media are also offered. **These images DO NOT receive updates** as they are intended to match installation iso contents. If you choose to use these images it is highly recommended that you include `RUN yum -y update && yum clean all` in your Dockerfile, or otherwise address any potential security concerns. To use these images, please specify the minor version tag: For example: `docker pull %%IMAGE%%:5.11` or `docker pull %%IMAGE%%:6.6` ## Overlayfs and yum Recent Docker versions support the [overlayfs](https: # Package documentation By default, the CentOS containers are built using yum's `nodocs` option, which helps reduce the size of the image. If you install a package and discover files missing, please comment out the line `tsflags=nodocs` in `/etc/yum.conf` and reinstall your package. # Systemd integration Systemd is now included in both the %%IMAGE%%:7 and %%IMAGE%%:latest base containers, but it is not active by default. In order to use systemd, you will need to include text similar to the example Dockerfile below: ## Dockerfile for systemd base image dockerfile FROM %%IMAGE%%:7 ENV container docker RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \ <API key>.service ] || rm -f $i; done); \
var utils = exports; var uglify = require('uglify-js'); utils.extend = function extend(target, source) { Object.keys(source).forEach(function (key) { target[key] = source[key]; }); }; utils.beautify = function beautify(code) { var ast = uglify.parser.parse(code); return uglify.uglify.gen_code(ast, { beautify: true }); }; utils.expressionify = function expressionify(code) { try { var ast = uglify.parser.parse('(function(){\n' + code + '\n})'); } catch(e) { console.error(e.message + ' on ' + (e.line - 1) + ':' + e.pos); console.error('in'); console.error(code); throw e; } ast[1] = ast[1][0][1][3]; function traverse(ast) { if (!Array.isArray(ast)) return ast; switch (ast[0]) { case 'toplevel': if (ast[1].length === 1 && ast[1][0][0] !== 'block') { return ast; } else { var children = ast[1][0][0] === 'block' ? ast[1][0][1] : ast[1]; return ['toplevel', [[ 'call', [ 'dot', [ 'function', null, [], children.map(function(child, i, children) { return (i == children.length - 1) ? traverse(child) : child; }) ], 'call' ], [ ['name', 'this'] ] ]]]; } case 'block': // Empty blocks can't be processed if (ast[1].length <= 0) return ast; var last = ast[1][ast[1].length - 1]; return [ ast[0], ast[1].slice(0, -1).concat([traverse(last)]) ]; case 'while': case 'for': case 'switch': return ast; case 'if': return [ 'if', ast[1], traverse(ast[2]), traverse(ast[3]) ]; case 'stat': return [ 'stat', traverse(ast[1]) ]; default: if (ast[0] === 'return') return ast; return [ 'return', ast ] } return ast; } return uglify.uglify.gen_code(traverse(ast)).replace(/;$/, ''); }; utils.localify = function localify(code, id) { var ast = uglify.parser.parse(code); if (ast[1].length !== 1 || ast[1][0][0] !== 'stat') { throw new TypeError('Incorrect code for local: ' + code); } var vars = [], set = [], unset = []; function traverse(node) { if (node[0] === 'assign') { if (node[1] !== true) { throw new TypeError('Incorrect assignment in local'); } if (node[2][0] === 'dot' || node[2][0] === 'sub') { var host = ['name', '$l' + id++]; vars.push(host[1]); set.push(['assign', true, host, node[2][1]]); node[2][1] = host; if (node[2][0] === 'sub') { var property = ['name', '$l' + id++]; vars.push(property[1]); set.push(['assign', true, property, node[2][2]]); node[2][2] = property; } } var target = ['name', '$l' + id++]; vars.push(target[1]); set.push(['assign', true, target, node[2]]); set.push(['assign', true, node[2], node[3]]); unset.push(['assign', true, node[2], target]); } else if (node[0] === 'seq') { traverse(node[1]); traverse(node[2]); } else { throw new TypeError( 'Incorrect code for local (' + node[0] + '): ' + code ); } } traverse(ast[1][0][1]); function generate(seqs) { return uglify.uglify.gen_code(seqs.reduce(function (current, acc) { return ['seq', current, acc]; })); } return { vars: vars, before: generate(set.concat([['name', 'true']])), afterSuccess: generate(unset.concat([['name', 'true']])), afterFail: generate(unset.concat([['name', 'false']])) }; }; utils.merge = function merge(a, b) { Object.keys(b).forEach(function(key) { a[key] = b[key]; }); };
// header.hpp #ifndef <API key> #define <API key> #include <string> namespace http { namespace server3 { struct header { std::string name; std::string value; }; } // namespace server3 } // namespace http #endif // <API key>
/* * Plugin to hide series in flot graphs. * * To activate, set legend.hideable to true in the flot options object. * To hide one or more series by default, set legend.hidden to an array of * label strings. * * At the moment, this only works with line and point graphs. * * Example: * * var plotdata = [ * { * data: [[1, 1], [2, 1], [3, 3], [4, 2], [5, 5]], * label: "graph 1" * }, * { * data: [[1, 0], [2, 1], [3, 0], [4, 4], [5, 3]], * label: "graph 2" * } * ]; * * plot = $.plot($("#placeholder"), plotdata, { * series: { * points: { show: true }, * lines: { show: true } * }, * legend: { * hideable: true, * hidden: ["graph 1", "graph 2"] * } * }); * */ (function ($) { var options = { }; var drawnOnce = false; function init(plot) { function findPlotSeries(label) { var plotdata = plot.getData(); for (var i = 0; i < plotdata.length; i++) { if (plotdata[i].label == label) { return plotdata[i]; } } return null; } function plotLabelClicked(label, mouseOut) { var series = findPlotSeries(label); if (!series) { return; } var switchedOff = false; if (typeof series.points.oldShow === "undefined") { series.points.oldShow = false; } if (typeof series.lines.oldShow === "undefined") { series.lines.oldShow = false; } if (series.points.show && !series.points.oldShow) { series.points.show = false; series.points.oldShow = true; switchedOff = true; } if (series.lines.show && !series.lines.oldShow) { series.lines.show = false; series.lines.oldShow = true; switchedOff = true; } if (switchedOff) { series.oldColor = series.color; series.color = "#fff"; } else { var switchedOn = false; if (!series.points.show && series.points.oldShow) { series.points.show = true; series.points.oldShow = false; switchedOn = true; } if (!series.lines.show && series.lines.oldShow) { series.lines.show = true; series.lines.oldShow = false; switchedOn = true; } if (switchedOn) { series.color = series.oldColor; } } // HACK: Reset the data, triggering recalculation of graph bounds plot.setData(plot.getData()); plot.setupGrid(); plot.draw(); } function plotLabelHandlers(plot, options) { $(".graphlabel").mouseenter(function() { $(this).css("cursor", "pointer"); }) .mouseleave(function() { $(this).css("cursor", "default"); }) .unbind("click").click(function() { plotLabelClicked($(this).parent().text()); }); if (!drawnOnce) { drawnOnce = true; if (options.legend.hidden) { for (var i = 0; i < options.legend.hidden.length; i++) { plotLabelClicked(options.legend.hidden[i], true); } } } } function checkOptions(plot, options) { if (!options.legend.hideable) { return; } options.legend.labelFormatter = function(label, series) { return '<span class="graphlabel">' + label + '</span>'; }; // Really just needed for initial draw; the mouse-enter/leave // functions will call plotLabelHandlers() directly, since they // only call setupGrid(). plot.hooks.draw.push(function (plot, ctx) { plotLabelHandlers(plot, options); }); } plot.hooks.processOptions.push(checkOptions); function <API key>(plot, s, datapoints) { if (!plot.getOptions().legend.hideable) { return; } if (!s.points.show && !s.lines.show) { s.datapoints.format = [ null, null ]; } } plot.hooks.processDatapoints.push(<API key>); } $.plot.plugins.push({ init: init, options: options, name: 'hiddenGraphs', version: '1.0' }); })(jQuery);
module ActiveRecord # = Active Record Through Association module Associations module ThroughAssociation #:nodoc: delegate :source_reflection, :through_reflection, :to => :reflection protected # We merge in these scopes for two reasons: # 1. To get the default_scope conditions for any of the other reflections in the chain # 2. To get the type conditions for any STI models in the chain def target_scope scope = super reflection.chain.drop(1).each do |reflection| relation = reflection.klass.all scope.merge!( relation.except(:select, :create_with, :includes, :preload, :joins, :eager_load) ) end scope end private # Construct attributes for :through pointing to owner and associate. This is used by the # methods which create and delete records on the association. # We only support indirectly modifying through associations which have a belongs_to source. # This is the "has_many :tags, through: :taggings" situation, where the join model # typically has a belongs_to on both side. In other words, associations which could also # be represented as <API key> associations. # We do not support creating/deleting records on the association where the source has # some other type, because this opens up a whole can of worms, and in basically any # situation it is more natural for the user to just create or modify their join records # directly as required. def <API key>(*records) ensure_mutable if source_reflection.<API key>(reflection.klass) == reflection.klass.primary_key join_attributes = { source_reflection.name => records } else join_attributes = { source_reflection.foreign_key => records.map { |record| record.send(source_reflection.<API key>(reflection.klass)) } } end if options[:source_type] join_attributes[source_reflection.foreign_type] = records.map { |record| record.class.base_class.name } end if records.count == 1 Hash[join_attributes.map { |k, v| [k, v.first] }] else join_attributes end end # Note: this does not capture all cases, for example it would be crazy to try to # properly support stale-checking for nested associations. def stale_state if through_reflection.belongs_to? owner[through_reflection.foreign_key] && owner[through_reflection.foreign_key].to_s end end def foreign_key_present? through_reflection.belongs_to? && !owner[through_reflection.foreign_key].nil? end def ensure_mutable unless source_reflection.belongs_to? if reflection.has_one? raise <API key>.new(owner, reflection) else raise <API key>.new(owner, reflection) end end end def ensure_not_nested if reflection.nested? if reflection.has_one? raise <API key>.new(owner, reflection) else raise <API key>.new(owner, reflection) end end end def build_record(attributes) inverse = source_reflection.inverse_of target = through_association.target if inverse && target && !target.is_a?(Array) attributes[inverse.foreign_key] = target.id end super(attributes) end end end end
Param( # comma- or semicolon-separated list of Chocolatey packages. [<API key>()] [Parameter(Mandatory=$True)] [string] $packageList ) Function Get-TempPassword() { Param( [int]$length=10, [string[]]$sourcedata ) For ($loop=1; $loop -le $length; $loop++) { $tempPassword+=($sourcedata | GET-RANDOM) } return $tempPassword } $ascii=$NULL;For ($a=33;$a -le 126;$a++) {$ascii+=,[char][byte]$a } $userName = "artifactInstaller" $<API key> -length 43 -sourcedata $ascii $cn = [ADSI]"WinNT://$env:ComputerName" # Create user $user = $cn.Create("User", $userName) $user.SetPassword($password) $user.SetInfo() $user.description = "DevTestLab artifact installer" $user.SetInfo() # Add user to the Administrators group $group = [ADSI]"WinNT://$env:ComputerName/Administrators,group" $group.add("WinNT://$env:ComputerName/$userName") $sec<API key> $password -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential("$env:COMPUTERNAME\$($username)", $secPassword) $command = $PSScriptRoot + "\<API key>.ps1" # Run Chocolatey as the artifactInstaller user Enable-PSRemoting -Force -<API key> Invoke-Command -FilePath $command -Credential $credential -ComputerName $env:COMPUTERNAME -ArgumentList $packageList Disable-PSRemoting -Force # Delete the artifactInstaller user $cn.Delete("User", $userName) # Delete the artifactInstaller user profile gwmi win32_userprofile | where { $_.LocalPath -like "*$userName*" } | foreach { $_.Delete() }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using NSubstitute; using Xunit; using System.Threading.Tasks; namespace Octokit.Tests.Clients { <summary> Client tests mostly just need to make sure they call the IApiConnection with the correct relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. </summary> public class SearchClientTests { public class TheConstructor { [Fact] public void <API key>() { Assert.Throws<<API key>>(() => new SearchClient(null)); } } public class <API key> { [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); client.SearchUsers(new SearchUsersRequest("something")); connection.Received().Get<SearchUsersResult>(Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Any<Dictionary<string, string>>()); } [Fact] public async Task <API key>() { var client = new SearchClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<<API key>>(() => client.SearchUsers(null)); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.AccountType = AccountSearchType.User; client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+type:User")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.AccountType = AccountSearchType.Org; client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+type:Org")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get users where the fullname contains 'github' var request = new SearchUsersRequest("github"); request.In = new[] { UserInQualifier.Fullname }; client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Fullname")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.In = new[] { UserInQualifier.Email }; client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Email")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.In = new[] { UserInQualifier.Username }; client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Username")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.In = new[] { UserInQualifier.Username, UserInQualifier.Fullname, UserInQualifier.Email }; client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Username,Fullname,Email")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Repositories = Range.GreaterThan(5); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:>5")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Repositories = Range.GreaterThanOrEquals(5); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:>=5")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Repositories = Range.LessThanOrEquals(5); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:<=5")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Repositories = Range.LessThan(5); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:<5")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Location = "San Francisco"; client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+location:San Francisco")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get users who have mostly repos where language is Ruby var request = new SearchUsersRequest("github"); request.Language = Language.Ruby; client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+language:Ruby")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Created = DateRange.GreaterThan(new DateTime(2014, 1, 1)); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Created = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1)); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>=2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Created = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1)); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<=2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Created = DateRange.LessThan(new DateTime(2014, 1, 1)); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Created = DateRange.Between(new DateTime(2014, 1, 1), new DateTime(2014, 2, 1)); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:2014-01-01..2014-02-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Followers = Range.GreaterThan(1); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:>1")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Followers = Range.GreaterThanOrEquals(1); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:>=1")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Followers = Range.LessThan(1); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:<1")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Followers = Range.LessThanOrEquals(1); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:<=1")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchUsersRequest("github"); request.Followers = new Range(1, 1000); client.SearchUsers(request); connection.Received().Get<SearchUsersResult>( Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:1..1000")); } } public class TheSearchRepoMethod { [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); client.SearchRepo(new <API key>("something")); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Any<Dictionary<string, string>>()); } [Fact] public async Task <API key>() { var client = new SearchClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<<API key>>(() => client.SearchRepo(null)); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new <API key>("github"); request.Size = Range.GreaterThan(1); client.SearchRepo(request); connection.Received().Get<<API key>>( Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+size:>1")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos whos stargazers are greater than 500 var request = new <API key>("github"); request.Stars = Range.GreaterThan(500); client.SearchRepo(request); connection.Received().Get<<API key>>( Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:>500")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos whos stargazers are less than 500 var request = new <API key>("github"); request.Stars = Range.LessThan(500); client.SearchRepo(request); connection.Received().Get<<API key>>( Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:<500")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos whos stargazers are less than 500 or equal to var request = new <API key>("github"); request.Stars = Range.LessThanOrEquals(500); client.SearchRepo(request); connection.Received().Get<<API key>>( Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:<=500")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos which has forks that are greater than 50 var request = new <API key>("github"); request.Forks = Range.GreaterThan(50); client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+forks:>50")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //search repos that contains rails and forks are included in the search var request = new <API key>("github"); request.Fork = ForkQualifier.IncludeForks; client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+fork:IncludeForks")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos whos language is Ruby var request = new <API key>("github"); request.Language = Language.Ruby; client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+language:Ruby")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos where the Description contains the test 'github' var request = new <API key>("github"); request.In = new[] { InQualifier.Description }; client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Description")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new <API key>("github"); request.In = new[] { InQualifier.Name }; client.SearchRepo(request); connection.Received().Get<<API key>>( Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Name")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new <API key>("github"); request.In = new[] { InQualifier.Readme }; client.SearchRepo(request); connection.Received().Get<<API key>>( Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Readme")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new <API key>("github"); request.In = new[] { InQualifier.Readme, InQualifier.Description, InQualifier.Name }; client.SearchRepo(request); connection.Received().Get<<API key>>( Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Readme,Description,Name")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos where the search contains 'github' and has been created after year jan 1 2011 var request = new <API key>("github"); request.Created = DateRange.GreaterThan(new DateTime(2011, 1, 1)); client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>2011-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos where the search contains 'github' and has been created after year jan 1 2011 var request = new <API key>("github"); request.Created = DateRange.GreaterThanOrEquals(new DateTime(2011, 1, 1)); client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>=2011-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos where the search contains 'github' and has been created after year jan 1 2011 var request = new <API key>("github"); request.Created = DateRange.LessThan(new DateTime(2011, 1, 1)); client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<2011-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos where the search contains 'github' and has been created after year jan 1 2011 var request = new <API key>("github"); request.Created = DateRange.LessThanOrEquals(new DateTime(2011, 1, 1)); client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<=2011-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new <API key>("github"); request.Created = DateRange.Between(new DateTime(2011, 1, 1), new DateTime(2012, 11, 11)); client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:2011-01-01..2012-11-11")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos where the search contains 'github' and has been pushed before year jan 1 2013 var request = new <API key>("github"); request.Updated = DateRange.GreaterThan(new DateTime(2013, 1, 1)); client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:>2013-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos where the search contains 'github' and has been pushed before year jan 1 2013 var request = new <API key>("github"); request.Updated = DateRange.GreaterThanOrEquals(new DateTime(2013, 1, 1)); client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:>=2013-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos where the search contains 'github' and has been pushed before year jan 1 2013 var request = new <API key>("github"); request.Updated = DateRange.LessThan(new DateTime(2013, 1, 1)); client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:<2013-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos where the search contains 'github' and has been pushed before year jan 1 2013 var request = new <API key>("github"); request.Updated = DateRange.LessThanOrEquals(new DateTime(2013, 1, 1)); client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:<=2013-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new <API key>("github"); request.Updated = DateRange.Between(new DateTime(2012, 4, 30), new DateTime(2012, 7, 4)); client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:2012-04-30..2012-07-04")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); //get repos where search contains 'github' and user/org is 'github' var request = new <API key>("github"); request.User = "rails"; client.SearchRepo(request); connection.Received().Get<<API key>>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+user:rails")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new <API key>("github"); request.SortField = RepoSearchSort.Stars; client.SearchRepo(request); connection.Received().Get<<API key>>( Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "github" && d["sort"] == "stars")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new <API key>(); client.SearchRepo(request); connection.Received().Get<<API key>>( Arg.Is<Uri>(u => u.ToString() == "search/repositories"), Arg.Is<Dictionary<string, string>>(d => String.IsNullOrEmpty(d["q"]))); } } public class <API key> { [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); client.SearchIssues(new SearchIssuesRequest("something")); connection.Received().Get<SearchIssuesResult>(Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Any<Dictionary<string, string>>()); } [Fact] public async Task <API key>() { var client = new SearchClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<<API key>>(() => client.SearchIssues(null)); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("pub"); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "pub")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.SortField = IssueSearchSort.Comments; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["sort"] == "comments")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.SortField = IssueSearchSort.Updated; request.Order = SortDirection.Ascending; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["sort"] == "updated" && d["order"] == "asc")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["order"] == "desc")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.In = new[] { IssueInQualifier.Comment }; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:comment")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.In = new[] { IssueInQualifier.Body, IssueInQualifier.Title }; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:body,title")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Type = IssueTypeQualifier.Issue; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+type:issue")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Type = IssueTypeQualifier.PR; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+type:pr")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Author = "alfhenrik"; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+author:alfhenrik")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Assignee = "alfhenrik"; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+assignee:alfhenrik")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Mentions = "alfhenrik"; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+mentions:alfhenrik")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Commenter = "alfhenrik"; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+commenter:alfhenrik")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Involves = "alfhenrik"; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+involves:alfhenrik")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.State = ItemState.Open; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+state:open")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.State = ItemState.Closed; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+state:closed")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Labels = new[] { "bug" }; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+label:bug")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Labels = new[] { "bug", "feature" }; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+label:bug+label:feature")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Language = Language.CSharp; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+language:CSharp")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Created = DateRange.GreaterThan(new DateTime(2014, 1, 1)); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:>2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Created = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1)); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:>=2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Created = DateRange.LessThan(new DateTime(2014, 1, 1)); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:<2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Created = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1)); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:<=2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Created = DateRange.Between(new DateTime(2014, 1, 1), new DateTime(2014, 2, 2)); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:2014-01-01..2014-02-02")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Updated = DateRange.GreaterThan(new DateTime(2014, 1, 1)); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:>2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Updated = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1)); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:>=2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Updated = DateRange.LessThan(new DateTime(2014, 1, 1)); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:<2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Updated = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1)); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:<=2014-01-01")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Comments = Range.GreaterThan(10); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:>10")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Comments = Range.GreaterThanOrEquals(10); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:>=10")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Comments = Range.LessThan(10); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:<10")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Comments = Range.LessThanOrEquals(10); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:<=10")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Comments = new Range(10, 20); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:10..20")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.User = "alfhenrik"; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+user:alfhenrik")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Repos.Add("octokit", "octokit.net"); client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+repo:octokit/octokit.net")); } [Fact] public async Task <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("windows"); request.Repos = new <API key> { "haha-business" }; request.SortField = IssueSearchSort.Created; request.Order = SortDirection.Descending; await Assert.ThrowsAsync<<API key>>( async () => await client.SearchIssues(request)); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchIssuesRequest("something"); request.Repos.Add("octokit/octokit.net"); request.User = "alfhenrik"; request.Labels = new[] { "bug" }; client.SearchIssues(request); connection.Received().Get<SearchIssuesResult>( Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+label:bug+user:alfhenrik+repo:octokit/octokit.net")); } } public class TheSearchCodeMethod { [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); client.SearchCode(new SearchCodeRequest("something")); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Any<Dictionary<string, string>>()); } [Fact] public async Task <API key>() { var client = new SearchClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<<API key>>(() => client.SearchCode(null)); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.SortField = CodeSearchSort.Indexed; client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["sort"] == "indexed")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.SortField = CodeSearchSort.Indexed; request.Order = SortDirection.Ascending; client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["sort"] == "indexed" && d["order"] == "asc")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["order"] == "desc")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.In = new[] { CodeInQualifier.File }; client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:file")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.In = new[] { CodeInQualifier.File, CodeInQualifier.Path }; client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:file,path")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.Language = Language.CSharp; client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+language:C } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.Forks = true; client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+fork:true")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.Size = Range.GreaterThan(10); client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:>10")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.Size = Range.GreaterThanOrEquals(10); client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:>=10")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.Size = Range.LessThan(10); client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:<10")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.Size = Range.LessThanOrEquals(10); client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:<=10")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.Size = new Range(10, 100); client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:10..100")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.Path = "app/public"; client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+path:app/public")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.Extension = "cs"; client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+extension:cs")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.FileName = "packages.config"; client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+filename:packages.config")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something"); request.User = "alfhenrik"; client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+user:alfhenrik")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something", "octokit", "octokit.net"); client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+repo:octokit/octokit.net")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something", "octokit", "octokit.net"); client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+repo:octokit/octokit.net")); } [Fact] public void <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("something", "octokit", "octokit.net"); request.Path = "tools/FAKE.core"; request.Extension = "fs"; client.SearchCode(request); connection.Received().Get<SearchCodeResult>( Arg.Is<Uri>(u => u.ToString() == "search/code"), Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+path:tools/FAKE.core+extension:fs+repo:octokit/octokit.net")); } [Fact] public async Task <API key>() { var connection = Substitute.For<IApiConnection>(); var client = new SearchClient(connection); var request = new SearchCodeRequest("windows"); request.Repos = new <API key> { "haha-business" }; request.Order = SortDirection.Descending; await Assert.ThrowsAsync<<API key>>( async () => await client.SearchCode(request)); } } } }
{% extends "layout.html" %} {% block page_title %} Apprenticeships {% endblock %} {% block content %} <script> var whereNow = function() { var goToEmployer = JSON.parse(localStorage.getItem('commitments.isEmployer')); if (goToEmployer == "yes") { window.location.href='../<API key>/provider-list'; } else { window.location.href='<API key>'; } }; </script> <style> .people-nav a { {% include "includes/nav-on-state-css.html" %} } </style> <main id="content" role="main"> {% include "includes/<API key>.html" %} {% include "includes/<API key>.html" %} <!--div class="breadcrumbs"> <ol role="breadcrumbs"> <li><a href="/{% include "includes/sprint-link.html" %}/balance">Access my funds</a></li> </ol> </div <div class="breadcrumbs back-breadcrumb"> <ol role="breadcrumbs"> {% include "includes/breadcrumbs/register-back.html" %} </ol> </div> <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-xlarge" >Instructions for your training provider</h1> <p class="lede">Let <span style="font-weight:700">Hackney Skills and Training Ltd</span> know which apprentices you'd like them to add.</p> <form action=""> <fieldset> <legend class="visuallyhidden">provider contact details and message - optional</legend> <div class="form-group"> <label class="form-label-bold" for="message">Instructions</label> <span class="form-hint">For example, please add the 12 admin level 2 apprentices and 13 engineering level 3 apprentices.</span> <textarea class="form-control" id="message" type="text" style="width:100%" rows="5" ></textarea> </div> </fieldset> <input class="button" id="Finish" onclick="whereNow()" type="button" value="Send"> </form> <div style="margin-top:50px"></div> <!-- template to pull in the start tabs so this doesn't get too messy - it is pulling in the tabs --> <!-- {% include "includes/start-tabs.html" %} --> </div> <div class="column-one-third"> <!--aside class="related"> <h2 class="heading-medium" style="margin-top:10px">Existing account</h2> <nav role="navigation"> <ul class="robSideNav"> <li> <a href="../login">Sign in</a> </li> </ul> </nav> </aside </div> </div> </main> <script> //jquery that runs the tabs. Uses the jquery.tabs.js from gov.uk {% endblock %}
require 'spec_helper' RSpec.configure do |c| c.os = 'Gentoo' end describe kernel_module('lp') do it { should be_loaded } its(:command) { should eq "lsmod | grep ^lp" } end describe kernel_module('invalid-module') do it { should_not be_loaded } end
<TS language="af_ZA" version="2.0"> <context> <name>AddressBookPage</name> <message> <source>Create a new address</source> <translation>Skep 'n nuwe adres</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Maak 'n kopie van die huidige adres na die stelsel klipbord</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Verwyder</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Etiket</translation> </message> <message> <source>Address</source> <translation>Adres</translation> </message> <message> <source>(no label)</source> <translation>(geen etiket)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Wagfrase Dialoog</translation> </message> <message> <source>Enter passphrase</source> <translation>Tik wagfrase in</translation> </message> <message> <source>New passphrase</source> <translation>Nuwe wagfrase</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Herhaal nuwe wagfrase</translation> </message> <message> <source>Encrypt wallet</source> <translation>Enkripteer beursie</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Hierdie operasie benodig 'n wagwoord om die beursie oop te sluit.</translation> </message> <message> <source>Unlock wallet</source> <translation>Sluit beursie oop</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Hierdie operasie benodig 'n wagwoord om die beursie oop te sluit.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Sluit beursie oop</translation> </message> <message> <source>Change passphrase</source> <translation>Verander wagfrase</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Bevestig beursie enkripsie.</translation> </message> <message> <source>Wallet encrypted</source> <translation>Die beursie is nou bewaak</translation> </message> <message> <source>Enter the old passphrase and new passphrase to the wallet.</source> <translation>Tik in die ou wagfrase en die nuwe wagfrase vir die beursie.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Die beursie kon nie bewaak word nie</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Beursie bewaaking het misluk as gevolg van 'n interne fout. Die beursie is nie bewaak nie!</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>Die wagfrase stem nie ooreen nie</translation> </message> <message> <source>Wallet unlock failed</source> <translation>Beursie oopsluiting het misluk</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Die wagfrase wat ingetik was om die beursie oop te sluit, was verkeerd.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>Beursie dekripsie het misluk</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>Die beursie se wagfrase verandering was suksesvol.</translation> </message> </context> <context> <name>BanTableModel</name> </context> <context> <name>BitcoinGUI</name> <message> <source>Synchronizing with network...</source> <translation>Sinchroniseer met die netwerk ...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Oorsig</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Wys algemene oorsig van die beursie</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transaksies</translation> </message> <message> <source>Browse transaction history</source> <translation>Besoek transaksie geskiedenis</translation> </message> <message> <source>E&amp;xit</source> <translation>S&amp;luit af</translation> </message> <message> <source>Quit application</source> <translation>Sluit af</translation> </message> <message> <source>Show information about Qt</source> <translation>Wys inligting oor Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opsies</translation> </message> <message> <source>Bitcoin</source> <translation>Bitcoin</translation> </message> <message> <source>Wallet</source> <translation>Beursie</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Lêer</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Instellings</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Hulp</translation> </message> <message> <source>Tabs toolbar</source> <translation>Blad nutsbalk</translation> </message> <message> <source>%1 behind</source> <translation>%1 agter</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>Ontvangs van laaste blok is %1 terug.</translation> </message> <message> <source>Error</source> <translation>Fout</translation> </message> <message> <source>Information</source> <translation>Informasie</translation> </message> </context> <context> <name>ClientModel</name> </context> <context> <name>CoinControlDialog</name> <message> <source>Amount:</source> <translation>Bedrag:</translation> </message> <message> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Copy address</source> <translation>Maak kopie van adres</translation> </message> <message> <source>Copy amount</source> <translation>Kopieer bedrag</translation> </message> <message> <source>(no label)</source> <translation>(geen etiket)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>&amp;Label</source> <translation>&amp;Etiket</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Adres</translation> </message> <message> <source>New receiving address</source> <translation>Nuwe ontvangende adres</translation> </message> <message> <source>New sending address</source> <translation>Nuwe stuurende adres</translation> </message> <message> <source>Edit receiving address</source> <translation>Wysig ontvangende adres</translation> </message> <message> <source>Edit sending address</source> <translation>Wysig stuurende adres</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Kon nie die beursie oopsluit nie.</translation> </message> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> <message> <source>Usage:</source> <translation>Gebruik:</translation> </message> </context> <context> <name>Intro</name> <message> <source>Error</source> <translation>Fout</translation> </message> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opsies</translation> </message> <message> <source>W&amp;allet</source> <translation>&amp;Beursie</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Vorm</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Bedrag</translation> </message> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>&amp;Information</source> <translation>Informasie</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>&amp;Bedrag:</translation> </message> <message> <source>&amp;Message:</source> <translation>&amp;Boodskap:</translation> </message> <message> <source>Copy amount</source> <translation>Kopieer bedrag</translation> </message> </context> <context> <name><API key></name> <message> <source>Address</source> <translation>Adres</translation> </message> <message> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <source>Label</source> <translation>Etiket</translation> </message> <message> <source>Message</source> <translation>Boodskap</translation> </message> </context> <context> <name><API key></name> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Label</source> <translation>Etiket</translation> </message> <message> <source>Message</source> <translation>Boodskap</translation> </message> <message> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <source>(no label)</source> <translation>(geen etiket)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Stuur Munstukke</translation> </message> <message> <source>Insufficient funds!</source> <translation>Onvoldoende fondse</translation> </message> <message> <source>Amount:</source> <translation>Bedrag:</translation> </message> <message> <source>Transaction Fee:</source> <translation>Transaksie fooi:</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Stuur aan vele ontvangers op eens</translation> </message> <message> <source>Balance:</source> <translation>Balans:</translation> </message> <message> <source>S&amp;end</source> <translation>S&amp;tuur</translation> </message> <message> <source>Copy amount</source> <translation>Kopieer bedrag</translation> </message> <message> <source>(no label)</source> <translation>(geen etiket)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>&amp;Bedrag:</translation> </message> <message> <source>Message:</source> <translation>Boodskap:</translation> </message> </context> <context> <name>ShutdownWindow</name> </context> <context> <name><API key></name> <message> <source>&amp;Sign Message</source> <translation>&amp;Teken boodskap</translation> </message> <message> <source>Signature</source> <translation>Handtekening</translation> </message> <message> <source>Sign &amp;Message</source> <translation>Teken &amp;Boodskap</translation> </message> </context> <context> <name>SplashScreen</name> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>From</source> <translation>Van</translation> </message> <message> <source>To</source> <translation>Na</translation> </message> <message> <source>own address</source> <translation>eie adres</translation> </message> <message> <source>label</source> <translation>etiket</translation> </message> <message> <source>Credit</source> <translation>Krediet</translation> </message> <message> <source>not accepted</source> <translation>nie aanvaar nie</translation> </message> <message> <source>Debit</source> <translation>Debiet</translation> </message> <message> <source>Transaction fee</source> <translation>Transaksie fooi</translation> </message> <message> <source>Net amount</source> <translation>Netto bedrag</translation> </message> <message> <source>Message</source> <translation>Boodskap</translation> </message> <message> <source>Transaction ID</source> <translation>Transaksie ID</translation> </message> <message> <source>Transaction</source> <translation>Transaksie</translation> </message> <message> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <source>true</source> <translation>waar</translation> </message> <message> <source>false</source> <translation>onwaar</translation> </message> <message> <source>unknown</source> <translation>onbekend</translation> </message> </context> <context> <name><API key></name> </context> <context> <name><API key></name> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Type</source> <translation>Tipe</translation> </message> <message> <source>Label</source> <translation>Etiket</translation> </message> <message> <source>Received with</source> <translation>Ontvang met</translation> </message> <message> <source>Received from</source> <translation>Ontvang van</translation> </message> <message> <source>Sent to</source> <translation>Gestuur na</translation> </message> <message> <source>Payment to yourself</source> <translation>Betalings Aan/na jouself</translation> </message> <message> <source>Mined</source> <translation>Gemyn</translation> </message> <message> <source>(n/a)</source> <translation>(n.v.t)</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>Datum en tyd wat die transaksie ontvang was.</translation> </message> <message> <source>Type of transaction.</source> <translation>Tipe transaksie.</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>Alles</translation> </message> <message> <source>Today</source> <translation>Vandag</translation> </message> <message> <source>This week</source> <translation>Hierdie week</translation> </message> <message> <source>This month</source> <translation>Hierdie maand</translation> </message> <message> <source>Last month</source> <translation>Verlede maand</translation> </message> <message> <source>This year</source> <translation>Hierdie jaar</translation> </message> <message> <source>Range...</source> <translation>Reeks...</translation> </message> <message> <source>Received with</source> <translation>Ontvang met</translation> </message> <message> <source>Sent to</source> <translation>Gestuur na</translation> </message> <message> <source>To yourself</source> <translation>Aan/na jouself</translation> </message> <message> <source>Mined</source> <translation>Gemyn</translation> </message> <message> <source>Other</source> <translation>Ander</translation> </message> <message> <source>Min amount</source> <translation>Min bedrag</translation> </message> <message> <source>Copy address</source> <translation>Maak kopie van adres</translation> </message> <message> <source>Copy amount</source> <translation>Kopieer bedrag</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Type</source> <translation>Tipe</translation> </message> <message> <source>Label</source> <translation>Etiket</translation> </message> <message> <source>Address</source> <translation>Adres</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Range:</source> <translation>Reeks:</translation> </message> <message> <source>to</source> <translation>aan</translation> </message> </context> <context> <name><API key></name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Stuur Munstukke</translation> </message> </context> <context> <name>WalletView</name> </context> <context> <name>bitcoin-core</name> <message> <source>Options:</source> <translation>Opsies:</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>Fout: Hardeskyf spasie is baie laag!</translation> </message> <message> <source>Information</source> <translation>Informasie</translation> </message> <message> <source>This help message</source> <translation>Hierdie help boodskap</translation> </message> <message> <source>Loading addresses...</source> <translation>Laai adresse...</translation> </message> <message> <source>Insufficient funds</source> <translation>Onvoldoende fondse</translation> </message> <message> <source>Loading block index...</source> <translation>Laai blok indeks...</translation> </message> <message> <source>Loading wallet...</source> <translation>Laai beursie...</translation> </message> <message> <source>Done loading</source> <translation>Klaar gelaai</translation> </message> <message> <source>Error</source> <translation>Fout</translation> </message> </context> </TS>
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Orleans.Serialization; namespace Orleans.Runtime.MembershipService { [Serializable] internal class <API key> { private readonly <API key> <API key>; private readonly Dictionary<SiloAddress, Tuple<MembershipEntry, string>> siloTable; private TableVersion tableVersion; private long lastETagCounter; public <API key>(<API key> <API key>) { this.<API key> = <API key>; siloTable = new Dictionary<SiloAddress, Tuple<MembershipEntry, string>>(); lastETagCounter = 0; tableVersion = new TableVersion(0, NewETag()); } public MembershipTableData Read(SiloAddress key) { return siloTable.ContainsKey(key) ? new MembershipTableData((Tuple<MembershipEntry, string>)this.<API key>.DeepCopy(siloTable[key]), tableVersion) : new MembershipTableData(tableVersion); } public MembershipTableData ReadAll() { return new MembershipTableData(siloTable.Values.Select(tuple => new Tuple<MembershipEntry, string>((MembershipEntry)this.<API key>.DeepCopy(tuple.Item1), tuple.Item2)).ToList(), tableVersion); } public TableVersion ReadTableVersion() { return tableVersion; } public bool Insert(MembershipEntry entry, TableVersion version) { Tuple<MembershipEntry, string> data; siloTable.TryGetValue(entry.SiloAddress, out data); if (data != null) return false; if (!tableVersion.VersionEtag.Equals(version.VersionEtag)) return false; siloTable[entry.SiloAddress] = new Tuple<MembershipEntry, string>( entry, lastETagCounter++.ToString(CultureInfo.InvariantCulture)); tableVersion = new TableVersion(version.Version, NewETag()); return true; } public bool Update(MembershipEntry entry, string etag, TableVersion version) { Tuple<MembershipEntry, string> data; siloTable.TryGetValue(entry.SiloAddress, out data); if (data == null) return false; if (!data.Item2.Equals(etag) || !tableVersion.VersionEtag.Equals(version.VersionEtag)) return false; siloTable[entry.SiloAddress] = new Tuple<MembershipEntry, string>( entry, lastETagCounter++.ToString(CultureInfo.InvariantCulture)); tableVersion = new TableVersion(version.Version, NewETag()); return true; } public void UpdateIAmAlive(MembershipEntry entry) { Tuple<MembershipEntry, string> data; siloTable.TryGetValue(entry.SiloAddress, out data); if (data == null) return; data.Item1.IAmAliveTime = entry.IAmAliveTime; siloTable[entry.SiloAddress] = new Tuple<MembershipEntry, string>(data.Item1, NewETag()); } public override string ToString() { return String.Format("Table = {0}, ETagCounter={1}", ReadAll().ToString(), lastETagCounter); } private string NewETag() { return lastETagCounter++.ToString(CultureInfo.InvariantCulture); } } }
// moment.hpp #ifndef <API key> #define <API key> #include <boost/config/no_tr1/cmath.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/assert.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/accumulators/framework/accumulator_base.hpp> #include <boost/accumulators/framework/extractor.hpp> #include <boost/accumulators/numeric/functional.hpp> #include <boost/accumulators/framework/parameters/sample.hpp> #include <boost/accumulators/framework/depends_on.hpp> #include <boost/accumulators/statistics_fwd.hpp> #include <boost/accumulators/statistics/count.hpp> namespace boost { namespace numeric { INTERNAL ONLY template<typename T> T const &pow(T const &x, mpl::int_<1>) { return x; } INTERNAL ONLY template<typename T, int N> T pow(T const &x, mpl::int_<N>) { using namespace operators; T y = numeric::pow(x, mpl::int_<N/2>()); T z = y * y; return (N % 2) ? (z * x) : z; } }} namespace boost { namespace accumulators { namespace impl { // moment_impl template<typename N, typename Sample> struct moment_impl : accumulator_base // TODO: also depends_on sum of powers { <API key>(N::value, >, 0); // for boost::result_of typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type; template<typename Args> moment_impl(Args const &args) : sum(args[sample | Sample()]) { } template<typename Args> void operator ()(Args const &args) { this->sum += numeric::pow(args[sample], N()); } template<typename Args> result_type result(Args const &args) const { return numeric::fdiv(this->sum, count(args)); } // make this accumulator serializeable template<class Archive> void serialize(Archive & ar, const unsigned int file_version) { ar & sum; } private: Sample sum; }; } // namespace impl // tag::moment namespace tag { template<int N> struct moment : depends_on<count> { INTERNAL ONLY typedef accumulators::impl::moment_impl<mpl::int_<N>, mpl::_1> impl; }; } // extract::moment namespace extract { <API key>(tag, moment, (int)) } using extract::moment; // So that moment<N> can be automatically substituted with // weighted_moment<N> when the weight parameter is non-void template<int N> struct as_weighted_feature<tag::moment<N> > { typedef tag::weighted_moment<N> type; }; template<int N> struct feature_of<tag::weighted_moment<N> > : feature_of<tag::moment<N> > { }; }} // namespace boost::accumulators #endif
/* * W.J. van der Laan 2011-2012 */ #include <QApplication> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "paymentserver.h" #include "splashscreen.h" #include <QMessageBox> #if QT_VERSION < 0x050000 #include <QTextCodec> #endif #include <QLocale> #include <QTimer> #include <QTranslator> #include <QLibraryInfo> #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #if defined(<API key>) && !defined(<API key>) #define <API key> #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static SplashScreen *splashref; static bool <API key>(const std::string& message, const std::string& caption, unsigned int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(guiref, "message", modal ? GUIUtil::<API key>() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); return false; } } static bool ThreadSafeAskFee(int64 nFeeRequired) { if(!guiref) return false; if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::<API key>(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); qApp->processEvents(); } printf("init message: %s\n", message.c_str()); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void <API key>(std::exception *e) { <API key>(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Dogecoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType< bool* >(); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::<API key>(<API key>, &app)); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Dogecoin", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) QApplication::setOrganizationName("Dogecoin"); QApplication::<API key>("<API key>.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet QApplication::setApplicationName("Dogecoin-Qt-testnet"); else QApplication::setApplicationName("Dogecoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.<API key>.connect(<API key>); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } #ifdef Q_OS_MAC // on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange) if(GetBoolArg("-testnet")) { MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); } #endif SplashScreen splash(QPixmap(), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { #if MAC_OSX // QSplashScreen on Mac seems to always stay on top. Ugh. splash.setWindowFlags(Qt::FramelessWindowHint); #endif splash.show(); splash.<API key>(true); splashref = &splash; } app.processEvents(); app.<API key>(false); try { #ifndef Q_OS_MAC // Regenerate startup link, to fix links to old versions // OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs) if (GUIUtil::<API key>()) GUIUtil::<API key>(true); #endif boost::thread_group threadGroup; BitcoinGUI window; guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel *walletModel = 0; if(pwalletMain) walletModel = new WalletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); if(walletModel) { window.addWallet("~Default", walletModel); window.setCurrentWallet("~Default"); } // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.removeAllWallets(); guiref = 0; delete walletModel; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); return 1; } } catch (std::exception& e) { <API key>(&e); } catch (...) { <API key>(NULL); } return 0; } #endif // BITCOIN_QT_TEST
//DO NOT DELETE THIS, this is in use... angular.module('umbraco') .controller("Umbraco.PropertyEditors.<API key>", function($scope, dialogService, entityResource, macroService){ $scope.renderModel = []; $scope.allowOpenButton = true; $scope.allowRemoveButton = true; $scope.sortableOptions = {}; if($scope.model.value){ var macros = $scope.model.value.split('>'); angular.forEach(macros, function(syntax, key){ if(syntax && syntax.length > 10){ //re-add the char we split on syntax = syntax + ">"; var parsed = macroService.parseMacroSyntax(syntax); if(!parsed){ parsed = {}; } parsed.syntax = syntax; collectDetails(parsed); $scope.renderModel.push(parsed); setSortingState($scope.renderModel); } }); } function collectDetails(macro){ macro.details = ""; macro.icon = "icon-settings-alt"; if(macro.<API key>){ angular.forEach((macro.<API key>), function(value, key){ macro.details += key + ": " + value + " "; }); } } function openDialog(index){ var dialogData = { allowedMacros: $scope.model.config.allowed }; if(index !== null && $scope.renderModel[index]) { var macro = $scope.renderModel[index]; dialogData["macroData"] = macro; } $scope.macroPickerOverlay = {}; $scope.macroPickerOverlay.view = "macropicker"; $scope.macroPickerOverlay.dialogData = dialogData; $scope.macroPickerOverlay.show = true; $scope.macroPickerOverlay.submit = function(model) { var macroObject = macroService.collectValueData(model.selectedMacro, model.macroParams, dialogData.renderingEngine); collectDetails(macroObject); //update the raw syntax and the list... if(index !== null && $scope.renderModel[index]) { $scope.renderModel[index] = macroObject; } else { $scope.renderModel.push(macroObject); } setSortingState($scope.renderModel); $scope.macroPickerOverlay.show = false; $scope.macroPickerOverlay = null; }; $scope.macroPickerOverlay.close = function(oldModel) { $scope.macroPickerOverlay.show = false; $scope.macroPickerOverlay = null; }; } $scope.edit =function(index){ openDialog(index); }; $scope.add = function () { if ($scope.model.config.max && $scope.model.config.max > 0 && $scope.renderModel.length >= $scope.model.config.max) { //cannot add more than the max return; } openDialog(); }; $scope.remove =function(index){ $scope.renderModel.splice(index, 1); setSortingState($scope.renderModel); }; $scope.clear = function() { $scope.model.value = ""; $scope.renderModel = []; }; var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { var syntax = []; angular.forEach($scope.renderModel, function(value, key){ syntax.push(value.syntax); }); $scope.model.value = syntax.join(""); }); //when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { unsubscribe(); }); function trim(str, chr) { var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^'+chr+'+|'+chr+'+$', 'g'); return str.replace(rgxtrim, ''); } function setSortingState(items) { // disable sorting if the list only consist of one item if(items.length > 1) { $scope.sortableOptions.disabled = false; } else { $scope.sortableOptions.disabled = true; } } });
<a href='https://github.com/angular/angular.js/edit/v1.4.x/src/ngMessages/messages.js?message=docs(ngMessagesInclude)%3A%20describe%20your%20change...#L482' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit">&nbsp;</i>Improve this Doc</a> <a href='https://github.com/angular/angular.js/tree/v1.4.7/src/ngMessages/messages.js#L482' class='view-source pull-right btn btn-primary'> <i class="glyphicon glyphicon-zoom-in">&nbsp;</i>View Source </a> <header class="api-profile-header"> <h1 class="<API key>">ngMessagesInclude</h1> <ol class="<API key> naked-list step-list"> <li> - directive in module <a href="api/ngMessages">ngMessages</a> </li> </ol> </header> <div class="<API key>"> <p><code>ngMessagesInclude</code> is a directive with the purpose to import existing ngMessage template code from a remote template and place the downloaded template code into the exact spot that the ngMessagesInclude directive is placed within the ngMessages container. This allows for a series of pre-defined messages to be reused and also allows for the developer to determine what messages are overridden due to the placement of the ngMessagesInclude directive.</p> </div> <div> <h2>Directive Info</h2> <ul> <li>This directive creates new scope.</li> <li>This directive executes at priority level 0.</li> </ul> <h2 id="usage">Usage</h2> <div class="usage"> <pre><code class="lang-html">&lt;!-- using attribute directives --&gt; &lt;ANY ng-messages=&quot;expression&quot; role=&quot;alert&quot;&gt; &lt;ANY ng-messages-include=&quot;remoteTplString&quot;&gt;...&lt;/ANY&gt; &lt;/ANY&gt; &lt;!-- or by using element directives --&gt; &lt;ng-messages for=&quot;expression&quot; role=&quot;alert&quot;&gt; &lt;ng-messages-include src=&quot;expressionValue1&quot;&gt;...&lt;/ng-messages-include&gt; &lt;/ng-messages&gt; </code></pre> <p><a href="api/ngMessages">Click here</a> to learn more about <code>ngMessages</code> and <code>ngMessage</code>.</p> </div> <section class="api-section"> <h3>Arguments</h3> <table class="variables-matrix input-arguments"> <thead> <tr> <th>Param</th> <th>Type</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> ngMessagesInclude | src </td> <td> <a href="" class="label type-hint type-hint-string">string</a> </td> <td> <p>a string value corresponding to the remote template.</p> </td> </tr> </tbody> </table> </section> </div>
<?php class <API key> extends SiteOrigin_Widget { function __construct() { parent::__construct( 'sow-editor', __('SiteOrigin Editor', 'so-widgets-bundle'), array( 'description' => __('A rich-text, text editor.', 'so-widgets-bundle'), 'help' => 'https://siteorigin.com/widgets-bundle/editor-widget/' ), array(), false, plugin_dir_path(__FILE__) ); } function initialize_form(){ return array( 'title' => array( 'type' => 'text', 'label' => __('Title', 'so-widgets-bundle'), ), 'text' => array( 'type' => 'tinymce', 'rows' => 20 ), 'autop' => array( 'type' => 'checkbox', 'default' => true, 'label' => __('Automatically add paragraphs', 'so-widgets-bundle'), ), ); } function unwpautop($string) { $string = str_replace("<p>", "", $string); $string = str_replace(array("<br />", "<br>", "<br/>"), "\n", $string); $string = str_replace("</p>", "\n\n", $string); return $string; } public function <API key>( $instance, $args ) { $instance = wp_parse_args( $instance, array( 'text' => '' ) ); $instance['text'] = $this->unwpautop( $instance['text'] ); $instance['text'] = apply_filters( 'widget_text', $instance['text'] ); // Run some known stuff if( !empty($GLOBALS['wp_embed']) ) { $instance['text'] = $GLOBALS['wp_embed']->autoembed( $instance['text'] ); } if (function_exists('<API key>')) { $instance['text'] = <API key>( $instance['text'] ); } if( $instance['autop'] ) { $instance['text'] = wpautop( $instance['text'] ); } $instance['text'] = do_shortcode( shortcode_unautop( $instance['text'] ) ); return array( 'text' => $instance['text'], ); } function get_style_name($instance) { // We're not using a style return false; } } <API key>( 'sow-editor', __FILE__, '<API key>' );
/** * @file Token_Manager.h * * $Id: Token_Manager.h 80826 2008-03-04 14:51:23Z wotte $ * * @author Tim Harrison (harrison@cs.wustl.edu) */ #ifndef ACE_TOKEN_MANAGER_H #define ACE_TOKEN_MANAGER_H #include "ace/pre.h" #include "ace/config-all.h" #if !defined (<API key>) # pragma once #endif /* <API key> */ #include "ace/Local_Tokens.h" #if defined (<API key>) #include "ace/Null_Mutex.h" #include "ace/Map_Manager.h" <API key> class ACE_Local_Mutex; class ACE_Mutex_Token; /** * @class ACE_Token_Manager * * @brief Manages all tokens in a process space. * * Factory: Proxies use the token manager to obtain token * references. This allows multiple proxies to reference the same * logical token. * Deadlock detection: Tokens use the manager to check for * deadlock situations during acquires. */ class ACE_Export ACE_Token_Manager : public ACE_Cleanup { // To add a new type of token (e.g. semaphore), do the following // steps: 1. Create a new derivation of ACE_Token. This class // defines the semantics of the new Token. 2. Create a // derivation of ACE_Token_Manager. You will only need to // redefine make_mutex. public: ACE_Token_Manager (void); virtual ~ACE_Token_Manager (void); Get the pointer to token manager singleton. static ACE_Token_Manager *instance (void); Set the pointer to token manager singleton. void instance (ACE_Token_Manager *); /** * The Token manager uses ACE_Token_Proxy::token_id_ to look for * an existing token. If none is found, the Token Manager calls * ACE_Token_Proxy::create_token to create a new one. When * finished, sets ACE_Token_Proxy::token_. @a token_name uniquely * id's the token name. */ void get_token (ACE_Token_Proxy *, const ACE_TCHAR *token_name); /** * Check whether acquire will cause deadlock or not. * returns 1 if the acquire will _not_ cause deadlock. * returns 0 if the acquire _will_ cause deadlock. * This method ignores recursive acquisition. That is, it will not * report deadlock if the client holding the token requests the * token again. Thus, it assumes recursive mutexes. */ int check_deadlock (ACE_Token_Proxy *proxy); int check_deadlock (ACE_Tokens *token, ACE_Token_Proxy *proxy); Notify the token manager that a token has been released. If as a result, there is no owner of the token, the token is deleted. void release_token (ACE_Tokens *&token); /** * This is to allow Tokens to perform atomic transactions. The * typical usage is to acquire this mutex, check for a safe_acquire, * perform some queueing (if need be) and then release the lock. * This is necessary since safe_acquire is implemented in terms of * the Token queues. */ ACE_TOKEN_CONST::MUTEX &mutex (void); Dump the state of the class. void dump (void) const; Turn debug mode on/off. void debug (bool d); private: Whether to print debug messages or not. bool debug_; pointer to singleton token manager. static ACE_Token_Manager *token_manager_; Return the token that the given client_id is waiting for, if any ACE_Tokens *token_waiting_for (const ACE_TCHAR *client_id); ACE_Mutex_Token used to lock internal data structures. ACE_TOKEN_CONST::MUTEX lock_; This may be changed to a template type. typedef ACE_Token_Name TOKEN_NAME; COLLECTION maintains a mapping from token names to ACE_Tokens* typedef ACE_Map_Manager<TOKEN_NAME, ACE_Tokens *, ACE_Null_Mutex> COLLECTION; Allows iterations through collection_ /** * @deprecated Deprecated typedef. Use COLLECTION::ITERATOR trait * instead. */ typedef COLLECTION::ITERATOR COLLECTION_ITERATOR; Allows iterations through collection_ /** * @deprecated Deprecated typedef. Use COLLECTION::ENTRY trait * instead. */ typedef COLLECTION::ENTRY COLLECTION_ENTRY; COLLECTION maintains a mapping from token names to ACE_Tokens*. COLLECTION collection_; }; <API key> #if defined (__ACE_INLINE__) #include "ace/Token_Manager.inl" #endif /* __ACE_INLINE__ */ #endif /* <API key> */ #include "ace/post.h" #endif /* ACE_TOKEN_MANAGER_H */
// GC graphics pipeline // 3d commands are issued through the fifo. The GPU draws to the 2MB EFB. // The efb can be copied back into ram in two forms: as textures or as XFB. // The XFB is the region in RAM that the VI chip scans out to the television. // So, after all rendering to EFB is done, the image is copied into one of two XFBs in RAM. // Next frame, that one is scanned out and the other one gets the copy. = double buffering. #include <cinttypes> #include <cmath> #include <string> #include "Common/Atomic.h" #include "Common/Event.h" #include "Common/Profiler.h" #include "Common/StringUtil.h" #include "Common/Timer.h" #include "Core/ConfigManager.h" #include "Core/Core.h" #include "Core/Host.h" #include "Core/Movie.h" #include "Core/FifoPlayer/FifoRecorder.h" #include "Core/HW/VideoInterface.h" #include "VideoCommon/AVIDump.h" #include "VideoCommon/BPMemory.h" #include "VideoCommon/CommandProcessor.h" #include "VideoCommon/CPMemory.h" #include "VideoCommon/Debugger.h" #include "VideoCommon/Fifo.h" #include "VideoCommon/FPSCounter.h" #include "VideoCommon/<API key>.h" #include "VideoCommon/MainBase.h" #include "VideoCommon/OpcodeDecoding.h" #include "VideoCommon/RenderBase.h" #include "VideoCommon/Statistics.h" #include "VideoCommon/TextureCacheBase.h" #include "VideoCommon/VideoConfig.h" #include "VideoCommon/XFMemory.h" // TODO: Move these out of here. int frameCount; int OSDChoice; static int OSDTime; Renderer *g_renderer = nullptr; std::mutex Renderer::<API key>; std::string Renderer::s_sScreenshotName; Common::Event Renderer::<API key>; volatile bool Renderer::s_bScreenshot; // The framebuffer size int Renderer::s_target_width; int Renderer::s_target_height; // TODO: Add functionality to reinit all the render targets when the window is resized. int Renderer::s_backbuffer_width; int Renderer::s_backbuffer_height; <API key>* Renderer::m_post_processor; TargetRectangle Renderer::target_rc; int Renderer::s_last_efb_scale; bool Renderer::XFBWrited; PEControl::PixelFormat Renderer::prev_efb_format = PEControl::INVALID_FMT; unsigned int Renderer::<API key> = 1; unsigned int Renderer::<API key> = 1; unsigned int Renderer::<API key> = 1; unsigned int Renderer::<API key> = 1; Renderer::Renderer() : frame_data() , bLastFrameDumped(false) { UpdateActiveConfig(); TextureCache::OnConfigChanged(g_ActiveConfig); #if defined _WIN32 || defined HAVE_LIBAV bAVIDumping = false; #endif OSDChoice = 0; OSDTime = 0; } Renderer::~Renderer() { // invalidate previous efb format prev_efb_format = PEControl::INVALID_FMT; <API key> = <API key> = <API key> = <API key> = 1; #if defined _WIN32 || defined HAVE_LIBAV if (SConfig::GetInstance().m_DumpFrames && bLastFrameDumped && bAVIDumping) AVIDump::Stop(); #else if (pFrameDump.IsOpen()) pFrameDump.Close(); #endif } void Renderer::RenderToXFB(u32 xfbAddr, const EFBRectangle& sourceRc, u32 fbStride, u32 fbHeight, float Gamma) { CheckFifoRecording(); if (!fbStride || !fbHeight) return; XFBWrited = true; if (g_ActiveConfig.bUseXFB) { <API key>::CopyToXFB(xfbAddr, fbStride, fbHeight, sourceRc, Gamma); } else { // below div two to convert from bytes to pixels - it expects width, not stride Swap(xfbAddr, fbStride/2, fbStride/2, fbHeight, sourceRc, Gamma); } } int Renderer::EFBToScaledX(int x) { switch (g_ActiveConfig.iEFBScale) { case SCALE_AUTO: // fractional return <API key>::<API key>(x); default: return x * (int)<API key> / (int)<API key>; }; } int Renderer::EFBToScaledY(int y) { switch (g_ActiveConfig.iEFBScale) { case SCALE_AUTO: // fractional return <API key>::<API key>(y); default: return y * (int)<API key> / (int)<API key>; }; } void Renderer::<API key>(int x, int y, int* scaledX, int* scaledY) { if (g_ActiveConfig.iEFBScale == SCALE_AUTO || g_ActiveConfig.iEFBScale == SCALE_AUTO_INTEGRAL) { *scaledX = x; *scaledY = y; } else { *scaledX = x * (int)<API key> / (int)<API key>; *scaledY = y * (int)<API key> / (int)<API key>; } } // return true if target size changed bool Renderer::CalculateTargetSize(unsigned int framebuffer_width, unsigned int framebuffer_height) { int newEFBWidth, newEFBHeight; newEFBWidth = newEFBHeight = 0; // TODO: Ugly. Clean up switch (s_last_efb_scale) { case SCALE_AUTO: case SCALE_AUTO_INTEGRAL: newEFBWidth = <API key>::<API key>(EFB_WIDTH); newEFBHeight = <API key>::<API key>(EFB_HEIGHT); if (s_last_efb_scale == SCALE_AUTO_INTEGRAL) { newEFBWidth = ((newEFBWidth-1) / EFB_WIDTH + 1) * EFB_WIDTH; newEFBHeight = ((newEFBHeight-1) / EFB_HEIGHT + 1) * EFB_HEIGHT; } <API key> = newEFBWidth; <API key> = EFB_WIDTH; <API key> = newEFBHeight; <API key> = EFB_HEIGHT; break; case SCALE_1X: <API key> = <API key> = 1; <API key> = <API key> = 1; break; case SCALE_1_5X: <API key> = <API key> = 3; <API key> = <API key> = 2; break; case SCALE_2X: <API key> = <API key> = 2; <API key> = <API key> = 1; break; case SCALE_2_5X: <API key> = <API key> = 5; <API key> = <API key> = 2; break; default: <API key> = <API key> = s_last_efb_scale - 3; <API key> = <API key> = 1; int maxSize; maxSize = GetMaxTextureSize(); if ((unsigned)maxSize < EFB_WIDTH * <API key> / <API key>) { <API key> = <API key> = (maxSize / EFB_WIDTH); <API key> = <API key> = 1; } break; } if (s_last_efb_scale > SCALE_AUTO_INTEGRAL) <API key>(EFB_WIDTH, EFB_HEIGHT, &newEFBWidth, &newEFBHeight); if (newEFBWidth != s_target_width || newEFBHeight != s_target_height) { s_target_width = newEFBWidth; s_target_height = newEFBHeight; return true; } return false; } void Renderer::<API key>(const TargetRectangle& rc, TargetRectangle& leftRc, TargetRectangle& rightRc) { // Resize target to half its original size TargetRectangle drawRc = rc; if (g_ActiveConfig.iStereoMode == STEREO_TAB) { // The height may be negative due to flipped rectangles int height = rc.bottom - rc.top; drawRc.top += height / 4; drawRc.bottom -= height / 4; } else { int width = rc.right - rc.left; drawRc.left += width / 4; drawRc.right -= width / 4; } // Create two target rectangle offset to the sides of the backbuffer leftRc = drawRc, rightRc = drawRc; if (g_ActiveConfig.iStereoMode == STEREO_TAB) { leftRc.top -= s_backbuffer_height / 4; leftRc.bottom -= s_backbuffer_height / 4; rightRc.top += s_backbuffer_height / 4; rightRc.bottom += s_backbuffer_height / 4; } else { leftRc.left -= s_backbuffer_width / 4; leftRc.right -= s_backbuffer_width / 4; rightRc.left += s_backbuffer_width / 4; rightRc.right += s_backbuffer_width / 4; } } void Renderer::SetScreenshot(const std::string& filename) { std::lock_guard<std::mutex> lk(<API key>); s_sScreenshotName = filename; s_bScreenshot = true; } // Create On-Screen-Messages void Renderer::DrawDebugText() { std::string final_yellow, final_cyan; if (g_ActiveConfig.bShowFPS || SConfig::GetInstance().m_ShowFrameCount) { if (g_ActiveConfig.bShowFPS) final_cyan += StringFromFormat("FPS: %d", g_renderer->m_fps_counter.m_fps); if (g_ActiveConfig.bShowFPS && SConfig::GetInstance().m_ShowFrameCount) final_cyan += " - "; if (SConfig::GetInstance().m_ShowFrameCount) { final_cyan += StringFromFormat("Frame: %llu", (unsigned long long) Movie::g_currentFrame); if (Movie::IsPlayingInput()) final_cyan += StringFromFormat(" / %llu", (unsigned long long) Movie::g_totalFrames); } final_cyan += "\n"; final_yellow += "\n"; } if (SConfig::GetInstance().m_ShowLag) { final_cyan += StringFromFormat("Lag: %" PRIu64 "\n", Movie::g_currentLagCount); final_yellow += "\n"; } if (SConfig::GetInstance().m_ShowInputDisplay) { final_cyan += Movie::GetInputDisplay(); final_yellow += "\n"; } // OSD Menu messages if (OSDChoice > 0) { OSDTime = Common::Timer::GetTimeMs() + 3000; OSDChoice = -OSDChoice; } if ((u32)OSDTime > Common::Timer::GetTimeMs()) { std::string res_text; switch (g_ActiveConfig.iEFBScale) { case SCALE_AUTO: res_text = "Auto (fractional)"; break; case SCALE_AUTO_INTEGRAL: res_text = "Auto (integral)"; break; case SCALE_1X: res_text = "Native"; break; case SCALE_1_5X: res_text = "1.5x"; break; case SCALE_2X: res_text = "2x"; break; case SCALE_2_5X: res_text = "2.5x"; break; default: res_text = StringFromFormat("%dx", g_ActiveConfig.iEFBScale - 3); break; } const char* ar_text = ""; switch (g_ActiveConfig.iAspectRatio) { case ASPECT_AUTO: ar_text = "Auto"; break; case ASPECT_STRETCH: ar_text = "Stretch"; break; case ASPECT_ANALOG: ar_text = "Force 4:3"; break; case ASPECT_ANALOG_WIDE: ar_text = "Force 16:9"; } const char* const efbcopy_text = g_ActiveConfig.bSkipEFBCopyToRam ? "to Texture" : "to RAM"; // The rows const std::string lines[] = { std::string("Internal Resolution: ") + res_text, std::string("Aspect Ratio: ") + ar_text + (g_ActiveConfig.bCrop ? " (crop)" : ""), std::string("Copy EFB: ") + efbcopy_text, std::string("Fog: ") + (g_ActiveConfig.bDisableFog ? "Disabled" : "Enabled"), }; enum { lines_count = sizeof(lines) / sizeof(*lines) }; // The latest changed setting in yellow for (int i = 0; i != lines_count; ++i) { if (OSDChoice == -i - 1) final_yellow += lines[i]; final_yellow += '\n'; } // The other settings in cyan for (int i = 0; i != lines_count; ++i) { if (OSDChoice != -i - 1) final_cyan += lines[i]; final_cyan += '\n'; } } final_cyan += Common::Profiler::ToString(); if (g_ActiveConfig.bOverlayStats) final_cyan += Statistics::ToString(); if (g_ActiveConfig.bOverlayProjStats) final_cyan += Statistics::ToStringProj(); //and then the text g_renderer->RenderText(final_cyan, 20, 20, 0xFF00FFFF); g_renderer->RenderText(final_yellow, 20, 20, 0xFFFFFF00); } void Renderer::UpdateDrawRectangle(int backbuffer_width, int backbuffer_height) { float FloatGLWidth = (float)backbuffer_width; float FloatGLHeight = (float)backbuffer_height; float FloatXOffset = 0; float FloatYOffset = 0; // The rendering window size const float WinWidth = FloatGLWidth; const float WinHeight = FloatGLHeight; // Update aspect ratio hack values // Won't take effect until next frame // Don't know if there is a better place for this code so there isn't a 1 frame delay if (g_ActiveConfig.bWidescreenHack) { float source_aspect = VideoInterface::GetAspectRatio(g_aspect_wide); float target_aspect; switch (g_ActiveConfig.iAspectRatio) { case ASPECT_STRETCH: target_aspect = WinWidth / WinHeight; break; case ASPECT_ANALOG: target_aspect = VideoInterface::GetAspectRatio(false); break; case ASPECT_ANALOG_WIDE: target_aspect = VideoInterface::GetAspectRatio(true); break; default: // ASPECT_AUTO target_aspect = source_aspect; break; } float adjust = source_aspect / target_aspect; if (adjust > 1) { // Vert+ g_Config.fAspectRatioHackW = 1; g_Config.fAspectRatioHackH = 1 / adjust; } else { // Hor+ g_Config.fAspectRatioHackW = adjust; g_Config.fAspectRatioHackH = 1; } } else { // Hack is disabled g_Config.fAspectRatioHackW = 1; g_Config.fAspectRatioHackH = 1; } // Check for force-settings and override. // The rendering window aspect ratio as a proportion of the 4:3 or 16:9 ratio float Ratio; switch (g_ActiveConfig.iAspectRatio) { case ASPECT_ANALOG_WIDE: Ratio = (WinWidth / WinHeight) / VideoInterface::GetAspectRatio(true); break; case ASPECT_ANALOG: Ratio = (WinWidth / WinHeight) / VideoInterface::GetAspectRatio(false); break; default: Ratio = (WinWidth / WinHeight) / VideoInterface::GetAspectRatio(g_aspect_wide); break; } if (g_ActiveConfig.iAspectRatio != ASPECT_STRETCH) { if (Ratio > 1.0f) { // Scale down and center in the X direction. FloatGLWidth /= Ratio; FloatXOffset = (WinWidth - FloatGLWidth) / 2.0f; } // The window is too high, we have to limit the height else { // Scale down and center in the Y direction. FloatGLHeight *= Ratio; FloatYOffset = FloatYOffset + (WinHeight - FloatGLHeight) / 2.0f; } } // Crop the picture from Analog to 4:3 or from Analog (Wide) to 16:9. // Output: FloatGLWidth, FloatGLHeight, FloatXOffset, FloatYOffset if (g_ActiveConfig.iAspectRatio != ASPECT_STRETCH && g_ActiveConfig.bCrop) { switch (g_ActiveConfig.iAspectRatio) { case ASPECT_ANALOG_WIDE: Ratio = (16.0f / 9.0f) / VideoInterface::GetAspectRatio(true); break; case ASPECT_ANALOG: Ratio = (4.0f / 3.0f) / VideoInterface::GetAspectRatio(false); break; default: Ratio = (!g_aspect_wide ? (4.0f / 3.0f) : (16.0f / 9.0f)) / VideoInterface::GetAspectRatio(g_aspect_wide); break; } if (Ratio <= 1.0f) { Ratio = 1.0f / Ratio; } // The width and height we will add (calculate this before FloatGLWidth and FloatGLHeight is adjusted) float IncreasedWidth = (Ratio - 1.0f) * FloatGLWidth; float IncreasedHeight = (Ratio - 1.0f) * FloatGLHeight; // The new width and height FloatGLWidth = FloatGLWidth * Ratio; FloatGLHeight = FloatGLHeight * Ratio; // Adjust the X and Y offset FloatXOffset = FloatXOffset - (IncreasedWidth * 0.5f); FloatYOffset = FloatYOffset - (IncreasedHeight * 0.5f); } int XOffset = (int)(FloatXOffset + 0.5f); int YOffset = (int)(FloatYOffset + 0.5f); int iWhidth = (int)ceil(FloatGLWidth); int iHeight = (int)ceil(FloatGLHeight); iWhidth -= iWhidth % 4; // ensure divisibility by 4 to make it compatible with all the video encoders iHeight -= iHeight % 4; target_rc.left = XOffset; target_rc.top = YOffset; target_rc.right = XOffset + iWhidth; target_rc.bottom = YOffset + iHeight; } void Renderer::SetWindowSize(int width, int height) { if (width < 1) width = 1; if (height < 1) height = 1; // Scale the window size by the EFB scale. <API key>(width, height, &width, &height); <API key>(width, height); } void Renderer::CheckFifoRecording() { bool wasRecording = g_bRecordFifoData; g_bRecordFifoData = FifoRecorder::GetInstance().IsRecording(); if (g_bRecordFifoData) { if (!wasRecording) { RecordVideoMemory(); } FifoRecorder::GetInstance().EndFrame(CommandProcessor::fifo.CPBase, CommandProcessor::fifo.CPEnd); } } void Renderer::RecordVideoMemory() { u32 *bpmem_ptr = (u32*)&bpmem; u32 cpmem[256]; // The FIFO recording format splits XF memory into xfmem and xfregs; follow // that split here. u32 *xfmem_ptr = (u32*)&xfmem; u32 *xfregs_ptr = (u32*)&xfmem + FifoDataFile::XF_MEM_SIZE; u32 xfregs_size = sizeof(XFMemory) / 4 - FifoDataFile::XF_MEM_SIZE; memset(cpmem, 0, 256 * 4); FillCPMemoryArray(cpmem); FifoRecorder::GetInstance().SetVideoMemory(bpmem_ptr, cpmem, xfmem_ptr, xfregs_ptr, xfregs_size); } void Renderer::Swap(u32 xfbAddr, u32 fbWidth, u32 fbStride, u32 fbHeight, const EFBRectangle& rc, float Gamma) { // TODO: merge more generic parts into VideoCommon g_renderer->SwapImpl(xfbAddr, fbWidth, fbStride, fbHeight, rc, Gamma); if (XFBWrited) g_renderer->m_fps_counter.Update(); frameCount++; <API key>(NEXT_FRAME, true); // Begin new frame // Set default viewport and scissor, for the clear to work correctly // New frame stats.ResetFrame(); Core::<API key>(XFBWrited || (g_ActiveConfig.bUseXFB && g_ActiveConfig.bUseRealXFB)); XFBWrited = false; } void Renderer::PokeEFB(EFBAccessType type, const std::vector<EfbPokeData>& data) { for (EfbPokeData poke : data) { AccessEFB(type, poke.x, poke.y, poke.data); } }
extern int shlib_1_func (void); int main () { /* We need a reference to shlib_1_func to make sure its shlib is not discarded from the link. This happens on windows. */ int x = shlib_1_func (); return 0; }
<?php wp_enqueue_script( 'pods' ); wp_enqueue_style( 'pods-form' ); if ( empty( $fields ) || !is_array( $fields ) ) $fields = $obj->pod->fields; if ( !isset( $duplicate ) ) $duplicate = false; else $duplicate = (boolean) $duplicate; $groups = PodsInit::$meta->groups_get( $pod->pod_data[ 'type' ], $pod->pod_data[ 'name' ], $fields ); $group_fields = array(); $submittable_fields = array(); foreach ( $groups as $g => $group ) { // unset fields foreach ( $group[ 'fields' ] as $k => $field ) { if ( in_array( $field[ 'name' ], array( 'created', 'modified' ) ) ) { unset( $group[ 'fields' ][ $k ] ); continue; } elseif ( false === PodsForm::permission( $field[ 'type' ], $field[ 'name' ], $field[ 'options' ], $group[ 'fields' ], $pod, $pod->id() ) ) { if ( pods_var( 'hidden', $field[ 'options' ], false ) ) { $group[ 'fields' ][ $k ][ 'type' ] = 'hidden'; } elseif ( pods_var( 'read_only', $field[ 'options' ], false ) ) { $group[ 'fields' ][ $k ][ 'readonly' ] = true; } else { unset( $group[ 'fields' ][ $k ] ); continue; } } elseif ( !<API key>( $field[ 'options' ] ) ) { if ( pods_var( 'hidden', $field[ 'options' ], false ) ) { $group[ 'fields' ][ $k ][ 'type' ] = 'hidden'; } elseif ( pods_var( 'read_only', $field[ 'options' ], false ) ) { $group[ 'fields' ][ $k ][ 'readonly' ] = true; } } if ( !pods_var( 'readonly', $field, false ) ) { $submittable_fields[ $field[ 'name' ]] = $group[ 'fields' ][ $k ]; } $group_fields[ $field[ 'name' ] ] = $group[ 'fields' ][ $k ]; } $groups[ $g ] = $group; } if ( !isset( $thank_you_alt ) ) $thank_you_alt = $thank_you; $uri_hash = wp_create_nonce( 'pods_uri_' . $_SERVER[ 'REQUEST_URI' ] ); $field_hash = wp_create_nonce( 'pods_fields_' . implode( ',', array_keys( $submittable_fields ) ) ); $uid = @session_id(); if ( is_user_logged_in() ) $uid = 'user_' . get_current_user_id(); $nonce = wp_create_nonce( 'pods_form_' . $pod->pod . '_' . $uid . '_' . ( $duplicate ? 0 : $pod->id() ) . '_' . $uri_hash . '_' . $field_hash ); if ( isset( $_POST[ '_pods_nonce' ] ) ) { $action = __( 'saved', 'pods' ); if ( 'create' == pods_var_raw( 'do', 'post', 'save' ) ) $action = __( 'created', 'pods' ); elseif ( 'duplicate' == pods_var_raw( 'do', 'get', 'save' ) ) $action = __( 'duplicated', 'pods' ); try { $params = pods_unslash( (array) $_POST ); $id = $pod->api->process_form( $params, $pod, $submittable_fields, $thank_you ); $message = sprintf( __( '<strong>Success!</strong> %s %s successfully.', 'pods' ), $obj->item, $action ); if ( 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) ) $message .= ' <a target="_blank" href="' . $pod->field( 'detail_url' ) . '">' . sprintf( __( 'View %s', 'pods' ), $obj->item ) . '</a>'; $error = sprintf( __( '<strong>Error:</strong> %s %s successfully.', 'pods' ), $obj->item, $action ); if ( 0 < $id ) echo $obj->message( $message ); else echo $obj->error( $error ); } catch ( Exception $e ) { echo $obj->error( $e->getMessage() ); } } elseif ( isset( $_GET[ 'do' ] ) ) { $action = __( 'saved', 'pods' ); if ( 'create' == pods_var_raw( 'do', 'get', 'save' ) ) $action = __( 'created', 'pods' ); elseif ( 'duplicate' == pods_var_raw( 'do', 'get', 'save' ) ) $action = __( 'duplicated', 'pods' ); $message = sprintf( __( '<strong>Success!</strong> %s %s successfully.', 'pods' ), $obj->item, $action ); if ( 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) ) $message .= ' <a target="_blank" href="' . $pod->field( 'detail_url' ) . '">' . sprintf( __( 'View %s', 'pods' ), $obj->item ) . '</a>'; $error = sprintf( __( '<strong>Error:</strong> %s not %s.', 'pods' ), $obj->item, $action ); if ( 0 < $pod->id() ) echo $obj->message( $message ); else echo $obj->error( $error ); } if ( !isset( $label ) ) $label = __( 'Save', 'pods' ); $do = 'create'; if ( 0 < $pod->id() ) { if ( $duplicate ) $do = 'duplicate'; else $do = 'save'; } ?> <form action="" method="post" class="pods-submittable pods-form pods-form-pod-<?php echo $pod->pod; ?> <API key>"> <div class="<API key>"> <?php echo PodsForm::field( 'action', 'pods_admin', 'hidden' ); echo PodsForm::field( 'method', 'process_form', 'hidden' ); echo PodsForm::field( 'do', $do, 'hidden' ); echo PodsForm::field( '_pods_nonce', $nonce, 'hidden' ); echo PodsForm::field( '_pods_pod', $pod->pod, 'hidden' ); echo PodsForm::field( '_pods_id', ( $duplicate ? 0 : $pod->id() ), 'hidden' ); echo PodsForm::field( '_pods_uri', $uri_hash, 'hidden' ); echo PodsForm::field( '_pods_form', implode( ',', array_keys( $submittable_fields ) ), 'hidden' ); echo PodsForm::field( '_pods_location', $_SERVER[ 'REQUEST_URI' ], 'hidden' ); foreach ( $group_fields as $field ) { if ( 'hidden' != $field[ 'type' ] ) continue; echo PodsForm::field( 'pods_field_' . $field[ 'name' ], $pod->field( array( 'name' => $field[ 'name' ], 'in_form' => true ) ), 'hidden' ); } /** * Action that runs before the meta boxes for an Advanced Content Type * * Occurs at the top of #poststuff * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.5 */ do_action( 'pods_meta_box_pre', $pod, $obj ); ?> <div id="poststuff" class="metabox-holder has-right-sidebar"> <!-- class "has-right-sidebar" preps for a sidebar... always present? --> <div id="side-info-column" class="inner-sidebar"> <?php /** * Action that runs before the sidebar of the editor for an Advanced Content Type * * Occurs at the top of #side-info-column * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.4.1 */ do_action( '<API key>', $pod, $obj ); ?> <div id="side-sortables" class="meta-box-sortables ui-sortable"> <!-- BEGIN PUBLISH DIV --> <div id="submitdiv" class="postbox"> <div class="handlediv" title="Click to toggle"><br /></div> <h3 class="hndle"><span><?php _e( 'Manage', 'pods' ); ?></span></h3> <div class="inside"> <div class="submitbox" id="submitpost"> <?php if ( 0 < $pod->id() && ( isset( $pod->pod_data[ 'fields' ][ 'created' ] ) || isset( $pod->pod_data[ 'fields' ][ 'modified' ] ) || 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) ) ) { ?> <div id="minor-publishing"> <?php if ( 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) ) { ?> <div id="<API key>"> <div id="preview-action"> <a class="button" href="<?php echo $pod->field( 'detail_url' ); ?>" target="_blank"><?php echo sprintf( __( 'View %s', 'pods' ), $obj->item ); ?></a> </div> <div class="clear"></div> </div> <?php } if ( isset( $pod->pod_data[ 'fields' ][ 'created' ] ) || isset( $pod->pod_data[ 'fields' ][ 'modified' ] ) ) { ?> <div id="<API key>"> <?php $datef = __( 'M j, Y @ G:i' ); if ( isset( $pod->pod_data[ 'fields' ][ 'created' ] ) ) { $date = date_i18n( $datef, strtotime( $pod->field( 'created' ) ) ); ?> <div class="misc-pub-section curtime"> <span id="timestamp"><?php _e( 'Created on', 'pods' ); ?>: <b><?php echo $date; ?></b></span> </div> <?php } if ( isset( $pod->pod_data[ 'fields' ][ 'modified' ] ) && $pod->display( 'created' ) != $pod->display( 'modified' ) ) { $date = date_i18n( $datef, strtotime( $pod->field( 'modified' ) ) ); ?> <div class="misc-pub-section curtime"> <span id="timestamp"><?php _e( 'Last Modified', 'pods' ); ?>: <b><?php echo $date; ?></b></span> </div> <?php } ?> <?php /** * Action that runs after the misc publish actions area for an Advanced Content Type * * Occurs at the end of #<API key> * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.5 */ do_action( '<API key>', $pod, $obj ); ?> </div> <?php } ?> </div> <!-- /#minor-publishing --> <?php } ?> <div id="<API key>"> <?php if ( pods_is_admin( array( 'pods', 'pods_delete_' . $pod->pod ) ) && null !== $pod->id() && !$duplicate && !in_array( 'delete', (array) $obj->actions_disabled ) && !in_array( 'delete', (array) $obj->actions_hidden ) ) { ?> <div id="delete-action"> <a class="submitdelete deletion" href="<?php echo pods_var_update( array( 'action' => 'delete' ) ) ?>" onclick="return confirm('You are about to permanently delete this item\n Choose \'Cancel\' to stop, \'OK\' to delete.');"><?php _e( 'Delete', 'pods' ); ?></a> </div> <!-- /#delete-action --> <?php } ?> <div id="publishing-action"> <img class="waiting" src="<?php echo esc_url( admin_url( 'images/wpspin_light.gif' ) ); ?>" alt="" /> <input type="submit" name="publish" id="publish" class="button button-primary button-large" value="<?php echo esc_attr( $label ); ?>" accesskey="p" /> <?php /** * Action that runs after the publish button for an Advanced Content Type * * Occurs at the end of #publishing-action * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.5 */ do_action( '<API key>', $pod, $obj ); ?> </div> <!-- /#publishing-action --> <div class="clear"></div> </div> <?php /** * Action that runs after the publish area for an Advanced Content Type * * Occurs at the end of #submitpost * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.5 */ do_action( '<API key>', $pod, $obj ); ?> <!-- /#<API key> --> </div> <!-- /#submitpost --> </div> <!-- /.inside --> </div> <!-- /#submitdiv --><!-- END PUBLISH DIV --><!-- TODO: minor column fields --> <?php if ( pods_var_raw( 'action' ) == 'edit' && !$duplicate && !in_array( 'navigate', (array) $obj->actions_disabled ) && !in_array( 'navigate', (array) $obj->actions_hidden ) ) { if ( !isset( $singular_label ) ) $singular_label = ucwords( str_replace( '_', ' ', $pod->pod_data[ 'name' ] ) ); $singular_label = pods_var_raw( 'label', $pod->pod_data[ 'options' ], $singular_label, null, true ); $singular_label = pods_var_raw( 'label_singular', $pod->pod_data[ 'options' ], $singular_label, null, true ); $pod->params = $obj->get_params( null, 'manage' ); $prev_next = apply_filters( '<API key>', array(), $pod, $obj ); if ( empty( $prev_next ) ) { $prev_next = array( 'prev' => $pod->prev_id(), 'next' => $pod->next_id() ); } $prev = $prev_next[ 'prev' ]; $next = $prev_next[ 'next' ]; if ( 0 < $prev || 0 < $next ) { ?> <div id="navigatediv" class="postbox"> <?php /** * Action that runs before the post navagiation in the editor for an Advanced Content Type * * Occurs at the top of #navigatediv * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.4.1 */ do_action( '<API key>', $pod, $obj ); ?> <div class="handlediv" title="Click to toggle"><br /></div> <h3 class="hndle"><span><?php _e( 'Navigate', 'pods' ); ?></span></h3> <div class="inside"> <div class="pods-admin" id="navigatebox"> <div id="navigation-actions"> <?php if ( 0 < $prev ) { ?> <a class="previous-item" href="<?php echo pods_var_update( array( 'id' => $prev ), null, 'do' ); ?>"> <span>&laquo;</span> <?php echo sprintf( __( 'Previous %s', 'pods' ), $singular_label ); ?> </a> <?php } if ( 0 < $next ) { ?> <a class="next-item" href="<?php echo pods_var_update( array( 'id' => $next ), null, 'do' ); ?>"> <?php echo sprintf( __( 'Next %s', 'pods' ), $singular_label ); ?> <span>&raquo;</span> </a> <?php } ?> <div class="clear"></div> </div> <!-- /#navigation-actions --> </div> <!-- /#navigatebox --> </div> <!-- /.inside --> <?php /** * Action that runs after the post navagiation in the editor for an Advanced Content Type * * Occurs at the bottom of #navigatediv * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.4.1 */ do_action( '<API key>', $pod, $obj ); ?> </div> <!-- /#navigatediv --> <?php } } ?> </div> <!-- /#side-sortables --> <?php /** * Action that runs after the sidebar of the editor for an Advanced Content Type * * Occurs at the bottom of #side-info-column * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.4.1 */ do_action( '<API key>', $pod, $obj ); ?> </div> <!-- /#side-info-column --> <div id="post-body"> <div id="post-body-content"> <?php $more = false; if ( $pod->pod_data[ 'field_index' ] != $pod->pod_data[ 'field_id' ] ) { foreach ( $group_fields as $field ) { if ( $pod->pod_data[ 'field_index' ] != $field[ 'name' ] || 'text' != $field[ 'type' ] ) continue; $more = true; $extra = ''; $max_length = (int) pods_var( 'maxlength', $field[ 'options' ], pods_var( $field[ 'type' ] . '_max_length', $field[ 'options' ], 0 ), null, true ); if ( 0 < $max_length ) $extra .= ' maxlength="' . $max_length . '"'; /** * Filter that lets you make the title field readonly * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.5 */ if ( pods_v( 'readonly', $field[ 'options' ], pods_v( 'readonly', $field, false ) ) || apply_filters( '<API key>', false, $pod, $obj ) ) { ?> <div id="titlediv"> <div id="titlewrap"> <h3><?php echo esc_html( $pod->index() ); ?></h3> <input type="hidden" name="pods_field_<?php echo $pod->pod_data[ 'field_index' ]; ?>" data-name-clean="pods-field-<?php echo $pod->pod_data[ 'field_index' ]; ?>" id="title" size="30" tabindex="1" value="<?php echo esc_attr( htmlspecialchars( $pod->index() ) ); ?>" class="<API key>-<?php echo $pod->pod_data[ 'field_index' ]; ?>" autocomplete="off"<?php echo $extra; ?> /> </div> <!-- /#titlewrap --> </div> <!-- /#titlediv --> <?php } else { ?> <div id="titlediv"> <?php /** * Action that runs before the title field of the editor for an Advanced Content Type * * Occurs at the top of #titlediv * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.4.1 */ do_action( '<API key>', $pod, $obj ); ?> <div id="titlewrap"> <label class="screen-reader-text" id="title-prompt-text" for="title"><?php echo apply_filters( '<API key>', __( 'Enter name here', 'pods' ), $pod, $fields ); ?></label> <input type="text" name="pods_field_<?php echo $pod->pod_data[ 'field_index' ]; ?>" data-name-clean="pods-field-<?php echo $pod->pod_data[ 'field_index' ]; ?>" id="title" size="30" tabindex="1" value="<?php echo esc_attr( htmlspecialchars( $pod->index() ) ); ?>" class="<API key>-<?php echo $pod->pod_data[ 'field_index' ]; ?>" autocomplete="off"<?php echo $extra; ?> /> <?php /** * Action that runs after the title field of the editor for an Advanced Content Type * * Occurs at the bottom of #titlediv * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.4.1 */ do_action( '<API key>', $pod, $obj ); ?> </div> <!-- /#titlewrap --> <div class="inside"> <div id="edit-slug-box"> </div> <!-- /#edit-slug-box --> </div> <!-- /.inside --> </div> <!-- /#titlediv --> <?php } unset( $group_fields[ $field[ 'name' ] ] ); } } if ( 0 < count( $groups ) ) { if ( $more && 1 == count( $groups ) ) { $first_group = current( $groups ); if ( 1 == count( $first_group[ 'fields' ] ) && isset( $first_group[ 'fields' ][ $pod->pod_data[ 'field_index' ] ] ) ) { $groups = array(); } } if ( 0 < count( $groups ) ) { ?> <div id="normal-sortables" class="meta-box-sortables ui-sortable"> <?php foreach ( $groups as $group ) { if ( empty( $group[ 'fields' ] ) ) { continue; } /** * Action that runs before the main fields metabox in the editor for an Advanced Content Type * * Occurs at the top of #normal-sortables * * @param obj $pod Current Pods object. * * @since 2.4.1 */ do_action( '<API key>', $pod ); ?> <div id="pods-meta-box-<?php echo sanitize_title( $group[ 'label' ] ); ?>" class="postbox" style=""> <div class="handlediv" title="Click to toggle"><br /></div> <h3 class="hndle"> <span> <?php if ( ! $more && 1 == count( $groups ) ) { $title = __( 'Fields', 'pods' ); } else { $title = $group[ 'label' ]; } /** This filter is documented in classes/PodsMeta.php */ echo apply_filters( '<API key>', $title, $pod, $fields, $pod->api->pod_data[ 'type' ], $pod->pod ); ?> </span> </h3> <div class="inside"> <?php if ( false === apply_filters( '<API key>', false, $pod, $group, $obj ) ) { ?> <table class="form-table pods-metabox"> <?php foreach ( $group[ 'fields' ] as $field ) { if ( 'hidden' == $field[ 'type' ] || $more === $field[ 'name' ] || !isset( $group_fields[ $field[ 'name' ] ] ) ) continue; ?> <tr class="form-field pods-field pods-field-input <?php echo '<API key>-' . $field[ 'type' ] . ' <API key>-' . PodsForm::clean( $field[ 'name' ], true ); ?>"> <th scope="row" valign="top"><?php echo PodsForm::label( 'pods_field_' . $field[ 'name' ], $field[ 'label' ], $field[ 'help' ], $field ); ?></th> <td> <?php echo PodsForm::field( 'pods_field_' . $field[ 'name' ], $pod->field( array( 'name' => $field[ 'name' ], 'in_form' => true ) ), $field[ 'type' ], $field, $pod, $pod->id() ); ?> <?php echo PodsForm::comment( 'pods_field_' . $field[ 'name' ], $field[ 'description' ], $field ); ?> </td> </tr> <?php } ?> </table> <?php } ?> </div> <!-- /.inside --> </div> <!-- /#pods-meta-box --> <?php } /** * Action that runs after the main fields metabox in the editor for an Advanced Content Type * * Occurs at the bottom of #normal-sortables * * @param Pods $pod Current Pods object. * @param PodsUI $obj Current PodsUI object. * * @since 2.4.1 */ do_action( '<API key>', $pod, $obj ); ?> </div> <!-- /#normal-sortables --> <?php } } ?> <!--<div id="advanced-sortables" class="meta-box-sortables ui-sortable"> </div> /#advanced-sortables --> </div> <!-- /#post-body-content --> <br class="clear" /> </div> <!-- /#post-body --> <br class="clear" /> </div> <!-- /#poststuff --> </div> </form> <!-- /#pods-record --> <script type="text/javascript"> if ( 'undefined' == typeof ajaxurl ) { var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>'; } jQuery( function ( $ ) { $( document ).Pods( 'validate' ); $( document ).Pods( 'submit' ); $( document ).Pods( 'dependency' ); $( document ).Pods( 'confirm' ); $( document ).Pods( 'exit_confirm' ); } ); if ( 'undefined' == typeof pods_form_thank_you ) { var pods_form_thank_you = null; } var <API key> = function ( id ) { id = parseInt( id ); var thank_you = '<?php echo pods_slash( $thank_you ); ?>'; var thank_you_alt = '<?php echo pods_slash( $thank_you_alt ); ?>'; if ( 'undefined' != typeof pods_form_thank_you && null !== pods_form_thank_you ) { thank_you = pods_form_thank_you; } if ( 'NaN' == id ) document.location = thank_you_alt.replace( 'X_ID_X', 0 ); else document.location = thank_you.replace( 'X_ID_X', id ); } </script>
/** * Colors */ /** * Breakpoints & Media Queries */ /** * SCSS Variables. * * Please use variables from this sheet to ensure consistency across the UI. * Don't add to this sheet unless you're pretty sure the value will be reused in many places. * For example, don't add rules to this sheet that affect block visuals. It's purely for UI. */ /** * Colors */ /** * Fonts & basic variables. */ /** * Dimensions. */ /** * Shadows. */ /** * Editor widths. */ /** * Block & Editor UI. */ /** * Block paddings. */ /** * React Native specific. * These variables do not appear to be used anywhere else. */ /** * Breakpoint mixins */ /** * Long content fade mixin * * Creates a fading overlay to signify that the content is longer * than the space allows. */ /** * Focus styles. */ /** * Applies editor left position to the selector passed as argument */ /** * Styles that are reused verbatim in a few places */ /** * Allows users to opt-out of animations via OS-level preferences. */ /** * Reset default styles for JavaScript UI based pages. * This is a WP-admin agnostic reset */ /** * Reset the WP Admin page styles for Gutenberg-like pages. */ ol.<API key> { margin-left: 0; } .<API key> .<API key> { padding-left: 0; } .<API key> { line-height: 1.1; list-style: none; margin-bottom: 1em; } .has-avatars .<API key> { min-height: 2.25em; list-style: none; } .has-avatars .<API key> .<API key>, .has-avatars .<API key> .<API key> { margin-left: 3.25em; } .has-dates .<API key>, .has-excerpts .<API key> { line-height: 1.5; } .<API key> p { font-size: 0.875em; line-height: 1.8; margin: 0.36em 0 1.4em; } .<API key> { display: block; font-size: 0.75em; } .<API key> .avatar, .<API key> { border-radius: 1.5em; display: block; float: left; height: 2.5em; margin-right: 0.75em; width: 2.5em; }
/* ScriptData SDName: <API key> SD%Complete: 100 SDComment: SDCategory: Scholomance EndScriptData */ #include "ScriptPCH.h" class <API key> : public CreatureScript { public: <API key>() : CreatureScript("<API key>") { } CreatureAI* GetAI(Creature* pCreature) const { return new <API key> (pCreature); } struct <API key> : public ScriptedAI { <API key>(Creature *c) : ScriptedAI(c) {} void Reset() { } void DamageTaken(Unit * /*done_by*/, uint32 &damage) { if (me->GetHealth() <= damage) DoCast(me, 23261, true); //Summon Darkreaver's Fallen Charger } void EnterCombat(Unit * /*who*/) { } }; }; void <API key>() { new <API key>(); }
// This program is free software; you can redistribute it and/or // as published by the Free Software Foundation; either version 2 // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // DESCRIPTION: // Mission begin melt/wipe screen special effect. #include <string.h> #include "z_zone.h" #include "i_video.h" #include "v_video.h" #include "m_random.h" #include "doomtype.h" #include "f_wipe.h" // SCREEN WIPE PACKAGE // when zero, stop the wipe static boolean go = 0; static byte* wipe_scr_start; static byte* wipe_scr_end; static byte* wipe_scr; void <API key> ( short* array, int width, int height ) { int x; int y; short* dest; dest = (short*) Z_Malloc(width*height*2, PU_STATIC, 0); for(y=0;y<height;y++) for(x=0;x<width;x++) dest[x*height+y] = array[y*width+x]; memcpy(array, dest, width*height*2); Z_Free(dest); } int wipe_initColorXForm ( int width, int height, int ticks ) { memcpy(wipe_scr, wipe_scr_start, width*height); return 0; } int wipe_doColorXForm ( int width, int height, int ticks ) { boolean changed; byte* w; byte* e; int newval; changed = false; w = wipe_scr; e = wipe_scr_end; while (w!=wipe_scr+width*height) { if (*w != *e) { if (*w > *e) { newval = *w - ticks; if (newval < *e) *w = *e; else *w = newval; changed = true; } else if (*w < *e) { newval = *w + ticks; if (newval > *e) *w = *e; else *w = newval; changed = true; } } w++; e++; } return !changed; } int wipe_exitColorXForm ( int width, int height, int ticks ) { return 0; } static int* y; int wipe_initMelt ( int width, int height, int ticks ) { int i, r; // copy start screen to main screen memcpy(wipe_scr, wipe_scr_start, width*height); // makes this wipe faster (in theory) // to have stuff in column-major format <API key>((short*)wipe_scr_start, width/2, height); <API key>((short*)wipe_scr_end, width/2, height); // setup initial column positions // (y<0 => not ready to scroll yet) y = (int *) Z_Malloc(width*sizeof(int), PU_STATIC, 0); y[0] = -(M_Random()%16); for (i=1;i<width;i++) { r = (M_Random()%3) - 1; y[i] = y[i-1] + r; if (y[i] > 0) y[i] = 0; else if (y[i] == -16) y[i] = -15; } return 0; } int wipe_doMelt ( int width, int height, int ticks ) { int i; int j; int dy; int idx; short* s; short* d; boolean done = true; width/=2; while (ticks { for (i=0;i<width;i++) { if (y[i]<0) { y[i]++; done = false; } else if (y[i] < height) { dy = (y[i] < 16) ? y[i]+1 : 8; if (y[i]+dy >= height) dy = height - y[i]; s = &((short *)wipe_scr_end)[i*height+y[i]]; d = &((short *)wipe_scr)[y[i]*width+i]; idx = 0; for (j=dy;j;j { d[idx] = *(s++); idx += width; } y[i] += dy; s = &((short *)wipe_scr_start)[i*height]; d = &((short *)wipe_scr)[y[i]*width+i]; idx = 0; for (j=height-y[i];j;j { d[idx] = *(s++); idx += width; } done = false; } } } return done; } int wipe_exitMelt ( int width, int height, int ticks ) { Z_Free(y); Z_Free(wipe_scr_start); Z_Free(wipe_scr_end); return 0; } int wipe_StartScreen ( int x, int y, int width, int height ) { wipe_scr_start = Z_Malloc(SCREENWIDTH * SCREENHEIGHT, PU_STATIC, NULL); I_ReadScreen(wipe_scr_start); return 0; } int wipe_EndScreen ( int x, int y, int width, int height ) { wipe_scr_end = Z_Malloc(SCREENWIDTH * SCREENHEIGHT, PU_STATIC, NULL); I_ReadScreen(wipe_scr_end); V_DrawBlock(x, y, width, height, wipe_scr_start); // restore start scr. return 0; } int wipe_ScreenWipe ( int wipeno, int x, int y, int width, int height, int ticks ) { int rc; static int (*wipes[])(int, int, int) = { wipe_initColorXForm, wipe_doColorXForm, wipe_exitColorXForm, wipe_initMelt, wipe_doMelt, wipe_exitMelt }; // initial stuff if (!go) { go = 1; // wipe_scr = (byte *) Z_Malloc(width*height, PU_STATIC, 0); // DEBUG wipe_scr = I_VideoBuffer; (*wipes[wipeno*3])(width, height, ticks); } // do a piece of wipe-in V_MarkRect(0, 0, width, height); rc = (*wipes[wipeno*3+1])(width, height, ticks); // V_DrawBlock(x, y, 0, width, height, wipe_scr); // DEBUG // final stuff if (rc) { go = 0; (*wipes[wipeno*3+2])(width, height, ticks); } return !go; }
#include <linux/module.h> #include <linux/moduleparam.h> #include <linux/stringify.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/compiler.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/in.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/pci.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/ethtool.h> #include <linux/mdio.h> #include <linux/mii.h> #include <linux/phy.h> #include <linux/brcmphy.h> #include <linux/if.h> #include <linux/if_vlan.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/workqueue.h> #include <linux/prefetch.h> #include <linux/dma-mapping.h> #include <linux/firmware.h> #include <linux/ssb/ssb_driver_gige.h> #include <linux/hwmon.h> #include <linux/hwmon-sysfs.h> #include <net/checksum.h> #include <net/ip.h> #include <linux/io.h> #include <asm/byteorder.h> #include <linux/uaccess.h> #include <uapi/linux/net_tstamp.h> #include <linux/ptp_clock_kernel.h> #ifdef CONFIG_SPARC #include <asm/idprom.h> #include <asm/prom.h> #endif #define BAR_0 0 #define BAR_2 2 #include "tg3.h" /* Functions & macros to verify TG3_FLAGS types */ static inline int _tg3_flag(enum TG3_FLAGS flag, unsigned long *bits) { return test_bit(flag, bits); } static inline void _tg3_flag_set(enum TG3_FLAGS flag, unsigned long *bits) { set_bit(flag, bits); } static inline void _tg3_flag_clear(enum TG3_FLAGS flag, unsigned long *bits) { clear_bit(flag, bits); } #define tg3_flag(tp, flag) \ _tg3_flag(TG3_FLAG_##flag, (tp)->tg3_flags) #define tg3_flag_set(tp, flag) \ _tg3_flag_set(TG3_FLAG_##flag, (tp)->tg3_flags) #define tg3_flag_clear(tp, flag) \ _tg3_flag_clear(TG3_FLAG_##flag, (tp)->tg3_flags) #define DRV_MODULE_NAME "tg3" #define TG3_MAJ_NUM 3 #define TG3_MIN_NUM 137 #define DRV_MODULE_VERSION \ __stringify(TG3_MAJ_NUM) "." __stringify(TG3_MIN_NUM) #define DRV_MODULE_RELDATE "May 11, 2014" #define RESET_KIND_SHUTDOWN 0 #define RESET_KIND_INIT 1 #define RESET_KIND_SUSPEND 2 #define TG3_DEF_RX_MODE 0 #define TG3_DEF_TX_MODE 0 #define TG3_DEF_MSG_ENABLE \ (NETIF_MSG_DRV | \ NETIF_MSG_PROBE | \ NETIF_MSG_LINK | \ NETIF_MSG_TIMER | \ NETIF_MSG_IFDOWN | \ NETIF_MSG_IFUP | \ NETIF_MSG_RX_ERR | \ NETIF_MSG_TX_ERR) #define <API key> 100 /* length of time before we decide the hardware is borked, * and dev->tx_timeout() should be called to fix the problem */ #define TG3_TX_TIMEOUT (5 * HZ) /* hardware minimum and maximum for a single frame's data payload */ #define TG3_MIN_MTU 60 #define TG3_MAX_MTU(tp) \ (tg3_flag(tp, JUMBO_CAPABLE) ? 9000 : 1500) /* These numbers seem to be hard coded in the NIC firmware somehow. * You can't change the ring sizes, but you can change where you place * them in the NIC onboard memory. */ #define <API key>(tp) \ (tg3_flag(tp, LRG_PROD_RING_CAP) ? \ <API key> : <API key>) #define <API key> 200 #define <API key>(tp) \ (tg3_flag(tp, LRG_PROD_RING_CAP) ? \ <API key> : <API key>) #define <API key> 100 /* Do not place this n-ring entries value into the tp struct itself, * we really want to expose these constants to GCC so that modulo et * al. operations are done with shifts and masks instead of with * hw multiply/modulo instructions. Another solution would be to * replace things like '% foo' with '& (foo - 1)'. */ #define TG3_TX_RING_SIZE 512 #define <API key> (TG3_TX_RING_SIZE - 1) #define <API key>(tp) \ (sizeof(struct tg3_rx_buffer_desc) * <API key>(tp)) #define <API key>(tp) \ (sizeof(struct <API key>) * <API key>(tp)) #define <API key>(tp) \ (sizeof(struct tg3_rx_buffer_desc) * (tp->rx_ret_ring_mask + 1)) #define TG3_TX_RING_BYTES (sizeof(struct tg3_tx_buffer_desc) * \ TG3_TX_RING_SIZE) #define NEXT_TX(N) (((N) + 1) & (TG3_TX_RING_SIZE - 1)) #define TG3_DMA_BYTE_ENAB 64 #define TG3_RX_STD_DMA_SZ 1536 #define TG3_RX_JMB_DMA_SZ 9046 #define <API key>(x) ((x) + TG3_DMA_BYTE_ENAB) #define TG3_RX_STD_MAP_SZ <API key>(TG3_RX_STD_DMA_SZ) #define TG3_RX_JMB_MAP_SZ <API key>(TG3_RX_JMB_DMA_SZ) #define <API key>(tp) \ (sizeof(struct ring_info) * <API key>(tp)) #define <API key>(tp) \ (sizeof(struct ring_info) * <API key>(tp)) /* Due to a hardware bug, the 5701 can only DMA to memory addresses * that are at least dword aligned when used in PCIX mode. The driver * works around this bug by double copying the packet. This workaround * is built into the normal double copy length check for efficiency. * * However, the double copy is only necessary on those architectures * where unaligned memory accesses are inefficient. For those architectures * where unaligned memory accesses incur little penalty, we can reintegrate * the 5701 in the normal rx path. Doing so saves a device structure * dereference by hardcoding the double copy threshold in place. */ #define <API key> 256 #if NET_IP_ALIGN == 0 || defined(<API key>) #define TG3_RX_COPY_THRESH(tp) <API key> #else #define TG3_RX_COPY_THRESH(tp) ((tp)->rx_copy_thresh) #endif #if (NET_IP_ALIGN != 0) #define TG3_RX_OFFSET(tp) ((tp)->rx_offset) #else #define TG3_RX_OFFSET(tp) (NET_SKB_PAD) #endif /* minimum number of free TX descriptors required to wake up TX process */ #define <API key>(tnapi) ((tnapi)->tx_pending / 4) #define <API key> 2048 #define <API key> 4096 #define TG3_RAW_IP_ALIGN 2 #define TG3_MAX_UCAST_ADDR(tp) (tg3_flag((tp), ENABLE_ASF) ? 2 : 3) #define TG3_UCAST_ADDR_IDX(tp) (tg3_flag((tp), ENABLE_ASF) ? 2 : 1) #define <API key> 5 #define <API key> (<API key> / 2) #define FIRMWARE_TG3 "tigon/tg3.bin" #define FIRMWARE_TG357766 "tigon/tg357766.bin" #define FIRMWARE_TG3TSO "tigon/tg3_tso.bin" #define FIRMWARE_TG3TSO5 "tigon/tg3_tso5.bin" static char version[] = DRV_MODULE_NAME ".c:v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")"; MODULE_AUTHOR("David S. Miller (davem@redhat.com) and Jeff Garzik (jgarzik@pobox.com)"); MODULE_DESCRIPTION("Broadcom Tigon3 ethernet driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_MODULE_VERSION); MODULE_FIRMWARE(FIRMWARE_TG3); MODULE_FIRMWARE(FIRMWARE_TG3TSO); MODULE_FIRMWARE(FIRMWARE_TG3TSO5); static int tg3_debug = -1; /* -1 == use TG3_DEF_MSG_ENABLE as value */ module_param(tg3_debug, int, 0); MODULE_PARM_DESC(tg3_debug, "Tigon3 bitmapped debugging message enable value"); #define <API key> 0x0001 #define <API key> 0x0002 static <API key>(tg3_pci_tbl) = { {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>), .driver_data = <API key> | <API key>}, {PCI_DEVICE(<API key>, <API key>), .driver_data = <API key> | <API key>}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>), .driver_data = <API key> | <API key>}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>), .driver_data = <API key>}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>), .driver_data = <API key>}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE_SUB(<API key>, <API key>, <API key>, <API key>), .driver_data = <API key>}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>), .driver_data = <API key>}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE_SUB(<API key>, <API key>, PCI_VENDOR_ID_AI, <API key>), .driver_data = <API key>}, {PCI_DEVICE_SUB(<API key>, <API key>, PCI_VENDOR_ID_AI, <API key>), .driver_data = <API key>}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>), .driver_data = <API key>}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>), .driver_data = <API key>}, {PCI_DEVICE(<API key>, <API key>), .driver_data = <API key>}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(<API key>, <API key>)}, {PCI_DEVICE(PCI_VENDOR_ID_APPLE, <API key>)}, {PCI_DEVICE(0x10cf, 0x11a2)}, /* Fujitsu 1000base-SX with BCM5703SKHB */ {} }; MODULE_DEVICE_TABLE(pci, tg3_pci_tbl); static const struct { const char string[ETH_GSTRING_LEN]; } ethtool_stats_keys[] = { { "rx_octets" }, { "rx_fragments" }, { "rx_ucast_packets" }, { "rx_mcast_packets" }, { "rx_bcast_packets" }, { "rx_fcs_errors" }, { "rx_align_errors" }, { "rx_xon_pause_rcvd" }, { "rx_xoff_pause_rcvd" }, { "rx_mac_ctrl_rcvd" }, { "rx_xoff_entered" }, { "<API key>" }, { "rx_jabbers" }, { "<API key>" }, { "rx_in_length_errors" }, { "<API key>" }, { "<API key>" }, { "<API key>" }, { "<API key>" }, { "<API key>" }, { "<API key>" }, { "<API key>" }, { "<API key>" }, { "<API key>" }, { "<API key>" }, { "<API key>" }, { "tx_octets" }, { "tx_collisions" }, { "tx_xon_sent" }, { "tx_xoff_sent" }, { "tx_flow_control" }, { "tx_mac_errors" }, { "<API key>" }, { "tx_mult_collisions" }, { "tx_deferred" }, { "<API key>" }, { "tx_late_collisions" }, { "tx_collide_2times" }, { "tx_collide_3times" }, { "tx_collide_4times" }, { "tx_collide_5times" }, { "tx_collide_6times" }, { "tx_collide_7times" }, { "tx_collide_8times" }, { "tx_collide_9times" }, { "tx_collide_10times" }, { "tx_collide_11times" }, { "tx_collide_12times" }, { "tx_collide_13times" }, { "tx_collide_14times" }, { "tx_collide_15times" }, { "tx_ucast_packets" }, { "tx_mcast_packets" }, { "tx_bcast_packets" }, { "<API key>" }, { "tx_discards" }, { "tx_errors" }, { "dma_writeq_full" }, { "<API key>" }, { "rxbds_empty" }, { "rx_discards" }, { "rx_errors" }, { "rx_threshold_hit" }, { "dma_readq_full" }, { "dma_read_prioq_full" }, { "tx_comp_queue_full" }, { "<API key>" }, { "ring_status_update" }, { "nic_irqs" }, { "nic_avoided_irqs" }, { "<API key>" }, { "mbuf_lwm_thresh_hit" }, }; #define TG3_NUM_STATS ARRAY_SIZE(ethtool_stats_keys) #define TG3_NVRAM_TEST 0 #define TG3_LINK_TEST 1 #define TG3_REGISTER_TEST 2 #define TG3_MEMORY_TEST 3 #define TG3_MAC_LOOPB_TEST 4 #define TG3_PHY_LOOPB_TEST 5 #define TG3_EXT_LOOPB_TEST 6 #define TG3_INTERRUPT_TEST 7 static const struct { const char string[ETH_GSTRING_LEN]; } ethtool_test_keys[] = { [TG3_NVRAM_TEST] = { "nvram test (online) " }, [TG3_LINK_TEST] = { "link test (online) " }, [TG3_REGISTER_TEST] = { "register test (offline)" }, [TG3_MEMORY_TEST] = { "memory test (offline)" }, [TG3_MAC_LOOPB_TEST] = { "mac loopback test (offline)" }, [TG3_PHY_LOOPB_TEST] = { "phy loopback test (offline)" }, [TG3_EXT_LOOPB_TEST] = { "ext loopback test (offline)" }, [TG3_INTERRUPT_TEST] = { "interrupt test (offline)" }, }; #define TG3_NUM_TEST ARRAY_SIZE(ethtool_test_keys) static void tg3_write32(struct tg3 *tp, u32 off, u32 val) { writel(val, tp->regs + off); } static u32 tg3_read32(struct tg3 *tp, u32 off) { return readl(tp->regs + off); } static void tg3_ape_write32(struct tg3 *tp, u32 off, u32 val) { writel(val, tp->aperegs + off); } static u32 tg3_ape_read32(struct tg3 *tp, u32 off) { return readl(tp->aperegs + off); } static void <API key>(struct tg3 *tp, u32 off, u32 val) { unsigned long flags; spin_lock_irqsave(&tp->indirect_lock, flags); <API key>(tp->pdev, <API key>, off); <API key>(tp->pdev, TG3PCI_REG_DATA, val); <API key>(&tp->indirect_lock, flags); } static void <API key>(struct tg3 *tp, u32 off, u32 val) { writel(val, tp->regs + off); readl(tp->regs + off); } static u32 <API key>(struct tg3 *tp, u32 off) { unsigned long flags; u32 val; spin_lock_irqsave(&tp->indirect_lock, flags); <API key>(tp->pdev, <API key>, off); <API key>(tp->pdev, TG3PCI_REG_DATA, &val); <API key>(&tp->indirect_lock, flags); return val; } static void <API key>(struct tg3 *tp, u32 off, u32 val) { unsigned long flags; if (off == (<API key> + TG3_64BIT_REG_LOW)) { <API key>(tp->pdev, <API key> + TG3_64BIT_REG_LOW, val); return; } if (off == <API key>) { <API key>(tp->pdev, <API key> + TG3_64BIT_REG_LOW, val); return; } spin_lock_irqsave(&tp->indirect_lock, flags); <API key>(tp->pdev, <API key>, off + 0x5600); <API key>(tp->pdev, TG3PCI_REG_DATA, val); <API key>(&tp->indirect_lock, flags); /* In indirect mode when disabling interrupts, we also need * to clear the interrupt bit in the GRC local ctrl register. */ if ((off == (MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW)) && (val == 0x1)) { <API key>(tp->pdev, <API key>, tp->grc_local_ctrl|<API key>); } } static u32 <API key>(struct tg3 *tp, u32 off) { unsigned long flags; u32 val; spin_lock_irqsave(&tp->indirect_lock, flags); <API key>(tp->pdev, <API key>, off + 0x5600); <API key>(tp->pdev, TG3PCI_REG_DATA, &val); <API key>(&tp->indirect_lock, flags); return val; } /* usec_wait specifies the wait time in usec when writing to certain registers * where it is unsafe to read back the register without some delay. * GRC_LOCAL_CTRL is one example if the GPIOs are toggled to switch power. * TG3PCI_CLOCK_CTRL is another example if the clock frequencies are changed. */ static void _tw32_flush(struct tg3 *tp, u32 off, u32 val, u32 usec_wait) { if (tg3_flag(tp, PCIX_TARGET_HWBUG) || tg3_flag(tp, ICH_WORKAROUND)) /* Non-posted methods */ tp->write32(tp, off, val); else { /* Posted method */ tg3_write32(tp, off, val); if (usec_wait) udelay(usec_wait); tp->read32(tp, off); } /* Wait again after the read for the posted method to guarantee that * the wait time is met. */ if (usec_wait) udelay(usec_wait); } static inline void tw32_mailbox_flush(struct tg3 *tp, u32 off, u32 val) { tp->write32_mbox(tp, off, val); if (tg3_flag(tp, FLUSH_POSTED_WRITES) || (!tg3_flag(tp, MBOX_WRITE_REORDER) && !tg3_flag(tp, ICH_WORKAROUND))) tp->read32_mbox(tp, off); } static void tg3_write32_tx_mbox(struct tg3 *tp, u32 off, u32 val) { void __iomem *mbox = tp->regs + off; writel(val, mbox); if (tg3_flag(tp, TXD_MBOX_HWBUG)) writel(val, mbox); if (tg3_flag(tp, MBOX_WRITE_REORDER) || tg3_flag(tp, FLUSH_POSTED_WRITES)) readl(mbox); } static u32 <API key>(struct tg3 *tp, u32 off) { return readl(tp->regs + off + GRCMBOX_BASE); } static void <API key>(struct tg3 *tp, u32 off, u32 val) { writel(val, tp->regs + off + GRCMBOX_BASE); } #define tw32_mailbox(reg, val) tp->write32_mbox(tp, reg, val) #define tw32_mailbox_f(reg, val) tw32_mailbox_flush(tp, (reg), (val)) #define tw32_rx_mbox(reg, val) tp->write32_rx_mbox(tp, reg, val) #define tw32_tx_mbox(reg, val) tp->write32_tx_mbox(tp, reg, val) #define tr32_mailbox(reg) tp->read32_mbox(tp, reg) #define tw32(reg, val) tp->write32(tp, reg, val) #define tw32_f(reg, val) _tw32_flush(tp, (reg), (val), 0) #define tw32_wait_f(reg, val, us) _tw32_flush(tp, (reg), (val), (us)) #define tr32(reg) tp->read32(tp, reg) static void tg3_write_mem(struct tg3 *tp, u32 off, u32 val) { unsigned long flags; if (tg3_asic_rev(tp) == ASIC_REV_5906 && (off >= NIC_SRAM_STATS_BLK) && (off < <API key>)) return; spin_lock_irqsave(&tp->indirect_lock, flags); if (tg3_flag(tp, SRAM_USE_CONFIG)) { <API key>(tp->pdev, <API key>, off); <API key>(tp->pdev, TG3PCI_MEM_WIN_DATA, val); /* Always leave this as zero. */ <API key>(tp->pdev, <API key>, 0); } else { tw32_f(<API key>, off); tw32_f(TG3PCI_MEM_WIN_DATA, val); /* Always leave this as zero. */ tw32_f(<API key>, 0); } <API key>(&tp->indirect_lock, flags); } static void tg3_read_mem(struct tg3 *tp, u32 off, u32 *val) { unsigned long flags; if (tg3_asic_rev(tp) == ASIC_REV_5906 && (off >= NIC_SRAM_STATS_BLK) && (off < <API key>)) { *val = 0; return; } spin_lock_irqsave(&tp->indirect_lock, flags); if (tg3_flag(tp, SRAM_USE_CONFIG)) { <API key>(tp->pdev, <API key>, off); <API key>(tp->pdev, TG3PCI_MEM_WIN_DATA, val); /* Always leave this as zero. */ <API key>(tp->pdev, <API key>, 0); } else { tw32_f(<API key>, off); *val = tr32(TG3PCI_MEM_WIN_DATA); /* Always leave this as zero. */ tw32_f(<API key>, 0); } <API key>(&tp->indirect_lock, flags); } static void tg3_ape_lock_init(struct tg3 *tp) { int i; u32 regbase, bit; if (tg3_asic_rev(tp) == ASIC_REV_5761) regbase = TG3_APE_LOCK_GRANT; else regbase = <API key>; /* Make sure the driver hasn't any stale locks. */ for (i = TG3_APE_LOCK_PHY0; i <= TG3_APE_LOCK_GPIO; i++) { switch (i) { case TG3_APE_LOCK_PHY0: case TG3_APE_LOCK_PHY1: case TG3_APE_LOCK_PHY2: case TG3_APE_LOCK_PHY3: bit = <API key>; break; default: if (!tp->pci_fn) bit = <API key>; else bit = 1 << tp->pci_fn; } tg3_ape_write32(tp, regbase + 4 * i, bit); } } static int tg3_ape_lock(struct tg3 *tp, int locknum) { int i, off; int ret = 0; u32 status, req, gnt, bit; if (!tg3_flag(tp, ENABLE_APE)) return 0; switch (locknum) { case TG3_APE_LOCK_GPIO: if (tg3_asic_rev(tp) == ASIC_REV_5761) return 0; case TG3_APE_LOCK_GRC: case TG3_APE_LOCK_MEM: if (!tp->pci_fn) bit = APE_LOCK_REQ_DRIVER; else bit = 1 << tp->pci_fn; break; case TG3_APE_LOCK_PHY0: case TG3_APE_LOCK_PHY1: case TG3_APE_LOCK_PHY2: case TG3_APE_LOCK_PHY3: bit = APE_LOCK_REQ_DRIVER; break; default: return -EINVAL; } if (tg3_asic_rev(tp) == ASIC_REV_5761) { req = TG3_APE_LOCK_REQ; gnt = TG3_APE_LOCK_GRANT; } else { req = <API key>; gnt = <API key>; } off = 4 * locknum; tg3_ape_write32(tp, req + off, bit); /* Wait for up to 1 millisecond to acquire lock. */ for (i = 0; i < 100; i++) { status = tg3_ape_read32(tp, gnt + off); if (status == bit) break; if (pci_channel_offline(tp->pdev)) break; udelay(10); } if (status != bit) { /* Revoke the lock request. */ tg3_ape_write32(tp, gnt + off, bit); ret = -EBUSY; } return ret; } static void tg3_ape_unlock(struct tg3 *tp, int locknum) { u32 gnt, bit; if (!tg3_flag(tp, ENABLE_APE)) return; switch (locknum) { case TG3_APE_LOCK_GPIO: if (tg3_asic_rev(tp) == ASIC_REV_5761) return; case TG3_APE_LOCK_GRC: case TG3_APE_LOCK_MEM: if (!tp->pci_fn) bit = <API key>; else bit = 1 << tp->pci_fn; break; case TG3_APE_LOCK_PHY0: case TG3_APE_LOCK_PHY1: case TG3_APE_LOCK_PHY2: case TG3_APE_LOCK_PHY3: bit = <API key>; break; default: return; } if (tg3_asic_rev(tp) == ASIC_REV_5761) gnt = TG3_APE_LOCK_GRANT; else gnt = <API key>; tg3_ape_write32(tp, gnt + 4 * locknum, bit); } static int tg3_ape_event_lock(struct tg3 *tp, u32 timeout_us) { u32 apedata; while (timeout_us) { if (tg3_ape_lock(tp, TG3_APE_LOCK_MEM)) return -EBUSY; apedata = tg3_ape_read32(tp, <API key>); if (!(apedata & <API key>)) break; tg3_ape_unlock(tp, TG3_APE_LOCK_MEM); udelay(10); timeout_us -= (timeout_us > 10) ? 10 : timeout_us; } return timeout_us ? 0 : -EBUSY; } static int <API key>(struct tg3 *tp, u32 timeout_us) { u32 i, apedata; for (i = 0; i < timeout_us / 10; i++) { apedata = tg3_ape_read32(tp, <API key>); if (!(apedata & <API key>)) break; udelay(10); } return i == timeout_us / 10; } static int <API key>(struct tg3 *tp, u32 *data, u32 base_off, u32 len) { int err; u32 i, bufoff, msgoff, maxlen, apedata; if (!tg3_flag(tp, APE_HAS_NCSI)) return 0; apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG); if (apedata != APE_SEG_SIG_MAGIC) return -ENODEV; apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS); if (!(apedata & APE_FW_STATUS_READY)) return -EAGAIN; bufoff = tg3_ape_read32(tp, <API key>) + TG3_APE_SHMEM_BASE; msgoff = bufoff + 2 * sizeof(u32); maxlen = tg3_ape_read32(tp, <API key>); while (len) { u32 length; /* Cap xfer sizes to scratchpad limits. */ length = (len > maxlen) ? maxlen : len; len -= length; apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS); if (!(apedata & APE_FW_STATUS_READY)) return -EAGAIN; /* Wait for up to 1 msec for APE to service previous event. */ err = tg3_ape_event_lock(tp, 1000); if (err) return err; apedata = <API key> | <API key> | <API key>; tg3_ape_write32(tp, <API key>, apedata); tg3_ape_write32(tp, bufoff, base_off); tg3_ape_write32(tp, bufoff + sizeof(u32), length); tg3_ape_unlock(tp, TG3_APE_LOCK_MEM); tg3_ape_write32(tp, TG3_APE_EVENT, APE_EVENT_1); base_off += length; if (<API key>(tp, 30000)) return -EAGAIN; for (i = 0; length; i += 4, length -= 4) { u32 val = tg3_ape_read32(tp, msgoff + i); memcpy(data, &val, sizeof(u32)); data++; } } return 0; } static int tg3_ape_send_event(struct tg3 *tp, u32 event) { int err; u32 apedata; apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG); if (apedata != APE_SEG_SIG_MAGIC) return -EAGAIN; apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS); if (!(apedata & APE_FW_STATUS_READY)) return -EAGAIN; /* Wait for up to 1 millisecond for APE to service previous event. */ err = tg3_ape_event_lock(tp, 1000); if (err) return err; tg3_ape_write32(tp, <API key>, event | <API key>); tg3_ape_unlock(tp, TG3_APE_LOCK_MEM); tg3_ape_write32(tp, TG3_APE_EVENT, APE_EVENT_1); return 0; } static void <API key>(struct tg3 *tp, int kind) { u32 event; u32 apedata; if (!tg3_flag(tp, ENABLE_APE)) return; switch (kind) { case RESET_KIND_INIT: tg3_ape_write32(tp, <API key>, <API key>); tg3_ape_write32(tp, <API key>, <API key>); apedata = tg3_ape_read32(tp, <API key>); tg3_ape_write32(tp, <API key>, ++apedata); tg3_ape_write32(tp, <API key>, <API key>(TG3_MAJ_NUM, TG3_MIN_NUM)); tg3_ape_write32(tp, <API key>, <API key>); tg3_ape_write32(tp, <API key>, <API key>); event = <API key>; break; case RESET_KIND_SHUTDOWN: /* With the interface we are currently using, * APE does not track driver state. Wiping * out the HOST SEGMENT SIGNATURE forces * the APE to assume OS absent status. */ tg3_ape_write32(tp, <API key>, 0x0); if (device_may_wakeup(&tp->pdev->dev) && tg3_flag(tp, WOL_ENABLE)) { tg3_ape_write32(tp, <API key>, <API key>); apedata = <API key>; } else apedata = <API key>; tg3_ape_write32(tp, <API key>, apedata); event = <API key>; break; default: return; } event |= <API key> | <API key>; tg3_ape_send_event(tp, event); } static void tg3_disable_ints(struct tg3 *tp) { int i; tw32(<API key>, (tp->misc_host_ctrl | <API key>)); for (i = 0; i < tp->irq_max; i++) tw32_mailbox_f(tp->napi[i].int_mbox, 0x00000001); } static void tg3_enable_ints(struct tg3 *tp) { int i; tp->irq_sync = 0; wmb(); tw32(<API key>, (tp->misc_host_ctrl & ~<API key>)); tp->coal_now = tp->coalesce_mode | HOSTCC_MODE_ENABLE; for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24); if (tg3_flag(tp, 1SHOT_MSI)) tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24); tp->coal_now |= tnapi->coal_now; } /* Force an initial interrupt */ if (!tg3_flag(tp, TAGGED_STATUS) && (tp->napi[0].hw_status->status & SD_STATUS_UPDATED)) tw32(GRC_LOCAL_CTRL, tp->grc_local_ctrl | GRC_LCLCTRL_SETINT); else tw32(HOSTCC_MODE, tp->coal_now); tp->coal_now &= ~(tp->napi[0].coal_now | tp->napi[1].coal_now); } static inline unsigned int tg3_has_work(struct tg3_napi *tnapi) { struct tg3 *tp = tnapi->tp; struct tg3_hw_status *sblk = tnapi->hw_status; unsigned int work_exists = 0; /* check for phy events */ if (!(tg3_flag(tp, USE_LINKCHG_REG) || tg3_flag(tp, POLL_SERDES))) { if (sblk->status & SD_STATUS_LINK_CHG) work_exists = 1; } /* check for TX work to do */ if (sblk->idx[0].tx_consumer != tnapi->tx_cons) work_exists = 1; /* check for RX work to do */ if (tnapi->rx_rcb_prod_idx && *(tnapi->rx_rcb_prod_idx) != tnapi->rx_rcb_ptr) work_exists = 1; return work_exists; } /* tg3_int_reenable * similar to tg3_enable_ints, but it accurately determines whether there * is new work pending and can return without flushing the PIO write * which reenables interrupts */ static void tg3_int_reenable(struct tg3_napi *tnapi) { struct tg3 *tp = tnapi->tp; tw32_mailbox(tnapi->int_mbox, tnapi->last_tag << 24); mmiowb(); /* When doing tagged status, this work check is unnecessary. * The last_tag we write above tells the chip which piece of * work we've completed. */ if (!tg3_flag(tp, TAGGED_STATUS) && tg3_has_work(tnapi)) tw32(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | tnapi->coal_now); } static void tg3_switch_clocks(struct tg3 *tp) { u32 clock_ctrl; u32 orig_clock_ctrl; if (tg3_flag(tp, CPMU_PRESENT) || tg3_flag(tp, 5780_CLASS)) return; clock_ctrl = tr32(TG3PCI_CLOCK_CTRL); orig_clock_ctrl = clock_ctrl; clock_ctrl &= (<API key> | <API key> | 0x1f); tp->pci_clock_ctrl = clock_ctrl; if (tg3_flag(tp, 5705_PLUS)) { if (orig_clock_ctrl & CLOCK_CTRL_625_CORE) { tw32_wait_f(TG3PCI_CLOCK_CTRL, clock_ctrl | CLOCK_CTRL_625_CORE, 40); } } else if ((orig_clock_ctrl & <API key>) != 0) { tw32_wait_f(TG3PCI_CLOCK_CTRL, clock_ctrl | (<API key> | CLOCK_CTRL_ALTCLK), 40); tw32_wait_f(TG3PCI_CLOCK_CTRL, clock_ctrl | (CLOCK_CTRL_ALTCLK), 40); } tw32_wait_f(TG3PCI_CLOCK_CTRL, clock_ctrl, 40); } #define PHY_BUSY_LOOPS 5000 static int __tg3_readphy(struct tg3 *tp, unsigned int phy_addr, int reg, u32 *val) { u32 frame_val; unsigned int loops; int ret; if ((tp->mi_mode & <API key>) != 0) { tw32_f(MAC_MI_MODE, (tp->mi_mode & ~<API key>)); udelay(80); } tg3_ape_lock(tp, tp->phy_ape_lock); *val = 0x0; frame_val = ((phy_addr << <API key>) & <API key>); frame_val |= ((reg << <API key>) & <API key>); frame_val |= (MI_COM_CMD_READ | MI_COM_START); tw32_f(MAC_MI_COM, frame_val); loops = PHY_BUSY_LOOPS; while (loops != 0) { udelay(10); frame_val = tr32(MAC_MI_COM); if ((frame_val & MI_COM_BUSY) == 0) { udelay(5); frame_val = tr32(MAC_MI_COM); break; } loops -= 1; } ret = -EBUSY; if (loops != 0) { *val = frame_val & MI_COM_DATA_MASK; ret = 0; } if ((tp->mi_mode & <API key>) != 0) { tw32_f(MAC_MI_MODE, tp->mi_mode); udelay(80); } tg3_ape_unlock(tp, tp->phy_ape_lock); return ret; } static int tg3_readphy(struct tg3 *tp, int reg, u32 *val) { return __tg3_readphy(tp, tp->phy_addr, reg, val); } static int __tg3_writephy(struct tg3 *tp, unsigned int phy_addr, int reg, u32 val) { u32 frame_val; unsigned int loops; int ret; if ((tp->phy_flags & TG3_PHYFLG_IS_FET) && (reg == MII_CTRL1000 || reg == MII_TG3_AUX_CTRL)) return 0; if ((tp->mi_mode & <API key>) != 0) { tw32_f(MAC_MI_MODE, (tp->mi_mode & ~<API key>)); udelay(80); } tg3_ape_lock(tp, tp->phy_ape_lock); frame_val = ((phy_addr << <API key>) & <API key>); frame_val |= ((reg << <API key>) & <API key>); frame_val |= (val & MI_COM_DATA_MASK); frame_val |= (MI_COM_CMD_WRITE | MI_COM_START); tw32_f(MAC_MI_COM, frame_val); loops = PHY_BUSY_LOOPS; while (loops != 0) { udelay(10); frame_val = tr32(MAC_MI_COM); if ((frame_val & MI_COM_BUSY) == 0) { udelay(5); frame_val = tr32(MAC_MI_COM); break; } loops -= 1; } ret = -EBUSY; if (loops != 0) ret = 0; if ((tp->mi_mode & <API key>) != 0) { tw32_f(MAC_MI_MODE, tp->mi_mode); udelay(80); } tg3_ape_unlock(tp, tp->phy_ape_lock); return ret; } static int tg3_writephy(struct tg3 *tp, int reg, u32 val) { return __tg3_writephy(tp, tp->phy_addr, reg, val); } static int tg3_phy_cl45_write(struct tg3 *tp, u32 devad, u32 addr, u32 val) { int err; err = tg3_writephy(tp, MII_TG3_MMD_CTRL, devad); if (err) goto done; err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, addr); if (err) goto done; err = tg3_writephy(tp, MII_TG3_MMD_CTRL, <API key> | devad); if (err) goto done; err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, val); done: return err; } static int tg3_phy_cl45_read(struct tg3 *tp, u32 devad, u32 addr, u32 *val) { int err; err = tg3_writephy(tp, MII_TG3_MMD_CTRL, devad); if (err) goto done; err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, addr); if (err) goto done; err = tg3_writephy(tp, MII_TG3_MMD_CTRL, <API key> | devad); if (err) goto done; err = tg3_readphy(tp, MII_TG3_MMD_ADDRESS, val); done: return err; } static int tg3_phydsp_read(struct tg3 *tp, u32 reg, u32 *val) { int err; err = tg3_writephy(tp, MII_TG3_DSP_ADDRESS, reg); if (!err) err = tg3_readphy(tp, MII_TG3_DSP_RW_PORT, val); return err; } static int tg3_phydsp_write(struct tg3 *tp, u32 reg, u32 val) { int err; err = tg3_writephy(tp, MII_TG3_DSP_ADDRESS, reg); if (!err) err = tg3_writephy(tp, MII_TG3_DSP_RW_PORT, val); return err; } static int tg3_phy_auxctl_read(struct tg3 *tp, int reg, u32 *val) { int err; err = tg3_writephy(tp, MII_TG3_AUX_CTRL, (reg << <API key>) | <API key>); if (!err) err = tg3_readphy(tp, MII_TG3_AUX_CTRL, val); return err; } static int <API key>(struct tg3 *tp, int reg, u32 set) { if (reg == <API key>) set |= <API key>; return tg3_writephy(tp, MII_TG3_AUX_CTRL, set | reg); } static int <API key>(struct tg3 *tp, bool enable) { u32 val; int err; err = tg3_phy_auxctl_read(tp, <API key>, &val); if (err) return err; if (enable) val |= <API key>; else val &= ~<API key>; err = <API key>((tp), <API key>, val | <API key>); return err; } static int tg3_phy_shdw_write(struct tg3 *tp, int reg, u32 val) { return tg3_writephy(tp, MII_TG3_MISC_SHDW, reg | val | <API key>); } static int tg3_bmcr_reset(struct tg3 *tp) { u32 phy_control; int limit, err; /* OK, reset it, and poll the BMCR_RESET bit until it * clears or we time out. */ phy_control = BMCR_RESET; err = tg3_writephy(tp, MII_BMCR, phy_control); if (err != 0) return -EBUSY; limit = 5000; while (limit err = tg3_readphy(tp, MII_BMCR, &phy_control); if (err != 0) return -EBUSY; if ((phy_control & BMCR_RESET) == 0) { udelay(40); break; } udelay(10); } if (limit < 0) return -EBUSY; return 0; } static int tg3_mdio_read(struct mii_bus *bp, int mii_id, int reg) { struct tg3 *tp = bp->priv; u32 val; spin_lock_bh(&tp->lock); if (__tg3_readphy(tp, mii_id, reg, &val)) val = -EIO; spin_unlock_bh(&tp->lock); return val; } static int tg3_mdio_write(struct mii_bus *bp, int mii_id, int reg, u16 val) { struct tg3 *tp = bp->priv; u32 ret = 0; spin_lock_bh(&tp->lock); if (__tg3_writephy(tp, mii_id, reg, val)) ret = -EIO; spin_unlock_bh(&tp->lock); return ret; } static void <API key>(struct tg3 *tp) { u32 val; struct phy_device *phydev; phydev = tp->mdio_bus->phy_map[tp->phy_addr]; switch (phydev->drv->phy_id & phydev->drv->phy_id_mask) { case PHY_ID_BCM50610: case PHY_ID_BCM50610M: val = <API key>; break; case PHY_ID_BCMAC131: val = <API key>; break; case PHY_ID_RTL8211C: val = <API key>; break; case PHY_ID_RTL8201E: val = <API key>; break; default: return; } if (phydev->interface != <API key>) { tw32(MAC_PHYCFG2, val); val = tr32(MAC_PHYCFG1); val &= ~(<API key> | <API key> | <API key>); val |= <API key> | <API key>; tw32(MAC_PHYCFG1, val); return; } if (!tg3_flag(tp, <API key>)) val |= <API key> | <API key> | <API key> | <API key> | <API key> | <API key>; tw32(MAC_PHYCFG2, val); val = tr32(MAC_PHYCFG1); val &= ~(<API key> | <API key> | <API key> | <API key>); if (!tg3_flag(tp, <API key>)) { if (tg3_flag(tp, <API key>)) val |= <API key>; if (tg3_flag(tp, <API key>)) val |= <API key>; } val |= <API key> | <API key> | <API key> | MAC_PHYCFG1_TXC_DRV; tw32(MAC_PHYCFG1, val); val = tr32(MAC_EXT_RGMII_MODE); val &= ~(<API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key>); if (!tg3_flag(tp, <API key>)) { if (tg3_flag(tp, <API key>)) val |= <API key> | <API key> | <API key> | <API key>; if (tg3_flag(tp, <API key>)) val |= <API key> | <API key> | <API key>; } tw32(MAC_EXT_RGMII_MODE, val); } static void tg3_mdio_start(struct tg3 *tp) { tp->mi_mode &= ~<API key>; tw32_f(MAC_MI_MODE, tp->mi_mode); udelay(80); if (tg3_flag(tp, MDIOBUS_INITED) && tg3_asic_rev(tp) == ASIC_REV_5785) <API key>(tp); } static int tg3_mdio_init(struct tg3 *tp) { int i; u32 reg; struct phy_device *phydev; if (tg3_flag(tp, 5717_PLUS)) { u32 is_serdes; tp->phy_addr = tp->pci_fn + 1; if (tg3_chip_rev_id(tp) != CHIPREV_ID_5717_A0) is_serdes = tr32(SG_DIG_STATUS) & SG_DIG_IS_SERDES; else is_serdes = tr32(TG3_CPMU_PHY_STRAP) & <API key>; if (is_serdes) tp->phy_addr += 7; } else if (tg3_flag(tp, IS_SSB_CORE) && tg3_flag(tp, ROBOSWITCH)) { int addr; addr = <API key>(tp->pdev); if (addr < 0) return addr; tp->phy_addr = addr; } else tp->phy_addr = TG3_PHY_MII_ADDR; tg3_mdio_start(tp); if (!tg3_flag(tp, USE_PHYLIB) || tg3_flag(tp, MDIOBUS_INITED)) return 0; tp->mdio_bus = mdiobus_alloc(); if (tp->mdio_bus == NULL) return -ENOMEM; tp->mdio_bus->name = "tg3 mdio bus"; snprintf(tp->mdio_bus->id, MII_BUS_ID_SIZE, "%x", (tp->pdev->bus->number << 8) | tp->pdev->devfn); tp->mdio_bus->priv = tp; tp->mdio_bus->parent = &tp->pdev->dev; tp->mdio_bus->read = &tg3_mdio_read; tp->mdio_bus->write = &tg3_mdio_write; tp->mdio_bus->phy_mask = ~(1 << tp->phy_addr); tp->mdio_bus->irq = &tp->mdio_irq[0]; for (i = 0; i < PHY_MAX_ADDR; i++) tp->mdio_bus->irq[i] = PHY_POLL; /* The bus registration will look for all the PHYs on the mdio bus. * Unfortunately, it does not ensure the PHY is powered up before * accessing the PHY ID registers. A chip reset is the * quickest way to bring the device back to an operational state.. */ if (tg3_readphy(tp, MII_BMCR, &reg) || (reg & BMCR_PDOWN)) tg3_bmcr_reset(tp); i = mdiobus_register(tp->mdio_bus); if (i) { dev_warn(&tp->pdev->dev, "mdiobus_reg failed (0x%x)\n", i); mdiobus_free(tp->mdio_bus); return i; } phydev = tp->mdio_bus->phy_map[tp->phy_addr]; if (!phydev || !phydev->drv) { dev_warn(&tp->pdev->dev, "No PHY devices\n"); mdiobus_unregister(tp->mdio_bus); mdiobus_free(tp->mdio_bus); return -ENODEV; } switch (phydev->drv->phy_id & phydev->drv->phy_id_mask) { case PHY_ID_BCM57780: phydev->interface = <API key>; phydev->dev_flags |= <API key>; break; case PHY_ID_BCM50610: case PHY_ID_BCM50610M: phydev->dev_flags |= <API key> | <API key> | <API key> | <API key>; if (tg3_flag(tp, <API key>)) phydev->dev_flags |= <API key>; if (tg3_flag(tp, <API key>)) phydev->dev_flags |= <API key>; if (tg3_flag(tp, <API key>)) phydev->dev_flags |= <API key>; /* fallthru */ case PHY_ID_RTL8211C: phydev->interface = <API key>; break; case PHY_ID_RTL8201E: case PHY_ID_BCMAC131: phydev->interface = <API key>; phydev->dev_flags |= <API key>; tp->phy_flags |= TG3_PHYFLG_IS_FET; break; } tg3_flag_set(tp, MDIOBUS_INITED); if (tg3_asic_rev(tp) == ASIC_REV_5785) <API key>(tp); return 0; } static void tg3_mdio_fini(struct tg3 *tp) { if (tg3_flag(tp, MDIOBUS_INITED)) { tg3_flag_clear(tp, MDIOBUS_INITED); mdiobus_unregister(tp->mdio_bus); mdiobus_free(tp->mdio_bus); } } /* tp->lock is held. */ static inline void <API key>(struct tg3 *tp) { u32 val; val = tr32(GRC_RX_CPU_EVENT); val |= <API key>; tw32_f(GRC_RX_CPU_EVENT, val); tp->last_event_jiffies = jiffies; } #define <API key> 2500 /* tp->lock is held. */ static void <API key>(struct tg3 *tp) { int i; unsigned int delay_cnt; long time_remain; /* If enough time has passed, no wait is necessary. */ time_remain = (long)(tp->last_event_jiffies + 1 + usecs_to_jiffies(<API key>)) - (long)jiffies; if (time_remain < 0) return; /* Check if we can shorten the wait time. */ delay_cnt = jiffies_to_usecs(time_remain); if (delay_cnt > <API key>) delay_cnt = <API key>; delay_cnt = (delay_cnt >> 3) + 1; for (i = 0; i < delay_cnt; i++) { if (!(tr32(GRC_RX_CPU_EVENT) & <API key>)) break; if (pci_channel_offline(tp->pdev)) break; udelay(8); } } /* tp->lock is held. */ static void <API key>(struct tg3 *tp, u32 *data) { u32 reg, val; val = 0; if (!tg3_readphy(tp, MII_BMCR, &reg)) val = reg << 16; if (!tg3_readphy(tp, MII_BMSR, &reg)) val |= (reg & 0xffff); *data++ = val; val = 0; if (!tg3_readphy(tp, MII_ADVERTISE, &reg)) val = reg << 16; if (!tg3_readphy(tp, MII_LPA, &reg)) val |= (reg & 0xffff); *data++ = val; val = 0; if (!(tp->phy_flags & <API key>)) { if (!tg3_readphy(tp, MII_CTRL1000, &reg)) val = reg << 16; if (!tg3_readphy(tp, MII_STAT1000, &reg)) val |= (reg & 0xffff); } *data++ = val; if (!tg3_readphy(tp, MII_PHYADDR, &reg)) val = reg << 16; else val = 0; *data++ = val; } /* tp->lock is held. */ static void tg3_ump_link_report(struct tg3 *tp) { u32 data[4]; if (!tg3_flag(tp, 5780_CLASS) || !tg3_flag(tp, ENABLE_ASF)) return; <API key>(tp, data); <API key>(tp); tg3_write_mem(tp, <API key>, <API key>); tg3_write_mem(tp, <API key>, 14); tg3_write_mem(tp, <API key> + 0x0, data[0]); tg3_write_mem(tp, <API key> + 0x4, data[1]); tg3_write_mem(tp, <API key> + 0x8, data[2]); tg3_write_mem(tp, <API key> + 0xc, data[3]); <API key>(tp); } /* tp->lock is held. */ static void tg3_stop_fw(struct tg3 *tp) { if (tg3_flag(tp, ENABLE_ASF) && !tg3_flag(tp, ENABLE_APE)) { /* Wait for RX cpu to ACK the previous event. */ <API key>(tp); tg3_write_mem(tp, <API key>, <API key>); <API key>(tp); /* Wait for RX cpu to ACK this event. */ <API key>(tp); } } /* tp->lock is held. */ static void <API key>(struct tg3 *tp, int kind) { tg3_write_mem(tp, <API key>, <API key>); if (tg3_flag(tp, ASF_NEW_HANDSHAKE)) { switch (kind) { case RESET_KIND_INIT: tg3_write_mem(tp, <API key>, DRV_STATE_START); break; case RESET_KIND_SHUTDOWN: tg3_write_mem(tp, <API key>, DRV_STATE_UNLOAD); break; case RESET_KIND_SUSPEND: tg3_write_mem(tp, <API key>, DRV_STATE_SUSPEND); break; default: break; } } } /* tp->lock is held. */ static void <API key>(struct tg3 *tp, int kind) { if (tg3_flag(tp, ASF_NEW_HANDSHAKE)) { switch (kind) { case RESET_KIND_INIT: tg3_write_mem(tp, <API key>, <API key>); break; case RESET_KIND_SHUTDOWN: tg3_write_mem(tp, <API key>, <API key>); break; default: break; } } } /* tp->lock is held. */ static void <API key>(struct tg3 *tp, int kind) { if (tg3_flag(tp, ENABLE_ASF)) { switch (kind) { case RESET_KIND_INIT: tg3_write_mem(tp, <API key>, DRV_STATE_START); break; case RESET_KIND_SHUTDOWN: tg3_write_mem(tp, <API key>, DRV_STATE_UNLOAD); break; case RESET_KIND_SUSPEND: tg3_write_mem(tp, <API key>, DRV_STATE_SUSPEND); break; default: break; } } } static int tg3_poll_fw(struct tg3 *tp) { int i; u32 val; if (tg3_flag(tp, NO_FWARE_REPORTED)) return 0; if (tg3_flag(tp, IS_SSB_CORE)) { /* We don't use firmware. */ return 0; } if (tg3_asic_rev(tp) == ASIC_REV_5906) { /* Wait up to 20ms for init done. */ for (i = 0; i < 200; i++) { if (tr32(VCPU_STATUS) & <API key>) return 0; if (pci_channel_offline(tp->pdev)) return -ENODEV; udelay(100); } return -ENODEV; } /* Wait for firmware initialization to complete. */ for (i = 0; i < 100000; i++) { tg3_read_mem(tp, <API key>, &val); if (val == ~<API key>) break; if (pci_channel_offline(tp->pdev)) { if (!tg3_flag(tp, NO_FWARE_REPORTED)) { tg3_flag_set(tp, NO_FWARE_REPORTED); netdev_info(tp->dev, "No firmware running\n"); } break; } udelay(10); } /* Chip might not be fitted with firmware. Some Sun onboard * parts are configured like that. So don't signal the timeout * of the above loop as an error, but do report the lack of * running firmware once. */ if (i >= 100000 && !tg3_flag(tp, NO_FWARE_REPORTED)) { tg3_flag_set(tp, NO_FWARE_REPORTED); netdev_info(tp->dev, "No firmware running\n"); } if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0) { /* The 57765 A0 needs a little more * time to do some important work. */ mdelay(10); } return 0; } static void tg3_link_report(struct tg3 *tp) { if (!netif_carrier_ok(tp->dev)) { netif_info(tp, link, tp->dev, "Link is down\n"); tg3_ump_link_report(tp); } else if (netif_msg_link(tp)) { netdev_info(tp->dev, "Link is up at %d Mbps, %s duplex\n", (tp->link_config.active_speed == SPEED_1000 ? 1000 : (tp->link_config.active_speed == SPEED_100 ? 100 : 10)), (tp->link_config.active_duplex == DUPLEX_FULL ? "full" : "half")); netdev_info(tp->dev, "Flow control is %s for TX and %s for RX\n", (tp->link_config.active_flowctrl & FLOW_CTRL_TX) ? "on" : "off", (tp->link_config.active_flowctrl & FLOW_CTRL_RX) ? "on" : "off"); if (tp->phy_flags & TG3_PHYFLG_EEE_CAP) netdev_info(tp->dev, "EEE is %s\n", tp->setlpicnt ? "enabled" : "disabled"); tg3_ump_link_report(tp); } tp->link_up = netif_carrier_ok(tp->dev); } static u32 <API key>(u32 adv) { u32 flowctrl = 0; if (adv & ADVERTISE_PAUSE_CAP) { flowctrl |= FLOW_CTRL_RX; if (!(adv & <API key>)) flowctrl |= FLOW_CTRL_TX; } else if (adv & <API key>) flowctrl |= FLOW_CTRL_TX; return flowctrl; } static u16 <API key>(u8 flow_ctrl) { u16 miireg; if ((flow_ctrl & FLOW_CTRL_TX) && (flow_ctrl & FLOW_CTRL_RX)) miireg = <API key>; else if (flow_ctrl & FLOW_CTRL_TX) miireg = <API key>; else if (flow_ctrl & FLOW_CTRL_RX) miireg = <API key> | <API key>; else miireg = 0; return miireg; } static u32 <API key>(u32 adv) { u32 flowctrl = 0; if (adv & <API key>) { flowctrl |= FLOW_CTRL_RX; if (!(adv & <API key>)) flowctrl |= FLOW_CTRL_TX; } else if (adv & <API key>) flowctrl |= FLOW_CTRL_TX; return flowctrl; } static u8 <API key>(u16 lcladv, u16 rmtadv) { u8 cap = 0; if (lcladv & rmtadv & <API key>) { cap = FLOW_CTRL_TX | FLOW_CTRL_RX; } else if (lcladv & rmtadv & <API key>) { if (lcladv & <API key>) cap = FLOW_CTRL_RX; if (rmtadv & <API key>) cap = FLOW_CTRL_TX; } return cap; } static void <API key>(struct tg3 *tp, u32 lcladv, u32 rmtadv) { u8 autoneg; u8 flowctrl = 0; u32 old_rx_mode = tp->rx_mode; u32 old_tx_mode = tp->tx_mode; if (tg3_flag(tp, USE_PHYLIB)) autoneg = tp->mdio_bus->phy_map[tp->phy_addr]->autoneg; else autoneg = tp->link_config.autoneg; if (autoneg == AUTONEG_ENABLE && tg3_flag(tp, PAUSE_AUTONEG)) { if (tp->phy_flags & <API key>) flowctrl = <API key>(lcladv, rmtadv); else flowctrl = <API key>(lcladv, rmtadv); } else flowctrl = tp->link_config.flowctrl; tp->link_config.active_flowctrl = flowctrl; if (flowctrl & FLOW_CTRL_RX) tp->rx_mode |= <API key>; else tp->rx_mode &= ~<API key>; if (old_rx_mode != tp->rx_mode) tw32_f(MAC_RX_MODE, tp->rx_mode); if (flowctrl & FLOW_CTRL_TX) tp->tx_mode |= <API key>; else tp->tx_mode &= ~<API key>; if (old_tx_mode != tp->tx_mode) tw32_f(MAC_TX_MODE, tp->tx_mode); } static void tg3_adjust_link(struct net_device *dev) { u8 oldflowctrl, linkmesg = 0; u32 mac_mode, lcl_adv, rmt_adv; struct tg3 *tp = netdev_priv(dev); struct phy_device *phydev = tp->mdio_bus->phy_map[tp->phy_addr]; spin_lock_bh(&tp->lock); mac_mode = tp->mac_mode & ~(<API key> | <API key>); oldflowctrl = tp->link_config.active_flowctrl; if (phydev->link) { lcl_adv = 0; rmt_adv = 0; if (phydev->speed == SPEED_100 || phydev->speed == SPEED_10) mac_mode |= <API key>; else if (phydev->speed == SPEED_1000 || tg3_asic_rev(tp) != ASIC_REV_5785) mac_mode |= <API key>; else mac_mode |= <API key>; if (phydev->duplex == DUPLEX_HALF) mac_mode |= <API key>; else { lcl_adv = <API key>( tp->link_config.flowctrl); if (phydev->pause) rmt_adv = LPA_PAUSE_CAP; if (phydev->asym_pause) rmt_adv |= LPA_PAUSE_ASYM; } <API key>(tp, lcl_adv, rmt_adv); } else mac_mode |= <API key>; if (mac_mode != tp->mac_mode) { tp->mac_mode = mac_mode; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); } if (tg3_asic_rev(tp) == ASIC_REV_5785) { if (phydev->speed == SPEED_10) tw32(MAC_MI_STAT, <API key> | <API key>); else tw32(MAC_MI_STAT, <API key>); } if (phydev->speed == SPEED_1000 && phydev->duplex == DUPLEX_HALF) tw32(MAC_TX_LENGTHS, ((2 << <API key>) | (6 << <API key>) | (0xff << <API key>))); else tw32(MAC_TX_LENGTHS, ((2 << <API key>) | (6 << <API key>) | (32 << <API key>))); if (phydev->link != tp->old_link || phydev->speed != tp->link_config.active_speed || phydev->duplex != tp->link_config.active_duplex || oldflowctrl != tp->link_config.active_flowctrl) linkmesg = 1; tp->old_link = phydev->link; tp->link_config.active_speed = phydev->speed; tp->link_config.active_duplex = phydev->duplex; spin_unlock_bh(&tp->lock); if (linkmesg) tg3_link_report(tp); } static int tg3_phy_init(struct tg3 *tp) { struct phy_device *phydev; if (tp->phy_flags & <API key>) return 0; /* Bring the PHY back to a known state. */ tg3_bmcr_reset(tp); phydev = tp->mdio_bus->phy_map[tp->phy_addr]; /* Attach the MAC to the PHY. */ phydev = phy_connect(tp->dev, dev_name(&phydev->dev), tg3_adjust_link, phydev->interface); if (IS_ERR(phydev)) { dev_err(&tp->pdev->dev, "Could not attach to PHY\n"); return PTR_ERR(phydev); } /* Mask with MAC supported features. */ switch (phydev->interface) { case <API key>: case <API key>: if (!(tp->phy_flags & <API key>)) { phydev->supported &= (PHY_GBIT_FEATURES | SUPPORTED_Pause | <API key>); break; } /* fallthru */ case <API key>: phydev->supported &= (PHY_BASIC_FEATURES | SUPPORTED_Pause | <API key>); break; default: phy_disconnect(tp->mdio_bus->phy_map[tp->phy_addr]); return -EINVAL; } tp->phy_flags |= <API key>; phydev->advertising = phydev->supported; return 0; } static void tg3_phy_start(struct tg3 *tp) { struct phy_device *phydev; if (!(tp->phy_flags & <API key>)) return; phydev = tp->mdio_bus->phy_map[tp->phy_addr]; if (tp->phy_flags & <API key>) { tp->phy_flags &= ~<API key>; phydev->speed = tp->link_config.speed; phydev->duplex = tp->link_config.duplex; phydev->autoneg = tp->link_config.autoneg; phydev->advertising = tp->link_config.advertising; } phy_start(phydev); phy_start_aneg(phydev); } static void tg3_phy_stop(struct tg3 *tp) { if (!(tp->phy_flags & <API key>)) return; phy_stop(tp->mdio_bus->phy_map[tp->phy_addr]); } static void tg3_phy_fini(struct tg3 *tp) { if (tp->phy_flags & <API key>) { phy_disconnect(tp->mdio_bus->phy_map[tp->phy_addr]); tp->phy_flags &= ~<API key>; } } static int <API key>(struct tg3 *tp) { int err; u32 val; if (tp->phy_flags & TG3_PHYFLG_IS_FET) return 0; if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) { /* Cannot do read-modify-write on 5401 */ err = <API key>(tp, <API key>, <API key> | 0x4c20); goto done; } err = tg3_phy_auxctl_read(tp, <API key>, &val); if (err) return err; val |= <API key>; err = <API key>(tp, <API key>, val); done: return err; } static void <API key>(struct tg3 *tp, bool enable) { u32 phytest; if (!tg3_readphy(tp, MII_TG3_FET_TEST, &phytest)) { u32 phy; tg3_writephy(tp, MII_TG3_FET_TEST, phytest | <API key>); if (!tg3_readphy(tp, <API key>, &phy)) { if (enable) phy |= <API key>; else phy &= ~<API key>; tg3_writephy(tp, <API key>, phy); } tg3_writephy(tp, MII_TG3_FET_TEST, phytest); } } static void tg3_phy_toggle_apd(struct tg3 *tp, bool enable) { u32 reg; if (!tg3_flag(tp, 5705_PLUS) || (tg3_flag(tp, 5717_PLUS) && (tp->phy_flags & <API key>))) return; if (tp->phy_flags & TG3_PHYFLG_IS_FET) { <API key>(tp, enable); return; } reg = <API key> | <API key> | <API key> | <API key>; if (tg3_asic_rev(tp) != ASIC_REV_5784 || !enable) reg |= <API key>; tg3_phy_shdw_write(tp, <API key>, reg); reg = <API key>; if (enable) reg |= <API key>; tg3_phy_shdw_write(tp, <API key>, reg); } static void <API key>(struct tg3 *tp, bool enable) { u32 phy; if (!tg3_flag(tp, 5705_PLUS) || (tp->phy_flags & <API key>)) return; if (tp->phy_flags & TG3_PHYFLG_IS_FET) { u32 ephy; if (!tg3_readphy(tp, MII_TG3_FET_TEST, &ephy)) { u32 reg = <API key>; tg3_writephy(tp, MII_TG3_FET_TEST, ephy | <API key>); if (!tg3_readphy(tp, reg, &phy)) { if (enable) phy |= <API key>; else phy &= ~<API key>; tg3_writephy(tp, reg, phy); } tg3_writephy(tp, MII_TG3_FET_TEST, ephy); } } else { int ret; ret = tg3_phy_auxctl_read(tp, <API key>, &phy); if (!ret) { if (enable) phy |= <API key>; else phy &= ~<API key>; <API key>(tp, <API key>, phy); } } } static void <API key>(struct tg3 *tp) { int ret; u32 val; if (tp->phy_flags & <API key>) return; ret = tg3_phy_auxctl_read(tp, <API key>, &val); if (!ret) <API key>(tp, <API key>, val | <API key>); } static void tg3_phy_apply_otp(struct tg3 *tp) { u32 otp, phy; if (!tp->phy_otp) return; otp = tp->phy_otp; if (<API key>(tp, true)) return; phy = ((otp & TG3_OTP_AGCTGT_MASK) >> <API key>); phy |= <API key>; tg3_phydsp_write(tp, MII_TG3_DSP_TAP1, phy); phy = ((otp & <API key>) >> <API key>) | ((otp & <API key>) >> <API key>); tg3_phydsp_write(tp, <API key>, phy); phy = ((otp & TG3_OTP_LPFDIS_MASK) >> <API key>); phy |= <API key>; tg3_phydsp_write(tp, <API key>, phy); phy = ((otp & TG3_OTP_VDAC_MASK) >> TG3_OTP_VDAC_SHIFT); tg3_phydsp_write(tp, MII_TG3_DSP_EXP75, phy); phy = ((otp & <API key>) >> <API key>); tg3_phydsp_write(tp, MII_TG3_DSP_EXP96, phy); phy = ((otp & TG3_OTP_ROFF_MASK) >> TG3_OTP_ROFF_SHIFT) | ((otp & TG3_OTP_RCOFF_MASK) >> TG3_OTP_RCOFF_SHIFT); tg3_phydsp_write(tp, MII_TG3_DSP_EXP97, phy); <API key>(tp, false); } static void tg3_eee_pull_config(struct tg3 *tp, struct ethtool_eee *eee) { u32 val; struct ethtool_eee *dest = &tp->eee; if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) return; if (eee) dest = eee; if (tg3_phy_cl45_read(tp, MDIO_MMD_AN, <API key>, &val)) return; /* Pull eee_active */ if (val == <API key> || val == <API key>) { dest->eee_active = 1; } else dest->eee_active = 0; /* Pull lp advertised settings */ if (tg3_phy_cl45_read(tp, MDIO_MMD_AN, MDIO_AN_EEE_LPABLE, &val)) return; dest->lp_advertised = <API key>(val); /* Pull advertised and eee_enabled settings */ if (tg3_phy_cl45_read(tp, MDIO_MMD_AN, MDIO_AN_EEE_ADV, &val)) return; dest->eee_enabled = !!val; dest->advertised = <API key>(val); /* Pull tx_lpi_enabled */ val = tr32(TG3_CPMU_EEE_MODE); dest->tx_lpi_enabled = !!(val & <API key>); /* Pull lpi timer value */ dest->tx_lpi_timer = tr32(TG3_CPMU_EEE_DBTMR1) & 0xffff; } static void tg3_phy_eee_adjust(struct tg3 *tp, bool current_link_up) { u32 val; if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) return; tp->setlpicnt = 0; if (tp->link_config.autoneg == AUTONEG_ENABLE && current_link_up && tp->link_config.active_duplex == DUPLEX_FULL && (tp->link_config.active_speed == SPEED_100 || tp->link_config.active_speed == SPEED_1000)) { u32 eeectl; if (tp->link_config.active_speed == SPEED_1000) eeectl = <API key>; else eeectl = <API key>; tw32(TG3_CPMU_EEE_CTRL, eeectl); tg3_eee_pull_config(tp, NULL); if (tp->eee.eee_active) tp->setlpicnt = 2; } if (!tp->setlpicnt) { if (current_link_up && !<API key>(tp, true)) { tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, 0x0000); <API key>(tp, false); } val = tr32(TG3_CPMU_EEE_MODE); tw32(TG3_CPMU_EEE_MODE, val & ~<API key>); } } static void tg3_phy_eee_enable(struct tg3 *tp) { u32 val; if (tp->link_config.active_speed == SPEED_1000 && (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_flag(tp, 57765_CLASS)) && !<API key>(tp, true)) { val = <API key> | <API key>; tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, val); <API key>(tp, false); } val = tr32(TG3_CPMU_EEE_MODE); tw32(TG3_CPMU_EEE_MODE, val | <API key>); } static int tg3_wait_macro_done(struct tg3 *tp) { int limit = 100; while (limit u32 tmp32; if (!tg3_readphy(tp, MII_TG3_DSP_CONTROL, &tmp32)) { if ((tmp32 & 0x1000) == 0) break; } } if (limit < 0) return -EBUSY; return 0; } static int <API key>(struct tg3 *tp, int *resetp) { static const u32 test_pat[4][6] = { { 0x00005555, 0x00000005, 0x00002aaa, 0x0000000a, 0x00003456, 0x00000003 }, { 0x00002aaa, 0x0000000a, 0x00003333, 0x00000003, 0x0000789a, 0x00000005 }, { 0x00005a5a, 0x00000005, 0x00002a6a, 0x0000000a, 0x00001bcd, 0x00000003 }, { 0x00002a5a, 0x0000000a, 0x000033c3, 0x00000003, 0x00002ef1, 0x00000005 } }; int chan; for (chan = 0; chan < 4; chan++) { int i; tg3_writephy(tp, MII_TG3_DSP_ADDRESS, (chan * 0x2000) | 0x0200); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0002); for (i = 0; i < 6; i++) tg3_writephy(tp, MII_TG3_DSP_RW_PORT, test_pat[chan][i]); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0202); if (tg3_wait_macro_done(tp)) { *resetp = 1; return -EBUSY; } tg3_writephy(tp, MII_TG3_DSP_ADDRESS, (chan * 0x2000) | 0x0200); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0082); if (tg3_wait_macro_done(tp)) { *resetp = 1; return -EBUSY; } tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0802); if (tg3_wait_macro_done(tp)) { *resetp = 1; return -EBUSY; } for (i = 0; i < 6; i += 2) { u32 low, high; if (tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &low) || tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &high) || tg3_wait_macro_done(tp)) { *resetp = 1; return -EBUSY; } low &= 0x7fff; high &= 0x000f; if (low != test_pat[chan][i] || high != test_pat[chan][i+1]) { tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x000b); tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x4001); tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x4005); return -EBUSY; } } } return 0; } static int <API key>(struct tg3 *tp) { int chan; for (chan = 0; chan < 4; chan++) { int i; tg3_writephy(tp, MII_TG3_DSP_ADDRESS, (chan * 0x2000) | 0x0200); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0002); for (i = 0; i < 6; i++) tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x000); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0202); if (tg3_wait_macro_done(tp)) return -EBUSY; } return 0; } static int <API key>(struct tg3 *tp) { u32 reg32, phy9_orig; int retries, do_phy_reset, err; retries = 10; do_phy_reset = 1; do { if (do_phy_reset) { err = tg3_bmcr_reset(tp); if (err) return err; do_phy_reset = 0; } /* Disable transmitter and interrupt. */ if (tg3_readphy(tp, MII_TG3_EXT_CTRL, &reg32)) continue; reg32 |= 0x3000; tg3_writephy(tp, MII_TG3_EXT_CTRL, reg32); /* Set full-duplex, 1000 mbps. */ tg3_writephy(tp, MII_BMCR, BMCR_FULLDPLX | BMCR_SPEED1000); /* Set to master mode. */ if (tg3_readphy(tp, MII_CTRL1000, &phy9_orig)) continue; tg3_writephy(tp, MII_CTRL1000, CTL1000_AS_MASTER | <API key>); err = <API key>(tp, true); if (err) return err; /* Block the PHY control access. */ tg3_phydsp_write(tp, 0x8005, 0x0800); err = <API key>(tp, &do_phy_reset); if (!err) break; } while (--retries); err = <API key>(tp); if (err) return err; tg3_phydsp_write(tp, 0x8005, 0x0000); tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x8200); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0000); <API key>(tp, false); tg3_writephy(tp, MII_CTRL1000, phy9_orig); err = tg3_readphy(tp, MII_TG3_EXT_CTRL, &reg32); if (err) return err; reg32 &= ~0x3000; tg3_writephy(tp, MII_TG3_EXT_CTRL, reg32); return 0; } static void tg3_carrier_off(struct tg3 *tp) { netif_carrier_off(tp->dev); tp->link_up = false; } static void <API key>(struct tg3 *tp) { if (tg3_flag(tp, ENABLE_ASF)) netdev_warn(tp->dev, "Management side-band traffic will be interrupted during phy settings change\n"); } /* This will reset the tigon3 PHY if there is no valid * link unless the FORCE argument is non-zero. */ static int tg3_phy_reset(struct tg3 *tp) { u32 val, cpmuctrl; int err; if (tg3_asic_rev(tp) == ASIC_REV_5906) { val = tr32(GRC_MISC_CFG); tw32_f(GRC_MISC_CFG, val & ~<API key>); udelay(40); } err = tg3_readphy(tp, MII_BMSR, &val); err |= tg3_readphy(tp, MII_BMSR, &val); if (err != 0) return -EBUSY; if (netif_running(tp->dev) && tp->link_up) { netif_carrier_off(tp->dev); tg3_link_report(tp); } if (tg3_asic_rev(tp) == ASIC_REV_5703 || tg3_asic_rev(tp) == ASIC_REV_5704 || tg3_asic_rev(tp) == ASIC_REV_5705) { err = <API key>(tp); if (err) return err; goto out; } cpmuctrl = 0; if (tg3_asic_rev(tp) == ASIC_REV_5784 && tg3_chip_rev(tp) != CHIPREV_5784_AX) { cpmuctrl = tr32(TG3_CPMU_CTRL); if (cpmuctrl & <API key>) tw32(TG3_CPMU_CTRL, cpmuctrl & ~<API key>); } err = tg3_bmcr_reset(tp); if (err) return err; if (cpmuctrl & <API key>) { val = <API key> | <API key>; tg3_phydsp_write(tp, MII_TG3_DSP_EXP8, val); tw32(TG3_CPMU_CTRL, cpmuctrl); } if (tg3_chip_rev(tp) == CHIPREV_5784_AX || tg3_chip_rev(tp) == CHIPREV_5761_AX) { val = tr32(<API key>); if ((val & <API key>) == <API key>) { val &= ~<API key>; udelay(40); tw32_f(<API key>, val); } } if (tg3_flag(tp, 5717_PLUS) && (tp->phy_flags & <API key>)) return 0; tg3_phy_apply_otp(tp); if (tp->phy_flags & <API key>) tg3_phy_toggle_apd(tp, true); else tg3_phy_toggle_apd(tp, false); out: if ((tp->phy_flags & TG3_PHYFLG_ADC_BUG) && !<API key>(tp, true)) { tg3_phydsp_write(tp, 0x201f, 0x2aaa); tg3_phydsp_write(tp, 0x000a, 0x0323); <API key>(tp, false); } if (tp->phy_flags & <API key>) { tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68); tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68); } if (tp->phy_flags & TG3_PHYFLG_BER_BUG) { if (!<API key>(tp, true)) { tg3_phydsp_write(tp, 0x000a, 0x310b); tg3_phydsp_write(tp, 0x201f, 0x9506); tg3_phydsp_write(tp, 0x401f, 0x14e2); <API key>(tp, false); } } else if (tp->phy_flags & <API key>) { if (!<API key>(tp, true)) { tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x000a); if (tp->phy_flags & <API key>) { tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x110b); tg3_writephy(tp, MII_TG3_TEST1, <API key> | 0x4); } else tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x010b); <API key>(tp, false); } } /* Set Extended packet length bit (bit 14) on all chips that */ /* support jumbo frames */ if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) { /* Cannot do read-modify-write on 5401 */ <API key>(tp, <API key>, 0x4c20); } else if (tg3_flag(tp, JUMBO_CAPABLE)) { /* Set bit 14 with read-modify-write to preserve other bits */ err = tg3_phy_auxctl_read(tp, <API key>, &val); if (!err) <API key>(tp, <API key>, val | <API key>); } /* Set phy register 0x10 bit 0 to high fifo elasticity to support * jumbo frames transmission. */ if (tg3_flag(tp, JUMBO_CAPABLE)) { if (!tg3_readphy(tp, MII_TG3_EXT_CTRL, &val)) tg3_writephy(tp, MII_TG3_EXT_CTRL, val | <API key>); } if (tg3_asic_rev(tp) == ASIC_REV_5906) { /* adjust output voltage */ tg3_writephy(tp, MII_TG3_FET_PTEST, 0x12); } if (tg3_chip_rev_id(tp) == CHIPREV_ID_5762_A0) tg3_phydsp_write(tp, 0xffb, 0x4000); <API key>(tp, true); <API key>(tp); return 0; } #define <API key> 0x00000001 #define <API key> 0x00000002 #define TG3_GPIO_MSG_MASK (<API key> | \ <API key>) #define <API key> \ ((<API key> << 0) | \ (<API key> << 4) | \ (<API key> << 8) | \ (<API key> << 12)) #define <API key> \ ((<API key> << 0) | \ (<API key> << 4) | \ (<API key> << 8) | \ (<API key> << 12)) static inline u32 <API key>(struct tg3 *tp, u32 newstat) { u32 status, shift; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719) status = tg3_ape_read32(tp, TG3_APE_GPIO_MSG); else status = tr32(TG3_CPMU_DRV_STATUS); shift = <API key> + 4 * tp->pci_fn; status &= ~(TG3_GPIO_MSG_MASK << shift); status |= (newstat << shift); if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719) tg3_ape_write32(tp, TG3_APE_GPIO_MSG, status); else tw32(TG3_CPMU_DRV_STATUS, status); return status >> <API key>; } static inline int <API key>(struct tg3 *tp) { if (!tg3_flag(tp, IS_NIC)) return 0; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) { if (tg3_ape_lock(tp, TG3_APE_LOCK_GPIO)) return -EIO; <API key>(tp, <API key>); tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl, <API key>); tg3_ape_unlock(tp, TG3_APE_LOCK_GPIO); } else { tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl, <API key>); } return 0; } static void <API key>(struct tg3 *tp) { u32 grc_local_ctrl; if (!tg3_flag(tp, IS_NIC) || tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) return; grc_local_ctrl = tp->grc_local_ctrl | <API key>; tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl | <API key>, <API key>); tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl, <API key>); tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl | <API key>, <API key>); } static void <API key>(struct tg3 *tp) { if (!tg3_flag(tp, IS_NIC)) return; if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) { tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl | (<API key> | <API key> | <API key> | <API key> | <API key>), <API key>); } else if (tp->pdev->device == <API key> || tp->pdev->device == <API key>) { /* The 5761 non-e device swaps GPIO 0 and GPIO 2. */ u32 grc_local_ctrl = <API key> | <API key> | <API key> | <API key> | <API key> | tp->grc_local_ctrl; tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl, <API key>); grc_local_ctrl |= <API key>; tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl, <API key>); grc_local_ctrl &= ~<API key>; tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl, <API key>); } else { u32 no_gpio2; u32 grc_local_ctrl = 0; /* Workaround to prevent overdrawing Amps. */ if (tg3_asic_rev(tp) == ASIC_REV_5714) { grc_local_ctrl |= <API key>; tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl | grc_local_ctrl, <API key>); } /* On 5753 and variants, GPIO2 cannot be used. */ no_gpio2 = tp->nic_sram_data_cfg & <API key>; grc_local_ctrl |= <API key> | <API key> | <API key> | <API key> | <API key>; if (no_gpio2) { grc_local_ctrl &= ~(<API key> | <API key>); } tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl | grc_local_ctrl, <API key>); grc_local_ctrl |= <API key>; tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl | grc_local_ctrl, <API key>); if (!no_gpio2) { grc_local_ctrl &= ~<API key>; tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl | grc_local_ctrl, <API key>); } } } static void <API key>(struct tg3 *tp, bool wol_enable) { u32 msg = 0; /* Serialize power state transitions */ if (tg3_ape_lock(tp, TG3_APE_LOCK_GPIO)) return; if (tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE) || wol_enable) msg = <API key>; msg = <API key>(tp, msg); if (msg & <API key>) goto done; if (msg & <API key>) <API key>(tp); else <API key>(tp); done: tg3_ape_unlock(tp, TG3_APE_LOCK_GPIO); } static void tg3_frob_aux_power(struct tg3 *tp, bool include_wol) { bool need_vaux = false; /* The GPIOs do something completely different on 57765. */ if (!tg3_flag(tp, IS_NIC) || tg3_flag(tp, 57765_CLASS)) return; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) { <API key>(tp, include_wol ? tg3_flag(tp, WOL_ENABLE) != 0 : 0); return; } if (tp->pdev_peer && tp->pdev_peer != tp->pdev) { struct net_device *dev_peer; dev_peer = pci_get_drvdata(tp->pdev_peer); /* remove_one() may have been run on the peer. */ if (dev_peer) { struct tg3 *tp_peer = netdev_priv(dev_peer); if (tg3_flag(tp_peer, INIT_COMPLETE)) return; if ((include_wol && tg3_flag(tp_peer, WOL_ENABLE)) || tg3_flag(tp_peer, ENABLE_ASF)) need_vaux = true; } } if ((include_wol && tg3_flag(tp, WOL_ENABLE)) || tg3_flag(tp, ENABLE_ASF)) need_vaux = true; if (need_vaux) <API key>(tp); else <API key>(tp); } static int <API key>(struct tg3 *tp, u32 speed) { if (tp->led_ctrl == LED_CTRL_MODE_PHY_2) return 1; else if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5411) { if (speed != SPEED_10) return 1; } else if (speed == SPEED_10) return 1; return 0; } static bool tg3_phy_power_bug(struct tg3 *tp) { switch (tg3_asic_rev(tp)) { case ASIC_REV_5700: case ASIC_REV_5704: return true; case ASIC_REV_5780: if (tp->phy_flags & <API key>) return true; return false; case ASIC_REV_5717: if (!tp->pci_fn) return true; return false; case ASIC_REV_5719: case ASIC_REV_5720: if ((tp->phy_flags & <API key>) && !tp->pci_fn) return true; return false; } return false; } static bool tg3_phy_led_bug(struct tg3 *tp) { switch (tg3_asic_rev(tp)) { case ASIC_REV_5719: case ASIC_REV_5720: if ((tp->phy_flags & <API key>) && !tp->pci_fn) return true; return false; } return false; } static void tg3_power_down_phy(struct tg3 *tp, bool do_low_power) { u32 val; if (tp->phy_flags & <API key>) return; if (tp->phy_flags & <API key>) { if (tg3_asic_rev(tp) == ASIC_REV_5704) { u32 sg_dig_ctrl = tr32(SG_DIG_CTRL); u32 serdes_cfg = tr32(MAC_SERDES_CFG); sg_dig_ctrl |= <API key> | SG_DIG_SOFT_RESET; tw32(SG_DIG_CTRL, sg_dig_ctrl); tw32(MAC_SERDES_CFG, serdes_cfg | (1 << 15)); } return; } if (tg3_asic_rev(tp) == ASIC_REV_5906) { tg3_bmcr_reset(tp); val = tr32(GRC_MISC_CFG); tw32_f(GRC_MISC_CFG, val | <API key>); udelay(40); return; } else if (tp->phy_flags & TG3_PHYFLG_IS_FET) { u32 phytest; if (!tg3_readphy(tp, MII_TG3_FET_TEST, &phytest)) { u32 phy; tg3_writephy(tp, MII_ADVERTISE, 0); tg3_writephy(tp, MII_BMCR, BMCR_ANENABLE | BMCR_ANRESTART); tg3_writephy(tp, MII_TG3_FET_TEST, phytest | <API key>); if (!tg3_readphy(tp, <API key>, &phy)) { phy |= <API key>; tg3_writephy(tp, <API key>, phy); } tg3_writephy(tp, MII_TG3_FET_TEST, phytest); } return; } else if (do_low_power) { if (!tg3_phy_led_bug(tp)) tg3_writephy(tp, MII_TG3_EXT_CTRL, <API key>); val = <API key> | <API key> | <API key>; <API key>(tp, <API key>, val); } /* The PHY should not be powered down on some chips because * of bugs. */ if (tg3_phy_power_bug(tp)) return; if (tg3_chip_rev(tp) == CHIPREV_5784_AX || tg3_chip_rev(tp) == CHIPREV_5761_AX) { val = tr32(<API key>); val &= ~<API key>; val |= <API key>; tw32_f(<API key>, val); } tg3_writephy(tp, MII_BMCR, BMCR_PDOWN); } /* tp->lock is held. */ static int tg3_nvram_lock(struct tg3 *tp) { if (tg3_flag(tp, NVRAM)) { int i; if (tp->nvram_lock_cnt == 0) { tw32(NVRAM_SWARB, SWARB_REQ_SET1); for (i = 0; i < 8000; i++) { if (tr32(NVRAM_SWARB) & SWARB_GNT1) break; udelay(20); } if (i == 8000) { tw32(NVRAM_SWARB, SWARB_REQ_CLR1); return -ENODEV; } } tp->nvram_lock_cnt++; } return 0; } /* tp->lock is held. */ static void tg3_nvram_unlock(struct tg3 *tp) { if (tg3_flag(tp, NVRAM)) { if (tp->nvram_lock_cnt > 0) tp->nvram_lock_cnt if (tp->nvram_lock_cnt == 0) tw32_f(NVRAM_SWARB, SWARB_REQ_CLR1); } } /* tp->lock is held. */ static void <API key>(struct tg3 *tp) { if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM)) { u32 nvaccess = tr32(NVRAM_ACCESS); tw32(NVRAM_ACCESS, nvaccess | ACCESS_ENABLE); } } /* tp->lock is held. */ static void <API key>(struct tg3 *tp) { if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM)) { u32 nvaccess = tr32(NVRAM_ACCESS); tw32(NVRAM_ACCESS, nvaccess & ~ACCESS_ENABLE); } } static int <API key>(struct tg3 *tp, u32 offset, u32 *val) { u32 tmp; int i; if (offset > <API key> || (offset % 4) != 0) return -EINVAL; tmp = tr32(GRC_EEPROM_ADDR) & ~(<API key> | <API key> | EEPROM_ADDR_READ); tw32(GRC_EEPROM_ADDR, tmp | (0 << <API key>) | ((offset << <API key>) & <API key>) | EEPROM_ADDR_READ | EEPROM_ADDR_START); for (i = 0; i < 1000; i++) { tmp = tr32(GRC_EEPROM_ADDR); if (tmp & <API key>) break; msleep(1); } if (!(tmp & <API key>)) return -EBUSY; tmp = tr32(GRC_EEPROM_DATA); /* * The data will always be opposite the native endian * format. Perform a blind byteswap to compensate. */ *val = swab32(tmp); return 0; } #define NVRAM_CMD_TIMEOUT 100 static int tg3_nvram_exec_cmd(struct tg3 *tp, u32 nvram_cmd) { int i; tw32(NVRAM_CMD, nvram_cmd); for (i = 0; i < NVRAM_CMD_TIMEOUT; i++) { udelay(10); if (tr32(NVRAM_CMD) & NVRAM_CMD_DONE) { udelay(10); break; } } if (i == NVRAM_CMD_TIMEOUT) return -EBUSY; return 0; } static u32 tg3_nvram_phys_addr(struct tg3 *tp, u32 addr) { if (tg3_flag(tp, NVRAM) && tg3_flag(tp, NVRAM_BUFFERED) && tg3_flag(tp, FLASH) && !tg3_flag(tp, NO_NVRAM_ADDR_TRANS) && (tp->nvram_jedecnum == JEDEC_ATMEL)) addr = ((addr / tp->nvram_pagesize) << <API key>) + (addr % tp->nvram_pagesize); return addr; } static u32 <API key>(struct tg3 *tp, u32 addr) { if (tg3_flag(tp, NVRAM) && tg3_flag(tp, NVRAM_BUFFERED) && tg3_flag(tp, FLASH) && !tg3_flag(tp, NO_NVRAM_ADDR_TRANS) && (tp->nvram_jedecnum == JEDEC_ATMEL)) addr = ((addr >> <API key>) * tp->nvram_pagesize) + (addr & ((1 << <API key>) - 1)); return addr; } /* NOTE: Data read in from NVRAM is byteswapped according to * the byteswapping settings for all other register accesses. * tg3 devices are BE devices, so on a BE machine, the data * returned will be exactly as it is seen in NVRAM. On a LE * machine, the 32-bit value will be byteswapped. */ static int tg3_nvram_read(struct tg3 *tp, u32 offset, u32 *val) { int ret; if (!tg3_flag(tp, NVRAM)) return <API key>(tp, offset, val); offset = tg3_nvram_phys_addr(tp, offset); if (offset > NVRAM_ADDR_MSK) return -EINVAL; ret = tg3_nvram_lock(tp); if (ret) return ret; <API key>(tp); tw32(NVRAM_ADDR, offset); ret = tg3_nvram_exec_cmd(tp, NVRAM_CMD_RD | NVRAM_CMD_GO | NVRAM_CMD_FIRST | NVRAM_CMD_LAST | NVRAM_CMD_DONE); if (ret == 0) *val = tr32(NVRAM_RDDATA); <API key>(tp); tg3_nvram_unlock(tp); return ret; } /* Ensures NVRAM data is in bytestream format. */ static int tg3_nvram_read_be32(struct tg3 *tp, u32 offset, __be32 *val) { u32 v; int res = tg3_nvram_read(tp, offset, &v); if (!res) *val = cpu_to_be32(v); return res; } static int <API key>(struct tg3 *tp, u32 offset, u32 len, u8 *buf) { int i, j, rc = 0; u32 val; for (i = 0; i < len; i += 4) { u32 addr; __be32 data; addr = offset + i; memcpy(&data, buf + i, 4); /* * The SEEPROM interface expects the data to always be opposite * the native endian format. We accomplish this by reversing * all the operations that would have been performed on the * data from a call to tg3_nvram_read_be32(). */ tw32(GRC_EEPROM_DATA, swab32(be32_to_cpu(data))); val = tr32(GRC_EEPROM_ADDR); tw32(GRC_EEPROM_ADDR, val | <API key>); val &= ~(<API key> | <API key> | EEPROM_ADDR_READ); tw32(GRC_EEPROM_ADDR, val | (0 << <API key>) | (addr & <API key>) | EEPROM_ADDR_START | EEPROM_ADDR_WRITE); for (j = 0; j < 1000; j++) { val = tr32(GRC_EEPROM_ADDR); if (val & <API key>) break; msleep(1); } if (!(val & <API key>)) { rc = -EBUSY; break; } } return rc; } /* offset and length are dword aligned */ static int <API key>(struct tg3 *tp, u32 offset, u32 len, u8 *buf) { int ret = 0; u32 pagesize = tp->nvram_pagesize; u32 pagemask = pagesize - 1; u32 nvram_cmd; u8 *tmp; tmp = kmalloc(pagesize, GFP_KERNEL); if (tmp == NULL) return -ENOMEM; while (len) { int j; u32 phy_addr, page_off, size; phy_addr = offset & ~pagemask; for (j = 0; j < pagesize; j += 4) { ret = tg3_nvram_read_be32(tp, phy_addr + j, (__be32 *) (tmp + j)); if (ret) break; } if (ret) break; page_off = offset & pagemask; size = pagesize; if (len < size) size = len; len -= size; memcpy(tmp + page_off, buf, size); offset = offset + (pagesize - page_off); <API key>(tp); /* * Before we can erase the flash page, we need * to issue a special "write enable" command. */ nvram_cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE; if (tg3_nvram_exec_cmd(tp, nvram_cmd)) break; /* Erase the target page */ tw32(NVRAM_ADDR, phy_addr); nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE | NVRAM_CMD_WR | NVRAM_CMD_FIRST | NVRAM_CMD_LAST | NVRAM_CMD_ERASE; if (tg3_nvram_exec_cmd(tp, nvram_cmd)) break; /* Issue another write enable to start the write. */ nvram_cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE; if (tg3_nvram_exec_cmd(tp, nvram_cmd)) break; for (j = 0; j < pagesize; j += 4) { __be32 data; data = *((__be32 *) (tmp + j)); tw32(NVRAM_WRDATA, be32_to_cpu(data)); tw32(NVRAM_ADDR, phy_addr + j); nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE | NVRAM_CMD_WR; if (j == 0) nvram_cmd |= NVRAM_CMD_FIRST; else if (j == (pagesize - 4)) nvram_cmd |= NVRAM_CMD_LAST; ret = tg3_nvram_exec_cmd(tp, nvram_cmd); if (ret) break; } if (ret) break; } nvram_cmd = NVRAM_CMD_WRDI | NVRAM_CMD_GO | NVRAM_CMD_DONE; tg3_nvram_exec_cmd(tp, nvram_cmd); kfree(tmp); return ret; } /* offset and length are dword aligned */ static int <API key>(struct tg3 *tp, u32 offset, u32 len, u8 *buf) { int i, ret = 0; for (i = 0; i < len; i += 4, offset += 4) { u32 page_off, phy_addr, nvram_cmd; __be32 data; memcpy(&data, buf + i, 4); tw32(NVRAM_WRDATA, be32_to_cpu(data)); page_off = offset % tp->nvram_pagesize; phy_addr = tg3_nvram_phys_addr(tp, offset); nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE | NVRAM_CMD_WR; if (page_off == 0 || i == 0) nvram_cmd |= NVRAM_CMD_FIRST; if (page_off == (tp->nvram_pagesize - 4)) nvram_cmd |= NVRAM_CMD_LAST; if (i == (len - 4)) nvram_cmd |= NVRAM_CMD_LAST; if ((nvram_cmd & NVRAM_CMD_FIRST) || !tg3_flag(tp, FLASH) || !tg3_flag(tp, 57765_PLUS)) tw32(NVRAM_ADDR, phy_addr); if (tg3_asic_rev(tp) != ASIC_REV_5752 && !tg3_flag(tp, 5755_PLUS) && (tp->nvram_jedecnum == JEDEC_ST) && (nvram_cmd & NVRAM_CMD_FIRST)) { u32 cmd; cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE; ret = tg3_nvram_exec_cmd(tp, cmd); if (ret) break; } if (!tg3_flag(tp, FLASH)) { /* We always do complete word writes to eeprom. */ nvram_cmd |= (NVRAM_CMD_FIRST | NVRAM_CMD_LAST); } ret = tg3_nvram_exec_cmd(tp, nvram_cmd); if (ret) break; } return ret; } /* offset and length are dword aligned */ static int <API key>(struct tg3 *tp, u32 offset, u32 len, u8 *buf) { int ret; if (tg3_flag(tp, EEPROM_WRITE_PROT)) { tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl & ~<API key>); udelay(40); } if (!tg3_flag(tp, NVRAM)) { ret = <API key>(tp, offset, len, buf); } else { u32 grc_mode; ret = tg3_nvram_lock(tp); if (ret) return ret; <API key>(tp); if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM)) tw32(NVRAM_WRITE1, 0x406); grc_mode = tr32(GRC_MODE); tw32(GRC_MODE, grc_mode | <API key>); if (tg3_flag(tp, NVRAM_BUFFERED) || !tg3_flag(tp, FLASH)) { ret = <API key>(tp, offset, len, buf); } else { ret = <API key>(tp, offset, len, buf); } grc_mode = tr32(GRC_MODE); tw32(GRC_MODE, grc_mode & ~<API key>); <API key>(tp); tg3_nvram_unlock(tp); } if (tg3_flag(tp, EEPROM_WRITE_PROT)) { tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl); udelay(40); } return ret; } #define RX_CPU_SCRATCH_BASE 0x30000 #define RX_CPU_SCRATCH_SIZE 0x04000 #define TX_CPU_SCRATCH_BASE 0x34000 #define TX_CPU_SCRATCH_SIZE 0x04000 /* tp->lock is held. */ static int tg3_pause_cpu(struct tg3 *tp, u32 cpu_base) { int i; const int iters = 10000; for (i = 0; i < iters; i++) { tw32(cpu_base + CPU_STATE, 0xffffffff); tw32(cpu_base + CPU_MODE, CPU_MODE_HALT); if (tr32(cpu_base + CPU_MODE) & CPU_MODE_HALT) break; if (pci_channel_offline(tp->pdev)) return -EBUSY; } return (i == iters) ? -EBUSY : 0; } /* tp->lock is held. */ static int tg3_rxcpu_pause(struct tg3 *tp) { int rc = tg3_pause_cpu(tp, RX_CPU_BASE); tw32(RX_CPU_BASE + CPU_STATE, 0xffffffff); tw32_f(RX_CPU_BASE + CPU_MODE, CPU_MODE_HALT); udelay(10); return rc; } /* tp->lock is held. */ static int tg3_txcpu_pause(struct tg3 *tp) { return tg3_pause_cpu(tp, TX_CPU_BASE); } /* tp->lock is held. */ static void tg3_resume_cpu(struct tg3 *tp, u32 cpu_base) { tw32(cpu_base + CPU_STATE, 0xffffffff); tw32_f(cpu_base + CPU_MODE, 0x00000000); } /* tp->lock is held. */ static void tg3_rxcpu_resume(struct tg3 *tp) { tg3_resume_cpu(tp, RX_CPU_BASE); } /* tp->lock is held. */ static int tg3_halt_cpu(struct tg3 *tp, u32 cpu_base) { int rc; BUG_ON(cpu_base == TX_CPU_BASE && tg3_flag(tp, 5705_PLUS)); if (tg3_asic_rev(tp) == ASIC_REV_5906) { u32 val = tr32(GRC_VCPU_EXT_CTRL); tw32(GRC_VCPU_EXT_CTRL, val | <API key>); return 0; } if (cpu_base == RX_CPU_BASE) { rc = tg3_rxcpu_pause(tp); } else { /* * There is only an Rx CPU for the 5750 derivative in the * BCM4785. */ if (tg3_flag(tp, IS_SSB_CORE)) return 0; rc = tg3_txcpu_pause(tp); } if (rc) { netdev_err(tp->dev, "%s timed out, %s CPU\n", __func__, cpu_base == RX_CPU_BASE ? "RX" : "TX"); return -ENODEV; } /* Clear firmware's nvram arbitration. */ if (tg3_flag(tp, NVRAM)) tw32(NVRAM_SWARB, SWARB_REQ_CLR0); return 0; } static int tg3_fw_data_len(struct tg3 *tp, const struct tg3_firmware_hdr *fw_hdr) { int fw_len; /* Non fragmented firmware have one firmware header followed by a * contiguous chunk of data to be written. The length field in that * header is not the length of data to be written but the complete * length of the bss. The data length is determined based on * tp->fw->size minus headers. * * Fragmented firmware have a main header followed by multiple * fragments. Each fragment is identical to non fragmented firmware * with a firmware header followed by a contiguous chunk of data. In * the main header, the length field is unused and set to 0xffffffff. * In each fragment header the length is the entire size of that * fragment i.e. fragment data + header length. Data length is * therefore length field in the header minus TG3_FW_HDR_LEN. */ if (tp->fw_len == 0xffffffff) fw_len = be32_to_cpu(fw_hdr->len); else fw_len = tp->fw->size; return (fw_len - TG3_FW_HDR_LEN) / sizeof(u32); } /* tp->lock is held. */ static int <API key>(struct tg3 *tp, u32 cpu_base, u32 cpu_scratch_base, int cpu_scratch_size, const struct tg3_firmware_hdr *fw_hdr) { int err, i; void (*write_op)(struct tg3 *, u32, u32); int total_len = tp->fw->size; if (cpu_base == TX_CPU_BASE && tg3_flag(tp, 5705_PLUS)) { netdev_err(tp->dev, "%s: Trying to load TX cpu firmware which is 5705\n", __func__); return -EINVAL; } if (tg3_flag(tp, 5705_PLUS) && tg3_asic_rev(tp) != ASIC_REV_57766) write_op = tg3_write_mem; else write_op = <API key>; if (tg3_asic_rev(tp) != ASIC_REV_57766) { /* It is possible that bootcode is still loading at this point. * Get the nvram lock first before halting the cpu. */ int lock_err = tg3_nvram_lock(tp); err = tg3_halt_cpu(tp, cpu_base); if (!lock_err) tg3_nvram_unlock(tp); if (err) goto out; for (i = 0; i < cpu_scratch_size; i += sizeof(u32)) write_op(tp, cpu_scratch_base + i, 0); tw32(cpu_base + CPU_STATE, 0xffffffff); tw32(cpu_base + CPU_MODE, tr32(cpu_base + CPU_MODE) | CPU_MODE_HALT); } else { /* Subtract additional main header for fragmented firmware and * advance to the first fragment */ total_len -= TG3_FW_HDR_LEN; fw_hdr++; } do { u32 *fw_data = (u32 *)(fw_hdr + 1); for (i = 0; i < tg3_fw_data_len(tp, fw_hdr); i++) write_op(tp, cpu_scratch_base + (be32_to_cpu(fw_hdr->base_addr) & 0xffff) + (i * sizeof(u32)), be32_to_cpu(fw_data[i])); total_len -= be32_to_cpu(fw_hdr->len); /* Advance to next fragment */ fw_hdr = (struct tg3_firmware_hdr *) ((void *)fw_hdr + be32_to_cpu(fw_hdr->len)); } while (total_len > 0); err = 0; out: return err; } /* tp->lock is held. */ static int <API key>(struct tg3 *tp, u32 cpu_base, u32 pc) { int i; const int iters = 5; tw32(cpu_base + CPU_STATE, 0xffffffff); tw32_f(cpu_base + CPU_PC, pc); for (i = 0; i < iters; i++) { if (tr32(cpu_base + CPU_PC) == pc) break; tw32(cpu_base + CPU_STATE, 0xffffffff); tw32(cpu_base + CPU_MODE, CPU_MODE_HALT); tw32_f(cpu_base + CPU_PC, pc); udelay(1000); } return (i == iters) ? -EBUSY : 0; } /* tp->lock is held. */ static int <API key>(struct tg3 *tp) { const struct tg3_firmware_hdr *fw_hdr; int err; fw_hdr = (struct tg3_firmware_hdr *)tp->fw->data; /* Firmware blob starts with version numbers, followed by start address and length. We are setting complete length. length = end_address_of_bss - <API key>. Remainder is the blob to be loaded contiguously from start address. */ err = <API key>(tp, RX_CPU_BASE, RX_CPU_SCRATCH_BASE, RX_CPU_SCRATCH_SIZE, fw_hdr); if (err) return err; err = <API key>(tp, TX_CPU_BASE, TX_CPU_SCRATCH_BASE, TX_CPU_SCRATCH_SIZE, fw_hdr); if (err) return err; /* Now startup only the RX cpu. */ err = <API key>(tp, RX_CPU_BASE, be32_to_cpu(fw_hdr->base_addr)); if (err) { netdev_err(tp->dev, "%s fails to set RX CPU PC, is %08x " "should be %08x\n", __func__, tr32(RX_CPU_BASE + CPU_PC), be32_to_cpu(fw_hdr->base_addr)); return -ENODEV; } tg3_rxcpu_resume(tp); return 0; } static int <API key>(struct tg3 *tp) { const int iters = 1000; int i; u32 val; /* Wait for boot code to complete initialization and enter service * loop. It is then safe to download service patches */ for (i = 0; i < iters; i++) { if (tr32(RX_CPU_HWBKPT) == <API key>) break; udelay(10); } if (i == iters) { netdev_err(tp->dev, "Boot code not ready for service patches\n"); return -EBUSY; } val = <API key>(tp, <API key>); if (val & 0xff) { netdev_warn(tp->dev, "Other patches exist. Not downloading EEE patch\n"); return -EEXIST; } return 0; } /* tp->lock is held. */ static void <API key>(struct tg3 *tp) { struct tg3_firmware_hdr *fw_hdr; if (!tg3_flag(tp, NO_NVRAM)) return; if (<API key>(tp)) return; if (!tp->fw) return; /* This firmware blob has a different format than older firmware * releases as given below. The main difference is we have fragmented * data to be written to non-contiguous locations. * * In the beginning we have a firmware header identical to other * firmware which consists of version, base addr and length. The length * here is unused and set to 0xffffffff. * * This is followed by a series of firmware fragments which are * individually identical to previous firmware. i.e. they have the * firmware header and followed by data for that fragment. The version * field of the individual fragment header is unused. */ fw_hdr = (struct tg3_firmware_hdr *)tp->fw->data; if (be32_to_cpu(fw_hdr->base_addr) != <API key>) return; if (tg3_rxcpu_pause(tp)) return; /* <API key>() will always succeed for the 57766 */ <API key>(tp, 0, <API key>, 0, fw_hdr); tg3_rxcpu_resume(tp); } /* tp->lock is held. */ static int <API key>(struct tg3 *tp) { const struct tg3_firmware_hdr *fw_hdr; unsigned long cpu_base, cpu_scratch_base, cpu_scratch_size; int err; if (!tg3_flag(tp, FW_TSO)) return 0; fw_hdr = (struct tg3_firmware_hdr *)tp->fw->data; /* Firmware blob starts with version numbers, followed by start address and length. We are setting complete length. length = end_address_of_bss - <API key>. Remainder is the blob to be loaded contiguously from start address. */ cpu_scratch_size = tp->fw_len; if (tg3_asic_rev(tp) == ASIC_REV_5705) { cpu_base = RX_CPU_BASE; cpu_scratch_base = <API key>; } else { cpu_base = TX_CPU_BASE; cpu_scratch_base = TX_CPU_SCRATCH_BASE; cpu_scratch_size = TX_CPU_SCRATCH_SIZE; } err = <API key>(tp, cpu_base, cpu_scratch_base, cpu_scratch_size, fw_hdr); if (err) return err; /* Now startup the cpu. */ err = <API key>(tp, cpu_base, be32_to_cpu(fw_hdr->base_addr)); if (err) { netdev_err(tp->dev, "%s fails to set CPU PC, is %08x should be %08x\n", __func__, tr32(cpu_base + CPU_PC), be32_to_cpu(fw_hdr->base_addr)); return -ENODEV; } tg3_resume_cpu(tp, cpu_base); return 0; } /* tp->lock is held. */ static void <API key>(struct tg3 *tp, u8 *mac_addr, int index) { u32 addr_high, addr_low; addr_high = ((mac_addr[0] << 8) | mac_addr[1]); addr_low = ((mac_addr[2] << 24) | (mac_addr[3] << 16) | (mac_addr[4] << 8) | mac_addr[5]); if (index < 4) { tw32(MAC_ADDR_0_HIGH + (index * 8), addr_high); tw32(MAC_ADDR_0_LOW + (index * 8), addr_low); } else { index -= 4; tw32(MAC_EXTADDR_0_HIGH + (index * 8), addr_high); tw32(MAC_EXTADDR_0_LOW + (index * 8), addr_low); } } /* tp->lock is held. */ static void __tg3_set_mac_addr(struct tg3 *tp, bool skip_mac_1) { u32 addr_high; int i; for (i = 0; i < 4; i++) { if (i == 1 && skip_mac_1) continue; <API key>(tp, tp->dev->dev_addr, i); } if (tg3_asic_rev(tp) == ASIC_REV_5703 || tg3_asic_rev(tp) == ASIC_REV_5704) { for (i = 4; i < 16; i++) <API key>(tp, tp->dev->dev_addr, i); } addr_high = (tp->dev->dev_addr[0] + tp->dev->dev_addr[1] + tp->dev->dev_addr[2] + tp->dev->dev_addr[3] + tp->dev->dev_addr[4] + tp->dev->dev_addr[5]) & <API key>; tw32(MAC_TX_BACKOFF_SEED, addr_high); } static void <API key>(struct tg3 *tp) { /* * Make sure register accesses (indirect or otherwise) will function * correctly. */ <API key>(tp->pdev, <API key>, tp->misc_host_ctrl); } static int tg3_power_up(struct tg3 *tp) { int err; <API key>(tp); err = pci_set_power_state(tp->pdev, PCI_D0); if (!err) { /* Switch out of Vaux if it is a NIC */ <API key>(tp); } else { netdev_err(tp->dev, "Transition to D0 failed\n"); } return err; } static int tg3_setup_phy(struct tg3 *, bool); static int <API key>(struct tg3 *tp) { u32 misc_host_ctrl; bool device_should_wake, do_low_power; <API key>(tp); /* Restore the CLKREQ setting. */ if (tg3_flag(tp, CLKREQ_BUG)) <API key>(tp->pdev, PCI_EXP_LNKCTL, <API key>); misc_host_ctrl = tr32(<API key>); tw32(<API key>, misc_host_ctrl | <API key>); device_should_wake = device_may_wakeup(&tp->pdev->dev) && tg3_flag(tp, WOL_ENABLE); if (tg3_flag(tp, USE_PHYLIB)) { do_low_power = false; if ((tp->phy_flags & <API key>) && !(tp->phy_flags & <API key>)) { struct phy_device *phydev; u32 phyid, advertising; phydev = tp->mdio_bus->phy_map[tp->phy_addr]; tp->phy_flags |= <API key>; tp->link_config.speed = phydev->speed; tp->link_config.duplex = phydev->duplex; tp->link_config.autoneg = phydev->autoneg; tp->link_config.advertising = phydev->advertising; advertising = ADVERTISED_TP | ADVERTISED_Pause | ADVERTISED_Autoneg | <API key>; if (tg3_flag(tp, ENABLE_ASF) || device_should_wake) { if (tg3_flag(tp, WOL_SPEED_100MB)) advertising |= <API key> | <API key> | <API key>; else advertising |= <API key>; } phydev->advertising = advertising; phy_start_aneg(phydev); phyid = phydev->drv->phy_id & phydev->drv->phy_id_mask; if (phyid != PHY_ID_BCMAC131) { phyid &= PHY_BCM_OUI_MASK; if (phyid == PHY_BCM_OUI_1 || phyid == PHY_BCM_OUI_2 || phyid == PHY_BCM_OUI_3) do_low_power = true; } } } else { do_low_power = true; if (!(tp->phy_flags & <API key>)) tp->phy_flags |= <API key>; if (!(tp->phy_flags & <API key>)) tg3_setup_phy(tp, false); } if (tg3_asic_rev(tp) == ASIC_REV_5906) { u32 val; val = tr32(GRC_VCPU_EXT_CTRL); tw32(GRC_VCPU_EXT_CTRL, val | <API key>); } else if (!tg3_flag(tp, ENABLE_ASF)) { int i; u32 val; for (i = 0; i < 200; i++) { tg3_read_mem(tp, <API key>, &val); if (val == ~<API key>) break; msleep(1); } } if (tg3_flag(tp, WOL_CAP)) tg3_write_mem(tp, NIC_SRAM_WOL_MBOX, WOL_SIGNATURE | <API key> | WOL_DRV_WOL | WOL_SET_MAGIC_PKT); if (device_should_wake) { u32 mac_mode; if (!(tp->phy_flags & <API key>)) { if (do_low_power && !(tp->phy_flags & TG3_PHYFLG_IS_FET)) { <API key>(tp, <API key>, <API key> | <API key> | <API key>); udelay(40); } if (tp->phy_flags & <API key>) mac_mode = <API key>; else if (tp->phy_flags & <API key>) { if (tp->link_config.active_speed == SPEED_1000) mac_mode = <API key>; else mac_mode = <API key>; } else mac_mode = <API key>; mac_mode |= tp->mac_mode & <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5700) { u32 speed = tg3_flag(tp, WOL_SPEED_100MB) ? SPEED_100 : SPEED_10; if (<API key>(tp, speed)) mac_mode |= <API key>; else mac_mode &= ~<API key>; } } else { mac_mode = <API key>; } if (!tg3_flag(tp, 5750_PLUS)) tw32(MAC_LED_CTRL, tp->led_ctrl); mac_mode |= <API key>; if ((tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, 5780_CLASS)) && (tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE))) mac_mode |= <API key>; if (tg3_flag(tp, ENABLE_APE)) mac_mode |= MAC_MODE_APE_TX_EN | MAC_MODE_APE_RX_EN | MAC_MODE_TDE_ENABLE; tw32_f(MAC_MODE, mac_mode); udelay(100); tw32_f(MAC_RX_MODE, RX_MODE_ENABLE); udelay(10); } if (!tg3_flag(tp, WOL_SPEED_100MB) && (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701)) { u32 base_val; base_val = tp->pci_clock_ctrl; base_val |= (<API key> | <API key>); tw32_wait_f(TG3PCI_CLOCK_CTRL, base_val | CLOCK_CTRL_ALTCLK | <API key>, 40); } else if (tg3_flag(tp, 5780_CLASS) || tg3_flag(tp, CPMU_PRESENT) || tg3_asic_rev(tp) == ASIC_REV_5906) { /* do nothing */ } else if (!(tg3_flag(tp, 5750_PLUS) && tg3_flag(tp, ENABLE_ASF))) { u32 newbits1, newbits2; if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) { newbits1 = (<API key> | <API key> | CLOCK_CTRL_ALTCLK); newbits2 = newbits1 | <API key>; } else if (tg3_flag(tp, 5705_PLUS)) { newbits1 = CLOCK_CTRL_625_CORE; newbits2 = newbits1 | CLOCK_CTRL_ALTCLK; } else { newbits1 = CLOCK_CTRL_ALTCLK; newbits2 = newbits1 | <API key>; } tw32_wait_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl | newbits1, 40); tw32_wait_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl | newbits2, 40); if (!tg3_flag(tp, 5705_PLUS)) { u32 newbits3; if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) { newbits3 = (<API key> | <API key> | <API key>); } else { newbits3 = <API key>; } tw32_wait_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl | newbits3, 40); } } if (!(device_should_wake) && !tg3_flag(tp, ENABLE_ASF)) tg3_power_down_phy(tp, do_low_power); tg3_frob_aux_power(tp, true); /* Workaround for unstable PLL clock */ if ((!tg3_flag(tp, IS_SSB_CORE)) && ((tg3_chip_rev(tp) == CHIPREV_5750_AX) || (tg3_chip_rev(tp) == CHIPREV_5750_BX))) { u32 val = tr32(0x7d00); val &= ~((1 << 16) | (1 << 4) | (1 << 2) | (1 << 1) | 1); tw32(0x7d00, val); if (!tg3_flag(tp, ENABLE_ASF)) { int err; err = tg3_nvram_lock(tp); tg3_halt_cpu(tp, RX_CPU_BASE); if (!err) tg3_nvram_unlock(tp); } } <API key>(tp, RESET_KIND_SHUTDOWN); <API key>(tp, RESET_KIND_SHUTDOWN); return 0; } static void tg3_power_down(struct tg3 *tp) { pci_wake_from_d3(tp->pdev, tg3_flag(tp, WOL_ENABLE)); pci_set_power_state(tp->pdev, PCI_D3hot); } static void <API key>(struct tg3 *tp, u32 val, u16 *speed, u8 *duplex) { switch (val & <API key>) { case <API key>: *speed = SPEED_10; *duplex = DUPLEX_HALF; break; case <API key>: *speed = SPEED_10; *duplex = DUPLEX_FULL; break; case <API key>: *speed = SPEED_100; *duplex = DUPLEX_HALF; break; case <API key>: *speed = SPEED_100; *duplex = DUPLEX_FULL; break; case <API key>: *speed = SPEED_1000; *duplex = DUPLEX_HALF; break; case <API key>: *speed = SPEED_1000; *duplex = DUPLEX_FULL; break; default: if (tp->phy_flags & TG3_PHYFLG_IS_FET) { *speed = (val & <API key>) ? SPEED_100 : SPEED_10; *duplex = (val & <API key>) ? DUPLEX_FULL : DUPLEX_HALF; break; } *speed = SPEED_UNKNOWN; *duplex = DUPLEX_UNKNOWN; break; } } static int tg3_phy_autoneg_cfg(struct tg3 *tp, u32 advertise, u32 flowctrl) { int err = 0; u32 val, new_adv; new_adv = ADVERTISE_CSMA; new_adv |= <API key>(advertise) & ADVERTISE_ALL; new_adv |= <API key>(flowctrl); err = tg3_writephy(tp, MII_ADVERTISE, new_adv); if (err) goto done; if (!(tp->phy_flags & <API key>)) { new_adv = <API key>(advertise); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0) new_adv |= CTL1000_AS_MASTER | <API key>; err = tg3_writephy(tp, MII_CTRL1000, new_adv); if (err) goto done; } if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) goto done; tw32(TG3_CPMU_EEE_MODE, tr32(TG3_CPMU_EEE_MODE) & ~<API key>); err = <API key>(tp, true); if (!err) { u32 err2; val = 0; /* Advertise 100-BaseTX EEE ability */ if (advertise & <API key>) val |= <API key>; /* Advertise 1000-BaseT EEE ability */ if (advertise & <API key>) val |= <API key>; if (!tp->eee.eee_enabled) { val = 0; tp->eee.advertised = 0; } else { tp->eee.advertised = advertise & (<API key> | <API key>); } err = tg3_phy_cl45_write(tp, MDIO_MMD_AN, MDIO_AN_EEE_ADV, val); if (err) val = 0; switch (tg3_asic_rev(tp)) { case ASIC_REV_5717: case ASIC_REV_57765: case ASIC_REV_57766: case ASIC_REV_5719: /* If we advertised any eee advertisements above... */ if (val) val = <API key> | <API key> | <API key>; tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, val); /* Fall through */ case ASIC_REV_5720: case ASIC_REV_5762: if (!tg3_phydsp_read(tp, MII_TG3_DSP_CH34TP2, &val)) tg3_phydsp_write(tp, MII_TG3_DSP_CH34TP2, val | <API key>); } err2 = <API key>(tp, false); if (!err) err = err2; } done: return err; } static void <API key>(struct tg3 *tp) { if (tp->link_config.autoneg == AUTONEG_ENABLE || (tp->phy_flags & <API key>)) { u32 adv, fc; if ((tp->phy_flags & <API key>) && !(tp->phy_flags & <API key>)) { adv = <API key> | <API key>; if (tg3_flag(tp, WOL_SPEED_100MB)) adv |= <API key> | <API key>; if (tp->phy_flags & <API key>) { if (!(tp->phy_flags & <API key>)) adv |= <API key>; adv |= <API key>; } fc = FLOW_CTRL_TX | FLOW_CTRL_RX; } else { adv = tp->link_config.advertising; if (tp->phy_flags & <API key>) adv &= ~(<API key> | <API key>); fc = tp->link_config.flowctrl; } tg3_phy_autoneg_cfg(tp, adv, fc); if ((tp->phy_flags & <API key>) && (tp->phy_flags & <API key>)) { /* Normally during power down we want to autonegotiate * the lowest possible speed for WOL. However, to avoid * link flap, we leave it untouched. */ return; } tg3_writephy(tp, MII_BMCR, BMCR_ANENABLE | BMCR_ANRESTART); } else { int i; u32 bmcr, orig_bmcr; tp->link_config.active_speed = tp->link_config.speed; tp->link_config.active_duplex = tp->link_config.duplex; if (tg3_asic_rev(tp) == ASIC_REV_5714) { /* With autoneg disabled, 5715 only links up when the * advertisement register has the configured speed * enabled. */ tg3_writephy(tp, MII_ADVERTISE, ADVERTISE_ALL); } bmcr = 0; switch (tp->link_config.speed) { default: case SPEED_10: break; case SPEED_100: bmcr |= BMCR_SPEED100; break; case SPEED_1000: bmcr |= BMCR_SPEED1000; break; } if (tp->link_config.duplex == DUPLEX_FULL) bmcr |= BMCR_FULLDPLX; if (!tg3_readphy(tp, MII_BMCR, &orig_bmcr) && (bmcr != orig_bmcr)) { tg3_writephy(tp, MII_BMCR, BMCR_LOOPBACK); for (i = 0; i < 1500; i++) { u32 tmp; udelay(10); if (tg3_readphy(tp, MII_BMSR, &tmp) || tg3_readphy(tp, MII_BMSR, &tmp)) continue; if (!(tmp & BMSR_LSTATUS)) { udelay(40); break; } } tg3_writephy(tp, MII_BMCR, bmcr); udelay(40); } } } static int tg3_phy_pull_config(struct tg3 *tp) { int err; u32 val; err = tg3_readphy(tp, MII_BMCR, &val); if (err) goto done; if (!(val & BMCR_ANENABLE)) { tp->link_config.autoneg = AUTONEG_DISABLE; tp->link_config.advertising = 0; tg3_flag_clear(tp, PAUSE_AUTONEG); err = -EIO; switch (val & (BMCR_SPEED1000 | BMCR_SPEED100)) { case 0: if (tp->phy_flags & <API key>) goto done; tp->link_config.speed = SPEED_10; break; case BMCR_SPEED100: if (tp->phy_flags & <API key>) goto done; tp->link_config.speed = SPEED_100; break; case BMCR_SPEED1000: if (!(tp->phy_flags & <API key>)) { tp->link_config.speed = SPEED_1000; break; } /* Fall through */ default: goto done; } if (val & BMCR_FULLDPLX) tp->link_config.duplex = DUPLEX_FULL; else tp->link_config.duplex = DUPLEX_HALF; tp->link_config.flowctrl = FLOW_CTRL_RX | FLOW_CTRL_TX; err = 0; goto done; } tp->link_config.autoneg = AUTONEG_ENABLE; tp->link_config.advertising = ADVERTISED_Autoneg; tg3_flag_set(tp, PAUSE_AUTONEG); if (!(tp->phy_flags & <API key>)) { u32 adv; err = tg3_readphy(tp, MII_ADVERTISE, &val); if (err) goto done; adv = <API key>(val & ADVERTISE_ALL); tp->link_config.advertising |= adv | ADVERTISED_TP; tp->link_config.flowctrl = <API key>(val); } else { tp->link_config.advertising |= ADVERTISED_FIBRE; } if (!(tp->phy_flags & <API key>)) { u32 adv; if (!(tp->phy_flags & <API key>)) { err = tg3_readphy(tp, MII_CTRL1000, &val); if (err) goto done; adv = <API key>(val); } else { err = tg3_readphy(tp, MII_ADVERTISE, &val); if (err) goto done; adv = <API key>(val); tp->link_config.flowctrl = adv; val &= (ADVERTISE_1000XHALF | ADVERTISE_1000XFULL); adv = <API key>(val); } tp->link_config.advertising |= adv; } done: return err; } static int <API key>(struct tg3 *tp) { int err; /* Turn off tap power management. */ /* Set Extended packet length bit */ err = <API key>(tp, <API key>, 0x4c20); err |= tg3_phydsp_write(tp, 0x0012, 0x1804); err |= tg3_phydsp_write(tp, 0x0013, 0x1204); err |= tg3_phydsp_write(tp, 0x8006, 0x0132); err |= tg3_phydsp_write(tp, 0x8006, 0x0232); err |= tg3_phydsp_write(tp, 0x201f, 0x0a20); udelay(40); return err; } static bool <API key>(struct tg3 *tp) { struct ethtool_eee eee; if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) return true; tg3_eee_pull_config(tp, &eee); if (tp->eee.eee_enabled) { if (tp->eee.advertised != eee.advertised || tp->eee.tx_lpi_timer != eee.tx_lpi_timer || tp->eee.tx_lpi_enabled != eee.tx_lpi_enabled) return false; } else { /* EEE is disabled but we're advertising */ if (eee.advertised) return false; } return true; } static bool <API key>(struct tg3 *tp, u32 *lcladv) { u32 advmsk, tgtadv, advertising; advertising = tp->link_config.advertising; tgtadv = <API key>(advertising) & ADVERTISE_ALL; advmsk = ADVERTISE_ALL; if (tp->link_config.active_duplex == DUPLEX_FULL) { tgtadv |= <API key>(tp->link_config.flowctrl); advmsk |= ADVERTISE_PAUSE_CAP | <API key>; } if (tg3_readphy(tp, MII_ADVERTISE, lcladv)) return false; if ((*lcladv & advmsk) != tgtadv) return false; if (!(tp->phy_flags & <API key>)) { u32 tg3_ctrl; tgtadv = <API key>(advertising); if (tg3_readphy(tp, MII_CTRL1000, &tg3_ctrl)) return false; if (tgtadv && (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0)) { tgtadv |= CTL1000_AS_MASTER | <API key>; tg3_ctrl &= (ADVERTISE_1000HALF | ADVERTISE_1000FULL | CTL1000_AS_MASTER | <API key>); } else { tg3_ctrl &= (ADVERTISE_1000HALF | ADVERTISE_1000FULL); } if (tg3_ctrl != tgtadv) return false; } return true; } static bool <API key>(struct tg3 *tp, u32 *rmtadv) { u32 lpeth = 0; if (!(tp->phy_flags & <API key>)) { u32 val; if (tg3_readphy(tp, MII_STAT1000, &val)) return false; lpeth = <API key>(val); } if (tg3_readphy(tp, MII_LPA, rmtadv)) return false; lpeth |= <API key>(*rmtadv); tp->link_config.rmt_adv = lpeth; return true; } static bool <API key>(struct tg3 *tp, bool curr_link_up) { if (curr_link_up != tp->link_up) { if (curr_link_up) { netif_carrier_on(tp->dev); } else { netif_carrier_off(tp->dev); if (tp->phy_flags & <API key>) tp->phy_flags &= ~<API key>; } tg3_link_report(tp); return true; } return false; } static void <API key>(struct tg3 *tp) { tw32(MAC_EVENT, 0); tw32_f(MAC_STATUS, <API key> | <API key> | <API key> | <API key>); udelay(40); } static void tg3_setup_eee(struct tg3 *tp) { u32 val; val = <API key> | <API key>; if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0) val |= <API key>; tw32_f(<API key>, val); tw32_f(TG3_CPMU_EEE_CTRL, <API key>); val = <API key> | (tp->eee.tx_lpi_enabled ? <API key> : 0) | <API key> | <API key>; if (tg3_asic_rev(tp) != ASIC_REV_5717) val |= <API key>; if (tg3_flag(tp, ENABLE_APE)) val |= <API key>; tw32_f(TG3_CPMU_EEE_MODE, tp->eee.eee_enabled ? val : 0); tw32_f(TG3_CPMU_EEE_DBTMR1, <API key> | (tp->eee.tx_lpi_timer & 0xffff)); tw32_f(TG3_CPMU_EEE_DBTMR2, <API key> | <API key>); } static int <API key>(struct tg3 *tp, bool force_reset) { bool current_link_up; u32 bmsr, val; u32 lcl_adv, rmt_adv; u16 current_speed; u8 current_duplex; int i, err; <API key>(tp); if ((tp->mi_mode & <API key>) != 0) { tw32_f(MAC_MI_MODE, (tp->mi_mode & ~<API key>)); udelay(80); } <API key>(tp, <API key>, 0); /* Some third-party PHYs need to be reset on link going * down. */ if ((tg3_asic_rev(tp) == ASIC_REV_5703 || tg3_asic_rev(tp) == ASIC_REV_5704 || tg3_asic_rev(tp) == ASIC_REV_5705) && tp->link_up) { tg3_readphy(tp, MII_BMSR, &bmsr); if (!tg3_readphy(tp, MII_BMSR, &bmsr) && !(bmsr & BMSR_LSTATUS)) force_reset = true; } if (force_reset) tg3_phy_reset(tp); if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) { tg3_readphy(tp, MII_BMSR, &bmsr); if (tg3_readphy(tp, MII_BMSR, &bmsr) || !tg3_flag(tp, INIT_COMPLETE)) bmsr = 0; if (!(bmsr & BMSR_LSTATUS)) { err = <API key>(tp); if (err) return err; tg3_readphy(tp, MII_BMSR, &bmsr); for (i = 0; i < 1000; i++) { udelay(10); if (!tg3_readphy(tp, MII_BMSR, &bmsr) && (bmsr & BMSR_LSTATUS)) { udelay(40); break; } } if ((tp->phy_id & TG3_PHY_ID_REV_MASK) == <API key> && !(bmsr & BMSR_LSTATUS) && tp->link_config.active_speed == SPEED_1000) { err = tg3_phy_reset(tp); if (!err) err = <API key>(tp); if (err) return err; } } } else if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0) { /* 5701 {A0,B0} CRC bug workaround */ tg3_writephy(tp, 0x15, 0x0a75); tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8c68); tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68); tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8c68); } /* Clear pending interrupts... */ tg3_readphy(tp, MII_TG3_ISTAT, &val); tg3_readphy(tp, MII_TG3_ISTAT, &val); if (tp->phy_flags & <API key>) tg3_writephy(tp, MII_TG3_IMASK, ~MII_TG3_INT_LINKCHG); else if (!(tp->phy_flags & TG3_PHYFLG_IS_FET)) tg3_writephy(tp, MII_TG3_IMASK, ~0); if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) { if (tp->led_ctrl == LED_CTRL_MODE_PHY_1) tg3_writephy(tp, MII_TG3_EXT_CTRL, <API key>); else tg3_writephy(tp, MII_TG3_EXT_CTRL, 0); } current_link_up = false; current_speed = SPEED_UNKNOWN; current_duplex = DUPLEX_UNKNOWN; tp->phy_flags &= ~<API key>; tp->link_config.rmt_adv = 0; if (tp->phy_flags & <API key>) { err = tg3_phy_auxctl_read(tp, <API key>, &val); if (!err && !(val & (1 << 10))) { <API key>(tp, <API key>, val | (1 << 10)); goto relink; } } bmsr = 0; for (i = 0; i < 100; i++) { tg3_readphy(tp, MII_BMSR, &bmsr); if (!tg3_readphy(tp, MII_BMSR, &bmsr) && (bmsr & BMSR_LSTATUS)) break; udelay(40); } if (bmsr & BMSR_LSTATUS) { u32 aux_stat, bmcr; tg3_readphy(tp, MII_TG3_AUX_STAT, &aux_stat); for (i = 0; i < 2000; i++) { udelay(10); if (!tg3_readphy(tp, MII_TG3_AUX_STAT, &aux_stat) && aux_stat) break; } <API key>(tp, aux_stat, &current_speed, &current_duplex); bmcr = 0; for (i = 0; i < 200; i++) { tg3_readphy(tp, MII_BMCR, &bmcr); if (tg3_readphy(tp, MII_BMCR, &bmcr)) continue; if (bmcr && bmcr != 0x7fff) break; udelay(10); } lcl_adv = 0; rmt_adv = 0; tp->link_config.active_speed = current_speed; tp->link_config.active_duplex = current_duplex; if (tp->link_config.autoneg == AUTONEG_ENABLE) { bool eee_config_ok = <API key>(tp); if ((bmcr & BMCR_ANENABLE) && eee_config_ok && <API key>(tp, &lcl_adv) && <API key>(tp, &rmt_adv)) current_link_up = true; /* EEE settings changes take effect only after a phy * reset. If we have skipped a reset due to Link Flap * Avoidance being enabled, do it now. */ if (!eee_config_ok && (tp->phy_flags & <API key>) && !force_reset) { tg3_setup_eee(tp); tg3_phy_reset(tp); } } else { if (!(bmcr & BMCR_ANENABLE) && tp->link_config.speed == current_speed && tp->link_config.duplex == current_duplex) { current_link_up = true; } } if (current_link_up && tp->link_config.active_duplex == DUPLEX_FULL) { u32 reg, bit; if (tp->phy_flags & TG3_PHYFLG_IS_FET) { reg = <API key>; bit = <API key>; } else { reg = MII_TG3_EXT_STAT; bit = <API key>; } if (!tg3_readphy(tp, reg, &val) && (val & bit)) tp->phy_flags |= <API key>; <API key>(tp, lcl_adv, rmt_adv); } } relink: if (!current_link_up || (tp->phy_flags & <API key>)) { <API key>(tp); if (tg3_flag(tp, ROBOSWITCH)) { current_link_up = true; /* FIXME: when BCM5325 switch is used use 100 MBit/s */ current_speed = SPEED_1000; current_duplex = DUPLEX_FULL; tp->link_config.active_speed = current_speed; tp->link_config.active_duplex = current_duplex; } tg3_readphy(tp, MII_BMSR, &bmsr); if ((!tg3_readphy(tp, MII_BMSR, &bmsr) && (bmsr & BMSR_LSTATUS)) || (tp->mac_mode & <API key>)) current_link_up = true; } tp->mac_mode &= ~<API key>; if (current_link_up) { if (tp->link_config.active_speed == SPEED_100 || tp->link_config.active_speed == SPEED_10) tp->mac_mode |= <API key>; else tp->mac_mode |= <API key>; } else if (tp->phy_flags & TG3_PHYFLG_IS_FET) tp->mac_mode |= <API key>; else tp->mac_mode |= <API key>; /* In order for the 5750 core in BCM4785 chip to work properly * in RGMII mode, the Led Control Register must be set up. */ if (tg3_flag(tp, RGMII_MODE)) { u32 led_ctrl = tr32(MAC_LED_CTRL); led_ctrl &= ~(<API key> | LED_CTRL_100MBPS_ON); if (tp->link_config.active_speed == SPEED_10) led_ctrl |= <API key>; else if (tp->link_config.active_speed == SPEED_100) led_ctrl |= (<API key> | LED_CTRL_100MBPS_ON); else if (tp->link_config.active_speed == SPEED_1000) led_ctrl |= (<API key> | <API key>); tw32(MAC_LED_CTRL, led_ctrl); udelay(40); } tp->mac_mode &= ~<API key>; if (tp->link_config.active_duplex == DUPLEX_HALF) tp->mac_mode |= <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5700) { if (current_link_up && <API key>(tp, tp->link_config.active_speed)) tp->mac_mode |= <API key>; else tp->mac_mode &= ~<API key>; } /* ??? Without this setting Netgear GA302T PHY does not * ??? send/receive packets... */ if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5411 && tg3_chip_rev_id(tp) == <API key>) { tp->mi_mode |= <API key>; tw32_f(MAC_MI_MODE, tp->mi_mode); udelay(80); } tw32_f(MAC_MODE, tp->mac_mode); udelay(40); tg3_phy_eee_adjust(tp, current_link_up); if (tg3_flag(tp, USE_LINKCHG_REG)) { /* Polled via timer. */ tw32_f(MAC_EVENT, 0); } else { tw32_f(MAC_EVENT, <API key>); } udelay(40); if (tg3_asic_rev(tp) == ASIC_REV_5700 && current_link_up && tp->link_config.active_speed == SPEED_1000 && (tg3_flag(tp, PCIX_MODE) || tg3_flag(tp, PCI_HIGH_SPEED))) { udelay(120); tw32_f(MAC_STATUS, (<API key> | <API key>)); udelay(40); tg3_write_mem(tp, <API key>, <API key>); } /* Prevent send BD corruption. */ if (tg3_flag(tp, CLKREQ_BUG)) { if (tp->link_config.active_speed == SPEED_100 || tp->link_config.active_speed == SPEED_10) <API key>(tp->pdev, PCI_EXP_LNKCTL, <API key>); else <API key>(tp->pdev, PCI_EXP_LNKCTL, <API key>); } <API key>(tp, current_link_up); return 0; } struct tg3_fiber_aneginfo { int state; #define ANEG_STATE_UNKNOWN 0 #define <API key> 1 #define <API key> 2 #define ANEG_STATE_RESTART 3 #define <API key> 4 #define <API key> 5 #define <API key> 6 #define <API key> 7 #define <API key> 8 #define <API key> 9 #define <API key> 10 #define <API key> 11 #define <API key> 12 #define ANEG_STATE_LINK_OK 13 #define <API key> 14 #define <API key> 15 u32 flags; #define MR_AN_ENABLE 0x00000001 #define MR_RESTART_AN 0x00000002 #define MR_AN_COMPLETE 0x00000004 #define MR_PAGE_RX 0x00000008 #define MR_NP_LOADED 0x00000010 #define MR_TOGGLE_TX 0x00000020 #define <API key> 0x00000040 #define <API key> 0x00000080 #define MR_LP_ADV_SYM_PAUSE 0x00000100 #define <API key> 0x00000200 #define <API key> 0x00000400 #define <API key> 0x00000800 #define MR_LP_ADV_NEXT_PAGE 0x00001000 #define MR_TOGGLE_RX 0x00002000 #define MR_NP_RX 0x00004000 #define MR_LINK_OK 0x80000000 unsigned long link_time, cur_time; u32 ability_match_cfg; int ability_match_count; char ability_match, idle_match, ack_match; u32 txconfig, rxconfig; #define ANEG_CFG_NP 0x00000080 #define ANEG_CFG_ACK 0x00000040 #define ANEG_CFG_RF2 0x00000020 #define ANEG_CFG_RF1 0x00000010 #define ANEG_CFG_PS2 0x00000001 #define ANEG_CFG_PS1 0x00008000 #define ANEG_CFG_HD 0x00004000 #define ANEG_CFG_FD 0x00002000 #define ANEG_CFG_INVAL 0x00001f06 }; #define ANEG_OK 0 #define ANEG_DONE 1 #define ANEG_TIMER_ENAB 2 #define ANEG_FAILED -1 #define <API key> 10000 static int <API key>(struct tg3 *tp, struct tg3_fiber_aneginfo *ap) { u16 flowctrl; unsigned long delta; u32 rx_cfg_reg; int ret; if (ap->state == ANEG_STATE_UNKNOWN) { ap->rxconfig = 0; ap->link_time = 0; ap->cur_time = 0; ap->ability_match_cfg = 0; ap->ability_match_count = 0; ap->ability_match = 0; ap->idle_match = 0; ap->ack_match = 0; } ap->cur_time++; if (tr32(MAC_STATUS) & MAC_STATUS_RCVD_CFG) { rx_cfg_reg = tr32(MAC_RX_AUTO_NEG); if (rx_cfg_reg != ap->ability_match_cfg) { ap->ability_match_cfg = rx_cfg_reg; ap->ability_match = 0; ap->ability_match_count = 0; } else { if (++ap->ability_match_count > 1) { ap->ability_match = 1; ap->ability_match_cfg = rx_cfg_reg; } } if (rx_cfg_reg & ANEG_CFG_ACK) ap->ack_match = 1; else ap->ack_match = 0; ap->idle_match = 0; } else { ap->idle_match = 1; ap->ability_match_cfg = 0; ap->ability_match_count = 0; ap->ability_match = 0; ap->ack_match = 0; rx_cfg_reg = 0; } ap->rxconfig = rx_cfg_reg; ret = ANEG_OK; switch (ap->state) { case ANEG_STATE_UNKNOWN: if (ap->flags & (MR_AN_ENABLE | MR_RESTART_AN)) ap->state = <API key>; /* fallthru */ case <API key>: ap->flags &= ~(MR_AN_COMPLETE | MR_PAGE_RX); if (ap->flags & MR_AN_ENABLE) { ap->link_time = 0; ap->cur_time = 0; ap->ability_match_cfg = 0; ap->ability_match_count = 0; ap->ability_match = 0; ap->idle_match = 0; ap->ack_match = 0; ap->state = <API key>; } else { ap->state = <API key>; } break; case <API key>: ap->link_time = ap->cur_time; ap->flags &= ~(MR_NP_LOADED); ap->txconfig = 0; tw32(MAC_TX_AUTO_NEG, 0); tp->mac_mode |= <API key>; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ret = ANEG_TIMER_ENAB; ap->state = ANEG_STATE_RESTART; /* fallthru */ case ANEG_STATE_RESTART: delta = ap->cur_time - ap->link_time; if (delta > <API key>) ap->state = <API key>; else ret = ANEG_TIMER_ENAB; break; case <API key>: ret = ANEG_DONE; break; case <API key>: ap->flags &= ~(MR_TOGGLE_TX); ap->txconfig = ANEG_CFG_FD; flowctrl = <API key>(tp->link_config.flowctrl); if (flowctrl & <API key>) ap->txconfig |= ANEG_CFG_PS1; if (flowctrl & <API key>) ap->txconfig |= ANEG_CFG_PS2; tw32(MAC_TX_AUTO_NEG, ap->txconfig); tp->mac_mode |= <API key>; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ap->state = <API key>; break; case <API key>: if (ap->ability_match != 0 && ap->rxconfig != 0) ap->state = <API key>; break; case <API key>: ap->txconfig |= ANEG_CFG_ACK; tw32(MAC_TX_AUTO_NEG, ap->txconfig); tp->mac_mode |= <API key>; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ap->state = <API key>; /* fallthru */ case <API key>: if (ap->ack_match != 0) { if ((ap->rxconfig & ~ANEG_CFG_ACK) == (ap->ability_match_cfg & ~ANEG_CFG_ACK)) { ap->state = <API key>; } else { ap->state = <API key>; } } else if (ap->ability_match != 0 && ap->rxconfig == 0) { ap->state = <API key>; } break; case <API key>: if (ap->rxconfig & ANEG_CFG_INVAL) { ret = ANEG_FAILED; break; } ap->flags &= ~(<API key> | <API key> | MR_LP_ADV_SYM_PAUSE | <API key> | <API key> | <API key> | MR_LP_ADV_NEXT_PAGE | MR_TOGGLE_RX | MR_NP_RX); if (ap->rxconfig & ANEG_CFG_FD) ap->flags |= <API key>; if (ap->rxconfig & ANEG_CFG_HD) ap->flags |= <API key>; if (ap->rxconfig & ANEG_CFG_PS1) ap->flags |= MR_LP_ADV_SYM_PAUSE; if (ap->rxconfig & ANEG_CFG_PS2) ap->flags |= <API key>; if (ap->rxconfig & ANEG_CFG_RF1) ap->flags |= <API key>; if (ap->rxconfig & ANEG_CFG_RF2) ap->flags |= <API key>; if (ap->rxconfig & ANEG_CFG_NP) ap->flags |= MR_LP_ADV_NEXT_PAGE; ap->link_time = ap->cur_time; ap->flags ^= (MR_TOGGLE_TX); if (ap->rxconfig & 0x0008) ap->flags |= MR_TOGGLE_RX; if (ap->rxconfig & ANEG_CFG_NP) ap->flags |= MR_NP_RX; ap->flags |= MR_PAGE_RX; ap->state = <API key>; ret = ANEG_TIMER_ENAB; break; case <API key>: if (ap->ability_match != 0 && ap->rxconfig == 0) { ap->state = <API key>; break; } delta = ap->cur_time - ap->link_time; if (delta > <API key>) { if (!(ap->flags & (MR_LP_ADV_NEXT_PAGE))) { ap->state = <API key>; } else { if ((ap->txconfig & ANEG_CFG_NP) == 0 && !(ap->flags & MR_NP_RX)) { ap->state = <API key>; } else { ret = ANEG_FAILED; } } } break; case <API key>: ap->link_time = ap->cur_time; tp->mac_mode &= ~<API key>; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ap->state = <API key>; ret = ANEG_TIMER_ENAB; break; case <API key>: if (ap->ability_match != 0 && ap->rxconfig == 0) { ap->state = <API key>; break; } delta = ap->cur_time - ap->link_time; if (delta > <API key>) { /* XXX another gem from the Broadcom driver :( */ ap->state = ANEG_STATE_LINK_OK; } break; case ANEG_STATE_LINK_OK: ap->flags |= (MR_AN_COMPLETE | MR_LINK_OK); ret = ANEG_DONE; break; case <API key>: /* ??? unimplemented */ break; case <API key>: /* ??? unimplemented */ break; default: ret = ANEG_FAILED; break; } return ret; } static int fiber_autoneg(struct tg3 *tp, u32 *txflags, u32 *rxflags) { int res = 0; struct tg3_fiber_aneginfo aninfo; int status = ANEG_FAILED; unsigned int tick; u32 tmp; tw32_f(MAC_TX_AUTO_NEG, 0); tmp = tp->mac_mode & ~<API key>; tw32_f(MAC_MODE, tmp | <API key>); udelay(40); tw32_f(MAC_MODE, tp->mac_mode | <API key>); udelay(40); memset(&aninfo, 0, sizeof(aninfo)); aninfo.flags |= MR_AN_ENABLE; aninfo.state = ANEG_STATE_UNKNOWN; aninfo.cur_time = 0; tick = 0; while (++tick < 195000) { status = <API key>(tp, &aninfo); if (status == ANEG_DONE || status == ANEG_FAILED) break; udelay(1); } tp->mac_mode &= ~<API key>; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); *txflags = aninfo.txconfig; *rxflags = aninfo.flags; if (status == ANEG_DONE && (aninfo.flags & (MR_AN_COMPLETE | MR_LINK_OK | <API key>))) res = 1; return res; } static void tg3_init_bcm8002(struct tg3 *tp) { u32 mac_status = tr32(MAC_STATUS); int i; /* Reset when initting first time or we have a link. */ if (tg3_flag(tp, INIT_COMPLETE) && !(mac_status & <API key>)) return; /* Set PLL lock range. */ tg3_writephy(tp, 0x16, 0x8007); /* SW reset */ tg3_writephy(tp, MII_BMCR, BMCR_RESET); /* Wait for reset to complete. */ /* XXX schedule_timeout() ... */ for (i = 0; i < 500; i++) udelay(10); /* Config mode; select PMA/Ch 1 regs. */ tg3_writephy(tp, 0x10, 0x8411); /* Enable auto-lock and comdet, select txclk for tx. */ tg3_writephy(tp, 0x11, 0x0a10); tg3_writephy(tp, 0x18, 0x00a0); tg3_writephy(tp, 0x16, 0x41ff); /* Assert and deassert POR. */ tg3_writephy(tp, 0x13, 0x0400); udelay(40); tg3_writephy(tp, 0x13, 0x0000); tg3_writephy(tp, 0x11, 0x0a50); udelay(40); tg3_writephy(tp, 0x11, 0x0a10); /* Wait for signal to stabilize */ /* XXX schedule_timeout() ... */ for (i = 0; i < 15000; i++) udelay(10); /* Deselect the channel register so we can read the PHYID * later. */ tg3_writephy(tp, 0x10, 0x8011); } static bool <API key>(struct tg3 *tp, u32 mac_status) { u16 flowctrl; bool current_link_up; u32 sg_dig_ctrl, sg_dig_status; u32 serdes_cfg, <API key>; int workaround, port_a; serdes_cfg = 0; <API key> = 0; workaround = 0; port_a = 1; current_link_up = false; if (tg3_chip_rev_id(tp) != CHIPREV_ID_5704_A0 && tg3_chip_rev_id(tp) != CHIPREV_ID_5704_A1) { workaround = 1; if (tr32(<API key>) & DUAL_MAC_CTRL_ID) port_a = 0; /* preserve bits 0-11,13,14 for signal pre-emphasis */ /* preserve bits 20-23 for voltage regulator */ serdes_cfg = tr32(MAC_SERDES_CFG) & 0x00f06fff; } sg_dig_ctrl = tr32(SG_DIG_CTRL); if (tp->link_config.autoneg != AUTONEG_ENABLE) { if (sg_dig_ctrl & <API key>) { if (workaround) { u32 val = serdes_cfg; if (port_a) val |= 0xc010000; else val |= 0x4010000; tw32_f(MAC_SERDES_CFG, val); } tw32_f(SG_DIG_CTRL, SG_DIG_COMMON_SETUP); } if (mac_status & <API key>) { <API key>(tp, 0, 0); current_link_up = true; } goto out; } /* Want auto-negotiation. */ <API key> = <API key> | SG_DIG_COMMON_SETUP; flowctrl = <API key>(tp->link_config.flowctrl); if (flowctrl & <API key>) <API key> |= SG_DIG_PAUSE_CAP; if (flowctrl & <API key>) <API key> |= SG_DIG_ASYM_PAUSE; if (sg_dig_ctrl != <API key>) { if ((tp->phy_flags & <API key>) && tp->serdes_counter && ((mac_status & (<API key> | MAC_STATUS_RCVD_CFG)) == <API key>)) { tp->serdes_counter current_link_up = true; goto out; } restart_autoneg: if (workaround) tw32_f(MAC_SERDES_CFG, serdes_cfg | 0xc011000); tw32_f(SG_DIG_CTRL, <API key> | SG_DIG_SOFT_RESET); udelay(5); tw32_f(SG_DIG_CTRL, <API key>); tp->serdes_counter = <API key>; tp->phy_flags &= ~<API key>; } else if (mac_status & (<API key> | <API key>)) { sg_dig_status = tr32(SG_DIG_STATUS); mac_status = tr32(MAC_STATUS); if ((sg_dig_status & <API key>) && (mac_status & <API key>)) { u32 local_adv = 0, remote_adv = 0; if (sg_dig_ctrl & SG_DIG_PAUSE_CAP) local_adv |= <API key>; if (sg_dig_ctrl & SG_DIG_ASYM_PAUSE) local_adv |= <API key>; if (sg_dig_status & <API key>) remote_adv |= LPA_1000XPAUSE; if (sg_dig_status & <API key>) remote_adv |= LPA_1000XPAUSE_ASYM; tp->link_config.rmt_adv = <API key>(remote_adv); <API key>(tp, local_adv, remote_adv); current_link_up = true; tp->serdes_counter = 0; tp->phy_flags &= ~<API key>; } else if (!(sg_dig_status & <API key>)) { if (tp->serdes_counter) tp->serdes_counter else { if (workaround) { u32 val = serdes_cfg; if (port_a) val |= 0xc010000; else val |= 0x4010000; tw32_f(MAC_SERDES_CFG, val); } tw32_f(SG_DIG_CTRL, SG_DIG_COMMON_SETUP); udelay(40); /* Link parallel detection - link is up */ /* only if we have PCS_SYNC and not */ /* receiving config code words */ mac_status = tr32(MAC_STATUS); if ((mac_status & <API key>) && !(mac_status & MAC_STATUS_RCVD_CFG)) { <API key>(tp, 0, 0); current_link_up = true; tp->phy_flags |= <API key>; tp->serdes_counter = <API key>; } else goto restart_autoneg; } } } else { tp->serdes_counter = <API key>; tp->phy_flags &= ~<API key>; } out: return current_link_up; } static bool <API key>(struct tg3 *tp, u32 mac_status) { bool current_link_up = false; if (!(mac_status & <API key>)) goto out; if (tp->link_config.autoneg == AUTONEG_ENABLE) { u32 txflags, rxflags; int i; if (fiber_autoneg(tp, &txflags, &rxflags)) { u32 local_adv = 0, remote_adv = 0; if (txflags & ANEG_CFG_PS1) local_adv |= <API key>; if (txflags & ANEG_CFG_PS2) local_adv |= <API key>; if (rxflags & MR_LP_ADV_SYM_PAUSE) remote_adv |= LPA_1000XPAUSE; if (rxflags & <API key>) remote_adv |= LPA_1000XPAUSE_ASYM; tp->link_config.rmt_adv = <API key>(remote_adv); <API key>(tp, local_adv, remote_adv); current_link_up = true; } for (i = 0; i < 30; i++) { udelay(20); tw32_f(MAC_STATUS, (<API key> | <API key>)); udelay(40); if ((tr32(MAC_STATUS) & (<API key> | <API key>)) == 0) break; } mac_status = tr32(MAC_STATUS); if (!current_link_up && (mac_status & <API key>) && !(mac_status & MAC_STATUS_RCVD_CFG)) current_link_up = true; } else { <API key>(tp, 0, 0); /* Forcing 1000FD link up. */ current_link_up = true; tw32_f(MAC_MODE, (tp->mac_mode | <API key>)); udelay(40); tw32_f(MAC_MODE, tp->mac_mode); udelay(40); } out: return current_link_up; } static int tg3_setup_fiber_phy(struct tg3 *tp, bool force_reset) { u32 orig_pause_cfg; u16 orig_active_speed; u8 orig_active_duplex; u32 mac_status; bool current_link_up; int i; orig_pause_cfg = tp->link_config.active_flowctrl; orig_active_speed = tp->link_config.active_speed; orig_active_duplex = tp->link_config.active_duplex; if (!tg3_flag(tp, HW_AUTONEG) && tp->link_up && tg3_flag(tp, INIT_COMPLETE)) { mac_status = tr32(MAC_STATUS); mac_status &= (<API key> | <API key> | <API key> | MAC_STATUS_RCVD_CFG); if (mac_status == (<API key> | <API key>)) { tw32_f(MAC_STATUS, (<API key> | <API key>)); return 0; } } tw32_f(MAC_TX_AUTO_NEG, 0); tp->mac_mode &= ~(<API key> | <API key>); tp->mac_mode |= <API key>; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); if (tp->phy_id == TG3_PHY_ID_BCM8002) tg3_init_bcm8002(tp); /* Enable link change event even when serdes polling. */ tw32_f(MAC_EVENT, <API key>); udelay(40); current_link_up = false; tp->link_config.rmt_adv = 0; mac_status = tr32(MAC_STATUS); if (tg3_flag(tp, HW_AUTONEG)) current_link_up = <API key>(tp, mac_status); else current_link_up = <API key>(tp, mac_status); tp->napi[0].hw_status->status = (SD_STATUS_UPDATED | (tp->napi[0].hw_status->status & ~SD_STATUS_LINK_CHG)); for (i = 0; i < 100; i++) { tw32_f(MAC_STATUS, (<API key> | <API key>)); udelay(5); if ((tr32(MAC_STATUS) & (<API key> | <API key> | <API key>)) == 0) break; } mac_status = tr32(MAC_STATUS); if ((mac_status & <API key>) == 0) { current_link_up = false; if (tp->link_config.autoneg == AUTONEG_ENABLE && tp->serdes_counter == 0) { tw32_f(MAC_MODE, (tp->mac_mode | <API key>)); udelay(1); tw32_f(MAC_MODE, tp->mac_mode); } } if (current_link_up) { tp->link_config.active_speed = SPEED_1000; tp->link_config.active_duplex = DUPLEX_FULL; tw32(MAC_LED_CTRL, (tp->led_ctrl | <API key> | <API key>)); } else { tp->link_config.active_speed = SPEED_UNKNOWN; tp->link_config.active_duplex = DUPLEX_UNKNOWN; tw32(MAC_LED_CTRL, (tp->led_ctrl | <API key> | <API key>)); } if (!<API key>(tp, current_link_up)) { u32 now_pause_cfg = tp->link_config.active_flowctrl; if (orig_pause_cfg != now_pause_cfg || orig_active_speed != tp->link_config.active_speed || orig_active_duplex != tp->link_config.active_duplex) tg3_link_report(tp); } return 0; } static int <API key>(struct tg3 *tp, bool force_reset) { int err = 0; u32 bmsr, bmcr; u16 current_speed = SPEED_UNKNOWN; u8 current_duplex = DUPLEX_UNKNOWN; bool current_link_up = false; u32 local_adv, remote_adv, sgsr; if ((tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) && !tg3_readphy(tp, <API key>, &sgsr) && (sgsr & <API key>)) { if (force_reset) tg3_phy_reset(tp); tp->mac_mode &= ~<API key>; if (!(sgsr & SERDES_TG3_LINK_UP)) { tp->mac_mode |= <API key>; } else { current_link_up = true; if (sgsr & <API key>) { current_speed = SPEED_1000; tp->mac_mode |= <API key>; } else if (sgsr & <API key>) { current_speed = SPEED_100; tp->mac_mode |= <API key>; } else { current_speed = SPEED_10; tp->mac_mode |= <API key>; } if (sgsr & <API key>) current_duplex = DUPLEX_FULL; else current_duplex = DUPLEX_HALF; } tw32_f(MAC_MODE, tp->mac_mode); udelay(40); <API key>(tp); goto fiber_setup_done; } tp->mac_mode |= <API key>; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); <API key>(tp); if (force_reset) tg3_phy_reset(tp); tp->link_config.rmt_adv = 0; err |= tg3_readphy(tp, MII_BMSR, &bmsr); err |= tg3_readphy(tp, MII_BMSR, &bmsr); if (tg3_asic_rev(tp) == ASIC_REV_5714) { if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP) bmsr |= BMSR_LSTATUS; else bmsr &= ~BMSR_LSTATUS; } err |= tg3_readphy(tp, MII_BMCR, &bmcr); if ((tp->link_config.autoneg == AUTONEG_ENABLE) && !force_reset && (tp->phy_flags & <API key>)) { /* do nothing, just check for link up at the end */ } else if (tp->link_config.autoneg == AUTONEG_ENABLE) { u32 adv, newadv; err |= tg3_readphy(tp, MII_ADVERTISE, &adv); newadv = adv & ~(ADVERTISE_1000XFULL | ADVERTISE_1000XHALF | <API key> | <API key> | ADVERTISE_SLCT); newadv |= <API key>(tp->link_config.flowctrl); newadv |= <API key>(tp->link_config.advertising); if ((newadv != adv) || !(bmcr & BMCR_ANENABLE)) { tg3_writephy(tp, MII_ADVERTISE, newadv); bmcr |= BMCR_ANENABLE | BMCR_ANRESTART; tg3_writephy(tp, MII_BMCR, bmcr); tw32_f(MAC_EVENT, <API key>); tp->serdes_counter = <API key>; tp->phy_flags &= ~<API key>; return err; } } else { u32 new_bmcr; bmcr &= ~BMCR_SPEED1000; new_bmcr = bmcr & ~(BMCR_ANENABLE | BMCR_FULLDPLX); if (tp->link_config.duplex == DUPLEX_FULL) new_bmcr |= BMCR_FULLDPLX; if (new_bmcr != bmcr) { /* BMCR_SPEED1000 is a reserved bit that needs * to be set on write. */ new_bmcr |= BMCR_SPEED1000; /* Force a linkdown */ if (tp->link_up) { u32 adv; err |= tg3_readphy(tp, MII_ADVERTISE, &adv); adv &= ~(ADVERTISE_1000XFULL | ADVERTISE_1000XHALF | ADVERTISE_SLCT); tg3_writephy(tp, MII_ADVERTISE, adv); tg3_writephy(tp, MII_BMCR, bmcr | BMCR_ANRESTART | BMCR_ANENABLE); udelay(10); tg3_carrier_off(tp); } tg3_writephy(tp, MII_BMCR, new_bmcr); bmcr = new_bmcr; err |= tg3_readphy(tp, MII_BMSR, &bmsr); err |= tg3_readphy(tp, MII_BMSR, &bmsr); if (tg3_asic_rev(tp) == ASIC_REV_5714) { if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP) bmsr |= BMSR_LSTATUS; else bmsr &= ~BMSR_LSTATUS; } tp->phy_flags &= ~<API key>; } } if (bmsr & BMSR_LSTATUS) { current_speed = SPEED_1000; current_link_up = true; if (bmcr & BMCR_FULLDPLX) current_duplex = DUPLEX_FULL; else current_duplex = DUPLEX_HALF; local_adv = 0; remote_adv = 0; if (bmcr & BMCR_ANENABLE) { u32 common; err |= tg3_readphy(tp, MII_ADVERTISE, &local_adv); err |= tg3_readphy(tp, MII_LPA, &remote_adv); common = local_adv & remote_adv; if (common & (ADVERTISE_1000XHALF | ADVERTISE_1000XFULL)) { if (common & ADVERTISE_1000XFULL) current_duplex = DUPLEX_FULL; else current_duplex = DUPLEX_HALF; tp->link_config.rmt_adv = <API key>(remote_adv); } else if (!tg3_flag(tp, 5780_CLASS)) { /* Link is up via parallel detect */ } else { current_link_up = false; } } } fiber_setup_done: if (current_link_up && current_duplex == DUPLEX_FULL) <API key>(tp, local_adv, remote_adv); tp->mac_mode &= ~<API key>; if (tp->link_config.active_duplex == DUPLEX_HALF) tp->mac_mode |= <API key>; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); tw32_f(MAC_EVENT, <API key>); tp->link_config.active_speed = current_speed; tp->link_config.active_duplex = current_duplex; <API key>(tp, current_link_up); return err; } static void <API key>(struct tg3 *tp) { if (tp->serdes_counter) { /* Give autoneg time to complete. */ tp->serdes_counter return; } if (!tp->link_up && (tp->link_config.autoneg == AUTONEG_ENABLE)) { u32 bmcr; tg3_readphy(tp, MII_BMCR, &bmcr); if (bmcr & BMCR_ANENABLE) { u32 phy1, phy2; /* Select shadow register 0x1f */ tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x7c00); tg3_readphy(tp, MII_TG3_MISC_SHDW, &phy1); /* Select expansion interrupt status register */ tg3_writephy(tp, MII_TG3_DSP_ADDRESS, <API key>); tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2); tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2); if ((phy1 & 0x10) && !(phy2 & 0x20)) { /* We have signal detect and not receiving * config code words, link is up by parallel * detection. */ bmcr &= ~BMCR_ANENABLE; bmcr |= BMCR_SPEED1000 | BMCR_FULLDPLX; tg3_writephy(tp, MII_BMCR, bmcr); tp->phy_flags |= <API key>; } } } else if (tp->link_up && (tp->link_config.autoneg == AUTONEG_ENABLE) && (tp->phy_flags & <API key>)) { u32 phy2; /* Select expansion interrupt status register */ tg3_writephy(tp, MII_TG3_DSP_ADDRESS, <API key>); tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2); if (phy2 & 0x20) { u32 bmcr; /* Config code words received, turn on autoneg. */ tg3_readphy(tp, MII_BMCR, &bmcr); tg3_writephy(tp, MII_BMCR, bmcr | BMCR_ANENABLE); tp->phy_flags &= ~<API key>; } } } static int tg3_setup_phy(struct tg3 *tp, bool force_reset) { u32 val; int err; if (tp->phy_flags & <API key>) err = tg3_setup_fiber_phy(tp, force_reset); else if (tp->phy_flags & <API key>) err = <API key>(tp, force_reset); else err = <API key>(tp, force_reset); if (tg3_chip_rev(tp) == CHIPREV_5784_AX) { u32 scale; val = tr32(TG3_CPMU_CLCK_STAT) & <API key>; if (val == <API key>) scale = 65; else if (val == <API key>) scale = 6; else scale = 12; val = tr32(GRC_MISC_CFG) & ~<API key>; val |= (scale << <API key>); tw32(GRC_MISC_CFG, val); } val = (2 << <API key>) | (6 << <API key>); if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) val |= tr32(MAC_TX_LENGTHS) & (<API key> | <API key>); if (tp->link_config.active_speed == SPEED_1000 && tp->link_config.active_duplex == DUPLEX_HALF) tw32(MAC_TX_LENGTHS, val | (0xff << <API key>)); else tw32(MAC_TX_LENGTHS, val | (32 << <API key>)); if (!tg3_flag(tp, 5705_PLUS)) { if (tp->link_up) { tw32(<API key>, tp->coal.<API key>); } else { tw32(<API key>, 0); } } if (tg3_flag(tp, ASPM_WORKAROUND)) { val = tr32(<API key>); if (!tp->link_up) val = (val & ~<API key>) | tp->pwrmgmt_thresh; else val |= <API key>; tw32(<API key>, val); } return err; } /* tp->lock must be held */ static u64 tg3_refclk_read(struct tg3 *tp) { u64 stamp = tr32(<API key>); return stamp | (u64)tr32(<API key>) << 32; } /* tp->lock must be held */ static void tg3_refclk_write(struct tg3 *tp, u64 newval) { u32 clock_ctl = tr32(<API key>); tw32(<API key>, clock_ctl | <API key>); tw32(<API key>, newval & 0xffffffff); tw32(<API key>, newval >> 32); tw32_f(<API key>, clock_ctl | <API key>); } static inline void tg3_full_lock(struct tg3 *tp, int irq_sync); static inline void tg3_full_unlock(struct tg3 *tp); static int tg3_get_ts_info(struct net_device *dev, struct ethtool_ts_info *info) { struct tg3 *tp = netdev_priv(dev); info->so_timestamping = <API key> | <API key> | <API key>; if (tg3_flag(tp, PTP_CAPABLE)) { info->so_timestamping |= <API key> | <API key> | <API key>; } if (tp->ptp_clock) info->phc_index = ptp_clock_index(tp->ptp_clock); else info->phc_index = -1; info->tx_types = (1 << HWTSTAMP_TX_OFF) | (1 << HWTSTAMP_TX_ON); info->rx_filters = (1 << <API key>) | (1 << <API key>) | (1 << <API key>) | (1 << <API key>); return 0; } static int tg3_ptp_adjfreq(struct ptp_clock_info *ptp, s32 ppb) { struct tg3 *tp = container_of(ptp, struct tg3, ptp_info); bool neg_adj = false; u32 correction = 0; if (ppb < 0) { neg_adj = true; ppb = -ppb; } /* Frequency adjustment is performed using hardware with a 24 bit * accumulator and a programmable correction value. On each clk, the * correction value gets added to the accumulator and when it * overflows, the time counter is incremented/decremented. * * So conversion from ppb to correction value is * ppb * (1 << 24) / 1000000000 */ correction = div_u64((u64)ppb * (1 << 24), 1000000000ULL) & <API key>; tg3_full_lock(tp, 0); if (correction) tw32(<API key>, <API key> | (neg_adj ? <API key> : 0) | correction); else tw32(<API key>, 0); tg3_full_unlock(tp); return 0; } static int tg3_ptp_adjtime(struct ptp_clock_info *ptp, s64 delta) { struct tg3 *tp = container_of(ptp, struct tg3, ptp_info); tg3_full_lock(tp, 0); tp->ptp_adjust += delta; tg3_full_unlock(tp); return 0; } static int tg3_ptp_gettime(struct ptp_clock_info *ptp, struct timespec *ts) { u64 ns; u32 remainder; struct tg3 *tp = container_of(ptp, struct tg3, ptp_info); tg3_full_lock(tp, 0); ns = tg3_refclk_read(tp); ns += tp->ptp_adjust; tg3_full_unlock(tp); ts->tv_sec = div_u64_rem(ns, 1000000000, &remainder); ts->tv_nsec = remainder; return 0; } static int tg3_ptp_settime(struct ptp_clock_info *ptp, const struct timespec *ts) { u64 ns; struct tg3 *tp = container_of(ptp, struct tg3, ptp_info); ns = timespec_to_ns(ts); tg3_full_lock(tp, 0); tg3_refclk_write(tp, ns); tp->ptp_adjust = 0; tg3_full_unlock(tp); return 0; } static int tg3_ptp_enable(struct ptp_clock_info *ptp, struct ptp_clock_request *rq, int on) { struct tg3 *tp = container_of(ptp, struct tg3, ptp_info); u32 clock_ctl; int rval = 0; switch (rq->type) { case PTP_CLK_REQ_PEROUT: if (rq->perout.index != 0) return -EINVAL; tg3_full_lock(tp, 0); clock_ctl = tr32(<API key>); clock_ctl &= ~<API key>; if (on) { u64 nsec; nsec = rq->perout.start.sec * 1000000000ULL + rq->perout.start.nsec; if (rq->perout.period.sec || rq->perout.period.nsec) { netdev_warn(tp->dev, "Device supports only a one-shot timesync output, period must be 0\n"); rval = -EINVAL; goto err_out; } if (nsec & (1ULL << 63)) { netdev_warn(tp->dev, "Start value (nsec) is over limit. Maximum size of start is only 63 bits\n"); rval = -EINVAL; goto err_out; } tw32(<API key>, (nsec & 0xffffffff)); tw32(<API key>, <API key> | ((nsec >> 32) & <API key>)); tw32(<API key>, clock_ctl | <API key>); } else { tw32(<API key>, 0); tw32(<API key>, clock_ctl); } err_out: tg3_full_unlock(tp); return rval; default: break; } return -EOPNOTSUPP; } static const struct ptp_clock_info tg3_ptp_caps = { .owner = THIS_MODULE, .name = "tg3 clock", .max_adj = 250000000, .n_alarm = 0, .n_ext_ts = 0, .n_per_out = 1, .n_pins = 0, .pps = 0, .adjfreq = tg3_ptp_adjfreq, .adjtime = tg3_ptp_adjtime, .gettime = tg3_ptp_gettime, .settime = tg3_ptp_settime, .enable = tg3_ptp_enable, }; static void <API key>(struct tg3 *tp, u64 hwclock, struct <API key> *timestamp) { memset(timestamp, 0, sizeof(struct <API key>)); timestamp->hwtstamp = ns_to_ktime((hwclock & TG3_TSTAMP_MASK) + tp->ptp_adjust); } /* tp->lock must be held */ static void tg3_ptp_init(struct tg3 *tp) { if (!tg3_flag(tp, PTP_CAPABLE)) return; /* Initialize the hardware clock to the system time. */ tg3_refclk_write(tp, ktime_to_ns(ktime_get_real())); tp->ptp_adjust = 0; tp->ptp_info = tg3_ptp_caps; } /* tp->lock must be held */ static void tg3_ptp_resume(struct tg3 *tp) { if (!tg3_flag(tp, PTP_CAPABLE)) return; tg3_refclk_write(tp, ktime_to_ns(ktime_get_real()) + tp->ptp_adjust); tp->ptp_adjust = 0; } static void tg3_ptp_fini(struct tg3 *tp) { if (!tg3_flag(tp, PTP_CAPABLE) || !tp->ptp_clock) return; <API key>(tp->ptp_clock); tp->ptp_clock = NULL; tp->ptp_adjust = 0; } static inline int tg3_irq_sync(struct tg3 *tp) { return tp->irq_sync; } static inline void tg3_rd32_loop(struct tg3 *tp, u32 *dst, u32 off, u32 len) { int i; dst = (u32 *)((u8 *)dst + off); for (i = 0; i < len; i += sizeof(u32)) *dst++ = tr32(off + i); } static void <API key>(struct tg3 *tp, u32 *regs) { tg3_rd32_loop(tp, regs, TG3PCI_VENDOR, 0xb0); tg3_rd32_loop(tp, regs, MAILBOX_INTERRUPT_0, 0x200); tg3_rd32_loop(tp, regs, MAC_MODE, 0x4f0); tg3_rd32_loop(tp, regs, SNDDATAI_MODE, 0xe0); tg3_rd32_loop(tp, regs, SNDDATAC_MODE, 0x04); tg3_rd32_loop(tp, regs, SNDBDS_MODE, 0x80); tg3_rd32_loop(tp, regs, SNDBDI_MODE, 0x48); tg3_rd32_loop(tp, regs, SNDBDC_MODE, 0x04); tg3_rd32_loop(tp, regs, RCVLPC_MODE, 0x20); tg3_rd32_loop(tp, regs, RCVLPC_SELLST_BASE, 0x15c); tg3_rd32_loop(tp, regs, RCVDBDI_MODE, 0x0c); tg3_rd32_loop(tp, regs, RCVDBDI_JUMBO_BD, 0x3c); tg3_rd32_loop(tp, regs, <API key>, 0x44); tg3_rd32_loop(tp, regs, RCVDCC_MODE, 0x04); tg3_rd32_loop(tp, regs, RCVBDI_MODE, 0x20); tg3_rd32_loop(tp, regs, RCVCC_MODE, 0x14); tg3_rd32_loop(tp, regs, RCVLSC_MODE, 0x08); tg3_rd32_loop(tp, regs, MBFREE_MODE, 0x08); tg3_rd32_loop(tp, regs, HOSTCC_MODE, 0x100); if (tg3_flag(tp, SUPPORT_MSIX)) tg3_rd32_loop(tp, regs, <API key>, 0x180); tg3_rd32_loop(tp, regs, MEMARB_MODE, 0x10); tg3_rd32_loop(tp, regs, BUFMGR_MODE, 0x58); tg3_rd32_loop(tp, regs, RDMAC_MODE, 0x08); tg3_rd32_loop(tp, regs, WDMAC_MODE, 0x08); tg3_rd32_loop(tp, regs, RX_CPU_MODE, 0x04); tg3_rd32_loop(tp, regs, RX_CPU_STATE, 0x04); tg3_rd32_loop(tp, regs, RX_CPU_PGMCTR, 0x04); tg3_rd32_loop(tp, regs, RX_CPU_HWBKPT, 0x04); if (!tg3_flag(tp, 5705_PLUS)) { tg3_rd32_loop(tp, regs, TX_CPU_MODE, 0x04); tg3_rd32_loop(tp, regs, TX_CPU_STATE, 0x04); tg3_rd32_loop(tp, regs, TX_CPU_PGMCTR, 0x04); } tg3_rd32_loop(tp, regs, GRCMBOX_INTERRUPT_0, 0x110); tg3_rd32_loop(tp, regs, FTQ_RESET, 0x120); tg3_rd32_loop(tp, regs, MSGINT_MODE, 0x0c); tg3_rd32_loop(tp, regs, DMAC_MODE, 0x04); tg3_rd32_loop(tp, regs, GRC_MODE, 0x4c); if (tg3_flag(tp, NVRAM)) tg3_rd32_loop(tp, regs, NVRAM_CMD, 0x24); } static void tg3_dump_state(struct tg3 *tp) { int i; u32 *regs; regs = kzalloc(TG3_REG_BLK_SIZE, GFP_ATOMIC); if (!regs) return; if (tg3_flag(tp, PCI_EXPRESS)) { /* Read up to but not including private PCI registers */ for (i = 0; i < <API key>; i += sizeof(u32)) regs[i / sizeof(u32)] = tr32(i); } else <API key>(tp, regs); for (i = 0; i < TG3_REG_BLK_SIZE / sizeof(u32); i += 4) { if (!regs[i + 0] && !regs[i + 1] && !regs[i + 2] && !regs[i + 3]) continue; netdev_err(tp->dev, "0x%08x: 0x%08x, 0x%08x, 0x%08x, 0x%08x\n", i * 4, regs[i + 0], regs[i + 1], regs[i + 2], regs[i + 3]); } kfree(regs); for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; /* SW status block */ netdev_err(tp->dev, "%d: Host status block [%08x:%08x:(%04x:%04x:%04x):(%04x:%04x)]\n", i, tnapi->hw_status->status, tnapi->hw_status->status_tag, tnapi->hw_status->rx_jumbo_consumer, tnapi->hw_status->rx_consumer, tnapi->hw_status->rx_mini_consumer, tnapi->hw_status->idx[0].rx_producer, tnapi->hw_status->idx[0].tx_consumer); netdev_err(tp->dev, "%d: NAPI info [%08x:%08x:(%04x:%04x:%04x):%04x:(%04x:%04x:%04x:%04x)]\n", i, tnapi->last_tag, tnapi->last_irq_tag, tnapi->tx_prod, tnapi->tx_cons, tnapi->tx_pending, tnapi->rx_rcb_ptr, tnapi->prodring.rx_std_prod_idx, tnapi->prodring.rx_std_cons_idx, tnapi->prodring.rx_jmb_prod_idx, tnapi->prodring.rx_jmb_cons_idx); } } /* This is called whenever we suspect that the system chipset is re- * ordering the sequence of MMIO to the tx send mailbox. The symptom * is bogus tx completions. We try to recover by setting the * <API key> flag and resetting the chip later * in the workqueue. */ static void tg3_tx_recover(struct tg3 *tp) { BUG_ON(tg3_flag(tp, MBOX_WRITE_REORDER) || tp->write32_tx_mbox == <API key>); netdev_warn(tp->dev, "The system may be re-ordering memory-mapped I/O " "cycles to the network device, attempting to recover. " "Please report the problem to the driver maintainer " "and include system chipset information.\n"); tg3_flag_set(tp, TX_RECOVERY_PENDING); } static inline u32 tg3_tx_avail(struct tg3_napi *tnapi) { /* Tell compiler to fetch tx indices from memory. */ barrier(); return tnapi->tx_pending - ((tnapi->tx_prod - tnapi->tx_cons) & (TG3_TX_RING_SIZE - 1)); } /* Tigon3 never reports partial packet sends. So we do not * need special logic to handle SKBs that have not had all * of their frags sent yet, like SunGEM does. */ static void tg3_tx(struct tg3_napi *tnapi) { struct tg3 *tp = tnapi->tp; u32 hw_idx = tnapi->hw_status->idx[0].tx_consumer; u32 sw_idx = tnapi->tx_cons; struct netdev_queue *txq; int index = tnapi - tp->napi; unsigned int pkts_compl = 0, bytes_compl = 0; if (tg3_flag(tp, ENABLE_TSS)) index txq = netdev_get_tx_queue(tp->dev, index); while (sw_idx != hw_idx) { struct tg3_tx_ring_info *ri = &tnapi->tx_buffers[sw_idx]; struct sk_buff *skb = ri->skb; int i, tx_bug = 0; if (unlikely(skb == NULL)) { tg3_tx_recover(tp); return; } if (tnapi->tx_ring[sw_idx].len_flags & TXD_FLAG_HWTSTAMP) { struct <API key> timestamp; u64 hwclock = tr32(TG3_TX_TSTAMP_LSB); hwclock |= (u64)tr32(TG3_TX_TSTAMP_MSB) << 32; <API key>(tp, hwclock, &timestamp); skb_tstamp_tx(skb, &timestamp); } pci_unmap_single(tp->pdev, dma_unmap_addr(ri, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); ri->skb = NULL; while (ri->fragmented) { ri->fragmented = false; sw_idx = NEXT_TX(sw_idx); ri = &tnapi->tx_buffers[sw_idx]; } sw_idx = NEXT_TX(sw_idx); for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { ri = &tnapi->tx_buffers[sw_idx]; if (unlikely(ri->skb != NULL || sw_idx == hw_idx)) tx_bug = 1; pci_unmap_page(tp->pdev, dma_unmap_addr(ri, mapping), skb_frag_size(&skb_shinfo(skb)->frags[i]), PCI_DMA_TODEVICE); while (ri->fragmented) { ri->fragmented = false; sw_idx = NEXT_TX(sw_idx); ri = &tnapi->tx_buffers[sw_idx]; } sw_idx = NEXT_TX(sw_idx); } pkts_compl++; bytes_compl += skb->len; dev_kfree_skb_any(skb); if (unlikely(tx_bug)) { tg3_tx_recover(tp); return; } } <API key>(txq, pkts_compl, bytes_compl); tnapi->tx_cons = sw_idx; /* Need to make the tx_cons update visible to tg3_start_xmit() * before checking for netif_queue_stopped(). Without the * memory barrier, there is a small possibility that tg3_start_xmit() * will miss it and cause the queue to be stopped forever. */ smp_mb(); if (unlikely(<API key>(txq) && (tg3_tx_avail(tnapi) > <API key>(tnapi)))) { __netif_tx_lock(txq, smp_processor_id()); if (<API key>(txq) && (tg3_tx_avail(tnapi) > <API key>(tnapi))) netif_tx_wake_queue(txq); __netif_tx_unlock(txq); } } static void tg3_frag_free(bool is_frag, void *data) { if (is_frag) put_page(virt_to_head_page(data)); else kfree(data); } static void tg3_rx_data_free(struct tg3 *tp, struct ring_info *ri, u32 map_sz) { unsigned int skb_size = SKB_DATA_ALIGN(map_sz + TG3_RX_OFFSET(tp)) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); if (!ri->data) return; pci_unmap_single(tp->pdev, dma_unmap_addr(ri, mapping), map_sz, PCI_DMA_FROMDEVICE); tg3_frag_free(skb_size <= PAGE_SIZE, ri->data); ri->data = NULL; } /* Returns size of skb allocated or < 0 on error. * * We only need to fill in the address because the other members * of the RX descriptor are invariant, see tg3_init_rings. * * Note the purposeful assymetry of cpu vs. chip accesses. For * posting buffers we only dirty the first cache line of the RX * descriptor (containing the address). Whereas for the RX status * buffers the cpu only reads the last cacheline of the RX descriptor * (to fetch the error flags, vlan tag, checksum, and opaque cookie). */ static int tg3_alloc_rx_data(struct tg3 *tp, struct tg3_rx_prodring_set *tpr, u32 opaque_key, u32 dest_idx_unmasked, unsigned int *frag_size) { struct tg3_rx_buffer_desc *desc; struct ring_info *map; u8 *data; dma_addr_t mapping; int skb_size, data_size, dest_idx; switch (opaque_key) { case RXD_OPAQUE_RING_STD: dest_idx = dest_idx_unmasked & tp->rx_std_ring_mask; desc = &tpr->rx_std[dest_idx]; map = &tpr->rx_std_buffers[dest_idx]; data_size = tp->rx_pkt_map_sz; break; case <API key>: dest_idx = dest_idx_unmasked & tp->rx_jmb_ring_mask; desc = &tpr->rx_jmb[dest_idx].std; map = &tpr->rx_jmb_buffers[dest_idx]; data_size = TG3_RX_JMB_MAP_SZ; break; default: return -EINVAL; } /* Do not overwrite any of the map or rp information * until we are sure we can commit to a new buffer. * * Callers depend upon this behavior and assume that * we leave everything unchanged if we fail. */ skb_size = SKB_DATA_ALIGN(data_size + TG3_RX_OFFSET(tp)) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); if (skb_size <= PAGE_SIZE) { data = netdev_alloc_frag(skb_size); *frag_size = skb_size; } else { data = kmalloc(skb_size, GFP_ATOMIC); *frag_size = 0; } if (!data) return -ENOMEM; mapping = pci_map_single(tp->pdev, data + TG3_RX_OFFSET(tp), data_size, PCI_DMA_FROMDEVICE); if (unlikely(<API key>(tp->pdev, mapping))) { tg3_frag_free(skb_size <= PAGE_SIZE, data); return -EIO; } map->data = data; dma_unmap_addr_set(map, mapping, mapping); desc->addr_hi = ((u64)mapping >> 32); desc->addr_lo = ((u64)mapping & 0xffffffff); return data_size; } /* We only need to move over in the address because the other * members of the RX descriptor are invariant. See notes above * tg3_alloc_rx_data for full details. */ static void tg3_recycle_rx(struct tg3_napi *tnapi, struct tg3_rx_prodring_set *dpr, u32 opaque_key, int src_idx, u32 dest_idx_unmasked) { struct tg3 *tp = tnapi->tp; struct tg3_rx_buffer_desc *src_desc, *dest_desc; struct ring_info *src_map, *dest_map; struct tg3_rx_prodring_set *spr = &tp->napi[0].prodring; int dest_idx; switch (opaque_key) { case RXD_OPAQUE_RING_STD: dest_idx = dest_idx_unmasked & tp->rx_std_ring_mask; dest_desc = &dpr->rx_std[dest_idx]; dest_map = &dpr->rx_std_buffers[dest_idx]; src_desc = &spr->rx_std[src_idx]; src_map = &spr->rx_std_buffers[src_idx]; break; case <API key>: dest_idx = dest_idx_unmasked & tp->rx_jmb_ring_mask; dest_desc = &dpr->rx_jmb[dest_idx].std; dest_map = &dpr->rx_jmb_buffers[dest_idx]; src_desc = &spr->rx_jmb[src_idx].std; src_map = &spr->rx_jmb_buffers[src_idx]; break; default: return; } dest_map->data = src_map->data; dma_unmap_addr_set(dest_map, mapping, dma_unmap_addr(src_map, mapping)); dest_desc->addr_hi = src_desc->addr_hi; dest_desc->addr_lo = src_desc->addr_lo; /* Ensure that the update to the skb happens after the physical * addresses have been transferred to the new BD location. */ smp_wmb(); src_map->data = NULL; } /* The RX ring scheme is composed of multiple rings which post fresh * buffers to the chip, and one special ring the chip uses to report * status back to the host. * * The special ring reports the status of received packets to the * host. The chip does not write into the original descriptor the * RX buffer was obtained from. The chip simply takes the original * descriptor as provided by the host, updates the status and length * field, then writes this into the next status ring entry. * * Each ring the host uses to post buffers to the chip is described * by a TG3_BDINFO entry in the chips SRAM area. When a packet arrives, * it is first placed into the on-chip ram. When the packet's length * is known, it walks down the TG3_BDINFO entries to select the ring. * Each TG3_BDINFO specifies a MAXLEN field and the first TG3_BDINFO * which is within the range of the new packet's length is chosen. * * The "separate ring for rx status" scheme may sound queer, but it makes * sense from a cache coherency perspective. If only the host writes * to the buffer post rings, and only the chip writes to the rx status * rings, then cache lines never move beyond shared-modified state. * If both the host and chip were to write into the same ring, cache line * eviction could occur since both entities want it in an exclusive state. */ static int tg3_rx(struct tg3_napi *tnapi, int budget) { struct tg3 *tp = tnapi->tp; u32 work_mask, rx_std_posted = 0; u32 std_prod_idx, jmb_prod_idx; u32 sw_idx = tnapi->rx_rcb_ptr; u16 hw_idx; int received; struct tg3_rx_prodring_set *tpr = &tnapi->prodring; hw_idx = *(tnapi->rx_rcb_prod_idx); /* * We need to order the read of hw_idx and the read of * the opaque cookie. */ rmb(); work_mask = 0; received = 0; std_prod_idx = tpr->rx_std_prod_idx; jmb_prod_idx = tpr->rx_jmb_prod_idx; while (sw_idx != hw_idx && budget > 0) { struct ring_info *ri; struct tg3_rx_buffer_desc *desc = &tnapi->rx_rcb[sw_idx]; unsigned int len; struct sk_buff *skb; dma_addr_t dma_addr; u32 opaque_key, desc_idx, *post_ptr; u8 *data; u64 tstamp = 0; desc_idx = desc->opaque & <API key>; opaque_key = desc->opaque & <API key>; if (opaque_key == RXD_OPAQUE_RING_STD) { ri = &tp->napi[0].prodring.rx_std_buffers[desc_idx]; dma_addr = dma_unmap_addr(ri, mapping); data = ri->data; post_ptr = &std_prod_idx; rx_std_posted++; } else if (opaque_key == <API key>) { ri = &tp->napi[0].prodring.rx_jmb_buffers[desc_idx]; dma_addr = dma_unmap_addr(ri, mapping); data = ri->data; post_ptr = &jmb_prod_idx; } else goto next_pkt_nopost; work_mask |= opaque_key; if (desc->err_vlan & RXD_ERR_MASK) { drop_it: tg3_recycle_rx(tnapi, tpr, opaque_key, desc_idx, *post_ptr); drop_it_no_recycle: /* Other statistics kept track of by card. */ tp->rx_dropped++; goto next_pkt; } prefetch(data + TG3_RX_OFFSET(tp)); len = ((desc->idx_len & RXD_LEN_MASK) >> RXD_LEN_SHIFT) - ETH_FCS_LEN; if ((desc->type_flags & <API key>) == <API key> || (desc->type_flags & <API key>) == <API key>) { tstamp = tr32(TG3_RX_TSTAMP_LSB); tstamp |= (u64)tr32(TG3_RX_TSTAMP_MSB) << 32; } if (len > TG3_RX_COPY_THRESH(tp)) { int skb_size; unsigned int frag_size; skb_size = tg3_alloc_rx_data(tp, tpr, opaque_key, *post_ptr, &frag_size); if (skb_size < 0) goto drop_it; pci_unmap_single(tp->pdev, dma_addr, skb_size, PCI_DMA_FROMDEVICE); /* Ensure that the update to the data happens * after the usage of the old DMA mapping. */ smp_wmb(); ri->data = NULL; skb = build_skb(data, frag_size); if (!skb) { tg3_frag_free(frag_size != 0, data); goto drop_it_no_recycle; } skb_reserve(skb, TG3_RX_OFFSET(tp)); } else { tg3_recycle_rx(tnapi, tpr, opaque_key, desc_idx, *post_ptr); skb = netdev_alloc_skb(tp->dev, len + TG3_RAW_IP_ALIGN); if (skb == NULL) goto drop_it_no_recycle; skb_reserve(skb, TG3_RAW_IP_ALIGN); <API key>(tp->pdev, dma_addr, len, PCI_DMA_FROMDEVICE); memcpy(skb->data, data + TG3_RX_OFFSET(tp), len); <API key>(tp->pdev, dma_addr, len, PCI_DMA_FROMDEVICE); } skb_put(skb, len); if (tstamp) <API key>(tp, tstamp, skb_hwtstamps(skb)); if ((tp->dev->features & NETIF_F_RXCSUM) && (desc->type_flags & <API key>) && (((desc->ip_tcp_csum & RXD_TCPCSUM_MASK) >> RXD_TCPCSUM_SHIFT) == 0xffff)) skb->ip_summed = <API key>; else <API key>(skb); skb->protocol = eth_type_trans(skb, tp->dev); if (len > (tp->dev->mtu + ETH_HLEN) && skb->protocol != htons(ETH_P_8021Q)) { dev_kfree_skb_any(skb); goto drop_it_no_recycle; } if (desc->type_flags & RXD_FLAG_VLAN && !(tp->rx_mode & <API key>)) <API key>(skb, htons(ETH_P_8021Q), desc->err_vlan & RXD_VLAN_MASK); napi_gro_receive(&tnapi->napi, skb); received++; budget next_pkt: (*post_ptr)++; if (unlikely(rx_std_posted >= tp->rx_std_max_post)) { tpr->rx_std_prod_idx = std_prod_idx & tp->rx_std_ring_mask; tw32_rx_mbox(<API key>, tpr->rx_std_prod_idx); work_mask &= ~RXD_OPAQUE_RING_STD; rx_std_posted = 0; } next_pkt_nopost: sw_idx++; sw_idx &= tp->rx_ret_ring_mask; /* Refresh hw_idx to see if there is new work */ if (sw_idx == hw_idx) { hw_idx = *(tnapi->rx_rcb_prod_idx); rmb(); } } /* ACK the status ring. */ tnapi->rx_rcb_ptr = sw_idx; tw32_rx_mbox(tnapi->consmbox, sw_idx); /* Refill RX ring(s). */ if (!tg3_flag(tp, ENABLE_RSS)) { /* Sync BD data before updating mailbox */ wmb(); if (work_mask & RXD_OPAQUE_RING_STD) { tpr->rx_std_prod_idx = std_prod_idx & tp->rx_std_ring_mask; tw32_rx_mbox(<API key>, tpr->rx_std_prod_idx); } if (work_mask & <API key>) { tpr->rx_jmb_prod_idx = jmb_prod_idx & tp->rx_jmb_ring_mask; tw32_rx_mbox(<API key>, tpr->rx_jmb_prod_idx); } mmiowb(); } else if (work_mask) { /* rx_std_buffers[] and rx_jmb_buffers[] entries must be * updated before the producer indices can be updated. */ smp_wmb(); tpr->rx_std_prod_idx = std_prod_idx & tp->rx_std_ring_mask; tpr->rx_jmb_prod_idx = jmb_prod_idx & tp->rx_jmb_ring_mask; if (tnapi != &tp->napi[1]) { tp->rx_refill = true; napi_schedule(&tp->napi[1].napi); } } return received; } static void tg3_poll_link(struct tg3 *tp) { /* handle link change and other phy events */ if (!(tg3_flag(tp, USE_LINKCHG_REG) || tg3_flag(tp, POLL_SERDES))) { struct tg3_hw_status *sblk = tp->napi[0].hw_status; if (sblk->status & SD_STATUS_LINK_CHG) { sblk->status = SD_STATUS_UPDATED | (sblk->status & ~SD_STATUS_LINK_CHG); spin_lock(&tp->lock); if (tg3_flag(tp, USE_PHYLIB)) { tw32_f(MAC_STATUS, (<API key> | <API key> | <API key> | <API key>)); udelay(40); } else tg3_setup_phy(tp, false); spin_unlock(&tp->lock); } } } static int <API key>(struct tg3 *tp, struct tg3_rx_prodring_set *dpr, struct tg3_rx_prodring_set *spr) { u32 si, di, cpycnt, src_prod_idx; int i, err = 0; while (1) { src_prod_idx = spr->rx_std_prod_idx; /* Make sure updates to the rx_std_buffers[] entries and the * standard producer index are seen in the correct order. */ smp_rmb(); if (spr->rx_std_cons_idx == src_prod_idx) break; if (spr->rx_std_cons_idx < src_prod_idx) cpycnt = src_prod_idx - spr->rx_std_cons_idx; else cpycnt = tp->rx_std_ring_mask + 1 - spr->rx_std_cons_idx; cpycnt = min(cpycnt, tp->rx_std_ring_mask + 1 - dpr->rx_std_prod_idx); si = spr->rx_std_cons_idx; di = dpr->rx_std_prod_idx; for (i = di; i < di + cpycnt; i++) { if (dpr->rx_std_buffers[i].data) { cpycnt = i - di; err = -ENOSPC; break; } } if (!cpycnt) break; /* Ensure that updates to the rx_std_buffers ring and the * shadowed hardware producer ring from tg3_recycle_skb() are * ordered correctly WRT the skb check above. */ smp_rmb(); memcpy(&dpr->rx_std_buffers[di], &spr->rx_std_buffers[si], cpycnt * sizeof(struct ring_info)); for (i = 0; i < cpycnt; i++, di++, si++) { struct tg3_rx_buffer_desc *sbd, *dbd; sbd = &spr->rx_std[si]; dbd = &dpr->rx_std[di]; dbd->addr_hi = sbd->addr_hi; dbd->addr_lo = sbd->addr_lo; } spr->rx_std_cons_idx = (spr->rx_std_cons_idx + cpycnt) & tp->rx_std_ring_mask; dpr->rx_std_prod_idx = (dpr->rx_std_prod_idx + cpycnt) & tp->rx_std_ring_mask; } while (1) { src_prod_idx = spr->rx_jmb_prod_idx; /* Make sure updates to the rx_jmb_buffers[] entries and * the jumbo producer index are seen in the correct order. */ smp_rmb(); if (spr->rx_jmb_cons_idx == src_prod_idx) break; if (spr->rx_jmb_cons_idx < src_prod_idx) cpycnt = src_prod_idx - spr->rx_jmb_cons_idx; else cpycnt = tp->rx_jmb_ring_mask + 1 - spr->rx_jmb_cons_idx; cpycnt = min(cpycnt, tp->rx_jmb_ring_mask + 1 - dpr->rx_jmb_prod_idx); si = spr->rx_jmb_cons_idx; di = dpr->rx_jmb_prod_idx; for (i = di; i < di + cpycnt; i++) { if (dpr->rx_jmb_buffers[i].data) { cpycnt = i - di; err = -ENOSPC; break; } } if (!cpycnt) break; /* Ensure that updates to the rx_jmb_buffers ring and the * shadowed hardware producer ring from tg3_recycle_skb() are * ordered correctly WRT the skb check above. */ smp_rmb(); memcpy(&dpr->rx_jmb_buffers[di], &spr->rx_jmb_buffers[si], cpycnt * sizeof(struct ring_info)); for (i = 0; i < cpycnt; i++, di++, si++) { struct tg3_rx_buffer_desc *sbd, *dbd; sbd = &spr->rx_jmb[si].std; dbd = &dpr->rx_jmb[di].std; dbd->addr_hi = sbd->addr_hi; dbd->addr_lo = sbd->addr_lo; } spr->rx_jmb_cons_idx = (spr->rx_jmb_cons_idx + cpycnt) & tp->rx_jmb_ring_mask; dpr->rx_jmb_prod_idx = (dpr->rx_jmb_prod_idx + cpycnt) & tp->rx_jmb_ring_mask; } return err; } static int tg3_poll_work(struct tg3_napi *tnapi, int work_done, int budget) { struct tg3 *tp = tnapi->tp; /* run TX completion thread */ if (tnapi->hw_status->idx[0].tx_consumer != tnapi->tx_cons) { tg3_tx(tnapi); if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING))) return work_done; } if (!tnapi->rx_rcb_prod_idx) return work_done; /* run RX thread, within the bounds set by NAPI. * All RX "locking" is done by ensuring outside * code synchronizes with tg3->napi.poll() */ if (*(tnapi->rx_rcb_prod_idx) != tnapi->rx_rcb_ptr) work_done += tg3_rx(tnapi, budget - work_done); if (tg3_flag(tp, ENABLE_RSS) && tnapi == &tp->napi[1]) { struct tg3_rx_prodring_set *dpr = &tp->napi[0].prodring; int i, err = 0; u32 std_prod_idx = dpr->rx_std_prod_idx; u32 jmb_prod_idx = dpr->rx_jmb_prod_idx; tp->rx_refill = false; for (i = 1; i <= tp->rxq_cnt; i++) err |= <API key>(tp, dpr, &tp->napi[i].prodring); wmb(); if (std_prod_idx != dpr->rx_std_prod_idx) tw32_rx_mbox(<API key>, dpr->rx_std_prod_idx); if (jmb_prod_idx != dpr->rx_jmb_prod_idx) tw32_rx_mbox(<API key>, dpr->rx_jmb_prod_idx); mmiowb(); if (err) tw32_f(HOSTCC_MODE, tp->coal_now); } return work_done; } static inline void <API key>(struct tg3 *tp) { if (!test_and_set_bit(<API key>, tp->tg3_flags)) schedule_work(&tp->reset_task); } static inline void <API key>(struct tg3 *tp) { cancel_work_sync(&tp->reset_task); tg3_flag_clear(tp, RESET_TASK_PENDING); tg3_flag_clear(tp, TX_RECOVERY_PENDING); } static int tg3_poll_msix(struct napi_struct *napi, int budget) { struct tg3_napi *tnapi = container_of(napi, struct tg3_napi, napi); struct tg3 *tp = tnapi->tp; int work_done = 0; struct tg3_hw_status *sblk = tnapi->hw_status; while (1) { work_done = tg3_poll_work(tnapi, work_done, budget); if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING))) goto tx_recovery; if (unlikely(work_done >= budget)) break; /* tp->last_tag is used in tg3_int_reenable() below * to tell the hw how much work has been processed, * so we must read it before checking for more work. */ tnapi->last_tag = sblk->status_tag; tnapi->last_irq_tag = tnapi->last_tag; rmb(); /* check for RX/TX work to do */ if (likely(sblk->idx[0].tx_consumer == tnapi->tx_cons && *(tnapi->rx_rcb_prod_idx) == tnapi->rx_rcb_ptr)) { /* This test here is not race free, but will reduce * the number of interrupts by looping again. */ if (tnapi == &tp->napi[1] && tp->rx_refill) continue; napi_complete(napi); /* Reenable interrupts. */ tw32_mailbox(tnapi->int_mbox, tnapi->last_tag << 24); /* This test here is synchronized by napi_schedule() * and napi_complete() to close the race condition. */ if (unlikely(tnapi == &tp->napi[1] && tp->rx_refill)) { tw32(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | tnapi->coal_now); } mmiowb(); break; } } return work_done; tx_recovery: /* work_done is guaranteed to be less than budget. */ napi_complete(napi); <API key>(tp); return work_done; } static void tg3_process_error(struct tg3 *tp) { u32 val; bool real_error = false; if (tg3_flag(tp, ERROR_PROCESSED)) return; /* Check Flow Attention register */ val = tr32(HOSTCC_FLOW_ATTN); if (val & ~<API key>) { netdev_err(tp->dev, "FLOW Attention error. Resetting chip.\n"); real_error = true; } if (tr32(MSGINT_STATUS) & ~<API key>) { netdev_err(tp->dev, "MSI Status error. Resetting chip.\n"); real_error = true; } if (tr32(RDMAC_STATUS) || tr32(WDMAC_STATUS)) { netdev_err(tp->dev, "DMA Status error. Resetting chip.\n"); real_error = true; } if (!real_error) return; tg3_dump_state(tp); tg3_flag_set(tp, ERROR_PROCESSED); <API key>(tp); } static int tg3_poll(struct napi_struct *napi, int budget) { struct tg3_napi *tnapi = container_of(napi, struct tg3_napi, napi); struct tg3 *tp = tnapi->tp; int work_done = 0; struct tg3_hw_status *sblk = tnapi->hw_status; while (1) { if (sblk->status & SD_STATUS_ERROR) tg3_process_error(tp); tg3_poll_link(tp); work_done = tg3_poll_work(tnapi, work_done, budget); if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING))) goto tx_recovery; if (unlikely(work_done >= budget)) break; if (tg3_flag(tp, TAGGED_STATUS)) { /* tp->last_tag is used in tg3_int_reenable() below * to tell the hw how much work has been processed, * so we must read it before checking for more work. */ tnapi->last_tag = sblk->status_tag; tnapi->last_irq_tag = tnapi->last_tag; rmb(); } else sblk->status &= ~SD_STATUS_UPDATED; if (likely(!tg3_has_work(tnapi))) { napi_complete(napi); tg3_int_reenable(tnapi); break; } } return work_done; tx_recovery: /* work_done is guaranteed to be less than budget. */ napi_complete(napi); <API key>(tp); return work_done; } static void tg3_napi_disable(struct tg3 *tp) { int i; for (i = tp->irq_cnt - 1; i >= 0; i napi_disable(&tp->napi[i].napi); } static void tg3_napi_enable(struct tg3 *tp) { int i; for (i = 0; i < tp->irq_cnt; i++) napi_enable(&tp->napi[i].napi); } static void tg3_napi_init(struct tg3 *tp) { int i; netif_napi_add(tp->dev, &tp->napi[0].napi, tg3_poll, 64); for (i = 1; i < tp->irq_cnt; i++) netif_napi_add(tp->dev, &tp->napi[i].napi, tg3_poll_msix, 64); } static void tg3_napi_fini(struct tg3 *tp) { int i; for (i = 0; i < tp->irq_cnt; i++) netif_napi_del(&tp->napi[i].napi); } static inline void tg3_netif_stop(struct tg3 *tp) { tp->dev->trans_start = jiffies; /* prevent tx timeout */ tg3_napi_disable(tp); netif_carrier_off(tp->dev); netif_tx_disable(tp->dev); } /* tp->lock must be held */ static inline void tg3_netif_start(struct tg3 *tp) { tg3_ptp_resume(tp); /* NOTE: unconditional <API key> is only * appropriate so long as all callers are assured to * have free tx slots (such as after tg3_init_hw) */ <API key>(tp->dev); if (tp->link_up) netif_carrier_on(tp->dev); tg3_napi_enable(tp); tp->napi[0].hw_status->status |= SD_STATUS_UPDATED; tg3_enable_ints(tp); } static void tg3_irq_quiesce(struct tg3 *tp) { int i; BUG_ON(tp->irq_sync); tp->irq_sync = 1; smp_mb(); for (i = 0; i < tp->irq_cnt; i++) synchronize_irq(tp->napi[i].irq_vec); } /* Fully shutdown all tg3 driver activity elsewhere in the system. * If irq_sync is non-zero, then the IRQ handler must be synchronized * with as well. Most of the time, this is not necessary except when * shutting down the device. */ static inline void tg3_full_lock(struct tg3 *tp, int irq_sync) { spin_lock_bh(&tp->lock); if (irq_sync) tg3_irq_quiesce(tp); } static inline void tg3_full_unlock(struct tg3 *tp) { spin_unlock_bh(&tp->lock); } /* One-shot MSI handler - Chip automatically disables interrupt * after sending MSI so driver doesn't have to do it. */ static irqreturn_t tg3_msi_1shot(int irq, void *dev_id) { struct tg3_napi *tnapi = dev_id; struct tg3 *tp = tnapi->tp; prefetch(tnapi->hw_status); if (tnapi->rx_rcb) prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]); if (likely(!tg3_irq_sync(tp))) napi_schedule(&tnapi->napi); return IRQ_HANDLED; } /* MSI ISR - No need to check for interrupt sharing and no need to * flush status block and interrupt mailbox. PCI ordering rules * guarantee that MSI will arrive after the status block. */ static irqreturn_t tg3_msi(int irq, void *dev_id) { struct tg3_napi *tnapi = dev_id; struct tg3 *tp = tnapi->tp; prefetch(tnapi->hw_status); if (tnapi->rx_rcb) prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]); /* * Writing any value to intr-mbox-0 clears PCI INTA# and * chip-internal interrupt pending events. * Writing non-zero to intr-mbox-0 additional tells the * NIC to stop sending us irqs, engaging "in-intr-handler" * event coalescing. */ tw32_mailbox(tnapi->int_mbox, 0x00000001); if (likely(!tg3_irq_sync(tp))) napi_schedule(&tnapi->napi); return IRQ_RETVAL(1); } static irqreturn_t tg3_interrupt(int irq, void *dev_id) { struct tg3_napi *tnapi = dev_id; struct tg3 *tp = tnapi->tp; struct tg3_hw_status *sblk = tnapi->hw_status; unsigned int handled = 1; /* In INTx mode, it is possible for the interrupt to arrive at * the CPU before the status block posted prior to the interrupt. * Reading the PCI State register will confirm whether the * interrupt is ours and will flush the status block. */ if (unlikely(!(sblk->status & SD_STATUS_UPDATED))) { if (tg3_flag(tp, CHIP_RESETTING) || (tr32(TG3PCI_PCISTATE) & <API key>)) { handled = 0; goto out; } } /* * Writing any value to intr-mbox-0 clears PCI INTA# and * chip-internal interrupt pending events. * Writing non-zero to intr-mbox-0 additional tells the * NIC to stop sending us irqs, engaging "in-intr-handler" * event coalescing. * * Flush the mailbox to de-assert the IRQ immediately to prevent * spurious interrupts. The flush impacts performance but * excessive spurious interrupts can be worse in some cases. */ tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW, 0x00000001); if (tg3_irq_sync(tp)) goto out; sblk->status &= ~SD_STATUS_UPDATED; if (likely(tg3_has_work(tnapi))) { prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]); napi_schedule(&tnapi->napi); } else { /* No work, shared interrupt perhaps? re-enable * interrupts, and flush that PCI write */ tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW, 0x00000000); } out: return IRQ_RETVAL(handled); } static irqreturn_t <API key>(int irq, void *dev_id) { struct tg3_napi *tnapi = dev_id; struct tg3 *tp = tnapi->tp; struct tg3_hw_status *sblk = tnapi->hw_status; unsigned int handled = 1; /* In INTx mode, it is possible for the interrupt to arrive at * the CPU before the status block posted prior to the interrupt. * Reading the PCI State register will confirm whether the * interrupt is ours and will flush the status block. */ if (unlikely(sblk->status_tag == tnapi->last_irq_tag)) { if (tg3_flag(tp, CHIP_RESETTING) || (tr32(TG3PCI_PCISTATE) & <API key>)) { handled = 0; goto out; } } /* * writing any value to intr-mbox-0 clears PCI INTA# and * chip-internal interrupt pending events. * writing non-zero to intr-mbox-0 additional tells the * NIC to stop sending us irqs, engaging "in-intr-handler" * event coalescing. * * Flush the mailbox to de-assert the IRQ immediately to prevent * spurious interrupts. The flush impacts performance but * excessive spurious interrupts can be worse in some cases. */ tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW, 0x00000001); /* * In a shared interrupt configuration, sometimes other devices' * interrupts will scream. We record the current status tag here * so that the above check can report that the screaming interrupts * are unhandled. Eventually they will be silenced. */ tnapi->last_irq_tag = sblk->status_tag; if (tg3_irq_sync(tp)) goto out; prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]); napi_schedule(&tnapi->napi); out: return IRQ_RETVAL(handled); } /* ISR for interrupt test */ static irqreturn_t tg3_test_isr(int irq, void *dev_id) { struct tg3_napi *tnapi = dev_id; struct tg3 *tp = tnapi->tp; struct tg3_hw_status *sblk = tnapi->hw_status; if ((sblk->status & SD_STATUS_UPDATED) || !(tr32(TG3PCI_PCISTATE) & <API key>)) { tg3_disable_ints(tp); return IRQ_RETVAL(1); } return IRQ_RETVAL(0); } #ifdef <API key> static void tg3_poll_controller(struct net_device *dev) { int i; struct tg3 *tp = netdev_priv(dev); if (tg3_irq_sync(tp)) return; for (i = 0; i < tp->irq_cnt; i++) tg3_interrupt(tp->napi[i].irq_vec, &tp->napi[i]); } #endif static void tg3_tx_timeout(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); if (netif_msg_tx_err(tp)) { netdev_err(dev, "transmit timed out, resetting\n"); tg3_dump_state(tp); } <API key>(tp); } /* Test for DMA buffers crossing any 4GB boundaries: 4G, 8G, etc */ static inline int <API key>(dma_addr_t mapping, int len) { u32 base = (u32) mapping & 0xffffffff; return base + len + 8 < base; } /* Test for TSO DMA buffers that cross into regions which are within MSS bytes * of any 4GB boundaries: 4G, 8G, etc */ static inline int <API key>(struct tg3 *tp, dma_addr_t mapping, u32 len, u32 mss) { if (tg3_asic_rev(tp) == ASIC_REV_5762 && mss) { u32 base = (u32) mapping & 0xffffffff; return ((base + len + (mss & 0x3fff)) < base); } return 0; } /* Test for DMA addresses > 40-bit */ static inline int <API key>(struct tg3 *tp, dma_addr_t mapping, int len) { #if defined(CONFIG_HIGHMEM) && (BITS_PER_LONG == 64) if (tg3_flag(tp, 40BIT_DMA_BUG)) return ((u64) mapping + len) > DMA_BIT_MASK(40); return 0; #else return 0; #endif } static inline void tg3_tx_set_bd(struct tg3_tx_buffer_desc *txbd, dma_addr_t mapping, u32 len, u32 flags, u32 mss, u32 vlan) { txbd->addr_hi = ((u64) mapping >> 32); txbd->addr_lo = ((u64) mapping & 0xffffffff); txbd->len_flags = (len << TXD_LEN_SHIFT) | (flags & 0x0000ffff); txbd->vlan_tag = (mss << TXD_MSS_SHIFT) | (vlan << TXD_VLAN_TAG_SHIFT); } static bool tg3_tx_frag_set(struct tg3_napi *tnapi, u32 *entry, u32 *budget, dma_addr_t map, u32 len, u32 flags, u32 mss, u32 vlan) { struct tg3 *tp = tnapi->tp; bool hwbug = false; if (tg3_flag(tp, SHORT_DMA_BUG) && len <= 8) hwbug = true; if (<API key>(map, len)) hwbug = true; if (<API key>(tp, map, len, mss)) hwbug = true; if (<API key>(tp, map, len)) hwbug = true; if (tp->dma_limit) { u32 prvidx = *entry; u32 tmp_flag = flags & ~TXD_FLAG_END; while (len > tp->dma_limit && *budget) { u32 frag_len = tp->dma_limit; len -= tp->dma_limit; /* Avoid the 8byte DMA problem */ if (len <= 8) { len += tp->dma_limit / 2; frag_len = tp->dma_limit / 2; } tnapi->tx_buffers[*entry].fragmented = true; tg3_tx_set_bd(&tnapi->tx_ring[*entry], map, frag_len, tmp_flag, mss, vlan); *budget -= 1; prvidx = *entry; *entry = NEXT_TX(*entry); map += frag_len; } if (len) { if (*budget) { tg3_tx_set_bd(&tnapi->tx_ring[*entry], map, len, flags, mss, vlan); *budget -= 1; *entry = NEXT_TX(*entry); } else { hwbug = true; tnapi->tx_buffers[prvidx].fragmented = false; } } } else { tg3_tx_set_bd(&tnapi->tx_ring[*entry], map, len, flags, mss, vlan); *entry = NEXT_TX(*entry); } return hwbug; } static void tg3_tx_skb_unmap(struct tg3_napi *tnapi, u32 entry, int last) { int i; struct sk_buff *skb; struct tg3_tx_ring_info *txb = &tnapi->tx_buffers[entry]; skb = txb->skb; txb->skb = NULL; pci_unmap_single(tnapi->tp->pdev, dma_unmap_addr(txb, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); while (txb->fragmented) { txb->fragmented = false; entry = NEXT_TX(entry); txb = &tnapi->tx_buffers[entry]; } for (i = 0; i <= last; i++) { const skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; entry = NEXT_TX(entry); txb = &tnapi->tx_buffers[entry]; pci_unmap_page(tnapi->tp->pdev, dma_unmap_addr(txb, mapping), skb_frag_size(frag), PCI_DMA_TODEVICE); while (txb->fragmented) { txb->fragmented = false; entry = NEXT_TX(entry); txb = &tnapi->tx_buffers[entry]; } } } /* Workaround 4GB and 40-bit hardware DMA bugs. */ static int <API key>(struct tg3_napi *tnapi, struct sk_buff **pskb, u32 *entry, u32 *budget, u32 base_flags, u32 mss, u32 vlan) { struct tg3 *tp = tnapi->tp; struct sk_buff *new_skb, *skb = *pskb; dma_addr_t new_addr = 0; int ret = 0; if (tg3_asic_rev(tp) != ASIC_REV_5701) new_skb = skb_copy(skb, GFP_ATOMIC); else { int more_headroom = 4 - ((unsigned long)skb->data & 3); new_skb = skb_copy_expand(skb, skb_headroom(skb) + more_headroom, skb_tailroom(skb), GFP_ATOMIC); } if (!new_skb) { ret = -1; } else { /* New SKB is guaranteed to be linear. */ new_addr = pci_map_single(tp->pdev, new_skb->data, new_skb->len, PCI_DMA_TODEVICE); /* Make sure the mapping succeeded */ if (<API key>(tp->pdev, new_addr)) { dev_kfree_skb_any(new_skb); ret = -1; } else { u32 save_entry = *entry; base_flags |= TXD_FLAG_END; tnapi->tx_buffers[*entry].skb = new_skb; dma_unmap_addr_set(&tnapi->tx_buffers[*entry], mapping, new_addr); if (tg3_tx_frag_set(tnapi, entry, budget, new_addr, new_skb->len, base_flags, mss, vlan)) { tg3_tx_skb_unmap(tnapi, save_entry, -1); dev_kfree_skb_any(new_skb); ret = -1; } } } dev_kfree_skb_any(skb); *pskb = new_skb; return ret; } static netdev_tx_t tg3_start_xmit(struct sk_buff *, struct net_device *); /* Use GSO to workaround a rare TSO bug that may be triggered when the * TSO header is greater than 80 bytes. */ static int tg3_tso_bug(struct tg3 *tp, struct sk_buff *skb) { struct sk_buff *segs, *nskb; u32 frag_cnt_est = skb_shinfo(skb)->gso_segs * 3; /* Estimate the number of fragments in the worst case */ if (unlikely(tg3_tx_avail(&tp->napi[0]) <= frag_cnt_est)) { netif_stop_queue(tp->dev); /* netif_tx_stop_queue() must be done before checking * checking tx index in tg3_tx_avail() below, because in * tg3_tx(), we update tx index before checking for * <API key>(). */ smp_mb(); if (tg3_tx_avail(&tp->napi[0]) <= frag_cnt_est) return NETDEV_TX_BUSY; netif_wake_queue(tp->dev); } segs = skb_gso_segment(skb, tp->dev->features & ~NETIF_F_TSO); if (IS_ERR(segs)) goto tg3_tso_bug_end; do { nskb = segs; segs = segs->next; nskb->next = NULL; tg3_start_xmit(nskb, tp->dev); } while (segs); tg3_tso_bug_end: dev_kfree_skb_any(skb); return NETDEV_TX_OK; } /* hard_start_xmit for all devices */ static netdev_tx_t tg3_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); u32 len, entry, base_flags, mss, vlan = 0; u32 budget; int i = -1, would_hit_hwbug; dma_addr_t mapping; struct tg3_napi *tnapi; struct netdev_queue *txq; unsigned int last; struct iphdr *iph = NULL; struct tcphdr *tcph = NULL; __sum16 tcp_csum = 0, ip_csum = 0; __be16 ip_tot_len = 0; txq = netdev_get_tx_queue(dev, <API key>(skb)); tnapi = &tp->napi[<API key>(skb)]; if (tg3_flag(tp, ENABLE_TSS)) tnapi++; budget = tg3_tx_avail(tnapi); /* We are running in BH disabled context with netif_tx_lock * and TX reclaim runs via tp->napi.poll inside of a software * interrupt. Furthermore, IRQ processing runs lockless so we have * no IRQ context deadlocks to worry about either. Rejoice! */ if (unlikely(budget <= (skb_shinfo(skb)->nr_frags + 1))) { if (!<API key>(txq)) { netif_tx_stop_queue(txq); /* This is a hard error, log it. */ netdev_err(dev, "BUG! Tx Ring full when queue awake!\n"); } return NETDEV_TX_BUSY; } entry = tnapi->tx_prod; base_flags = 0; if (skb->ip_summed == CHECKSUM_PARTIAL) base_flags |= <API key>; mss = skb_shinfo(skb)->gso_size; if (mss) { u32 tcp_opt_len, hdr_len; if (skb_cow_head(skb, 0)) goto drop; iph = ip_hdr(skb); tcp_opt_len = tcp_optlen(skb); hdr_len = <API key>(skb) + tcp_hdrlen(skb) - ETH_HLEN; if (!skb_is_gso_v6(skb)) { if (unlikely((ETH_HLEN + hdr_len) > 80) && tg3_flag(tp, TSO_BUG)) return tg3_tso_bug(tp, skb); ip_csum = iph->check; ip_tot_len = iph->tot_len; iph->check = 0; iph->tot_len = htons(mss + hdr_len); } base_flags |= (<API key> | <API key>); tcph = tcp_hdr(skb); tcp_csum = tcph->check; if (tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) { tcph->check = 0; base_flags &= ~<API key>; } else { tcph->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr, 0, IPPROTO_TCP, 0); } if (tg3_flag(tp, HW_TSO_3)) { mss |= (hdr_len & 0xc) << 12; if (hdr_len & 0x10) base_flags |= 0x00000010; base_flags |= (hdr_len & 0x3e0) << 5; } else if (tg3_flag(tp, HW_TSO_2)) mss |= hdr_len << 9; else if (tg3_flag(tp, HW_TSO_1) || tg3_asic_rev(tp) == ASIC_REV_5705) { if (tcp_opt_len || iph->ihl > 5) { int tsflags; tsflags = (iph->ihl - 5) + (tcp_opt_len >> 2); mss |= (tsflags << 11); } } else { if (tcp_opt_len || iph->ihl > 5) { int tsflags; tsflags = (iph->ihl - 5) + (tcp_opt_len >> 2); base_flags |= tsflags << 12; } } } if (tg3_flag(tp, USE_JUMBO_BDFLAG) && !mss && skb->len > VLAN_ETH_FRAME_LEN) base_flags |= TXD_FLAG_JMB_PKT; if (vlan_tx_tag_present(skb)) { base_flags |= TXD_FLAG_VLAN; vlan = vlan_tx_tag_get(skb); } if ((unlikely(skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP)) && tg3_flag(tp, TX_TSTAMP_EN)) { skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS; base_flags |= TXD_FLAG_HWTSTAMP; } len = skb_headlen(skb); mapping = pci_map_single(tp->pdev, skb->data, len, PCI_DMA_TODEVICE); if (<API key>(tp->pdev, mapping)) goto drop; tnapi->tx_buffers[entry].skb = skb; dma_unmap_addr_set(&tnapi->tx_buffers[entry], mapping, mapping); would_hit_hwbug = 0; if (tg3_flag(tp, 5701_DMA_BUG)) would_hit_hwbug = 1; if (tg3_tx_frag_set(tnapi, &entry, &budget, mapping, len, base_flags | ((skb_shinfo(skb)->nr_frags == 0) ? TXD_FLAG_END : 0), mss, vlan)) { would_hit_hwbug = 1; } else if (skb_shinfo(skb)->nr_frags > 0) { u32 tmp_mss = mss; if (!tg3_flag(tp, HW_TSO_1) && !tg3_flag(tp, HW_TSO_2) && !tg3_flag(tp, HW_TSO_3)) tmp_mss = 0; /* Now loop through additional data * fragments, and queue them. */ last = skb_shinfo(skb)->nr_frags - 1; for (i = 0; i <= last; i++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; len = skb_frag_size(frag); mapping = skb_frag_dma_map(&tp->pdev->dev, frag, 0, len, DMA_TO_DEVICE); tnapi->tx_buffers[entry].skb = NULL; dma_unmap_addr_set(&tnapi->tx_buffers[entry], mapping, mapping); if (dma_mapping_error(&tp->pdev->dev, mapping)) goto dma_error; if (!budget || tg3_tx_frag_set(tnapi, &entry, &budget, mapping, len, base_flags | ((i == last) ? TXD_FLAG_END : 0), tmp_mss, vlan)) { would_hit_hwbug = 1; break; } } } if (would_hit_hwbug) { tg3_tx_skb_unmap(tnapi, tnapi->tx_prod, i); if (mss) { /* If it's a TSO packet, do GSO instead of * allocating and copying to a large linear SKB */ if (ip_tot_len) { iph->check = ip_csum; iph->tot_len = ip_tot_len; } tcph->check = tcp_csum; return tg3_tso_bug(tp, skb); } /* If the workaround fails due to memory/mapping * failure, silently drop this packet. */ entry = tnapi->tx_prod; budget = tg3_tx_avail(tnapi); if (<API key>(tnapi, &skb, &entry, &budget, base_flags, mss, vlan)) goto drop_nofree; } skb_tx_timestamp(skb); <API key>(txq, skb->len); /* Sync BD data before updating mailbox */ wmb(); /* Packets are ready, update Tx producer idx local and on card. */ tw32_tx_mbox(tnapi->prodmbox, entry); tnapi->tx_prod = entry; if (unlikely(tg3_tx_avail(tnapi) <= (MAX_SKB_FRAGS + 1))) { netif_tx_stop_queue(txq); /* netif_tx_stop_queue() must be done before checking * checking tx index in tg3_tx_avail() below, because in * tg3_tx(), we update tx index before checking for * <API key>(). */ smp_mb(); if (tg3_tx_avail(tnapi) > <API key>(tnapi)) netif_tx_wake_queue(txq); } mmiowb(); return NETDEV_TX_OK; dma_error: tg3_tx_skb_unmap(tnapi, tnapi->tx_prod, --i); tnapi->tx_buffers[tnapi->tx_prod].skb = NULL; drop: dev_kfree_skb_any(skb); drop_nofree: tp->tx_dropped++; return NETDEV_TX_OK; } static void tg3_mac_loopback(struct tg3 *tp, bool enable) { if (enable) { tp->mac_mode &= ~(<API key> | <API key>); tp->mac_mode |= <API key>; if (!tg3_flag(tp, 5705_PLUS)) tp->mac_mode |= <API key>; if (tp->phy_flags & <API key>) tp->mac_mode |= <API key>; else tp->mac_mode |= <API key>; } else { tp->mac_mode &= ~<API key>; if (tg3_flag(tp, 5705_PLUS) || (tp->phy_flags & <API key>) || tg3_asic_rev(tp) == ASIC_REV_5700) tp->mac_mode &= ~<API key>; } tw32(MAC_MODE, tp->mac_mode); udelay(40); } static int tg3_phy_lpbk_set(struct tg3 *tp, u32 speed, bool extlpbk) { u32 val, bmcr, mac_mode, ptest = 0; tg3_phy_toggle_apd(tp, false); <API key>(tp, false); if (extlpbk && <API key>(tp)) return -EIO; bmcr = BMCR_FULLDPLX; switch (speed) { case SPEED_10: break; case SPEED_100: bmcr |= BMCR_SPEED100; break; case SPEED_1000: default: if (tp->phy_flags & TG3_PHYFLG_IS_FET) { speed = SPEED_100; bmcr |= BMCR_SPEED100; } else { speed = SPEED_1000; bmcr |= BMCR_SPEED1000; } } if (extlpbk) { if (!(tp->phy_flags & TG3_PHYFLG_IS_FET)) { tg3_readphy(tp, MII_CTRL1000, &val); val |= CTL1000_AS_MASTER | <API key>; tg3_writephy(tp, MII_CTRL1000, val); } else { ptest = <API key> | <API key>; tg3_writephy(tp, MII_TG3_FET_PTEST, ptest); } } else bmcr |= BMCR_LOOPBACK; tg3_writephy(tp, MII_BMCR, bmcr); /* The write needs to be flushed for the FETs */ if (tp->phy_flags & TG3_PHYFLG_IS_FET) tg3_readphy(tp, MII_BMCR, &bmcr); udelay(40); if ((tp->phy_flags & TG3_PHYFLG_IS_FET) && tg3_asic_rev(tp) == ASIC_REV_5785) { tg3_writephy(tp, MII_TG3_FET_PTEST, ptest | <API key> | <API key>); /* The write needs to be flushed for the AC131 */ tg3_readphy(tp, MII_TG3_FET_PTEST, &val); } /* Reset to prevent losing 1st rx packet intermittently */ if ((tp->phy_flags & <API key>) && tg3_flag(tp, 5780_CLASS)) { tw32_f(MAC_RX_MODE, RX_MODE_RESET); udelay(10); tw32_f(MAC_RX_MODE, tp->rx_mode); } mac_mode = tp->mac_mode & ~(<API key> | <API key>); if (speed == SPEED_1000) mac_mode |= <API key>; else mac_mode |= <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5700) { u32 masked_phy_id = tp->phy_id & TG3_PHY_ID_MASK; if (masked_phy_id == TG3_PHY_ID_BCM5401) mac_mode &= ~<API key>; else if (masked_phy_id == TG3_PHY_ID_BCM5411) mac_mode |= <API key>; tg3_writephy(tp, MII_TG3_EXT_CTRL, <API key>); } tw32(MAC_MODE, mac_mode); udelay(40); return 0; } static void tg3_set_loopback(struct net_device *dev, netdev_features_t features) { struct tg3 *tp = netdev_priv(dev); if (features & NETIF_F_LOOPBACK) { if (tp->mac_mode & <API key>) return; spin_lock_bh(&tp->lock); tg3_mac_loopback(tp, true); netif_carrier_on(tp->dev); spin_unlock_bh(&tp->lock); netdev_info(dev, "Internal MAC loopback mode enabled.\n"); } else { if (!(tp->mac_mode & <API key>)) return; spin_lock_bh(&tp->lock); tg3_mac_loopback(tp, false); /* Force link status check */ tg3_setup_phy(tp, true); spin_unlock_bh(&tp->lock); netdev_info(dev, "Internal MAC loopback mode disabled.\n"); } } static netdev_features_t tg3_fix_features(struct net_device *dev, netdev_features_t features) { struct tg3 *tp = netdev_priv(dev); if (dev->mtu > ETH_DATA_LEN && tg3_flag(tp, 5780_CLASS)) features &= ~NETIF_F_ALL_TSO; return features; } static int tg3_set_features(struct net_device *dev, netdev_features_t features) { netdev_features_t changed = dev->features ^ features; if ((changed & NETIF_F_LOOPBACK) && netif_running(dev)) tg3_set_loopback(dev, features); return 0; } static void <API key>(struct tg3 *tp, struct tg3_rx_prodring_set *tpr) { int i; if (tpr != &tp->napi[0].prodring) { for (i = tpr->rx_std_cons_idx; i != tpr->rx_std_prod_idx; i = (i + 1) & tp->rx_std_ring_mask) tg3_rx_data_free(tp, &tpr->rx_std_buffers[i], tp->rx_pkt_map_sz); if (tg3_flag(tp, JUMBO_CAPABLE)) { for (i = tpr->rx_jmb_cons_idx; i != tpr->rx_jmb_prod_idx; i = (i + 1) & tp->rx_jmb_ring_mask) { tg3_rx_data_free(tp, &tpr->rx_jmb_buffers[i], TG3_RX_JMB_MAP_SZ); } } return; } for (i = 0; i <= tp->rx_std_ring_mask; i++) tg3_rx_data_free(tp, &tpr->rx_std_buffers[i], tp->rx_pkt_map_sz); if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS)) { for (i = 0; i <= tp->rx_jmb_ring_mask; i++) tg3_rx_data_free(tp, &tpr->rx_jmb_buffers[i], TG3_RX_JMB_MAP_SZ); } } /* Initialize rx rings for packet processing. * * The chip has been shut down and the driver detached from * the networking, so no interrupts or new tx packets will * end up in the driver. tp->{tx,}lock are held and thus * we may not sleep. */ static int <API key>(struct tg3 *tp, struct tg3_rx_prodring_set *tpr) { u32 i, rx_pkt_dma_sz; tpr->rx_std_cons_idx = 0; tpr->rx_std_prod_idx = 0; tpr->rx_jmb_cons_idx = 0; tpr->rx_jmb_prod_idx = 0; if (tpr != &tp->napi[0].prodring) { memset(&tpr->rx_std_buffers[0], 0, <API key>(tp)); if (tpr->rx_jmb_buffers) memset(&tpr->rx_jmb_buffers[0], 0, <API key>(tp)); goto done; } /* Zero out all descriptors. */ memset(tpr->rx_std, 0, <API key>(tp)); rx_pkt_dma_sz = TG3_RX_STD_DMA_SZ; if (tg3_flag(tp, 5780_CLASS) && tp->dev->mtu > ETH_DATA_LEN) rx_pkt_dma_sz = TG3_RX_JMB_DMA_SZ; tp->rx_pkt_map_sz = <API key>(rx_pkt_dma_sz); /* Initialize invariants of the rings, we only set this * stuff once. This works because the card does not * write into the rx buffer posting rings. */ for (i = 0; i <= tp->rx_std_ring_mask; i++) { struct tg3_rx_buffer_desc *rxd; rxd = &tpr->rx_std[i]; rxd->idx_len = rx_pkt_dma_sz << RXD_LEN_SHIFT; rxd->type_flags = (RXD_FLAG_END << RXD_FLAGS_SHIFT); rxd->opaque = (RXD_OPAQUE_RING_STD | (i << <API key>)); } /* Now allocate fresh SKBs for each rx ring. */ for (i = 0; i < tp->rx_pending; i++) { unsigned int frag_size; if (tg3_alloc_rx_data(tp, tpr, RXD_OPAQUE_RING_STD, i, &frag_size) < 0) { netdev_warn(tp->dev, "Using a smaller RX standard ring. Only " "%d out of %d buffers were allocated " "successfully\n", i, tp->rx_pending); if (i == 0) goto initfail; tp->rx_pending = i; break; } } if (!tg3_flag(tp, JUMBO_CAPABLE) || tg3_flag(tp, 5780_CLASS)) goto done; memset(tpr->rx_jmb, 0, <API key>(tp)); if (!tg3_flag(tp, JUMBO_RING_ENABLE)) goto done; for (i = 0; i <= tp->rx_jmb_ring_mask; i++) { struct tg3_rx_buffer_desc *rxd; rxd = &tpr->rx_jmb[i].std; rxd->idx_len = TG3_RX_JMB_DMA_SZ << RXD_LEN_SHIFT; rxd->type_flags = (RXD_FLAG_END << RXD_FLAGS_SHIFT) | RXD_FLAG_JUMBO; rxd->opaque = (<API key> | (i << <API key>)); } for (i = 0; i < tp->rx_jumbo_pending; i++) { unsigned int frag_size; if (tg3_alloc_rx_data(tp, tpr, <API key>, i, &frag_size) < 0) { netdev_warn(tp->dev, "Using a smaller RX jumbo ring. Only %d " "out of %d buffers were allocated " "successfully\n", i, tp->rx_jumbo_pending); if (i == 0) goto initfail; tp->rx_jumbo_pending = i; break; } } done: return 0; initfail: <API key>(tp, tpr); return -ENOMEM; } static void <API key>(struct tg3 *tp, struct tg3_rx_prodring_set *tpr) { kfree(tpr->rx_std_buffers); tpr->rx_std_buffers = NULL; kfree(tpr->rx_jmb_buffers); tpr->rx_jmb_buffers = NULL; if (tpr->rx_std) { dma_free_coherent(&tp->pdev->dev, <API key>(tp), tpr->rx_std, tpr->rx_std_mapping); tpr->rx_std = NULL; } if (tpr->rx_jmb) { dma_free_coherent(&tp->pdev->dev, <API key>(tp), tpr->rx_jmb, tpr->rx_jmb_mapping); tpr->rx_jmb = NULL; } } static int <API key>(struct tg3 *tp, struct tg3_rx_prodring_set *tpr) { tpr->rx_std_buffers = kzalloc(<API key>(tp), GFP_KERNEL); if (!tpr->rx_std_buffers) return -ENOMEM; tpr->rx_std = dma_alloc_coherent(&tp->pdev->dev, <API key>(tp), &tpr->rx_std_mapping, GFP_KERNEL); if (!tpr->rx_std) goto err_out; if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS)) { tpr->rx_jmb_buffers = kzalloc(<API key>(tp), GFP_KERNEL); if (!tpr->rx_jmb_buffers) goto err_out; tpr->rx_jmb = dma_alloc_coherent(&tp->pdev->dev, <API key>(tp), &tpr->rx_jmb_mapping, GFP_KERNEL); if (!tpr->rx_jmb) goto err_out; } return 0; err_out: <API key>(tp, tpr); return -ENOMEM; } /* Free up pending packets in all rx/tx rings. * * The chip has been shut down and the driver detached from * the networking, so no interrupts or new tx packets will * end up in the driver. tp->{tx,}lock is not held and we are not * in an interrupt context and thus may sleep. */ static void tg3_free_rings(struct tg3 *tp) { int i, j; for (j = 0; j < tp->irq_cnt; j++) { struct tg3_napi *tnapi = &tp->napi[j]; <API key>(tp, &tnapi->prodring); if (!tnapi->tx_buffers) continue; for (i = 0; i < TG3_TX_RING_SIZE; i++) { struct sk_buff *skb = tnapi->tx_buffers[i].skb; if (!skb) continue; tg3_tx_skb_unmap(tnapi, i, skb_shinfo(skb)->nr_frags - 1); dev_kfree_skb_any(skb); } <API key>(netdev_get_tx_queue(tp->dev, j)); } } /* Initialize tx/rx rings for packet processing. * * The chip has been shut down and the driver detached from * the networking, so no interrupts or new tx packets will * end up in the driver. tp->{tx,}lock are held and thus * we may not sleep. */ static int tg3_init_rings(struct tg3 *tp) { int i; /* Free up all the SKBs. */ tg3_free_rings(tp); for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; tnapi->last_tag = 0; tnapi->last_irq_tag = 0; tnapi->hw_status->status = 0; tnapi->hw_status->status_tag = 0; memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE); tnapi->tx_prod = 0; tnapi->tx_cons = 0; if (tnapi->tx_ring) memset(tnapi->tx_ring, 0, TG3_TX_RING_BYTES); tnapi->rx_rcb_ptr = 0; if (tnapi->rx_rcb) memset(tnapi->rx_rcb, 0, <API key>(tp)); if (<API key>(tp, &tnapi->prodring)) { tg3_free_rings(tp); return -ENOMEM; } } return 0; } static void tg3_mem_tx_release(struct tg3 *tp) { int i; for (i = 0; i < tp->irq_max; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (tnapi->tx_ring) { dma_free_coherent(&tp->pdev->dev, TG3_TX_RING_BYTES, tnapi->tx_ring, tnapi->tx_desc_mapping); tnapi->tx_ring = NULL; } kfree(tnapi->tx_buffers); tnapi->tx_buffers = NULL; } } static int tg3_mem_tx_acquire(struct tg3 *tp) { int i; struct tg3_napi *tnapi = &tp->napi[0]; /* If multivector TSS is enabled, vector 0 does not handle * tx interrupts. Don't allocate any resources for it. */ if (tg3_flag(tp, ENABLE_TSS)) tnapi++; for (i = 0; i < tp->txq_cnt; i++, tnapi++) { tnapi->tx_buffers = kzalloc(sizeof(struct tg3_tx_ring_info) * TG3_TX_RING_SIZE, GFP_KERNEL); if (!tnapi->tx_buffers) goto err_out; tnapi->tx_ring = dma_alloc_coherent(&tp->pdev->dev, TG3_TX_RING_BYTES, &tnapi->tx_desc_mapping, GFP_KERNEL); if (!tnapi->tx_ring) goto err_out; } return 0; err_out: tg3_mem_tx_release(tp); return -ENOMEM; } static void tg3_mem_rx_release(struct tg3 *tp) { int i; for (i = 0; i < tp->irq_max; i++) { struct tg3_napi *tnapi = &tp->napi[i]; <API key>(tp, &tnapi->prodring); if (!tnapi->rx_rcb) continue; dma_free_coherent(&tp->pdev->dev, <API key>(tp), tnapi->rx_rcb, tnapi->rx_rcb_mapping); tnapi->rx_rcb = NULL; } } static int tg3_mem_rx_acquire(struct tg3 *tp) { unsigned int i, limit; limit = tp->rxq_cnt; /* If RSS is enabled, we need a (dummy) producer ring * set on vector zero. This is the true hw prodring. */ if (tg3_flag(tp, ENABLE_RSS)) limit++; for (i = 0; i < limit; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (<API key>(tp, &tnapi->prodring)) goto err_out; /* If multivector RSS is enabled, vector 0 * does not handle rx or tx interrupts. * Don't allocate any resources for it. */ if (!i && tg3_flag(tp, ENABLE_RSS)) continue; tnapi->rx_rcb = dma_zalloc_coherent(&tp->pdev->dev, <API key>(tp), &tnapi->rx_rcb_mapping, GFP_KERNEL); if (!tnapi->rx_rcb) goto err_out; } return 0; err_out: tg3_mem_rx_release(tp); return -ENOMEM; } /* * Must not be invoked with interrupt sources disabled and * the hardware shutdown down. */ static void tg3_free_consistent(struct tg3 *tp) { int i; for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (tnapi->hw_status) { dma_free_coherent(&tp->pdev->dev, TG3_HW_STATUS_SIZE, tnapi->hw_status, tnapi->status_mapping); tnapi->hw_status = NULL; } } tg3_mem_rx_release(tp); tg3_mem_tx_release(tp); if (tp->hw_stats) { dma_free_coherent(&tp->pdev->dev, sizeof(struct tg3_hw_stats), tp->hw_stats, tp->stats_mapping); tp->hw_stats = NULL; } } /* * Must not be invoked with interrupt sources disabled and * the hardware shutdown down. Can sleep. */ static int <API key>(struct tg3 *tp) { int i; tp->hw_stats = dma_zalloc_coherent(&tp->pdev->dev, sizeof(struct tg3_hw_stats), &tp->stats_mapping, GFP_KERNEL); if (!tp->hw_stats) goto err_out; for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; struct tg3_hw_status *sblk; tnapi->hw_status = dma_zalloc_coherent(&tp->pdev->dev, TG3_HW_STATUS_SIZE, &tnapi->status_mapping, GFP_KERNEL); if (!tnapi->hw_status) goto err_out; sblk = tnapi->hw_status; if (tg3_flag(tp, ENABLE_RSS)) { u16 *prodptr = NULL; /* * When RSS is enabled, the status block format changes * slightly. The "rx_jumbo_consumer", "reserved", * and "rx_mini_consumer" members get mapped to the * other three rx return ring producer indexes. */ switch (i) { case 1: prodptr = &sblk->idx[0].rx_producer; break; case 2: prodptr = &sblk->rx_jumbo_consumer; break; case 3: prodptr = &sblk->reserved; break; case 4: prodptr = &sblk->rx_mini_consumer; break; } tnapi->rx_rcb_prod_idx = prodptr; } else { tnapi->rx_rcb_prod_idx = &sblk->idx[0].rx_producer; } } if (tg3_mem_tx_acquire(tp) || tg3_mem_rx_acquire(tp)) goto err_out; return 0; err_out: tg3_free_consistent(tp); return -ENOMEM; } #define MAX_WAIT_CNT 1000 /* To stop a block, clear the enable bit and poll till it * clears. tp->lock is held. */ static int tg3_stop_block(struct tg3 *tp, unsigned long ofs, u32 enable_bit, bool silent) { unsigned int i; u32 val; if (tg3_flag(tp, 5705_PLUS)) { switch (ofs) { case RCVLSC_MODE: case DMAC_MODE: case MBFREE_MODE: case BUFMGR_MODE: case MEMARB_MODE: /* We can't enable/disable these bits of the * 5705/5750, just say success. */ return 0; default: break; } } val = tr32(ofs); val &= ~enable_bit; tw32_f(ofs, val); for (i = 0; i < MAX_WAIT_CNT; i++) { if (pci_channel_offline(tp->pdev)) { dev_err(&tp->pdev->dev, "tg3_stop_block device offline, " "ofs=%lx enable_bit=%x\n", ofs, enable_bit); return -ENODEV; } udelay(100); val = tr32(ofs); if ((val & enable_bit) == 0) break; } if (i == MAX_WAIT_CNT && !silent) { dev_err(&tp->pdev->dev, "tg3_stop_block timed out, ofs=%lx enable_bit=%x\n", ofs, enable_bit); return -ENODEV; } return 0; } /* tp->lock is held. */ static int tg3_abort_hw(struct tg3 *tp, bool silent) { int i, err; tg3_disable_ints(tp); if (pci_channel_offline(tp->pdev)) { tp->rx_mode &= ~(RX_MODE_ENABLE | TX_MODE_ENABLE); tp->mac_mode &= ~MAC_MODE_TDE_ENABLE; err = -ENODEV; goto err_no_dev; } tp->rx_mode &= ~RX_MODE_ENABLE; tw32_f(MAC_RX_MODE, tp->rx_mode); udelay(10); err = tg3_stop_block(tp, RCVBDI_MODE, RCVBDI_MODE_ENABLE, silent); err |= tg3_stop_block(tp, RCVLPC_MODE, RCVLPC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, RCVLSC_MODE, RCVLSC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, RCVDBDI_MODE, RCVDBDI_MODE_ENABLE, silent); err |= tg3_stop_block(tp, RCVDCC_MODE, RCVDCC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, RCVCC_MODE, RCVCC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, SNDBDS_MODE, SNDBDS_MODE_ENABLE, silent); err |= tg3_stop_block(tp, SNDBDI_MODE, SNDBDI_MODE_ENABLE, silent); err |= tg3_stop_block(tp, SNDDATAI_MODE, <API key>, silent); err |= tg3_stop_block(tp, RDMAC_MODE, RDMAC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, SNDDATAC_MODE, <API key>, silent); err |= tg3_stop_block(tp, DMAC_MODE, DMAC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, SNDBDC_MODE, SNDBDC_MODE_ENABLE, silent); tp->mac_mode &= ~MAC_MODE_TDE_ENABLE; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); tp->tx_mode &= ~TX_MODE_ENABLE; tw32_f(MAC_TX_MODE, tp->tx_mode); for (i = 0; i < MAX_WAIT_CNT; i++) { udelay(100); if (!(tr32(MAC_TX_MODE) & TX_MODE_ENABLE)) break; } if (i >= MAX_WAIT_CNT) { dev_err(&tp->pdev->dev, "%s timed out, TX_MODE_ENABLE will not clear " "MAC_TX_MODE=%08x\n", __func__, tr32(MAC_TX_MODE)); err |= -ENODEV; } err |= tg3_stop_block(tp, HOSTCC_MODE, HOSTCC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, WDMAC_MODE, WDMAC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, MBFREE_MODE, MBFREE_MODE_ENABLE, silent); tw32(FTQ_RESET, 0xffffffff); tw32(FTQ_RESET, 0x00000000); err |= tg3_stop_block(tp, BUFMGR_MODE, BUFMGR_MODE_ENABLE, silent); err |= tg3_stop_block(tp, MEMARB_MODE, MEMARB_MODE_ENABLE, silent); err_no_dev: for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (tnapi->hw_status) memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE); } return err; } /* Save PCI command register before chip reset */ static void tg3_save_pci_state(struct tg3 *tp) { <API key>(tp->pdev, PCI_COMMAND, &tp->pci_cmd); } /* Restore PCI state after chip reset */ static void <API key>(struct tg3 *tp) { u32 val; /* Re-enable indirect register accesses. */ <API key>(tp->pdev, <API key>, tp->misc_host_ctrl); /* Set MAX PCI retry to zero. */ val = (PCISTATE_ROM_ENABLE | <API key>); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0 && tg3_flag(tp, PCIX_MODE)) val |= <API key>; /* Allow reads and writes to the APE register and memory space. */ if (tg3_flag(tp, ENABLE_APE)) val |= <API key> | <API key> | <API key>; <API key>(tp->pdev, TG3PCI_PCISTATE, val); <API key>(tp->pdev, PCI_COMMAND, tp->pci_cmd); if (!tg3_flag(tp, PCI_EXPRESS)) { <API key>(tp->pdev, PCI_CACHE_LINE_SIZE, tp->pci_cacheline_sz); <API key>(tp->pdev, PCI_LATENCY_TIMER, tp->pci_lat_timer); } /* Make sure PCI-X relaxed ordering bit is clear. */ if (tg3_flag(tp, PCIX_MODE)) { u16 pcix_cmd; <API key>(tp->pdev, tp->pcix_cap + PCI_X_CMD, &pcix_cmd); pcix_cmd &= ~PCI_X_CMD_ERO; <API key>(tp->pdev, tp->pcix_cap + PCI_X_CMD, pcix_cmd); } if (tg3_flag(tp, 5780_CLASS)) { /* Chip reset on 5780 will reset MSI enable bit, * so need to restore it. */ if (tg3_flag(tp, USING_MSI)) { u16 ctrl; <API key>(tp->pdev, tp->msi_cap + PCI_MSI_FLAGS, &ctrl); <API key>(tp->pdev, tp->msi_cap + PCI_MSI_FLAGS, ctrl | <API key>); val = tr32(MSGINT_MODE); tw32(MSGINT_MODE, val | MSGINT_MODE_ENABLE); } } } static void tg3_override_clk(struct tg3 *tp) { u32 val; switch (tg3_asic_rev(tp)) { case ASIC_REV_5717: val = tr32(<API key>); tw32(<API key>, val | <API key>); break; case ASIC_REV_5719: case ASIC_REV_5720: tw32(TG3_CPMU_CLCK_ORIDE, <API key>); break; default: return; } } static void tg3_restore_clk(struct tg3 *tp) { u32 val; switch (tg3_asic_rev(tp)) { case ASIC_REV_5717: val = tr32(<API key>); tw32(<API key>, val & ~<API key>); break; case ASIC_REV_5719: case ASIC_REV_5720: val = tr32(TG3_CPMU_CLCK_ORIDE); tw32(TG3_CPMU_CLCK_ORIDE, val & ~<API key>); break; default: return; } } /* tp->lock is held. */ static int tg3_chip_reset(struct tg3 *tp) { u32 val; void (*write_op)(struct tg3 *, u32, u32); int i, err; if (!<API key>(tp->pdev)) return -ENODEV; tg3_nvram_lock(tp); tg3_ape_lock(tp, TG3_APE_LOCK_GRC); /* No matching tg3_nvram_unlock() after this because * chip reset below will undo the nvram lock. */ tp->nvram_lock_cnt = 0; /* GRC_MISC_CFG core clock reset will clear the memory * enable bit in PCI register 4 and the MSI enable bit * on some chips, so we save relevant registers here. */ tg3_save_pci_state(tp); if (tg3_asic_rev(tp) == ASIC_REV_5752 || tg3_flag(tp, 5755_PLUS)) tw32(GRC_FASTBOOT_PC, 0); /* * We must avoid the readl() that normally takes place. * It locks machines, causes machine checks, and other * fun things. So, temporarily disable the 5701 * hardware workaround, while we do the reset. */ write_op = tp->write32; if (write_op == <API key>) tp->write32 = tg3_write32; /* Prevent the irq handler from reading or writing PCI registers * during chip reset when the memory enable bit in the PCI command * register may be cleared. The chip does not generate interrupt * at this time, but the irq handler may still be called due to irq * sharing or irqpoll. */ tg3_flag_set(tp, CHIP_RESETTING); for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (tnapi->hw_status) { tnapi->hw_status->status = 0; tnapi->hw_status->status_tag = 0; } tnapi->last_tag = 0; tnapi->last_irq_tag = 0; } smp_mb(); for (i = 0; i < tp->irq_cnt; i++) synchronize_irq(tp->napi[i].irq_vec); if (tg3_asic_rev(tp) == ASIC_REV_57780) { val = tr32(TG3_PCIE_LNKCTL) & ~<API key>; tw32(TG3_PCIE_LNKCTL, val | <API key>); } /* do the reset */ val = <API key>; if (tg3_flag(tp, PCI_EXPRESS)) { /* Force PCIe 1.0a mode */ if (tg3_asic_rev(tp) != ASIC_REV_5785 && !tg3_flag(tp, 57765_PLUS) && tr32(TG3_PCIE_PHY_TSTCTL) == (<API key> | <API key>)) tw32(TG3_PCIE_PHY_TSTCTL, <API key>); if (tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0) { tw32(GRC_MISC_CFG, (1 << 29)); val |= (1 << 29); } } if (tg3_asic_rev(tp) == ASIC_REV_5906) { tw32(VCPU_STATUS, tr32(VCPU_STATUS) | <API key>); tw32(GRC_VCPU_EXT_CTRL, tr32(GRC_VCPU_EXT_CTRL) & ~<API key>); } /* Set the clock to the highest frequency to avoid timeouts. With link * aware mode, the clock speed could be slow and bootcode does not * complete within the expected time. Override the clock to allow the * bootcode to finish sooner and then restore it. */ tg3_override_clk(tp); /* Manage gphy power for all CPMU absent PCIe devices. */ if (tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, CPMU_PRESENT)) val |= <API key>; tw32(GRC_MISC_CFG, val); /* restore 5701 hardware bug workaround write method */ tp->write32 = write_op; /* Unfortunately, we have to delay before the PCI read back. * Some 575X chips even will not respond to a PCI cfg access * when the reset command is given to the chip. * * How do these hardware designers expect things to work * properly if the PCI write is posted for a long period * of time? It is always necessary to have some method by * which a register read back can occur to push the write * out which does the reset. * * For most tg3 variants the trick below was working. * Ho hum... */ udelay(120); /* Flush PCI posted writes. The normal MMIO registers * are inaccessible at this time so this is the only * way to make this reliably (actually, this is no longer * the case, see above). I tried to use indirect * register read/write but this upset some 5701 variants. */ <API key>(tp->pdev, PCI_COMMAND, &val); udelay(120); if (tg3_flag(tp, PCI_EXPRESS) && pci_is_pcie(tp->pdev)) { u16 val16; if (tg3_chip_rev_id(tp) == CHIPREV_ID_5750_A0) { int j; u32 cfg_val; /* Wait for link training to complete. */ for (j = 0; j < 5000; j++) udelay(100); <API key>(tp->pdev, 0xc4, &cfg_val); <API key>(tp->pdev, 0xc4, cfg_val | (1 << 15)); } /* Clear the "no snoop" and "relaxed ordering" bits. */ val16 = <API key> | <API key>; /* * Older PCIe devices only support the 128 byte * MPS setting. Enforce the restriction. */ if (!tg3_flag(tp, CPMU_PRESENT)) val16 |= <API key>; <API key>(tp->pdev, PCI_EXP_DEVCTL, val16); /* Clear error status */ <API key>(tp->pdev, PCI_EXP_DEVSTA, PCI_EXP_DEVSTA_CED | PCI_EXP_DEVSTA_NFED | PCI_EXP_DEVSTA_FED | PCI_EXP_DEVSTA_URD); } <API key>(tp); tg3_flag_clear(tp, CHIP_RESETTING); tg3_flag_clear(tp, ERROR_PROCESSED); val = 0; if (tg3_flag(tp, 5780_CLASS)) val = tr32(MEMARB_MODE); tw32(MEMARB_MODE, val | MEMARB_MODE_ENABLE); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5750_A3) { tg3_stop_fw(tp); tw32(0x5000, 0x400); } if (tg3_flag(tp, IS_SSB_CORE)) { /* * BCM4785: In order to avoid repercussions from using * potentially defective internal ROM, stop the Rx RISC CPU, * which is not required. */ tg3_stop_fw(tp); tg3_halt_cpu(tp, RX_CPU_BASE); } err = tg3_poll_fw(tp); if (err) return err; tw32(GRC_MODE, tp->grc_mode); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A0) { val = tr32(0xc4); tw32(0xc4, val | (1 << 15)); } if ((tp->nic_sram_data_cfg & <API key>) != 0 && tg3_asic_rev(tp) == ASIC_REV_5705) { tp->pci_clock_ctrl |= <API key>; if (tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A0) tp->pci_clock_ctrl |= <API key>; tw32(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl); } if (tp->phy_flags & <API key>) { tp->mac_mode = <API key>; val = tp->mac_mode; } else if (tp->phy_flags & <API key>) { tp->mac_mode = <API key>; val = tp->mac_mode; } else val = 0; tw32_f(MAC_MODE, val); udelay(40); tg3_ape_unlock(tp, TG3_APE_LOCK_GRC); tg3_mdio_start(tp); if (tg3_flag(tp, PCI_EXPRESS) && tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0 && tg3_asic_rev(tp) != ASIC_REV_5785 && !tg3_flag(tp, 57765_PLUS)) { val = tr32(0x7c00); tw32(0x7c00, val | (1 << 25)); } tg3_restore_clk(tp); /* Reprobe ASF enable state. */ tg3_flag_clear(tp, ENABLE_ASF); tp->phy_flags &= ~(<API key> | <API key>); tg3_flag_clear(tp, ASF_NEW_HANDSHAKE); tg3_read_mem(tp, NIC_SRAM_DATA_SIG, &val); if (val == <API key>) { u32 nic_cfg; tg3_read_mem(tp, NIC_SRAM_DATA_CFG, &nic_cfg); if (nic_cfg & <API key>) { tg3_flag_set(tp, ENABLE_ASF); tp->last_event_jiffies = jiffies; if (tg3_flag(tp, 5750_PLUS)) tg3_flag_set(tp, ASF_NEW_HANDSHAKE); tg3_read_mem(tp, NIC_SRAM_DATA_CFG_3, &nic_cfg); if (nic_cfg & <API key>) tp->phy_flags |= <API key>; if (nic_cfg & <API key>) tp->phy_flags |= <API key>; } } return 0; } static void tg3_get_nstats(struct tg3 *, struct rtnl_link_stats64 *); static void tg3_get_estats(struct tg3 *, struct tg3_ethtool_stats *); static void __tg3_set_rx_mode(struct net_device *); /* tp->lock is held. */ static int tg3_halt(struct tg3 *tp, int kind, bool silent) { int err; tg3_stop_fw(tp); <API key>(tp, kind); tg3_abort_hw(tp, silent); err = tg3_chip_reset(tp); __tg3_set_mac_addr(tp, false); <API key>(tp, kind); <API key>(tp, kind); if (tp->hw_stats) { /* Save the stats across chip resets... */ tg3_get_nstats(tp, &tp->net_stats_prev); tg3_get_estats(tp, &tp->estats_prev); /* And make sure the next sample is new data */ memset(tp->hw_stats, 0, sizeof(struct tg3_hw_stats)); } return err; } static int tg3_set_mac_addr(struct net_device *dev, void *p) { struct tg3 *tp = netdev_priv(dev); struct sockaddr *addr = p; int err = 0; bool skip_mac_1 = false; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; memcpy(dev->dev_addr, addr->sa_data, dev->addr_len); if (!netif_running(dev)) return 0; if (tg3_flag(tp, ENABLE_ASF)) { u32 addr0_high, addr0_low, addr1_high, addr1_low; addr0_high = tr32(MAC_ADDR_0_HIGH); addr0_low = tr32(MAC_ADDR_0_LOW); addr1_high = tr32(MAC_ADDR_1_HIGH); addr1_low = tr32(MAC_ADDR_1_LOW); /* Skip MAC addr 1 if ASF is using it. */ if ((addr0_high != addr1_high || addr0_low != addr1_low) && !(addr1_high == 0 && addr1_low == 0)) skip_mac_1 = true; } spin_lock_bh(&tp->lock); __tg3_set_mac_addr(tp, skip_mac_1); __tg3_set_rx_mode(dev); spin_unlock_bh(&tp->lock); return err; } /* tp->lock is held. */ static void tg3_set_bdinfo(struct tg3 *tp, u32 bdinfo_addr, dma_addr_t mapping, u32 maxlen_flags, u32 nic_addr) { tg3_write_mem(tp, (bdinfo_addr + <API key> + TG3_64BIT_REG_HIGH), ((u64) mapping >> 32)); tg3_write_mem(tp, (bdinfo_addr + <API key> + TG3_64BIT_REG_LOW), ((u64) mapping & 0xffffffff)); tg3_write_mem(tp, (bdinfo_addr + <API key>), maxlen_flags); if (!tg3_flag(tp, 5705_PLUS)) tg3_write_mem(tp, (bdinfo_addr + TG3_BDINFO_NIC_ADDR), nic_addr); } static void tg3_coal_tx_init(struct tg3 *tp, struct ethtool_coalesce *ec) { int i = 0; if (!tg3_flag(tp, ENABLE_TSS)) { tw32(HOSTCC_TXCOL_TICKS, ec->tx_coalesce_usecs); tw32(HOSTCC_TXMAX_FRAMES, ec-><API key>); tw32(<API key>, ec-><API key>); } else { tw32(HOSTCC_TXCOL_TICKS, 0); tw32(HOSTCC_TXMAX_FRAMES, 0); tw32(<API key>, 0); for (; i < tp->txq_cnt; i++) { u32 reg; reg = <API key> + i * 0x18; tw32(reg, ec->tx_coalesce_usecs); reg = <API key> + i * 0x18; tw32(reg, ec-><API key>); reg = <API key> + i * 0x18; tw32(reg, ec-><API key>); } } for (; i < tp->irq_max - 1; i++) { tw32(<API key> + i * 0x18, 0); tw32(<API key> + i * 0x18, 0); tw32(<API key> + i * 0x18, 0); } } static void tg3_coal_rx_init(struct tg3 *tp, struct ethtool_coalesce *ec) { int i = 0; u32 limit = tp->rxq_cnt; if (!tg3_flag(tp, ENABLE_RSS)) { tw32(HOSTCC_RXCOL_TICKS, ec->rx_coalesce_usecs); tw32(HOSTCC_RXMAX_FRAMES, ec-><API key>); tw32(<API key>, ec-><API key>); limit } else { tw32(HOSTCC_RXCOL_TICKS, 0); tw32(HOSTCC_RXMAX_FRAMES, 0); tw32(<API key>, 0); } for (; i < limit; i++) { u32 reg; reg = <API key> + i * 0x18; tw32(reg, ec->rx_coalesce_usecs); reg = <API key> + i * 0x18; tw32(reg, ec-><API key>); reg = <API key> + i * 0x18; tw32(reg, ec-><API key>); } for (; i < tp->irq_max - 1; i++) { tw32(<API key> + i * 0x18, 0); tw32(<API key> + i * 0x18, 0); tw32(<API key> + i * 0x18, 0); } } static void __tg3_set_coalesce(struct tg3 *tp, struct ethtool_coalesce *ec) { tg3_coal_tx_init(tp, ec); tg3_coal_rx_init(tp, ec); if (!tg3_flag(tp, 5705_PLUS)) { u32 val = ec-><API key>; tw32(<API key>, ec-><API key>); tw32(<API key>, ec-><API key>); if (!tp->link_up) val = 0; tw32(<API key>, val); } } /* tp->lock is held. */ static void tg3_tx_rcbs_disable(struct tg3 *tp) { u32 txrcb, limit; /* Disable all transmit rings but the first. */ if (!tg3_flag(tp, 5705_PLUS)) limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 16; else if (tg3_flag(tp, 5717_PLUS)) limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 4; else if (tg3_flag(tp, 57765_CLASS) || tg3_asic_rev(tp) == ASIC_REV_5762) limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 2; else limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE; for (txrcb = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE; txrcb < limit; txrcb += TG3_BDINFO_SIZE) tg3_write_mem(tp, txrcb + <API key>, <API key>); } /* tp->lock is held. */ static void tg3_tx_rcbs_init(struct tg3 *tp) { int i = 0; u32 txrcb = NIC_SRAM_SEND_RCB; if (tg3_flag(tp, ENABLE_TSS)) i++; for (; i < tp->irq_max; i++, txrcb += TG3_BDINFO_SIZE) { struct tg3_napi *tnapi = &tp->napi[i]; if (!tnapi->tx_ring) continue; tg3_set_bdinfo(tp, txrcb, tnapi->tx_desc_mapping, (TG3_TX_RING_SIZE << <API key>), <API key>); } } /* tp->lock is held. */ static void <API key>(struct tg3 *tp) { u32 rxrcb, limit; /* Disable all receive return rings but the first. */ if (tg3_flag(tp, 5717_PLUS)) limit = <API key> + TG3_BDINFO_SIZE * 17; else if (!tg3_flag(tp, 5705_PLUS)) limit = <API key> + TG3_BDINFO_SIZE * 16; else if (tg3_asic_rev(tp) == ASIC_REV_5755 || tg3_asic_rev(tp) == ASIC_REV_5762 || tg3_flag(tp, 57765_CLASS)) limit = <API key> + TG3_BDINFO_SIZE * 4; else limit = <API key> + TG3_BDINFO_SIZE; for (rxrcb = <API key> + TG3_BDINFO_SIZE; rxrcb < limit; rxrcb += TG3_BDINFO_SIZE) tg3_write_mem(tp, rxrcb + <API key>, <API key>); } /* tp->lock is held. */ static void <API key>(struct tg3 *tp) { int i = 0; u32 rxrcb = <API key>; if (tg3_flag(tp, ENABLE_RSS)) i++; for (; i < tp->irq_max; i++, rxrcb += TG3_BDINFO_SIZE) { struct tg3_napi *tnapi = &tp->napi[i]; if (!tnapi->rx_rcb) continue; tg3_set_bdinfo(tp, rxrcb, tnapi->rx_rcb_mapping, (tp->rx_ret_ring_mask + 1) << <API key>, 0); } } /* tp->lock is held. */ static void tg3_rings_reset(struct tg3 *tp) { int i; u32 stblk; struct tg3_napi *tnapi = &tp->napi[0]; tg3_tx_rcbs_disable(tp); <API key>(tp); /* Disable interrupts */ tw32_mailbox_f(tp->napi[0].int_mbox, 1); tp->napi[0].chk_msi_cnt = 0; tp->napi[0].last_rx_cons = 0; tp->napi[0].last_tx_cons = 0; /* Zero mailbox registers. */ if (tg3_flag(tp, SUPPORT_MSIX)) { for (i = 1; i < tp->irq_max; i++) { tp->napi[i].tx_prod = 0; tp->napi[i].tx_cons = 0; if (tg3_flag(tp, ENABLE_TSS)) tw32_mailbox(tp->napi[i].prodmbox, 0); tw32_rx_mbox(tp->napi[i].consmbox, 0); tw32_mailbox_f(tp->napi[i].int_mbox, 1); tp->napi[i].chk_msi_cnt = 0; tp->napi[i].last_rx_cons = 0; tp->napi[i].last_tx_cons = 0; } if (!tg3_flag(tp, ENABLE_TSS)) tw32_mailbox(tp->napi[0].prodmbox, 0); } else { tp->napi[0].tx_prod = 0; tp->napi[0].tx_cons = 0; tw32_mailbox(tp->napi[0].prodmbox, 0); tw32_rx_mbox(tp->napi[0].consmbox, 0); } /* Make sure the NIC-based send BD rings are disabled. */ if (!tg3_flag(tp, 5705_PLUS)) { u32 mbox = <API key> + TG3_64BIT_REG_LOW; for (i = 0; i < 16; i++) tw32_tx_mbox(mbox + i * 8, 0); } /* Clear status block in ram. */ memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE); /* Set status block DMA address */ tw32(<API key> + TG3_64BIT_REG_HIGH, ((u64) tnapi->status_mapping >> 32)); tw32(<API key> + TG3_64BIT_REG_LOW, ((u64) tnapi->status_mapping & 0xffffffff)); stblk = <API key>; for (i = 1, tnapi++; i < tp->irq_cnt; i++, tnapi++) { u64 mapping = (u64)tnapi->status_mapping; tw32(stblk + TG3_64BIT_REG_HIGH, mapping >> 32); tw32(stblk + TG3_64BIT_REG_LOW, mapping & 0xffffffff); stblk += 8; /* Clear status block in ram. */ memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE); } tg3_tx_rcbs_init(tp); <API key>(tp); } static void <API key>(struct tg3 *tp) { u32 val, bdcache_maxcnt, host_rep_thresh, nic_rep_thresh; if (!tg3_flag(tp, 5750_PLUS) || tg3_flag(tp, 5780_CLASS) || tg3_asic_rev(tp) == ASIC_REV_5750 || tg3_asic_rev(tp) == ASIC_REV_5752 || tg3_flag(tp, 57765_PLUS)) bdcache_maxcnt = <API key>; else if (tg3_asic_rev(tp) == ASIC_REV_5755 || tg3_asic_rev(tp) == ASIC_REV_5787) bdcache_maxcnt = <API key>; else bdcache_maxcnt = <API key>; nic_rep_thresh = min(bdcache_maxcnt / 2, tp->rx_std_max_post); host_rep_thresh = max_t(u32, tp->rx_pending / 8, 1); val = min(nic_rep_thresh, host_rep_thresh); tw32(RCVBDI_STD_THRESH, val); if (tg3_flag(tp, 57765_PLUS)) tw32(STD_REPLENISH_LWM, bdcache_maxcnt); if (!tg3_flag(tp, JUMBO_CAPABLE) || tg3_flag(tp, 5780_CLASS)) return; bdcache_maxcnt = <API key>; host_rep_thresh = max_t(u32, tp->rx_jumbo_pending / 8, 1); val = min(bdcache_maxcnt / 2, host_rep_thresh); tw32(RCVBDI_JUMBO_THRESH, val); if (tg3_flag(tp, 57765_PLUS)) tw32(JMB_REPLENISH_LWM, bdcache_maxcnt); } static inline u32 calc_crc(unsigned char *buf, int len) { u32 reg; u32 tmp; int j, k; reg = 0xffffffff; for (j = 0; j < len; j++) { reg ^= buf[j]; for (k = 0; k < 8; k++) { tmp = reg & 0x01; reg >>= 1; if (tmp) reg ^= 0xedb88320; } } return ~reg; } static void tg3_set_multi(struct tg3 *tp, unsigned int accept_all) { /* accept or reject all multicast frames */ tw32(MAC_HASH_REG_0, accept_all ? 0xffffffff : 0); tw32(MAC_HASH_REG_1, accept_all ? 0xffffffff : 0); tw32(MAC_HASH_REG_2, accept_all ? 0xffffffff : 0); tw32(MAC_HASH_REG_3, accept_all ? 0xffffffff : 0); } static void __tg3_set_rx_mode(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); u32 rx_mode; rx_mode = tp->rx_mode & ~(RX_MODE_PROMISC | <API key>); #if !defined(CONFIG_VLAN_8021Q) && !defined(<API key>) /* When ASF is in use, we always keep the <API key> * flag clear. */ if (!tg3_flag(tp, ENABLE_ASF)) rx_mode |= <API key>; #endif if (dev->flags & IFF_PROMISC) { /* Promiscuous mode. */ rx_mode |= RX_MODE_PROMISC; } else if (dev->flags & IFF_ALLMULTI) { /* Accept all multicast. */ tg3_set_multi(tp, 1); } else if (netdev_mc_empty(dev)) { /* Reject all multicast. */ tg3_set_multi(tp, 0); } else { /* Accept one or more multicast(s). */ struct netdev_hw_addr *ha; u32 mc_filter[4] = { 0, }; u32 regidx; u32 bit; u32 crc; <API key>(ha, dev) { crc = calc_crc(ha->addr, ETH_ALEN); bit = ~crc & 0x7f; regidx = (bit & 0x60) >> 5; bit &= 0x1f; mc_filter[regidx] |= (1 << bit); } tw32(MAC_HASH_REG_0, mc_filter[0]); tw32(MAC_HASH_REG_1, mc_filter[1]); tw32(MAC_HASH_REG_2, mc_filter[2]); tw32(MAC_HASH_REG_3, mc_filter[3]); } if (netdev_uc_count(dev) > TG3_MAX_UCAST_ADDR(tp)) { rx_mode |= RX_MODE_PROMISC; } else if (!(dev->flags & IFF_PROMISC)) { /* Add all entries into to the mac addr filter list */ int i = 0; struct netdev_hw_addr *ha; <API key>(ha, dev) { <API key>(tp, ha->addr, i + TG3_UCAST_ADDR_IDX(tp)); i++; } } if (rx_mode != tp->rx_mode) { tp->rx_mode = rx_mode; tw32_f(MAC_RX_MODE, rx_mode); udelay(10); } } static void <API key>(struct tg3 *tp, u32 qcnt) { int i; for (i = 0; i < <API key>; i++) tp->rss_ind_tbl[i] = <API key>(i, qcnt); } static void <API key>(struct tg3 *tp) { int i; if (!tg3_flag(tp, SUPPORT_MSIX)) return; if (tp->rxq_cnt == 1) { memset(&tp->rss_ind_tbl[0], 0, sizeof(tp->rss_ind_tbl)); return; } /* Validate table against current IRQ count */ for (i = 0; i < <API key>; i++) { if (tp->rss_ind_tbl[i] >= tp->rxq_cnt) break; } if (i != <API key>) <API key>(tp, tp->rxq_cnt); } static void <API key>(struct tg3 *tp) { int i = 0; u32 reg = MAC_RSS_INDIR_TBL_0; while (i < <API key>) { u32 val = tp->rss_ind_tbl[i]; i++; for (; i % 8; i++) { val <<= 4; val |= tp->rss_ind_tbl[i]; } tw32(reg, val); reg += 4; } } static inline u32 <API key>(struct tg3 *tp) { if (tg3_asic_rev(tp) == ASIC_REV_5719) return <API key>; else return <API key>; } /* tp->lock is held. */ static int tg3_reset_hw(struct tg3 *tp, bool reset_phy) { u32 val, rdmac_mode; int i, err, limit; struct tg3_rx_prodring_set *tpr = &tp->napi[0].prodring; tg3_disable_ints(tp); tg3_stop_fw(tp); <API key>(tp, RESET_KIND_INIT); if (tg3_flag(tp, INIT_COMPLETE)) tg3_abort_hw(tp, 1); if ((tp->phy_flags & <API key>) && !(tp->phy_flags & <API key>)) { tg3_phy_pull_config(tp); tg3_eee_pull_config(tp, NULL); tp->phy_flags |= <API key>; } /* Enable MAC control of LPI */ if (tp->phy_flags & TG3_PHYFLG_EEE_CAP) tg3_setup_eee(tp); if (reset_phy) tg3_phy_reset(tp); err = tg3_chip_reset(tp); if (err) return err; <API key>(tp, RESET_KIND_INIT); if (tg3_chip_rev(tp) == CHIPREV_5784_AX) { val = tr32(TG3_CPMU_CTRL); val &= ~(<API key> | <API key>); tw32(TG3_CPMU_CTRL, val); val = tr32(<API key>); val &= ~<API key>; val |= <API key>; tw32(<API key>, val); val = tr32(<API key>); val &= ~<API key>; val |= <API key>; tw32(<API key>, val); val = tr32(TG3_CPMU_HST_ACC); val &= ~<API key>; val |= <API key>; tw32(TG3_CPMU_HST_ACC, val); } if (tg3_asic_rev(tp) == ASIC_REV_57780) { val = tr32(<API key>) & ~<API key>; val |= <API key> | <API key>; tw32(<API key>, val); val = tr32(<API key>) & ~<API key>; tw32(<API key>, val | <API key>); tw32(TG3_CORR_ERR_STAT, <API key>); val = tr32(TG3_PCIE_LNKCTL) & ~<API key>; tw32(TG3_PCIE_LNKCTL, val | <API key>); } if (tg3_flag(tp, L1PLLPD_EN)) { u32 grc_mode = tr32(GRC_MODE); /* Access the lower 1K of PL PCIE block registers. */ val = grc_mode & ~<API key>; tw32(GRC_MODE, val | <API key>); val = tr32(<API key> + <API key>); tw32(<API key> + <API key>, val | <API key>); tw32(GRC_MODE, grc_mode); } if (tg3_flag(tp, 57765_CLASS)) { if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0) { u32 grc_mode = tr32(GRC_MODE); /* Access the lower 1K of PL PCIE block registers. */ val = grc_mode & ~<API key>; tw32(GRC_MODE, val | <API key>); val = tr32(<API key> + <API key>); tw32(<API key> + <API key>, val | <API key>); tw32(GRC_MODE, grc_mode); } if (tg3_chip_rev(tp) != CHIPREV_57765_AX) { u32 grc_mode; /* Fix transmit hangs */ val = tr32(TG3_CPMU_PADRNG_CTL); val |= <API key>; tw32(TG3_CPMU_PADRNG_CTL, val); grc_mode = tr32(GRC_MODE); /* Access the lower 1K of DL PCIE block registers. */ val = grc_mode & ~<API key>; tw32(GRC_MODE, val | <API key>); val = tr32(<API key> + <API key>); val &= ~<API key>; tw32(<API key> + <API key>, val | <API key>); tw32(GRC_MODE, grc_mode); } val = tr32(<API key>); val &= ~<API key>; val |= <API key>; tw32(<API key>, val); } /* This works around an issue with Athlon chipsets on * B3 tigon3 silicon. This bit has no effect on any * other revision. But do not set this on PCI Express * chips and don't even touch the clocks if the CPMU is present. */ if (!tg3_flag(tp, CPMU_PRESENT)) { if (!tg3_flag(tp, PCI_EXPRESS)) tp->pci_clock_ctrl |= <API key>; tw32_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl); } if (tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0 && tg3_flag(tp, PCIX_MODE)) { val = tr32(TG3PCI_PCISTATE); val |= <API key>; tw32(TG3PCI_PCISTATE, val); } if (tg3_flag(tp, ENABLE_APE)) { /* Allow reads and writes to the * APE register and memory space. */ val = tr32(TG3PCI_PCISTATE); val |= <API key> | <API key> | <API key>; tw32(TG3PCI_PCISTATE, val); } if (tg3_chip_rev(tp) == CHIPREV_5704_BX) { /* Enable some hw fixes. */ val = tr32(TG3PCI_MSI_DATA); val |= (1 << 26) | (1 << 28) | (1 << 29); tw32(TG3PCI_MSI_DATA, val); } /* Descriptor ring init may make accesses to the * NIC SRAM area to setup the TX descriptors, so we * can only do this after the hardware has been * successfully reset. */ err = tg3_init_rings(tp); if (err) return err; if (tg3_flag(tp, 57765_PLUS)) { val = tr32(TG3PCI_DMA_RW_CTRL) & ~<API key>; if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0) val &= ~<API key>; if (!tg3_flag(tp, 57765_CLASS) && tg3_asic_rev(tp) != ASIC_REV_5717 && tg3_asic_rev(tp) != ASIC_REV_5762) val |= <API key>; tw32(TG3PCI_DMA_RW_CTRL, val | tp->dma_rwctrl); } else if (tg3_asic_rev(tp) != ASIC_REV_5784 && tg3_asic_rev(tp) != ASIC_REV_5761) { /* This value is determined during the probe time DMA * engine test, tg3_test_dma. */ tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl); } tp->grc_mode &= ~(<API key> | <API key> | <API key> | <API key>); tp->grc_mode |= <API key>; /* Pseudo-header checksum is done by hardware logic and not * the offload processers, so make the chip do the pseudo- * header checksums on receive. For transmit it is more * convenient to do the pseudo-header checksum in software * as Linux does that on transmit for us in all cases. */ tp->grc_mode |= <API key>; val = <API key> | <API key>; if (tp->rxptpctl) tw32(TG3_RX_PTP_CTL, tp->rxptpctl | <API key>); if (tg3_flag(tp, PTP_CAPABLE)) val |= <API key>; tw32(GRC_MODE, tp->grc_mode | val); /* Setup the timer prescalar register. Clock is always 66Mhz. */ val = tr32(GRC_MISC_CFG); val &= ~0xff; val |= (65 << <API key>); tw32(GRC_MISC_CFG, val); /* Initialize MBUF/DESC pool. */ if (tg3_flag(tp, 5750_PLUS)) { /* Do nothing. */ } else if (tg3_asic_rev(tp) != ASIC_REV_5705) { tw32(BUFMGR_MB_POOL_ADDR, <API key>); if (tg3_asic_rev(tp) == ASIC_REV_5704) tw32(BUFMGR_MB_POOL_SIZE, <API key>); else tw32(BUFMGR_MB_POOL_SIZE, <API key>); tw32(<API key>, <API key>); tw32(<API key>, <API key>); } else if (tg3_flag(tp, TSO_CAPABLE)) { int fw_len; fw_len = tp->fw_len; fw_len = (fw_len + (0x80 - 1)) & ~(0x80 - 1); tw32(BUFMGR_MB_POOL_ADDR, <API key> + fw_len); tw32(BUFMGR_MB_POOL_SIZE, <API key> - fw_len - 0xa00); } if (tp->dev->mtu <= ETH_DATA_LEN) { tw32(<API key>, tp->bufmgr_config.<API key>); tw32(<API key>, tp->bufmgr_config.<API key>); tw32(<API key>, tp->bufmgr_config.mbuf_high_water); } else { tw32(<API key>, tp->bufmgr_config.<API key>); tw32(<API key>, tp->bufmgr_config.<API key>); tw32(<API key>, tp->bufmgr_config.<API key>); } tw32(<API key>, tp->bufmgr_config.dma_low_water); tw32(<API key>, tp->bufmgr_config.dma_high_water); val = BUFMGR_MODE_ENABLE | <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5719) val |= <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5762 || tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5720_A0) val |= <API key>; tw32(BUFMGR_MODE, val); for (i = 0; i < 2000; i++) { if (tr32(BUFMGR_MODE) & BUFMGR_MODE_ENABLE) break; udelay(10); } if (i >= 2000) { netdev_err(tp->dev, "%s cannot enable BUFMGR\n", __func__); return -ENODEV; } if (tg3_chip_rev_id(tp) == CHIPREV_ID_5906_A1) tw32(ISO_PKT_TX, (tr32(ISO_PKT_TX) & ~0x3) | 0x2); <API key>(tp); /* Initialize TG3_BDINFO's at: * RCVDBDI_STD_BD: standard eth size rx ring * RCVDBDI_JUMBO_BD: jumbo frame rx ring * RCVDBDI_MINI_BD: small frame rx ring (??? does not work) * * like so: * <API key>: high/low parts of DMA address of ring * <API key>: (rx max buffer size << 16) | * ring attribute flags * TG3_BDINFO_NIC_ADDR: location of descriptors in nic SRAM * * Standard receive ring @ <API key>, 512 entries. * Jumbo receive ring @ <API key>, 256 entries. * * The size of each ring is fixed in the firmware, but the location is * configurable. */ tw32(RCVDBDI_STD_BD + <API key> + TG3_64BIT_REG_HIGH, ((u64) tpr->rx_std_mapping >> 32)); tw32(RCVDBDI_STD_BD + <API key> + TG3_64BIT_REG_LOW, ((u64) tpr->rx_std_mapping & 0xffffffff)); if (!tg3_flag(tp, 5717_PLUS)) tw32(RCVDBDI_STD_BD + TG3_BDINFO_NIC_ADDR, <API key>); /* Disable the mini ring */ if (!tg3_flag(tp, 5705_PLUS)) tw32(RCVDBDI_MINI_BD + <API key>, <API key>); /* Program the jumbo buffer descriptor ring control * blocks on those devices that have them. */ if (tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 || (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS))) { if (tg3_flag(tp, JUMBO_RING_ENABLE)) { tw32(RCVDBDI_JUMBO_BD + <API key> + TG3_64BIT_REG_HIGH, ((u64) tpr->rx_jmb_mapping >> 32)); tw32(RCVDBDI_JUMBO_BD + <API key> + TG3_64BIT_REG_LOW, ((u64) tpr->rx_jmb_mapping & 0xffffffff)); val = <API key>(tp) << <API key>; tw32(RCVDBDI_JUMBO_BD + <API key>, val | <API key>); if (!tg3_flag(tp, USE_JUMBO_BDFLAG) || tg3_flag(tp, 57765_CLASS) || tg3_asic_rev(tp) == ASIC_REV_5762) tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_NIC_ADDR, <API key>); } else { tw32(RCVDBDI_JUMBO_BD + <API key>, <API key>); } if (tg3_flag(tp, 57765_PLUS)) { val = <API key>(tp); val <<= <API key>; val |= (TG3_RX_STD_DMA_SZ << 2); } else val = TG3_RX_STD_DMA_SZ << <API key>; } else val = <API key> << <API key>; tw32(RCVDBDI_STD_BD + <API key>, val); tpr->rx_std_prod_idx = tp->rx_pending; tw32_rx_mbox(<API key>, tpr->rx_std_prod_idx); tpr->rx_jmb_prod_idx = tg3_flag(tp, JUMBO_RING_ENABLE) ? tp->rx_jumbo_pending : 0; tw32_rx_mbox(<API key>, tpr->rx_jmb_prod_idx); tg3_rings_reset(tp); /* Initialize MAC address and backoff seed. */ __tg3_set_mac_addr(tp, false); /* MTU + ethernet header + FCS + optional VLAN tag */ tw32(MAC_RX_MTU_SIZE, tp->dev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN); /* The slot time is changed by tg3_setup_phy if we * run at gigabit with half duplex. */ val = (2 << <API key>) | (6 << <API key>) | (32 << <API key>); if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) val |= tr32(MAC_TX_LENGTHS) & (<API key> | <API key>); tw32(MAC_TX_LENGTHS, val); /* Receive rules. */ tw32(MAC_RCV_RULE_CFG, <API key>); tw32(RCVLPC_CONFIG, 0x0181); /* Calculate RDMAC_MODE setting early, we need it to determine * the RCVLPC_STATE_ENABLE mask. */ rdmac_mode = (RDMAC_MODE_ENABLE | <API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key>); if (tg3_asic_rev(tp) == ASIC_REV_5717) rdmac_mode |= <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780) rdmac_mode |= <API key> | <API key> | <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5705 && tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) { if (tg3_flag(tp, TSO_CAPABLE) && tg3_asic_rev(tp) == ASIC_REV_5705) { rdmac_mode |= <API key>; } else if (!(tr32(TG3PCI_PCISTATE) & <API key>) && !tg3_flag(tp, IS_5788)) { rdmac_mode |= <API key>; } } if (tg3_flag(tp, PCI_EXPRESS)) rdmac_mode |= <API key>; if (tg3_asic_rev(tp) == ASIC_REV_57766) { tp->dma_limit = 0; if (tp->dev->mtu <= ETH_DATA_LEN) { rdmac_mode |= <API key>; tp->dma_limit = <API key>; } } if (tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) rdmac_mode |= <API key>; if (tg3_flag(tp, 57765_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780) rdmac_mode |= <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) rdmac_mode |= tr32(RDMAC_MODE) & <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5761 || tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780 || tg3_flag(tp, 57765_PLUS)) { u32 tgtreg; if (tg3_asic_rev(tp) == ASIC_REV_5762) tgtreg = <API key>; else tgtreg = <API key>; val = tr32(tgtreg); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 || tg3_asic_rev(tp) == ASIC_REV_5762) { val &= ~(<API key> | <API key> | <API key>); val |= <API key> | <API key> | <API key>; } tw32(tgtreg, val | <API key>); } if (tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) { u32 tgtreg; if (tg3_asic_rev(tp) == ASIC_REV_5762) tgtreg = <API key>; else tgtreg = <API key>; val = tr32(tgtreg); tw32(tgtreg, val | <API key> | <API key>); } /* Receive/send statistics. */ if (tg3_flag(tp, 5750_PLUS)) { val = tr32(RCVLPC_STATS_ENABLE); val &= ~<API key>; tw32(RCVLPC_STATS_ENABLE, val); } else if ((rdmac_mode & <API key>) && tg3_flag(tp, TSO_CAPABLE)) { val = tr32(RCVLPC_STATS_ENABLE); val &= ~<API key>; tw32(RCVLPC_STATS_ENABLE, val); } else { tw32(RCVLPC_STATS_ENABLE, 0xffffff); } tw32(RCVLPC_STATSCTRL, <API key>); tw32(SNDDATAI_STATSENAB, 0xffffff); tw32(SNDDATAI_STATSCTRL, (<API key> | <API key>)); /* Setup host coalescing engine. */ tw32(HOSTCC_MODE, 0); for (i = 0; i < 2000; i++) { if (!(tr32(HOSTCC_MODE) & HOSTCC_MODE_ENABLE)) break; udelay(10); } __tg3_set_coalesce(tp, &tp->coal); if (!tg3_flag(tp, 5705_PLUS)) { /* Status/statistics block address. See tg3_timer, * the <API key> call there, and * tg3_get_stats to see how this works for 5705/5750 chips. */ tw32(<API key> + TG3_64BIT_REG_HIGH, ((u64) tp->stats_mapping >> 32)); tw32(<API key> + TG3_64BIT_REG_LOW, ((u64) tp->stats_mapping & 0xffffffff)); tw32(<API key>, NIC_SRAM_STATS_BLK); tw32(<API key>, NIC_SRAM_STATUS_BLK); /* Clear statistics and status block memory areas */ for (i = NIC_SRAM_STATS_BLK; i < NIC_SRAM_STATUS_BLK + TG3_HW_STATUS_SIZE; i += sizeof(u32)) { tg3_write_mem(tp, i, 0); udelay(40); } } tw32(HOSTCC_MODE, HOSTCC_MODE_ENABLE | tp->coalesce_mode); tw32(RCVCC_MODE, RCVCC_MODE_ENABLE | <API key>); tw32(RCVLPC_MODE, RCVLPC_MODE_ENABLE); if (!tg3_flag(tp, 5705_PLUS)) tw32(RCVLSC_MODE, RCVLSC_MODE_ENABLE | <API key>); if (tp->phy_flags & <API key>) { tp->phy_flags &= ~<API key>; /* reset to prevent losing 1st rx packet intermittently */ tw32_f(MAC_RX_MODE, RX_MODE_RESET); udelay(10); } tp->mac_mode |= <API key> | <API key> | MAC_MODE_TDE_ENABLE | MAC_MODE_RDE_ENABLE | <API key>; if (tg3_flag(tp, ENABLE_APE)) tp->mac_mode |= MAC_MODE_APE_TX_EN | MAC_MODE_APE_RX_EN; if (!tg3_flag(tp, 5705_PLUS) && !(tp->phy_flags & <API key>) && tg3_asic_rev(tp) != ASIC_REV_5700) tp->mac_mode |= <API key>; tw32_f(MAC_MODE, tp->mac_mode | <API key> | <API key>); udelay(40); /* tp->grc_local_ctrl is partially set up during tg3_get_invariants(). * If TG3_FLAG_IS_NIC is zero, we should read the * register to preserve the GPIO settings for LOMs. The GPIOs, * whether used as inputs or outputs, are set by boot code after * reset. */ if (!tg3_flag(tp, IS_NIC)) { u32 gpio_mask; gpio_mask = <API key> | <API key> | <API key> | <API key> | <API key> | <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5752) gpio_mask |= <API key> | <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5755) gpio_mask |= <API key>; tp->grc_local_ctrl &= ~gpio_mask; tp->grc_local_ctrl |= tr32(GRC_LOCAL_CTRL) & gpio_mask; /* GPIO1 must be driven high for eeprom write protect */ if (tg3_flag(tp, EEPROM_WRITE_PROT)) tp->grc_local_ctrl |= (<API key> | <API key>); } tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl); udelay(100); if (tg3_flag(tp, USING_MSIX)) { val = tr32(MSGINT_MODE); val |= MSGINT_MODE_ENABLE; if (tp->irq_cnt > 1) val |= <API key>; if (!tg3_flag(tp, 1SHOT_MSI)) val |= <API key>; tw32(MSGINT_MODE, val); } if (!tg3_flag(tp, 5705_PLUS)) { tw32_f(DMAC_MODE, DMAC_MODE_ENABLE); udelay(40); } val = (WDMAC_MODE_ENABLE | <API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key> | <API key>); if (tg3_asic_rev(tp) == ASIC_REV_5705 && tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) { if (tg3_flag(tp, TSO_CAPABLE) && (tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A1 || tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A2)) { /* nothing */ } else if (!(tr32(TG3PCI_PCISTATE) & <API key>) && !tg3_flag(tp, IS_5788)) { val |= WDMAC_MODE_RX_ACCEL; } } /* Enable host coalescing bug fix */ if (tg3_flag(tp, 5755_PLUS)) val |= <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5785) val |= <API key>; tw32_f(WDMAC_MODE, val); udelay(40); if (tg3_flag(tp, PCIX_MODE)) { u16 pcix_cmd; <API key>(tp->pdev, tp->pcix_cap + PCI_X_CMD, &pcix_cmd); if (tg3_asic_rev(tp) == ASIC_REV_5703) { pcix_cmd &= ~PCI_X_CMD_MAX_READ; pcix_cmd |= PCI_X_CMD_READ_2K; } else if (tg3_asic_rev(tp) == ASIC_REV_5704) { pcix_cmd &= ~(PCI_X_CMD_MAX_SPLIT | PCI_X_CMD_MAX_READ); pcix_cmd |= PCI_X_CMD_READ_2K; } <API key>(tp->pdev, tp->pcix_cap + PCI_X_CMD, pcix_cmd); } tw32_f(RDMAC_MODE, rdmac_mode); udelay(40); if (tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) { for (i = 0; i < <API key>; i++) { if (tr32(TG3_RDMA_LENGTH + (i << 2)) > TG3_MAX_MTU(tp)) break; } if (i < <API key>) { val = tr32(<API key>); val |= <API key>(tp); tw32(<API key>, val); tg3_flag_set(tp, 5719_5720_RDMA_BUG); } } tw32(RCVDCC_MODE, RCVDCC_MODE_ENABLE | <API key>); if (!tg3_flag(tp, 5705_PLUS)) tw32(MBFREE_MODE, MBFREE_MODE_ENABLE); if (tg3_asic_rev(tp) == ASIC_REV_5761) tw32(SNDDATAC_MODE, <API key> | <API key>); else tw32(SNDDATAC_MODE, <API key>); tw32(SNDBDC_MODE, SNDBDC_MODE_ENABLE | <API key>); tw32(RCVBDI_MODE, RCVBDI_MODE_ENABLE | <API key>); val = RCVDBDI_MODE_ENABLE | <API key>; if (tg3_flag(tp, LRG_PROD_RING_CAP)) val |= <API key>; tw32(RCVDBDI_MODE, val); tw32(SNDDATAI_MODE, <API key>); if (tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) tw32(SNDDATAI_MODE, <API key> | 0x8); val = SNDBDI_MODE_ENABLE | <API key>; if (tg3_flag(tp, ENABLE_TSS)) val |= <API key>; tw32(SNDBDI_MODE, val); tw32(SNDBDS_MODE, SNDBDS_MODE_ENABLE | <API key>); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0) { err = <API key>(tp); if (err) return err; } if (tg3_asic_rev(tp) == ASIC_REV_57766) { /* Ignore any errors for the firmware download. If download * fails, the device will operate with EEE disabled */ <API key>(tp); } if (tg3_flag(tp, TSO_CAPABLE)) { err = <API key>(tp); if (err) return err; } tp->tx_mode = TX_MODE_ENABLE; if (tg3_flag(tp, 5755_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5906) tp->tx_mode |= <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) { val = TX_MODE_JMB_FRM_LEN | TX_MODE_CNT_DN_MODE; tp->tx_mode &= ~val; tp->tx_mode |= tr32(MAC_TX_MODE) & val; } tw32_f(MAC_TX_MODE, tp->tx_mode); udelay(100); if (tg3_flag(tp, ENABLE_RSS)) { <API key>(tp); /* Setup the "secret" hash key. */ tw32(MAC_RSS_HASH_KEY_0, 0x5f865437); tw32(MAC_RSS_HASH_KEY_1, 0xe4ac62cc); tw32(MAC_RSS_HASH_KEY_2, 0x50103a45); tw32(MAC_RSS_HASH_KEY_3, 0x36621985); tw32(MAC_RSS_HASH_KEY_4, 0xbf14c0e8); tw32(MAC_RSS_HASH_KEY_5, 0x1bc27a1e); tw32(MAC_RSS_HASH_KEY_6, 0x84f4b556); tw32(MAC_RSS_HASH_KEY_7, 0x094ea6fe); tw32(MAC_RSS_HASH_KEY_8, 0x7dda01e7); tw32(MAC_RSS_HASH_KEY_9, 0xc04d7481); } tp->rx_mode = RX_MODE_ENABLE; if (tg3_flag(tp, 5755_PLUS)) tp->rx_mode |= <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5762) tp->rx_mode |= <API key>; if (tg3_flag(tp, ENABLE_RSS)) tp->rx_mode |= RX_MODE_RSS_ENABLE | <API key> | <API key> | <API key> | <API key> | <API key>; tw32_f(MAC_RX_MODE, tp->rx_mode); udelay(10); tw32(MAC_LED_CTRL, tp->led_ctrl); tw32(MAC_MI_STAT, <API key>); if (tp->phy_flags & <API key>) { tw32_f(MAC_RX_MODE, RX_MODE_RESET); udelay(10); } tw32_f(MAC_RX_MODE, tp->rx_mode); udelay(10); if (tp->phy_flags & <API key>) { if ((tg3_asic_rev(tp) == ASIC_REV_5704) && !(tp->phy_flags & <API key>)) { /* Set drive transmission level to 1.2V */ /* only if the signal pre-emphasis bit is not set */ val = tr32(MAC_SERDES_CFG); val &= 0xfffff000; val |= 0x880; tw32(MAC_SERDES_CFG, val); } if (tg3_chip_rev_id(tp) == CHIPREV_ID_5703_A1) tw32(MAC_SERDES_CFG, 0x616000); } /* Prevent chip from dropping frames when flow control * is enabled. */ if (tg3_flag(tp, 57765_CLASS)) val = 1; else val = 2; tw32_f(<API key>, val); if (tg3_asic_rev(tp) == ASIC_REV_5704 && (tp->phy_flags & <API key>)) { /* Use hardware link auto-negotiation */ tg3_flag_set(tp, HW_AUTONEG); } if ((tp->phy_flags & <API key>) && tg3_asic_rev(tp) == ASIC_REV_5714) { u32 tmp; tmp = tr32(SERDES_RX_CTRL); tw32(SERDES_RX_CTRL, tmp | <API key>); tp->grc_local_ctrl &= ~<API key>; tp->grc_local_ctrl |= <API key>; tw32(GRC_LOCAL_CTRL, tp->grc_local_ctrl); } if (!tg3_flag(tp, USE_PHYLIB)) { if (tp->phy_flags & <API key>) tp->phy_flags &= ~<API key>; err = tg3_setup_phy(tp, false); if (err) return err; if (!(tp->phy_flags & <API key>) && !(tp->phy_flags & TG3_PHYFLG_IS_FET)) { u32 tmp; /* Clear CRC stats. */ if (!tg3_readphy(tp, MII_TG3_TEST1, &tmp)) { tg3_writephy(tp, MII_TG3_TEST1, tmp | <API key>); tg3_readphy(tp, <API key>, &tmp); } } } __tg3_set_rx_mode(tp->dev); /* Initialize receive rules. */ tw32(MAC_RCV_RULE_0, 0xc2000000 & <API key>); tw32(MAC_RCV_VALUE_0, 0xffffffff & <API key>); tw32(MAC_RCV_RULE_1, 0x86000004 & <API key>); tw32(MAC_RCV_VALUE_1, 0xffffffff & <API key>); if (tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, 5780_CLASS)) limit = 8; else limit = 16; if (tg3_flag(tp, ENABLE_ASF)) limit -= 4; switch (limit) { case 16: tw32(MAC_RCV_RULE_15, 0); tw32(MAC_RCV_VALUE_15, 0); case 15: tw32(MAC_RCV_RULE_14, 0); tw32(MAC_RCV_VALUE_14, 0); case 14: tw32(MAC_RCV_RULE_13, 0); tw32(MAC_RCV_VALUE_13, 0); case 13: tw32(MAC_RCV_RULE_12, 0); tw32(MAC_RCV_VALUE_12, 0); case 12: tw32(MAC_RCV_RULE_11, 0); tw32(MAC_RCV_VALUE_11, 0); case 11: tw32(MAC_RCV_RULE_10, 0); tw32(MAC_RCV_VALUE_10, 0); case 10: tw32(MAC_RCV_RULE_9, 0); tw32(MAC_RCV_VALUE_9, 0); case 9: tw32(MAC_RCV_RULE_8, 0); tw32(MAC_RCV_VALUE_8, 0); case 8: tw32(MAC_RCV_RULE_7, 0); tw32(MAC_RCV_VALUE_7, 0); case 7: tw32(MAC_RCV_RULE_6, 0); tw32(MAC_RCV_VALUE_6, 0); case 6: tw32(MAC_RCV_RULE_5, 0); tw32(MAC_RCV_VALUE_5, 0); case 5: tw32(MAC_RCV_RULE_4, 0); tw32(MAC_RCV_VALUE_4, 0); case 4: /* tw32(MAC_RCV_RULE_3, 0); tw32(MAC_RCV_VALUE_3, 0); */ case 3: /* tw32(MAC_RCV_RULE_2, 0); tw32(MAC_RCV_VALUE_2, 0); */ case 2: case 1: default: break; } if (tg3_flag(tp, ENABLE_APE)) /* Write our heartbeat update interval to APE. */ tg3_ape_write32(tp, <API key>, <API key>); <API key>(tp, RESET_KIND_INIT); return 0; } /* Called at device open time to get the chip ready for * packet processing. Invoked with tp->lock held. */ static int tg3_init_hw(struct tg3 *tp, bool reset_phy) { /* Chip may have been just powered on. If so, the boot code may still * be running initialization. Wait for it to finish to avoid races in * accessing the hardware. */ <API key>(tp); tg3_poll_fw(tp); tg3_switch_clocks(tp); tw32(<API key>, 0); return tg3_reset_hw(tp, reset_phy); } static void <API key>(struct tg3 *tp, struct tg3_ocir *ocir) { int i; for (i = 0; i < TG3_SD_NUM_RECS; i++, ocir++) { u32 off = i * TG3_OCIR_LEN, len = TG3_OCIR_LEN; <API key>(tp, (u32 *) ocir, off, len); off += len; if (ocir->signature != TG3_OCIR_SIG_MAGIC || !(ocir->version_flags & <API key>)) memset(ocir, 0, TG3_OCIR_LEN); } } /* sysfs attributes for hwmon */ static ssize_t tg3_show_temp(struct device *dev, struct device_attribute *devattr, char *buf) { struct <API key> *attr = to_sensor_dev_attr(devattr); struct tg3 *tp = dev_get_drvdata(dev); u32 temperature; spin_lock_bh(&tp->lock); <API key>(tp, &temperature, attr->index, sizeof(temperature)); spin_unlock_bh(&tp->lock); return sprintf(buf, "%u\n", temperature); } static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, tg3_show_temp, NULL, <API key>); static SENSOR_DEVICE_ATTR(temp1_crit, S_IRUGO, tg3_show_temp, NULL, <API key>); static SENSOR_DEVICE_ATTR(temp1_max, S_IRUGO, tg3_show_temp, NULL, TG3_TEMP_MAX_OFFSET); static struct attribute *tg3_attrs[] = { &<API key>.dev_attr.attr, &<API key>.dev_attr.attr, &<API key>.dev_attr.attr, NULL }; ATTRIBUTE_GROUPS(tg3); static void tg3_hwmon_close(struct tg3 *tp) { if (tp->hwmon_dev) { <API key>(tp->hwmon_dev); tp->hwmon_dev = NULL; } } static void tg3_hwmon_open(struct tg3 *tp) { int i; u32 size = 0; struct pci_dev *pdev = tp->pdev; struct tg3_ocir ocirs[TG3_SD_NUM_RECS]; <API key>(tp, ocirs); for (i = 0; i < TG3_SD_NUM_RECS; i++) { if (!ocirs[i].src_data_length) continue; size += ocirs[i].src_hdr_length; size += ocirs[i].src_data_length; } if (!size) return; tp->hwmon_dev = <API key>(&pdev->dev, "tg3", tp, tg3_groups); if (IS_ERR(tp->hwmon_dev)) { tp->hwmon_dev = NULL; dev_err(&pdev->dev, "Cannot register hwmon device, aborting\n"); } } #define TG3_STAT_ADD32(PSTAT, REG) \ do { u32 __val = tr32(REG); \ (PSTAT)->low += __val; \ if ((PSTAT)->low < __val) \ (PSTAT)->high += 1; \ } while (0) static void <API key>(struct tg3 *tp) { struct tg3_hw_stats *sp = tp->hw_stats; if (!tp->link_up) return; TG3_STAT_ADD32(&sp->tx_octets, MAC_TX_STATS_OCTETS); TG3_STAT_ADD32(&sp->tx_collisions, <API key>); TG3_STAT_ADD32(&sp->tx_xon_sent, <API key>); TG3_STAT_ADD32(&sp->tx_xoff_sent, <API key>); TG3_STAT_ADD32(&sp->tx_mac_errors, <API key>); TG3_STAT_ADD32(&sp-><API key>, <API key>); TG3_STAT_ADD32(&sp->tx_mult_collisions, <API key>); TG3_STAT_ADD32(&sp->tx_deferred, <API key>); TG3_STAT_ADD32(&sp-><API key>, <API key>); TG3_STAT_ADD32(&sp->tx_late_collisions, <API key>); TG3_STAT_ADD32(&sp->tx_ucast_packets, MAC_TX_STATS_UCAST); TG3_STAT_ADD32(&sp->tx_mcast_packets, MAC_TX_STATS_MCAST); TG3_STAT_ADD32(&sp->tx_bcast_packets, MAC_TX_STATS_BCAST); if (unlikely(tg3_flag(tp, 5719_5720_RDMA_BUG) && (sp->tx_ucast_packets.low + sp->tx_mcast_packets.low + sp->tx_bcast_packets.low) > <API key>)) { u32 val; val = tr32(<API key>); val &= ~<API key>(tp); tw32(<API key>, val); tg3_flag_clear(tp, 5719_5720_RDMA_BUG); } TG3_STAT_ADD32(&sp->rx_octets, MAC_RX_STATS_OCTETS); TG3_STAT_ADD32(&sp->rx_fragments, <API key>); TG3_STAT_ADD32(&sp->rx_ucast_packets, MAC_RX_STATS_UCAST); TG3_STAT_ADD32(&sp->rx_mcast_packets, MAC_RX_STATS_MCAST); TG3_STAT_ADD32(&sp->rx_bcast_packets, MAC_RX_STATS_BCAST); TG3_STAT_ADD32(&sp->rx_fcs_errors, <API key>); TG3_STAT_ADD32(&sp->rx_align_errors, <API key>); TG3_STAT_ADD32(&sp->rx_xon_pause_rcvd, <API key>); TG3_STAT_ADD32(&sp->rx_xoff_pause_rcvd, <API key>); TG3_STAT_ADD32(&sp->rx_mac_ctrl_rcvd, <API key>); TG3_STAT_ADD32(&sp->rx_xoff_entered, <API key>); TG3_STAT_ADD32(&sp-><API key>, <API key>); TG3_STAT_ADD32(&sp->rx_jabbers, <API key>); TG3_STAT_ADD32(&sp-><API key>, <API key>); TG3_STAT_ADD32(&sp->rxbds_empty, <API key>); if (tg3_asic_rev(tp) != ASIC_REV_5717 && tg3_asic_rev(tp) != ASIC_REV_5762 && tg3_chip_rev_id(tp) != CHIPREV_ID_5719_A0 && tg3_chip_rev_id(tp) != CHIPREV_ID_5720_A0) { TG3_STAT_ADD32(&sp->rx_discards, <API key>); } else { u32 val = tr32(HOSTCC_FLOW_ATTN); val = (val & <API key>) ? 1 : 0; if (val) { tw32(HOSTCC_FLOW_ATTN, <API key>); sp->rx_discards.low += val; if (sp->rx_discards.low < val) sp->rx_discards.high += 1; } sp->mbuf_lwm_thresh_hit = sp->rx_discards; } TG3_STAT_ADD32(&sp->rx_errors, <API key>); } static void tg3_chk_missed_msi(struct tg3 *tp) { u32 i; for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (tg3_has_work(tnapi)) { if (tnapi->last_rx_cons == tnapi->rx_rcb_ptr && tnapi->last_tx_cons == tnapi->tx_cons) { if (tnapi->chk_msi_cnt < 1) { tnapi->chk_msi_cnt++; return; } tg3_msi(0, tnapi); } } tnapi->chk_msi_cnt = 0; tnapi->last_rx_cons = tnapi->rx_rcb_ptr; tnapi->last_tx_cons = tnapi->tx_cons; } } static void tg3_timer(unsigned long __opaque) { struct tg3 *tp = (struct tg3 *) __opaque; if (tp->irq_sync || tg3_flag(tp, RESET_TASK_PENDING)) goto restart_timer; spin_lock(&tp->lock); if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_flag(tp, 57765_CLASS)) tg3_chk_missed_msi(tp); if (tg3_flag(tp, FLUSH_POSTED_WRITES)) { /* BCM4785: Flush posted writes from GbE to host memory. */ tr32(HOSTCC_MODE); } if (!tg3_flag(tp, TAGGED_STATUS)) { /* All of this garbage is because when using non-tagged * IRQ status the mailbox/status_block protocol the chip * uses with the cpu is race prone. */ if (tp->napi[0].hw_status->status & SD_STATUS_UPDATED) { tw32(GRC_LOCAL_CTRL, tp->grc_local_ctrl | GRC_LCLCTRL_SETINT); } else { tw32(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | HOSTCC_MODE_NOW); } if (!(tr32(WDMAC_MODE) & WDMAC_MODE_ENABLE)) { spin_unlock(&tp->lock); <API key>(tp); goto restart_timer; } } /* This part only runs once per second. */ if (!--tp->timer_counter) { if (tg3_flag(tp, 5705_PLUS)) <API key>(tp); if (tp->setlpicnt && !--tp->setlpicnt) tg3_phy_eee_enable(tp); if (tg3_flag(tp, USE_LINKCHG_REG)) { u32 mac_stat; int phy_event; mac_stat = tr32(MAC_STATUS); phy_event = 0; if (tp->phy_flags & <API key>) { if (mac_stat & <API key>) phy_event = 1; } else if (mac_stat & <API key>) phy_event = 1; if (phy_event) tg3_setup_phy(tp, false); } else if (tg3_flag(tp, POLL_SERDES)) { u32 mac_stat = tr32(MAC_STATUS); int need_setup = 0; if (tp->link_up && (mac_stat & <API key>)) { need_setup = 1; } if (!tp->link_up && (mac_stat & (<API key> | <API key>))) { need_setup = 1; } if (need_setup) { if (!tp->serdes_counter) { tw32_f(MAC_MODE, (tp->mac_mode & ~<API key>)); udelay(40); tw32_f(MAC_MODE, tp->mac_mode); udelay(40); } tg3_setup_phy(tp, false); } } else if ((tp->phy_flags & <API key>) && tg3_flag(tp, 5780_CLASS)) { <API key>(tp); } else if (tg3_flag(tp, POLL_CPMU_LINK)) { u32 cpmu = tr32(TG3_CPMU_STATUS); bool link_up = !((cpmu & <API key>) == <API key>); if (link_up != tp->link_up) tg3_setup_phy(tp, false); } tp->timer_counter = tp->timer_multiplier; } /* Heartbeat is only sent once every 2 seconds. * * The heartbeat is to tell the ASF firmware that the host * driver is still alive. In the event that the OS crashes, * ASF needs to reset the hardware to free up the FIFO space * that may be filled with rx packets destined for the host. * If the FIFO is full, ASF will no longer function properly. * * Unintended resets have been reported on real time kernels * where the timer doesn't run on time. Netpoll will also have * same problem. * * The new FWCMD_NICDRV_ALIVE3 command tells the ASF firmware * to check the ring condition when the heartbeat is expiring * before doing the reset. This will prevent most unintended * resets. */ if (!--tp->asf_counter) { if (tg3_flag(tp, ENABLE_ASF) && !tg3_flag(tp, ENABLE_APE)) { <API key>(tp); tg3_write_mem(tp, <API key>, FWCMD_NICDRV_ALIVE3); tg3_write_mem(tp, <API key>, 4); tg3_write_mem(tp, <API key>, <API key>); <API key>(tp); } tp->asf_counter = tp->asf_multiplier; } spin_unlock(&tp->lock); restart_timer: tp->timer.expires = jiffies + tp->timer_offset; add_timer(&tp->timer); } static void tg3_timer_init(struct tg3 *tp) { if (tg3_flag(tp, TAGGED_STATUS) && tg3_asic_rev(tp) != ASIC_REV_5717 && !tg3_flag(tp, 57765_CLASS)) tp->timer_offset = HZ; else tp->timer_offset = HZ / 10; BUG_ON(tp->timer_offset > HZ); tp->timer_multiplier = (HZ / tp->timer_offset); tp->asf_multiplier = (HZ / tp->timer_offset) * <API key>; init_timer(&tp->timer); tp->timer.data = (unsigned long) tp; tp->timer.function = tg3_timer; } static void tg3_timer_start(struct tg3 *tp) { tp->asf_counter = tp->asf_multiplier; tp->timer_counter = tp->timer_multiplier; tp->timer.expires = jiffies + tp->timer_offset; add_timer(&tp->timer); } static void tg3_timer_stop(struct tg3 *tp) { del_timer_sync(&tp->timer); } /* Restart hardware after configuration changes, self-test, etc. * Invoked with tp->lock held. */ static int tg3_restart_hw(struct tg3 *tp, bool reset_phy) __releases(tp->lock) __acquires(tp->lock) { int err; err = tg3_init_hw(tp, reset_phy); if (err) { netdev_err(tp->dev, "Failed to re-initialize device, aborting\n"); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); tg3_full_unlock(tp); tg3_timer_stop(tp); tp->irq_sync = 0; tg3_napi_enable(tp); dev_close(tp->dev); tg3_full_lock(tp, 0); } return err; } static void tg3_reset_task(struct work_struct *work) { struct tg3 *tp = container_of(work, struct tg3, reset_task); int err; tg3_full_lock(tp, 0); if (!netif_running(tp->dev)) { tg3_flag_clear(tp, RESET_TASK_PENDING); tg3_full_unlock(tp); return; } tg3_full_unlock(tp); tg3_phy_stop(tp); tg3_netif_stop(tp); tg3_full_lock(tp, 1); if (tg3_flag(tp, TX_RECOVERY_PENDING)) { tp->write32_tx_mbox = tg3_write32_tx_mbox; tp->write32_rx_mbox = <API key>; tg3_flag_set(tp, MBOX_WRITE_REORDER); tg3_flag_clear(tp, TX_RECOVERY_PENDING); } tg3_halt(tp, RESET_KIND_SHUTDOWN, 0); err = tg3_init_hw(tp, true); if (err) goto out; tg3_netif_start(tp); out: tg3_full_unlock(tp); if (!err) tg3_phy_start(tp); tg3_flag_clear(tp, RESET_TASK_PENDING); } static int tg3_request_irq(struct tg3 *tp, int irq_num) { irq_handler_t fn; unsigned long flags; char *name; struct tg3_napi *tnapi = &tp->napi[irq_num]; if (tp->irq_cnt == 1) name = tp->dev->name; else { name = &tnapi->irq_lbl[0]; if (tnapi->tx_buffers && tnapi->rx_rcb) snprintf(name, IFNAMSIZ, "%s-txrx-%d", tp->dev->name, irq_num); else if (tnapi->tx_buffers) snprintf(name, IFNAMSIZ, "%s-tx-%d", tp->dev->name, irq_num); else if (tnapi->rx_rcb) snprintf(name, IFNAMSIZ, "%s-rx-%d", tp->dev->name, irq_num); else snprintf(name, IFNAMSIZ, "%s-%d", tp->dev->name, irq_num); name[IFNAMSIZ-1] = 0; } if (tg3_flag(tp, USING_MSI) || tg3_flag(tp, USING_MSIX)) { fn = tg3_msi; if (tg3_flag(tp, 1SHOT_MSI)) fn = tg3_msi_1shot; flags = 0; } else { fn = tg3_interrupt; if (tg3_flag(tp, TAGGED_STATUS)) fn = <API key>; flags = IRQF_SHARED; } return request_irq(tnapi->irq_vec, fn, flags, name, tnapi); } static int tg3_test_interrupt(struct tg3 *tp) { struct tg3_napi *tnapi = &tp->napi[0]; struct net_device *dev = tp->dev; int err, i, intr_ok = 0; u32 val; if (!netif_running(dev)) return -ENODEV; tg3_disable_ints(tp); free_irq(tnapi->irq_vec, tnapi); /* * Turn off MSI one shot mode. Otherwise this test has no * observable way to know whether the interrupt was delivered. */ if (tg3_flag(tp, 57765_PLUS)) { val = tr32(MSGINT_MODE) | <API key>; tw32(MSGINT_MODE, val); } err = request_irq(tnapi->irq_vec, tg3_test_isr, IRQF_SHARED, dev->name, tnapi); if (err) return err; tnapi->hw_status->status &= ~SD_STATUS_UPDATED; tg3_enable_ints(tp); tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | tnapi->coal_now); for (i = 0; i < 5; i++) { u32 int_mbox, misc_host_ctrl; int_mbox = tr32_mailbox(tnapi->int_mbox); misc_host_ctrl = tr32(<API key>); if ((int_mbox != 0) || (misc_host_ctrl & <API key>)) { intr_ok = 1; break; } if (tg3_flag(tp, 57765_PLUS) && tnapi->hw_status->status_tag != tnapi->last_tag) tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24); msleep(10); } tg3_disable_ints(tp); free_irq(tnapi->irq_vec, tnapi); err = tg3_request_irq(tp, 0); if (err) return err; if (intr_ok) { /* Reenable MSI one shot mode. */ if (tg3_flag(tp, 57765_PLUS) && tg3_flag(tp, 1SHOT_MSI)) { val = tr32(MSGINT_MODE) & ~<API key>; tw32(MSGINT_MODE, val); } return 0; } return -EIO; } /* Returns 0 if MSI test succeeds or MSI test fails and INTx mode is * successfully restored */ static int tg3_test_msi(struct tg3 *tp) { int err; u16 pci_cmd; if (!tg3_flag(tp, USING_MSI)) return 0; /* Turn off SERR reporting in case MSI terminates with Master * Abort. */ <API key>(tp->pdev, PCI_COMMAND, &pci_cmd); <API key>(tp->pdev, PCI_COMMAND, pci_cmd & ~PCI_COMMAND_SERR); err = tg3_test_interrupt(tp); <API key>(tp->pdev, PCI_COMMAND, pci_cmd); if (!err) return 0; /* other failures */ if (err != -EIO) return err; /* MSI test failed, go back to INTx mode */ netdev_warn(tp->dev, "No interrupt was generated using MSI. Switching " "to INTx mode. Please report this failure to the PCI " "maintainer and include system chipset information\n"); free_irq(tp->napi[0].irq_vec, &tp->napi[0]); pci_disable_msi(tp->pdev); tg3_flag_clear(tp, USING_MSI); tp->napi[0].irq_vec = tp->pdev->irq; err = tg3_request_irq(tp, 0); if (err) return err; /* Need to reset the chip because the MSI cycle may have terminated * with Master Abort. */ tg3_full_lock(tp, 1); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); err = tg3_init_hw(tp, true); tg3_full_unlock(tp); if (err) free_irq(tp->napi[0].irq_vec, &tp->napi[0]); return err; } static int <API key>(struct tg3 *tp) { const struct tg3_firmware_hdr *fw_hdr; if (request_firmware(&tp->fw, tp->fw_needed, &tp->pdev->dev)) { netdev_err(tp->dev, "Failed to load firmware \"%s\"\n", tp->fw_needed); return -ENOENT; } fw_hdr = (struct tg3_firmware_hdr *)tp->fw->data; /* Firmware blob starts with version numbers, followed by * start address and _full_ length including BSS sections * (which must be longer than the actual data, of course */ tp->fw_len = be32_to_cpu(fw_hdr->len); /* includes bss */ if (tp->fw_len < (tp->fw->size - TG3_FW_HDR_LEN)) { netdev_err(tp->dev, "bogus length %d in \"%s\"\n", tp->fw_len, tp->fw_needed); release_firmware(tp->fw); tp->fw = NULL; return -EINVAL; } /* We no longer need firmware; we have it. */ tp->fw_needed = NULL; return 0; } static u32 tg3_irq_count(struct tg3 *tp) { u32 irq_cnt = max(tp->rxq_cnt, tp->txq_cnt); if (irq_cnt > 1) { /* We want as many rx rings enabled as there are cpus. * In multiqueue MSI-X mode, the first MSI-X vector * only deals with link interrupts, etc, so we add * one to the number of vectors we are requesting. */ irq_cnt = min_t(unsigned, irq_cnt + 1, tp->irq_max); } return irq_cnt; } static bool tg3_enable_msix(struct tg3 *tp) { int i, rc; struct msix_entry msix_ent[TG3_IRQ_MAX_VECS]; tp->txq_cnt = tp->txq_req; tp->rxq_cnt = tp->rxq_req; if (!tp->rxq_cnt) tp->rxq_cnt = <API key>(); if (tp->rxq_cnt > tp->rxq_max) tp->rxq_cnt = tp->rxq_max; /* Disable multiple TX rings by default. Simple round-robin hardware * scheduling of the TX rings can cause starvation of rings with * small packets when other rings have TSO or jumbo packets. */ if (!tp->txq_req) tp->txq_cnt = 1; tp->irq_cnt = tg3_irq_count(tp); for (i = 0; i < tp->irq_max; i++) { msix_ent[i].entry = i; msix_ent[i].vector = 0; } rc = <API key>(tp->pdev, msix_ent, 1, tp->irq_cnt); if (rc < 0) { return false; } else if (rc < tp->irq_cnt) { netdev_notice(tp->dev, "Requested %d MSI-X vectors, received %d\n", tp->irq_cnt, rc); tp->irq_cnt = rc; tp->rxq_cnt = max(rc - 1, 1); if (tp->txq_cnt) tp->txq_cnt = min(tp->rxq_cnt, tp->txq_max); } for (i = 0; i < tp->irq_max; i++) tp->napi[i].irq_vec = msix_ent[i].vector; if (<API key>(tp->dev, tp->rxq_cnt)) { pci_disable_msix(tp->pdev); return false; } if (tp->irq_cnt == 1) return true; tg3_flag_set(tp, ENABLE_RSS); if (tp->txq_cnt > 1) tg3_flag_set(tp, ENABLE_TSS); <API key>(tp->dev, tp->txq_cnt); return true; } static void tg3_ints_init(struct tg3 *tp) { if ((tg3_flag(tp, SUPPORT_MSI) || tg3_flag(tp, SUPPORT_MSIX)) && !tg3_flag(tp, TAGGED_STATUS)) { /* All MSI supporting chips should support tagged * status. Assert that this is the case. */ netdev_warn(tp->dev, "MSI without TAGGED_STATUS? Not using MSI\n"); goto defcfg; } if (tg3_flag(tp, SUPPORT_MSIX) && tg3_enable_msix(tp)) tg3_flag_set(tp, USING_MSIX); else if (tg3_flag(tp, SUPPORT_MSI) && pci_enable_msi(tp->pdev) == 0) tg3_flag_set(tp, USING_MSI); if (tg3_flag(tp, USING_MSI) || tg3_flag(tp, USING_MSIX)) { u32 msi_mode = tr32(MSGINT_MODE); if (tg3_flag(tp, USING_MSIX) && tp->irq_cnt > 1) msi_mode |= <API key>; if (!tg3_flag(tp, 1SHOT_MSI)) msi_mode |= <API key>; tw32(MSGINT_MODE, msi_mode | MSGINT_MODE_ENABLE); } defcfg: if (!tg3_flag(tp, USING_MSIX)) { tp->irq_cnt = 1; tp->napi[0].irq_vec = tp->pdev->irq; } if (tp->irq_cnt == 1) { tp->txq_cnt = 1; tp->rxq_cnt = 1; <API key>(tp->dev, 1); <API key>(tp->dev, 1); } } static void tg3_ints_fini(struct tg3 *tp) { if (tg3_flag(tp, USING_MSIX)) pci_disable_msix(tp->pdev); else if (tg3_flag(tp, USING_MSI)) pci_disable_msi(tp->pdev); tg3_flag_clear(tp, USING_MSI); tg3_flag_clear(tp, USING_MSIX); tg3_flag_clear(tp, ENABLE_RSS); tg3_flag_clear(tp, ENABLE_TSS); } static int tg3_start(struct tg3 *tp, bool reset_phy, bool test_irq, bool init) { struct net_device *dev = tp->dev; int i, err; /* * Setup interrupts first so we know how * many NAPI resources to allocate */ tg3_ints_init(tp); <API key>(tp); /* The placement of this call is tied * to the setup and use of Host TX descriptors. */ err = <API key>(tp); if (err) goto out_ints_fini; tg3_napi_init(tp); tg3_napi_enable(tp); for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; err = tg3_request_irq(tp, i); if (err) { for (i--; i >= 0; i--) { tnapi = &tp->napi[i]; free_irq(tnapi->irq_vec, tnapi); } goto out_napi_fini; } } tg3_full_lock(tp, 0); if (init) <API key>(tp, RESET_KIND_INIT); err = tg3_init_hw(tp, reset_phy); if (err) { tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); tg3_free_rings(tp); } tg3_full_unlock(tp); if (err) goto out_free_irq; if (test_irq && tg3_flag(tp, USING_MSI)) { err = tg3_test_msi(tp); if (err) { tg3_full_lock(tp, 0); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); tg3_free_rings(tp); tg3_full_unlock(tp); goto out_napi_fini; } if (!tg3_flag(tp, 57765_PLUS) && tg3_flag(tp, USING_MSI)) { u32 val = tr32(<API key>); tw32(<API key>, val | <API key>); } } tg3_phy_start(tp); tg3_hwmon_open(tp); tg3_full_lock(tp, 0); tg3_timer_start(tp); tg3_flag_set(tp, INIT_COMPLETE); tg3_enable_ints(tp); if (init) tg3_ptp_init(tp); else tg3_ptp_resume(tp); tg3_full_unlock(tp); <API key>(dev); /* * Reset loopback feature if it was turned on while the device was down * make sure that it's installed properly now. */ if (dev->features & NETIF_F_LOOPBACK) tg3_set_loopback(dev, dev->features); return 0; out_free_irq: for (i = tp->irq_cnt - 1; i >= 0; i struct tg3_napi *tnapi = &tp->napi[i]; free_irq(tnapi->irq_vec, tnapi); } out_napi_fini: tg3_napi_disable(tp); tg3_napi_fini(tp); tg3_free_consistent(tp); out_ints_fini: tg3_ints_fini(tp); return err; } static void tg3_stop(struct tg3 *tp) { int i; <API key>(tp); tg3_netif_stop(tp); tg3_timer_stop(tp); tg3_hwmon_close(tp); tg3_phy_stop(tp); tg3_full_lock(tp, 1); tg3_disable_ints(tp); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); tg3_free_rings(tp); tg3_flag_clear(tp, INIT_COMPLETE); tg3_full_unlock(tp); for (i = tp->irq_cnt - 1; i >= 0; i struct tg3_napi *tnapi = &tp->napi[i]; free_irq(tnapi->irq_vec, tnapi); } tg3_ints_fini(tp); tg3_napi_fini(tp); tg3_free_consistent(tp); } static int tg3_open(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); int err; if (tp->fw_needed) { err = <API key>(tp); if (tg3_asic_rev(tp) == ASIC_REV_57766) { if (err) { netdev_warn(tp->dev, "EEE capability disabled\n"); tp->phy_flags &= ~TG3_PHYFLG_EEE_CAP; } else if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) { netdev_warn(tp->dev, "EEE capability restored\n"); tp->phy_flags |= TG3_PHYFLG_EEE_CAP; } } else if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0) { if (err) return err; } else if (err) { netdev_warn(tp->dev, "TSO capability disabled\n"); tg3_flag_clear(tp, TSO_CAPABLE); } else if (!tg3_flag(tp, TSO_CAPABLE)) { netdev_notice(tp->dev, "TSO capability restored\n"); tg3_flag_set(tp, TSO_CAPABLE); } } tg3_carrier_off(tp); err = tg3_power_up(tp); if (err) return err; tg3_full_lock(tp, 0); tg3_disable_ints(tp); tg3_flag_clear(tp, INIT_COMPLETE); tg3_full_unlock(tp); err = tg3_start(tp, !(tp->phy_flags & <API key>), true, true); if (err) { tg3_frob_aux_power(tp, false); pci_set_power_state(tp->pdev, PCI_D3hot); } if (tg3_flag(tp, PTP_CAPABLE)) { tp->ptp_clock = ptp_clock_register(&tp->ptp_info, &tp->pdev->dev); if (IS_ERR(tp->ptp_clock)) tp->ptp_clock = NULL; } return err; } static int tg3_close(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); tg3_ptp_fini(tp); tg3_stop(tp); /* Clear stats across close / open calls */ memset(&tp->net_stats_prev, 0, sizeof(tp->net_stats_prev)); memset(&tp->estats_prev, 0, sizeof(tp->estats_prev)); if (<API key>(tp->pdev)) { <API key>(tp); tg3_carrier_off(tp); } return 0; } static inline u64 get_stat64(tg3_stat64_t *val) { return ((u64)val->high << 32) | ((u64)val->low); } static u64 tg3_calc_crc_errors(struct tg3 *tp) { struct tg3_hw_stats *hw_stats = tp->hw_stats; if (!(tp->phy_flags & <API key>) && (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701)) { u32 val; if (!tg3_readphy(tp, MII_TG3_TEST1, &val)) { tg3_writephy(tp, MII_TG3_TEST1, val | <API key>); tg3_readphy(tp, <API key>, &val); } else val = 0; tp->phy_crc_errors += val; return tp->phy_crc_errors; } return get_stat64(&hw_stats->rx_fcs_errors); } #define ESTAT_ADD(member) \ estats->member = old_estats->member + \ get_stat64(&hw_stats->member) static void tg3_get_estats(struct tg3 *tp, struct tg3_ethtool_stats *estats) { struct tg3_ethtool_stats *old_estats = &tp->estats_prev; struct tg3_hw_stats *hw_stats = tp->hw_stats; ESTAT_ADD(rx_octets); ESTAT_ADD(rx_fragments); ESTAT_ADD(rx_ucast_packets); ESTAT_ADD(rx_mcast_packets); ESTAT_ADD(rx_bcast_packets); ESTAT_ADD(rx_fcs_errors); ESTAT_ADD(rx_align_errors); ESTAT_ADD(rx_xon_pause_rcvd); ESTAT_ADD(rx_xoff_pause_rcvd); ESTAT_ADD(rx_mac_ctrl_rcvd); ESTAT_ADD(rx_xoff_entered); ESTAT_ADD(<API key>); ESTAT_ADD(rx_jabbers); ESTAT_ADD(<API key>); ESTAT_ADD(rx_in_length_errors); ESTAT_ADD(<API key>); ESTAT_ADD(<API key>); ESTAT_ADD(<API key>); ESTAT_ADD(<API key>); ESTAT_ADD(<API key>); ESTAT_ADD(<API key>); ESTAT_ADD(<API key>); ESTAT_ADD(<API key>); ESTAT_ADD(<API key>); ESTAT_ADD(<API key>); ESTAT_ADD(<API key>); ESTAT_ADD(tx_octets); ESTAT_ADD(tx_collisions); ESTAT_ADD(tx_xon_sent); ESTAT_ADD(tx_xoff_sent); ESTAT_ADD(tx_flow_control); ESTAT_ADD(tx_mac_errors); ESTAT_ADD(<API key>); ESTAT_ADD(tx_mult_collisions); ESTAT_ADD(tx_deferred); ESTAT_ADD(<API key>); ESTAT_ADD(tx_late_collisions); ESTAT_ADD(tx_collide_2times); ESTAT_ADD(tx_collide_3times); ESTAT_ADD(tx_collide_4times); ESTAT_ADD(tx_collide_5times); ESTAT_ADD(tx_collide_6times); ESTAT_ADD(tx_collide_7times); ESTAT_ADD(tx_collide_8times); ESTAT_ADD(tx_collide_9times); ESTAT_ADD(tx_collide_10times); ESTAT_ADD(tx_collide_11times); ESTAT_ADD(tx_collide_12times); ESTAT_ADD(tx_collide_13times); ESTAT_ADD(tx_collide_14times); ESTAT_ADD(tx_collide_15times); ESTAT_ADD(tx_ucast_packets); ESTAT_ADD(tx_mcast_packets); ESTAT_ADD(tx_bcast_packets); ESTAT_ADD(<API key>); ESTAT_ADD(tx_discards); ESTAT_ADD(tx_errors); ESTAT_ADD(dma_writeq_full); ESTAT_ADD(<API key>); ESTAT_ADD(rxbds_empty); ESTAT_ADD(rx_discards); ESTAT_ADD(rx_errors); ESTAT_ADD(rx_threshold_hit); ESTAT_ADD(dma_readq_full); ESTAT_ADD(dma_read_prioq_full); ESTAT_ADD(tx_comp_queue_full); ESTAT_ADD(<API key>); ESTAT_ADD(ring_status_update); ESTAT_ADD(nic_irqs); ESTAT_ADD(nic_avoided_irqs); ESTAT_ADD(<API key>); ESTAT_ADD(mbuf_lwm_thresh_hit); } static void tg3_get_nstats(struct tg3 *tp, struct rtnl_link_stats64 *stats) { struct rtnl_link_stats64 *old_stats = &tp->net_stats_prev; struct tg3_hw_stats *hw_stats = tp->hw_stats; stats->rx_packets = old_stats->rx_packets + get_stat64(&hw_stats->rx_ucast_packets) + get_stat64(&hw_stats->rx_mcast_packets) + get_stat64(&hw_stats->rx_bcast_packets); stats->tx_packets = old_stats->tx_packets + get_stat64(&hw_stats->tx_ucast_packets) + get_stat64(&hw_stats->tx_mcast_packets) + get_stat64(&hw_stats->tx_bcast_packets); stats->rx_bytes = old_stats->rx_bytes + get_stat64(&hw_stats->rx_octets); stats->tx_bytes = old_stats->tx_bytes + get_stat64(&hw_stats->tx_octets); stats->rx_errors = old_stats->rx_errors + get_stat64(&hw_stats->rx_errors); stats->tx_errors = old_stats->tx_errors + get_stat64(&hw_stats->tx_errors) + get_stat64(&hw_stats->tx_mac_errors) + get_stat64(&hw_stats-><API key>) + get_stat64(&hw_stats->tx_discards); stats->multicast = old_stats->multicast + get_stat64(&hw_stats->rx_mcast_packets); stats->collisions = old_stats->collisions + get_stat64(&hw_stats->tx_collisions); stats->rx_length_errors = old_stats->rx_length_errors + get_stat64(&hw_stats-><API key>) + get_stat64(&hw_stats-><API key>); stats->rx_frame_errors = old_stats->rx_frame_errors + get_stat64(&hw_stats->rx_align_errors); stats->tx_aborted_errors = old_stats->tx_aborted_errors + get_stat64(&hw_stats->tx_discards); stats->tx_carrier_errors = old_stats->tx_carrier_errors + get_stat64(&hw_stats-><API key>); stats->rx_crc_errors = old_stats->rx_crc_errors + tg3_calc_crc_errors(tp); stats->rx_missed_errors = old_stats->rx_missed_errors + get_stat64(&hw_stats->rx_discards); stats->rx_dropped = tp->rx_dropped; stats->tx_dropped = tp->tx_dropped; } static int tg3_get_regs_len(struct net_device *dev) { return TG3_REG_BLK_SIZE; } static void tg3_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *_p) { struct tg3 *tp = netdev_priv(dev); regs->version = 0; memset(_p, 0, TG3_REG_BLK_SIZE); if (tp->phy_flags & <API key>) return; tg3_full_lock(tp, 0); <API key>(tp, (u32 *)_p); tg3_full_unlock(tp); } static int tg3_get_eeprom_len(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); return tp->nvram_size; } static int tg3_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data) { struct tg3 *tp = netdev_priv(dev); int ret, cpmu_restore = 0; u8 *pd; u32 i, offset, len, b_offset, b_count, cpmu_val = 0; __be32 val; if (tg3_flag(tp, NO_NVRAM)) return -EINVAL; offset = eeprom->offset; len = eeprom->len; eeprom->len = 0; eeprom->magic = TG3_EEPROM_MAGIC; /* Override clock, link aware and link idle modes */ if (tg3_flag(tp, CPMU_PRESENT)) { cpmu_val = tr32(TG3_CPMU_CTRL); if (cpmu_val & (<API key> | <API key>)) { tw32(TG3_CPMU_CTRL, cpmu_val & ~(<API key> | <API key>)); cpmu_restore = 1; } } tg3_override_clk(tp); if (offset & 3) { /* adjustments to start on required 4 byte boundary */ b_offset = offset & 3; b_count = 4 - b_offset; if (b_count > len) { /* i.e. offset=1 len=2 */ b_count = len; } ret = tg3_nvram_read_be32(tp, offset-b_offset, &val); if (ret) goto eeprom_done; memcpy(data, ((char *)&val) + b_offset, b_count); len -= b_count; offset += b_count; eeprom->len += b_count; } /* read bytes up to the last 4 byte boundary */ pd = &data[eeprom->len]; for (i = 0; i < (len - (len & 3)); i += 4) { ret = tg3_nvram_read_be32(tp, offset + i, &val); if (ret) { if (i) i -= 4; eeprom->len += i; goto eeprom_done; } memcpy(pd + i, &val, 4); if (need_resched()) { if (signal_pending(current)) { eeprom->len += i; ret = -EINTR; goto eeprom_done; } cond_resched(); } } eeprom->len += i; if (len & 3) { /* read last bytes not ending on 4 byte boundary */ pd = &data[eeprom->len]; b_count = len & 3; b_offset = offset + len - b_count; ret = tg3_nvram_read_be32(tp, b_offset, &val); if (ret) goto eeprom_done; memcpy(pd, &val, b_count); eeprom->len += b_count; } ret = 0; eeprom_done: /* Restore clock, link aware and link idle modes */ tg3_restore_clk(tp); if (cpmu_restore) tw32(TG3_CPMU_CTRL, cpmu_val); return ret; } static int tg3_set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data) { struct tg3 *tp = netdev_priv(dev); int ret; u32 offset, len, b_offset, odd_len; u8 *buf; __be32 start, end; if (tg3_flag(tp, NO_NVRAM) || eeprom->magic != TG3_EEPROM_MAGIC) return -EINVAL; offset = eeprom->offset; len = eeprom->len; if ((b_offset = (offset & 3))) { /* adjustments to start on required 4 byte boundary */ ret = tg3_nvram_read_be32(tp, offset-b_offset, &start); if (ret) return ret; len += b_offset; offset &= ~3; if (len < 4) len = 4; } odd_len = 0; if (len & 3) { /* adjustments to end on required 4 byte boundary */ odd_len = 1; len = (len + 3) & ~3; ret = tg3_nvram_read_be32(tp, offset+len-4, &end); if (ret) return ret; } buf = data; if (b_offset || odd_len) { buf = kmalloc(len, GFP_KERNEL); if (!buf) return -ENOMEM; if (b_offset) memcpy(buf, &start, 4); if (odd_len) memcpy(buf+len-4, &end, 4); memcpy(buf + b_offset, data, eeprom->len); } ret = <API key>(tp, offset, len, buf); if (buf != data) kfree(buf); return ret; } static int tg3_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct tg3 *tp = netdev_priv(dev); if (tg3_flag(tp, USE_PHYLIB)) { struct phy_device *phydev; if (!(tp->phy_flags & <API key>)) return -EAGAIN; phydev = tp->mdio_bus->phy_map[tp->phy_addr]; return phy_ethtool_gset(phydev, cmd); } cmd->supported = (SUPPORTED_Autoneg); if (!(tp->phy_flags & <API key>)) cmd->supported |= (<API key> | <API key>); if (!(tp->phy_flags & <API key>)) { cmd->supported |= (<API key> | <API key> | <API key> | <API key> | SUPPORTED_TP); cmd->port = PORT_TP; } else { cmd->supported |= SUPPORTED_FIBRE; cmd->port = PORT_FIBRE; } cmd->advertising = tp->link_config.advertising; if (tg3_flag(tp, PAUSE_AUTONEG)) { if (tp->link_config.flowctrl & FLOW_CTRL_RX) { if (tp->link_config.flowctrl & FLOW_CTRL_TX) { cmd->advertising |= ADVERTISED_Pause; } else { cmd->advertising |= ADVERTISED_Pause | <API key>; } } else if (tp->link_config.flowctrl & FLOW_CTRL_TX) { cmd->advertising |= <API key>; } } if (netif_running(dev) && tp->link_up) { <API key>(cmd, tp->link_config.active_speed); cmd->duplex = tp->link_config.active_duplex; cmd->lp_advertising = tp->link_config.rmt_adv; if (!(tp->phy_flags & <API key>)) { if (tp->phy_flags & <API key>) cmd->eth_tp_mdix = ETH_TP_MDI_X; else cmd->eth_tp_mdix = ETH_TP_MDI; } } else { <API key>(cmd, SPEED_UNKNOWN); cmd->duplex = DUPLEX_UNKNOWN; cmd->eth_tp_mdix = ETH_TP_MDI_INVALID; } cmd->phy_address = tp->phy_addr; cmd->transceiver = XCVR_INTERNAL; cmd->autoneg = tp->link_config.autoneg; cmd->maxtxpkt = 0; cmd->maxrxpkt = 0; return 0; } static int tg3_set_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct tg3 *tp = netdev_priv(dev); u32 speed = ethtool_cmd_speed(cmd); if (tg3_flag(tp, USE_PHYLIB)) { struct phy_device *phydev; if (!(tp->phy_flags & <API key>)) return -EAGAIN; phydev = tp->mdio_bus->phy_map[tp->phy_addr]; return phy_ethtool_sset(phydev, cmd); } if (cmd->autoneg != AUTONEG_ENABLE && cmd->autoneg != AUTONEG_DISABLE) return -EINVAL; if (cmd->autoneg == AUTONEG_DISABLE && cmd->duplex != DUPLEX_FULL && cmd->duplex != DUPLEX_HALF) return -EINVAL; if (cmd->autoneg == AUTONEG_ENABLE) { u32 mask = ADVERTISED_Autoneg | ADVERTISED_Pause | <API key>; if (!(tp->phy_flags & <API key>)) mask |= <API key> | <API key>; if (!(tp->phy_flags & <API key>)) mask |= <API key> | <API key> | <API key> | <API key> | ADVERTISED_TP; else mask |= ADVERTISED_FIBRE; if (cmd->advertising & ~mask) return -EINVAL; mask &= (<API key> | <API key> | <API key> | <API key> | <API key> | <API key>); cmd->advertising &= mask; } else { if (tp->phy_flags & <API key>) { if (speed != SPEED_1000) return -EINVAL; if (cmd->duplex != DUPLEX_FULL) return -EINVAL; } else { if (speed != SPEED_100 && speed != SPEED_10) return -EINVAL; } } tg3_full_lock(tp, 0); tp->link_config.autoneg = cmd->autoneg; if (cmd->autoneg == AUTONEG_ENABLE) { tp->link_config.advertising = (cmd->advertising | ADVERTISED_Autoneg); tp->link_config.speed = SPEED_UNKNOWN; tp->link_config.duplex = DUPLEX_UNKNOWN; } else { tp->link_config.advertising = 0; tp->link_config.speed = speed; tp->link_config.duplex = cmd->duplex; } tp->phy_flags |= <API key>; <API key>(tp); if (netif_running(dev)) tg3_setup_phy(tp, true); tg3_full_unlock(tp); return 0; } static void tg3_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct tg3 *tp = netdev_priv(dev); strlcpy(info->driver, DRV_MODULE_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_MODULE_VERSION, sizeof(info->version)); strlcpy(info->fw_version, tp->fw_ver, sizeof(info->fw_version)); strlcpy(info->bus_info, pci_name(tp->pdev), sizeof(info->bus_info)); } static void tg3_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct tg3 *tp = netdev_priv(dev); if (tg3_flag(tp, WOL_CAP) && device_can_wakeup(&tp->pdev->dev)) wol->supported = WAKE_MAGIC; else wol->supported = 0; wol->wolopts = 0; if (tg3_flag(tp, WOL_ENABLE) && device_can_wakeup(&tp->pdev->dev)) wol->wolopts = WAKE_MAGIC; memset(&wol->sopass, 0, sizeof(wol->sopass)); } static int tg3_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct tg3 *tp = netdev_priv(dev); struct device *dp = &tp->pdev->dev; if (wol->wolopts & ~WAKE_MAGIC) return -EINVAL; if ((wol->wolopts & WAKE_MAGIC) && !(tg3_flag(tp, WOL_CAP) && device_can_wakeup(dp))) return -EINVAL; <API key>(dp, wol->wolopts & WAKE_MAGIC); if (device_may_wakeup(dp)) tg3_flag_set(tp, WOL_ENABLE); else tg3_flag_clear(tp, WOL_ENABLE); return 0; } static u32 tg3_get_msglevel(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); return tp->msg_enable; } static void tg3_set_msglevel(struct net_device *dev, u32 value) { struct tg3 *tp = netdev_priv(dev); tp->msg_enable = value; } static int tg3_nway_reset(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); int r; if (!netif_running(dev)) return -EAGAIN; if (tp->phy_flags & <API key>) return -EINVAL; <API key>(tp); if (tg3_flag(tp, USE_PHYLIB)) { if (!(tp->phy_flags & <API key>)) return -EAGAIN; r = phy_start_aneg(tp->mdio_bus->phy_map[tp->phy_addr]); } else { u32 bmcr; spin_lock_bh(&tp->lock); r = -EINVAL; tg3_readphy(tp, MII_BMCR, &bmcr); if (!tg3_readphy(tp, MII_BMCR, &bmcr) && ((bmcr & BMCR_ANENABLE) || (tp->phy_flags & <API key>))) { tg3_writephy(tp, MII_BMCR, bmcr | BMCR_ANRESTART | BMCR_ANENABLE); r = 0; } spin_unlock_bh(&tp->lock); } return r; } static void tg3_get_ringparam(struct net_device *dev, struct ethtool_ringparam *ering) { struct tg3 *tp = netdev_priv(dev); ering->rx_max_pending = tp->rx_std_ring_mask; if (tg3_flag(tp, JUMBO_RING_ENABLE)) ering-><API key> = tp->rx_jmb_ring_mask; else ering-><API key> = 0; ering->tx_max_pending = TG3_TX_RING_SIZE - 1; ering->rx_pending = tp->rx_pending; if (tg3_flag(tp, JUMBO_RING_ENABLE)) ering->rx_jumbo_pending = tp->rx_jumbo_pending; else ering->rx_jumbo_pending = 0; ering->tx_pending = tp->napi[0].tx_pending; } static int tg3_set_ringparam(struct net_device *dev, struct ethtool_ringparam *ering) { struct tg3 *tp = netdev_priv(dev); int i, irq_sync = 0, err = 0; if ((ering->rx_pending > tp->rx_std_ring_mask) || (ering->rx_jumbo_pending > tp->rx_jmb_ring_mask) || (ering->tx_pending > TG3_TX_RING_SIZE - 1) || (ering->tx_pending <= MAX_SKB_FRAGS) || (tg3_flag(tp, TSO_BUG) && (ering->tx_pending <= (MAX_SKB_FRAGS * 3)))) return -EINVAL; if (netif_running(dev)) { tg3_phy_stop(tp); tg3_netif_stop(tp); irq_sync = 1; } tg3_full_lock(tp, irq_sync); tp->rx_pending = ering->rx_pending; if (tg3_flag(tp, MAX_RXPEND_64) && tp->rx_pending > 63) tp->rx_pending = 63; if (tg3_flag(tp, JUMBO_RING_ENABLE)) tp->rx_jumbo_pending = ering->rx_jumbo_pending; for (i = 0; i < tp->irq_max; i++) tp->napi[i].tx_pending = ering->tx_pending; if (netif_running(dev)) { tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); err = tg3_restart_hw(tp, false); if (!err) tg3_netif_start(tp); } tg3_full_unlock(tp); if (irq_sync && !err) tg3_phy_start(tp); return err; } static void tg3_get_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause) { struct tg3 *tp = netdev_priv(dev); epause->autoneg = !!tg3_flag(tp, PAUSE_AUTONEG); if (tp->link_config.flowctrl & FLOW_CTRL_RX) epause->rx_pause = 1; else epause->rx_pause = 0; if (tp->link_config.flowctrl & FLOW_CTRL_TX) epause->tx_pause = 1; else epause->tx_pause = 0; } static int tg3_set_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause) { struct tg3 *tp = netdev_priv(dev); int err = 0; if (tp->link_config.autoneg == AUTONEG_ENABLE) <API key>(tp); if (tg3_flag(tp, USE_PHYLIB)) { u32 newadv; struct phy_device *phydev; phydev = tp->mdio_bus->phy_map[tp->phy_addr]; if (!(phydev->supported & SUPPORTED_Pause) || (!(phydev->supported & <API key>) && (epause->rx_pause != epause->tx_pause))) return -EINVAL; tp->link_config.flowctrl = 0; if (epause->rx_pause) { tp->link_config.flowctrl |= FLOW_CTRL_RX; if (epause->tx_pause) { tp->link_config.flowctrl |= FLOW_CTRL_TX; newadv = ADVERTISED_Pause; } else newadv = ADVERTISED_Pause | <API key>; } else if (epause->tx_pause) { tp->link_config.flowctrl |= FLOW_CTRL_TX; newadv = <API key>; } else newadv = 0; if (epause->autoneg) tg3_flag_set(tp, PAUSE_AUTONEG); else tg3_flag_clear(tp, PAUSE_AUTONEG); if (tp->phy_flags & <API key>) { u32 oldadv = phydev->advertising & (ADVERTISED_Pause | <API key>); if (oldadv != newadv) { phydev->advertising &= ~(ADVERTISED_Pause | <API key>); phydev->advertising |= newadv; if (phydev->autoneg) { /* * Always renegotiate the link to * inform our link partner of our * flow control settings, even if the * flow control is forced. Let * tg3_adjust_link() do the final * flow control setup. */ return phy_start_aneg(phydev); } } if (!epause->autoneg) <API key>(tp, 0, 0); } else { tp->link_config.advertising &= ~(ADVERTISED_Pause | <API key>); tp->link_config.advertising |= newadv; } } else { int irq_sync = 0; if (netif_running(dev)) { tg3_netif_stop(tp); irq_sync = 1; } tg3_full_lock(tp, irq_sync); if (epause->autoneg) tg3_flag_set(tp, PAUSE_AUTONEG); else tg3_flag_clear(tp, PAUSE_AUTONEG); if (epause->rx_pause) tp->link_config.flowctrl |= FLOW_CTRL_RX; else tp->link_config.flowctrl &= ~FLOW_CTRL_RX; if (epause->tx_pause) tp->link_config.flowctrl |= FLOW_CTRL_TX; else tp->link_config.flowctrl &= ~FLOW_CTRL_TX; if (netif_running(dev)) { tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); err = tg3_restart_hw(tp, false); if (!err) tg3_netif_start(tp); } tg3_full_unlock(tp); } tp->phy_flags |= <API key>; return err; } static int tg3_get_sset_count(struct net_device *dev, int sset) { switch (sset) { case ETH_SS_TEST: return TG3_NUM_TEST; case ETH_SS_STATS: return TG3_NUM_STATS; default: return -EOPNOTSUPP; } } static int tg3_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info, u32 *rules __always_unused) { struct tg3 *tp = netdev_priv(dev); if (!tg3_flag(tp, SUPPORT_MSIX)) return -EOPNOTSUPP; switch (info->cmd) { case ETHTOOL_GRXRINGS: if (netif_running(tp->dev)) info->data = tp->rxq_cnt; else { info->data = num_online_cpus(); if (info->data > TG3_RSS_MAX_NUM_QS) info->data = TG3_RSS_MAX_NUM_QS; } /* The first interrupt vector only * handles link interrupts. */ info->data -= 1; return 0; default: return -EOPNOTSUPP; } } static u32 <API key>(struct net_device *dev) { u32 size = 0; struct tg3 *tp = netdev_priv(dev); if (tg3_flag(tp, SUPPORT_MSIX)) size = <API key>; return size; } static int tg3_get_rxfh(struct net_device *dev, u32 *indir, u8 *key) { struct tg3 *tp = netdev_priv(dev); int i; for (i = 0; i < <API key>; i++) indir[i] = tp->rss_ind_tbl[i]; return 0; } static int tg3_set_rxfh(struct net_device *dev, const u32 *indir, const u8 *key) { struct tg3 *tp = netdev_priv(dev); size_t i; for (i = 0; i < <API key>; i++) tp->rss_ind_tbl[i] = indir[i]; if (!netif_running(dev) || !tg3_flag(tp, ENABLE_RSS)) return 0; tg3_full_lock(tp, 0); <API key>(tp); tg3_full_unlock(tp); return 0; } static void tg3_get_channels(struct net_device *dev, struct ethtool_channels *channel) { struct tg3 *tp = netdev_priv(dev); u32 deflt_qs = <API key>(); channel->max_rx = tp->rxq_max; channel->max_tx = tp->txq_max; if (netif_running(dev)) { channel->rx_count = tp->rxq_cnt; channel->tx_count = tp->txq_cnt; } else { if (tp->rxq_req) channel->rx_count = tp->rxq_req; else channel->rx_count = min(deflt_qs, tp->rxq_max); if (tp->txq_req) channel->tx_count = tp->txq_req; else channel->tx_count = min(deflt_qs, tp->txq_max); } } static int tg3_set_channels(struct net_device *dev, struct ethtool_channels *channel) { struct tg3 *tp = netdev_priv(dev); if (!tg3_flag(tp, SUPPORT_MSIX)) return -EOPNOTSUPP; if (channel->rx_count > tp->rxq_max || channel->tx_count > tp->txq_max) return -EINVAL; tp->rxq_req = channel->rx_count; tp->txq_req = channel->tx_count; if (!netif_running(dev)) return 0; tg3_stop(tp); tg3_carrier_off(tp); tg3_start(tp, true, false, false); return 0; } static void tg3_get_strings(struct net_device *dev, u32 stringset, u8 *buf) { switch (stringset) { case ETH_SS_STATS: memcpy(buf, &ethtool_stats_keys, sizeof(ethtool_stats_keys)); break; case ETH_SS_TEST: memcpy(buf, &ethtool_test_keys, sizeof(ethtool_test_keys)); break; default: WARN_ON(1); /* we need a WARN() */ break; } } static int tg3_set_phys_id(struct net_device *dev, enum <API key> state) { struct tg3 *tp = netdev_priv(dev); if (!netif_running(tp->dev)) return -EAGAIN; switch (state) { case ETHTOOL_ID_ACTIVE: return 1; /* cycle on/off once per second */ case ETHTOOL_ID_ON: tw32(MAC_LED_CTRL, <API key> | <API key> | LED_CTRL_100MBPS_ON | LED_CTRL_10MBPS_ON | <API key> | <API key> | <API key>); break; case ETHTOOL_ID_OFF: tw32(MAC_LED_CTRL, <API key> | <API key>); break; case ETHTOOL_ID_INACTIVE: tw32(MAC_LED_CTRL, tp->led_ctrl); break; } return 0; } static void <API key>(struct net_device *dev, struct ethtool_stats *estats, u64 *tmp_stats) { struct tg3 *tp = netdev_priv(dev); if (tp->hw_stats) tg3_get_estats(tp, (struct tg3_ethtool_stats *)tmp_stats); else memset(tmp_stats, 0, sizeof(struct tg3_ethtool_stats)); } static __be32 *tg3_vpd_readblock(struct tg3 *tp, u32 *vpdlen) { int i; __be32 *buf; u32 offset = 0, len = 0; u32 magic, val; if (tg3_flag(tp, NO_NVRAM) || tg3_nvram_read(tp, 0, &magic)) return NULL; if (magic == TG3_EEPROM_MAGIC) { for (offset = TG3_NVM_DIR_START; offset < TG3_NVM_DIR_END; offset += TG3_NVM_DIRENT_SIZE) { if (tg3_nvram_read(tp, offset, &val)) return NULL; if ((val >> <API key>) == <API key>) break; } if (offset != TG3_NVM_DIR_END) { len = (val & <API key>) * 4; if (tg3_nvram_read(tp, offset + 4, &offset)) return NULL; offset = <API key>(tp, offset); } } if (!offset || !len) { offset = TG3_NVM_VPD_OFF; len = TG3_NVM_VPD_LEN; } buf = kmalloc(len, GFP_KERNEL); if (buf == NULL) return NULL; if (magic == TG3_EEPROM_MAGIC) { for (i = 0; i < len; i += 4) { /* The data is in little-endian format in NVRAM. * Use the big-endian read routines to preserve * the byte order as it exists in NVRAM. */ if (tg3_nvram_read_be32(tp, offset + i, &buf[i/4])) goto error; } } else { u8 *ptr; ssize_t cnt; unsigned int pos = 0; ptr = (u8 *)&buf[0]; for (i = 0; pos < len && i < 3; i++, pos += cnt, ptr += cnt) { cnt = pci_read_vpd(tp->pdev, pos, len - pos, ptr); if (cnt == -ETIMEDOUT || cnt == -EINTR) cnt = 0; else if (cnt < 0) goto error; } if (pos != len) goto error; } *vpdlen = len; return buf; error: kfree(buf); return NULL; } #define NVRAM_TEST_SIZE 0x100 #define <API key> 0x14 #define <API key> 0x18 #define <API key> 0x1c #define <API key> 0x20 #define <API key> 0x24 #define <API key> 0x50 #define <API key> 0x20 #define <API key> 0x1c static int tg3_test_nvram(struct tg3 *tp) { u32 csum, magic, len; __be32 *buf; int i, j, k, err = 0, size; if (tg3_flag(tp, NO_NVRAM)) return 0; if (tg3_nvram_read(tp, 0, &magic) != 0) return -EIO; if (magic == TG3_EEPROM_MAGIC) size = NVRAM_TEST_SIZE; else if ((magic & <API key>) == TG3_EEPROM_MAGIC_FW) { if ((magic & <API key>) == <API key>) { switch (magic & <API key>) { case <API key>: size = <API key>; break; case <API key>: size = <API key>; break; case <API key>: size = <API key>; break; case <API key>: size = <API key>; break; case <API key>: size = <API key>; break; case <API key>: size = <API key>; break; default: return -EIO; } } else return 0; } else if ((magic & <API key>) == TG3_EEPROM_MAGIC_HW) size = <API key>; else return -EIO; buf = kmalloc(size, GFP_KERNEL); if (buf == NULL) return -ENOMEM; err = -EIO; for (i = 0, j = 0; i < size; i += 4, j++) { err = tg3_nvram_read_be32(tp, i, &buf[j]); if (err) break; } if (i < size) goto out; /* Selfboot format */ magic = be32_to_cpu(buf[0]); if ((magic & <API key>) == TG3_EEPROM_MAGIC_FW) { u8 *buf8 = (u8 *) buf, csum8 = 0; if ((magic & <API key>) == <API key>) { /* For rev 2, the csum doesn't include the MBA. */ for (i = 0; i < <API key>; i++) csum8 += buf8[i]; for (i = <API key> + 4; i < size; i++) csum8 += buf8[i]; } else { for (i = 0; i < size; i++) csum8 += buf8[i]; } if (csum8 == 0) { err = 0; goto out; } err = -EIO; goto out; } if ((magic & <API key>) == TG3_EEPROM_MAGIC_HW) { u8 data[<API key>]; u8 parity[<API key>]; u8 *buf8 = (u8 *) buf; /* Separate the parity bits and the data bytes. */ for (i = 0, j = 0, k = 0; i < <API key>; i++) { if ((i == 0) || (i == 8)) { int l; u8 msk; for (l = 0, msk = 0x80; l < 7; l++, msk >>= 1) parity[k++] = buf8[i] & msk; i++; } else if (i == 16) { int l; u8 msk; for (l = 0, msk = 0x20; l < 6; l++, msk >>= 1) parity[k++] = buf8[i] & msk; i++; for (l = 0, msk = 0x80; l < 8; l++, msk >>= 1) parity[k++] = buf8[i] & msk; i++; } data[j++] = buf8[i]; } err = -EIO; for (i = 0; i < <API key>; i++) { u8 hw8 = hweight8(data[i]); if ((hw8 & 0x1) && parity[i]) goto out; else if (!(hw8 & 0x1) && !parity[i]) goto out; } err = 0; goto out; } err = -EIO; /* Bootstrap checksum at offset 0x10 */ csum = calc_crc((unsigned char *) buf, 0x10); if (csum != le32_to_cpu(buf[0x10/4])) goto out; /* Manufacturing block starts at offset 0x74, checksum at 0xfc */ csum = calc_crc((unsigned char *) &buf[0x74/4], 0x88); if (csum != le32_to_cpu(buf[0xfc/4])) goto out; kfree(buf); buf = tg3_vpd_readblock(tp, &len); if (!buf) return -ENOMEM; i = pci_vpd_find_tag((u8 *)buf, 0, len, <API key>); if (i > 0) { j = pci_vpd_lrdt_size(&((u8 *)buf)[i]); if (j < 0) goto out; if (i + <API key> + j > len) goto out; i += <API key>; j = <API key>((u8 *)buf, i, j, <API key>); if (j > 0) { u8 csum8 = 0; j += <API key>; for (i = 0; i <= j; i++) csum8 += ((u8 *)buf)[i]; if (csum8) goto out; } } err = 0; out: kfree(buf); return err; } #define <API key> 2 #define <API key> 6 static int tg3_test_link(struct tg3 *tp) { int i, max; if (!netif_running(tp->dev)) return -ENODEV; if (tp->phy_flags & <API key>) max = <API key>; else max = <API key>; for (i = 0; i < max; i++) { if (tp->link_up) return 0; if (<API key>(1000)) break; } return -EIO; } /* Only test the commonly used registers */ static int tg3_test_registers(struct tg3 *tp) { int i, is_5705, is_5750; u32 offset, read_mask, write_mask, val, save_val, read_val; static struct { u16 offset; u16 flags; #define TG3_FL_5705 0x1 #define TG3_FL_NOT_5705 0x2 #define TG3_FL_NOT_5788 0x4 #define TG3_FL_NOT_5750 0x8 u32 read_mask; u32 write_mask; } reg_tbl[] = { /* MAC Control Registers */ { MAC_MODE, TG3_FL_NOT_5705, 0x00000000, 0x00ef6f8c }, { MAC_MODE, TG3_FL_5705, 0x00000000, 0x01ef6b8c }, { MAC_STATUS, TG3_FL_NOT_5705, 0x03800107, 0x00000000 }, { MAC_STATUS, TG3_FL_5705, 0x03800100, 0x00000000 }, { MAC_ADDR_0_HIGH, 0x0000, 0x00000000, 0x0000ffff }, { MAC_ADDR_0_LOW, 0x0000, 0x00000000, 0xffffffff }, { MAC_RX_MTU_SIZE, 0x0000, 0x00000000, 0x0000ffff }, { MAC_TX_MODE, 0x0000, 0x00000000, 0x00000070 }, { MAC_TX_LENGTHS, 0x0000, 0x00000000, 0x00003fff }, { MAC_RX_MODE, TG3_FL_NOT_5705, 0x00000000, 0x000007fc }, { MAC_RX_MODE, TG3_FL_5705, 0x00000000, 0x000007dc }, { MAC_HASH_REG_0, 0x0000, 0x00000000, 0xffffffff }, { MAC_HASH_REG_1, 0x0000, 0x00000000, 0xffffffff }, { MAC_HASH_REG_2, 0x0000, 0x00000000, 0xffffffff }, { MAC_HASH_REG_3, 0x0000, 0x00000000, 0xffffffff }, /* Receive Data and Receive BD Initiator Control Registers. */ { RCVDBDI_JUMBO_BD+0, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { RCVDBDI_JUMBO_BD+4, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { RCVDBDI_JUMBO_BD+8, TG3_FL_NOT_5705, 0x00000000, 0x00000003 }, { RCVDBDI_JUMBO_BD+0xc, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { RCVDBDI_STD_BD+0, 0x0000, 0x00000000, 0xffffffff }, { RCVDBDI_STD_BD+4, 0x0000, 0x00000000, 0xffffffff }, { RCVDBDI_STD_BD+8, 0x0000, 0x00000000, 0xffff0002 }, { RCVDBDI_STD_BD+0xc, 0x0000, 0x00000000, 0xffffffff }, /* Receive BD Initiator Control Registers. */ { RCVBDI_STD_THRESH, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { RCVBDI_STD_THRESH, TG3_FL_5705, 0x00000000, 0x000003ff }, { RCVBDI_JUMBO_THRESH, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, /* Host Coalescing Control Registers. */ { HOSTCC_MODE, TG3_FL_NOT_5705, 0x00000000, 0x00000004 }, { HOSTCC_MODE, TG3_FL_5705, 0x00000000, 0x000000f6 }, { HOSTCC_RXCOL_TICKS, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_RXCOL_TICKS, TG3_FL_5705, 0x00000000, 0x000003ff }, { HOSTCC_TXCOL_TICKS, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_TXCOL_TICKS, TG3_FL_5705, 0x00000000, 0x000003ff }, { HOSTCC_RXMAX_FRAMES, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_RXMAX_FRAMES, TG3_FL_5705 | TG3_FL_NOT_5788, 0x00000000, 0x000000ff }, { HOSTCC_TXMAX_FRAMES, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_TXMAX_FRAMES, TG3_FL_5705 | TG3_FL_NOT_5788, 0x00000000, 0x000000ff }, { <API key>, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { <API key>, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { <API key>, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { <API key>, TG3_FL_5705 | TG3_FL_NOT_5788, 0x00000000, 0x000000ff }, { <API key>, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { <API key>, TG3_FL_5705 | TG3_FL_NOT_5788, 0x00000000, 0x000000ff }, { <API key>, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { <API key>, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { <API key>+4, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { <API key>, 0x0000, 0x00000000, 0xffffffff }, { <API key>+4, 0x0000, 0x00000000, 0xffffffff }, { <API key>, 0x0000, 0xffffffff, 0x00000000 }, { <API key>, 0x0000, 0xffffffff, 0x00000000 }, /* Buffer Manager Control Registers. */ { BUFMGR_MB_POOL_ADDR, TG3_FL_NOT_5750, 0x00000000, 0x007fff80 }, { BUFMGR_MB_POOL_SIZE, TG3_FL_NOT_5750, 0x00000000, 0x007fffff }, { <API key>, 0x0000, 0x00000000, 0x0000003f }, { <API key>, 0x0000, 0x00000000, 0x000001ff }, { <API key>, 0x0000, 0x00000000, 0x000001ff }, { <API key>, TG3_FL_NOT_5705, 0xffffffff, 0x00000000 }, { <API key>, TG3_FL_NOT_5705, 0xffffffff, 0x00000000 }, /* Mailbox Registers */ { <API key>+4, 0x0000, 0x00000000, 0x000001ff }, { <API key>+4, TG3_FL_NOT_5705, 0x00000000, 0x000001ff }, { <API key>+4, 0x0000, 0x00000000, 0x000007ff }, { <API key>+4, 0x0000, 0x00000000, 0x000001ff }, { 0xffff, 0x0000, 0x00000000, 0x00000000 }, }; is_5705 = is_5750 = 0; if (tg3_flag(tp, 5705_PLUS)) { is_5705 = 1; if (tg3_flag(tp, 5750_PLUS)) is_5750 = 1; } for (i = 0; reg_tbl[i].offset != 0xffff; i++) { if (is_5705 && (reg_tbl[i].flags & TG3_FL_NOT_5705)) continue; if (!is_5705 && (reg_tbl[i].flags & TG3_FL_5705)) continue; if (tg3_flag(tp, IS_5788) && (reg_tbl[i].flags & TG3_FL_NOT_5788)) continue; if (is_5750 && (reg_tbl[i].flags & TG3_FL_NOT_5750)) continue; offset = (u32) reg_tbl[i].offset; read_mask = reg_tbl[i].read_mask; write_mask = reg_tbl[i].write_mask; /* Save the original register content */ save_val = tr32(offset); /* Determine the read-only value. */ read_val = save_val & read_mask; /* Write zero to the register, then make sure the read-only bits * are not changed and the read/write bits are all zeros. */ tw32(offset, 0); val = tr32(offset); /* Test the read-only and read/write bits. */ if (((val & read_mask) != read_val) || (val & write_mask)) goto out; /* Write ones to all the bits defined by RdMask and WrMask, then * make sure the read-only bits are not changed and the * read/write bits are all ones. */ tw32(offset, read_mask | write_mask); val = tr32(offset); /* Test the read-only bits. */ if ((val & read_mask) != read_val) goto out; /* Test the read/write bits. */ if ((val & write_mask) != write_mask) goto out; tw32(offset, save_val); } return 0; out: if (netif_msg_hw(tp)) netdev_err(tp->dev, "Register test failed at offset %x\n", offset); tw32(offset, save_val); return -EIO; } static int tg3_do_mem_test(struct tg3 *tp, u32 offset, u32 len) { static const u32 test_pattern[] = { 0x00000000, 0xffffffff, 0xaa55a55a }; int i; u32 j; for (i = 0; i < ARRAY_SIZE(test_pattern); i++) { for (j = 0; j < len; j += 4) { u32 val; tg3_write_mem(tp, offset + j, test_pattern[i]); tg3_read_mem(tp, offset + j, &val); if (val != test_pattern[i]) return -EIO; } } return 0; } static int tg3_test_memory(struct tg3 *tp) { static struct mem_entry { u32 offset; u32 len; } mem_tbl_570x[] = { { 0x00000000, 0x00b50}, { 0x00002000, 0x1c000}, { 0xffffffff, 0x00000} }, mem_tbl_5705[] = { { 0x00000100, 0x0000c}, { 0x00000200, 0x00008}, { 0x00004000, 0x00800}, { 0x00006000, 0x01000}, { 0x00008000, 0x02000}, { 0x00010000, 0x0e000}, { 0xffffffff, 0x00000} }, mem_tbl_5755[] = { { 0x00000200, 0x00008}, { 0x00004000, 0x00800}, { 0x00006000, 0x00800}, { 0x00008000, 0x02000}, { 0x00010000, 0x0c000}, { 0xffffffff, 0x00000} }, mem_tbl_5906[] = { { 0x00000200, 0x00008}, { 0x00004000, 0x00400}, { 0x00006000, 0x00400}, { 0x00008000, 0x01000}, { 0x00010000, 0x01000}, { 0xffffffff, 0x00000} }, mem_tbl_5717[] = { { 0x00000200, 0x00008}, { 0x00010000, 0x0a000}, { 0x00020000, 0x13c00}, { 0xffffffff, 0x00000} }, mem_tbl_57765[] = { { 0x00000200, 0x00008}, { 0x00004000, 0x00800}, { 0x00006000, 0x09800}, { 0x00010000, 0x0a000}, { 0xffffffff, 0x00000} }; struct mem_entry *mem_tbl; int err = 0; int i; if (tg3_flag(tp, 5717_PLUS)) mem_tbl = mem_tbl_5717; else if (tg3_flag(tp, 57765_CLASS) || tg3_asic_rev(tp) == ASIC_REV_5762) mem_tbl = mem_tbl_57765; else if (tg3_flag(tp, 5755_PLUS)) mem_tbl = mem_tbl_5755; else if (tg3_asic_rev(tp) == ASIC_REV_5906) mem_tbl = mem_tbl_5906; else if (tg3_flag(tp, 5705_PLUS)) mem_tbl = mem_tbl_5705; else mem_tbl = mem_tbl_570x; for (i = 0; mem_tbl[i].offset != 0xffffffff; i++) { err = tg3_do_mem_test(tp, mem_tbl[i].offset, mem_tbl[i].len); if (err) break; } return err; } #define TG3_TSO_MSS 500 #define TG3_TSO_IP_HDR_LEN 20 #define TG3_TSO_TCP_HDR_LEN 20 #define TG3_TSO_TCP_OPT_LEN 12 static const u8 tg3_tso_header[] = { 0x08, 0x00, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x06, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x01, 0x0a, 0x00, 0x00, 0x02, 0x0d, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x80, 0x10, 0x10, 0x00, 0x14, 0x09, 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, }; static int tg3_run_loopback(struct tg3 *tp, u32 pktsz, bool tso_loopback) { u32 rx_start_idx, rx_idx, tx_idx, opaque_key; u32 base_flags = 0, mss = 0, desc_idx, coal_now, data_off, val; u32 budget; struct sk_buff *skb; u8 *tx_data, *rx_data; dma_addr_t map; int num_pkts, tx_len, rx_len, i, err; struct tg3_rx_buffer_desc *desc; struct tg3_napi *tnapi, *rnapi; struct tg3_rx_prodring_set *tpr = &tp->napi[0].prodring; tnapi = &tp->napi[0]; rnapi = &tp->napi[0]; if (tp->irq_cnt > 1) { if (tg3_flag(tp, ENABLE_RSS)) rnapi = &tp->napi[1]; if (tg3_flag(tp, ENABLE_TSS)) tnapi = &tp->napi[1]; } coal_now = tnapi->coal_now | rnapi->coal_now; err = -EIO; tx_len = pktsz; skb = netdev_alloc_skb(tp->dev, tx_len); if (!skb) return -ENOMEM; tx_data = skb_put(skb, tx_len); memcpy(tx_data, tp->dev->dev_addr, ETH_ALEN); memset(tx_data + ETH_ALEN, 0x0, 8); tw32(MAC_RX_MTU_SIZE, tx_len + ETH_FCS_LEN); if (tso_loopback) { struct iphdr *iph = (struct iphdr *)&tx_data[ETH_HLEN]; u32 hdr_len = TG3_TSO_IP_HDR_LEN + TG3_TSO_TCP_HDR_LEN + TG3_TSO_TCP_OPT_LEN; memcpy(tx_data + ETH_ALEN * 2, tg3_tso_header, sizeof(tg3_tso_header)); mss = TG3_TSO_MSS; val = tx_len - ETH_ALEN * 2 - sizeof(tg3_tso_header); num_pkts = DIV_ROUND_UP(val, TG3_TSO_MSS); /* Set the total length field in the IP header */ iph->tot_len = htons((u16)(mss + hdr_len)); base_flags = (<API key> | <API key>); if (tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) { struct tcphdr *th; val = ETH_HLEN + TG3_TSO_IP_HDR_LEN; th = (struct tcphdr *)&tx_data[val]; th->check = 0; } else base_flags |= <API key>; if (tg3_flag(tp, HW_TSO_3)) { mss |= (hdr_len & 0xc) << 12; if (hdr_len & 0x10) base_flags |= 0x00000010; base_flags |= (hdr_len & 0x3e0) << 5; } else if (tg3_flag(tp, HW_TSO_2)) mss |= hdr_len << 9; else if (tg3_flag(tp, HW_TSO_1) || tg3_asic_rev(tp) == ASIC_REV_5705) { mss |= (TG3_TSO_TCP_OPT_LEN << 9); } else { base_flags |= (TG3_TSO_TCP_OPT_LEN << 10); } data_off = ETH_ALEN * 2 + sizeof(tg3_tso_header); } else { num_pkts = 1; data_off = ETH_HLEN; if (tg3_flag(tp, USE_JUMBO_BDFLAG) && tx_len > VLAN_ETH_FRAME_LEN) base_flags |= TXD_FLAG_JMB_PKT; } for (i = data_off; i < tx_len; i++) tx_data[i] = (u8) (i & 0xff); map = pci_map_single(tp->pdev, skb->data, tx_len, PCI_DMA_TODEVICE); if (<API key>(tp->pdev, map)) { dev_kfree_skb(skb); return -EIO; } val = tnapi->tx_prod; tnapi->tx_buffers[val].skb = skb; dma_unmap_addr_set(&tnapi->tx_buffers[val], mapping, map); tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | rnapi->coal_now); udelay(10); rx_start_idx = rnapi->hw_status->idx[0].rx_producer; budget = tg3_tx_avail(tnapi); if (tg3_tx_frag_set(tnapi, &val, &budget, map, tx_len, base_flags | TXD_FLAG_END, mss, 0)) { tnapi->tx_buffers[val].skb = NULL; dev_kfree_skb(skb); return -EIO; } tnapi->tx_prod++; /* Sync BD data before updating mailbox */ wmb(); tw32_tx_mbox(tnapi->prodmbox, tnapi->tx_prod); tr32_mailbox(tnapi->prodmbox); udelay(10); /* 350 usec to allow enough time on some 10/100 Mbps devices. */ for (i = 0; i < 35; i++) { tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | coal_now); udelay(10); tx_idx = tnapi->hw_status->idx[0].tx_consumer; rx_idx = rnapi->hw_status->idx[0].rx_producer; if ((tx_idx == tnapi->tx_prod) && (rx_idx == (rx_start_idx + num_pkts))) break; } tg3_tx_skb_unmap(tnapi, tnapi->tx_prod - 1, -1); dev_kfree_skb(skb); if (tx_idx != tnapi->tx_prod) goto out; if (rx_idx != rx_start_idx + num_pkts) goto out; val = data_off; while (rx_idx != rx_start_idx) { desc = &rnapi->rx_rcb[rx_start_idx++]; desc_idx = desc->opaque & <API key>; opaque_key = desc->opaque & <API key>; if ((desc->err_vlan & RXD_ERR_MASK) != 0 && (desc->err_vlan != <API key>)) goto out; rx_len = ((desc->idx_len & RXD_LEN_MASK) >> RXD_LEN_SHIFT) - ETH_FCS_LEN; if (!tso_loopback) { if (rx_len != tx_len) goto out; if (pktsz <= TG3_RX_STD_DMA_SZ - ETH_FCS_LEN) { if (opaque_key != RXD_OPAQUE_RING_STD) goto out; } else { if (opaque_key != <API key>) goto out; } } else if ((desc->type_flags & <API key>) && (desc->ip_tcp_csum & RXD_TCPCSUM_MASK) >> RXD_TCPCSUM_SHIFT != 0xffff) { goto out; } if (opaque_key == RXD_OPAQUE_RING_STD) { rx_data = tpr->rx_std_buffers[desc_idx].data; map = dma_unmap_addr(&tpr->rx_std_buffers[desc_idx], mapping); } else if (opaque_key == <API key>) { rx_data = tpr->rx_jmb_buffers[desc_idx].data; map = dma_unmap_addr(&tpr->rx_jmb_buffers[desc_idx], mapping); } else goto out; <API key>(tp->pdev, map, rx_len, PCI_DMA_FROMDEVICE); rx_data += TG3_RX_OFFSET(tp); for (i = data_off; i < rx_len; i++, val++) { if (*(rx_data + i) != (u8) (val & 0xff)) goto out; } } err = 0; /* tg3_free_rings will unmap and free the rx_data */ out: return err; } #define <API key> 1 #define <API key> 2 #define <API key> 4 #define TG3_LOOPBACK_FAILED \ (<API key> | \ <API key> | \ <API key>) static int tg3_test_loopback(struct tg3 *tp, u64 *data, bool do_extlpbk) { int err = -EIO; u32 eee_cap; u32 jmb_pkt_sz = 9000; if (tp->dma_limit) jmb_pkt_sz = tp->dma_limit - ETH_HLEN; eee_cap = tp->phy_flags & TG3_PHYFLG_EEE_CAP; tp->phy_flags &= ~TG3_PHYFLG_EEE_CAP; if (!netif_running(tp->dev)) { data[TG3_MAC_LOOPB_TEST] = TG3_LOOPBACK_FAILED; data[TG3_PHY_LOOPB_TEST] = TG3_LOOPBACK_FAILED; if (do_extlpbk) data[TG3_EXT_LOOPB_TEST] = TG3_LOOPBACK_FAILED; goto done; } err = tg3_reset_hw(tp, true); if (err) { data[TG3_MAC_LOOPB_TEST] = TG3_LOOPBACK_FAILED; data[TG3_PHY_LOOPB_TEST] = TG3_LOOPBACK_FAILED; if (do_extlpbk) data[TG3_EXT_LOOPB_TEST] = TG3_LOOPBACK_FAILED; goto done; } if (tg3_flag(tp, ENABLE_RSS)) { int i; /* Reroute all rx packets to the 1st queue */ for (i = MAC_RSS_INDIR_TBL_0; i < MAC_RSS_INDIR_TBL_0 + <API key>; i += 4) tw32(i, 0x0); } /* HW errata - mac loopback fails in some cases on 5780. * Normal traffic and PHY loopback are not affected by * errata. Also, the MAC loopback test is deprecated for * all newer ASIC revisions. */ if (tg3_asic_rev(tp) != ASIC_REV_5780 && !tg3_flag(tp, CPMU_PRESENT)) { tg3_mac_loopback(tp, true); if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) data[TG3_MAC_LOOPB_TEST] |= <API key>; if (tg3_flag(tp, JUMBO_RING_ENABLE) && tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) data[TG3_MAC_LOOPB_TEST] |= <API key>; tg3_mac_loopback(tp, false); } if (!(tp->phy_flags & <API key>) && !tg3_flag(tp, USE_PHYLIB)) { int i; tg3_phy_lpbk_set(tp, 0, false); /* Wait for link */ for (i = 0; i < 100; i++) { if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP) break; mdelay(1); } if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) data[TG3_PHY_LOOPB_TEST] |= <API key>; if (tg3_flag(tp, TSO_CAPABLE) && tg3_run_loopback(tp, ETH_FRAME_LEN, true)) data[TG3_PHY_LOOPB_TEST] |= <API key>; if (tg3_flag(tp, JUMBO_RING_ENABLE) && tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) data[TG3_PHY_LOOPB_TEST] |= <API key>; if (do_extlpbk) { tg3_phy_lpbk_set(tp, 0, true); /* All link indications report up, but the hardware * isn't really ready for about 20 msec. Double it * to be sure. */ mdelay(40); if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) data[TG3_EXT_LOOPB_TEST] |= <API key>; if (tg3_flag(tp, TSO_CAPABLE) && tg3_run_loopback(tp, ETH_FRAME_LEN, true)) data[TG3_EXT_LOOPB_TEST] |= <API key>; if (tg3_flag(tp, JUMBO_RING_ENABLE) && tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) data[TG3_EXT_LOOPB_TEST] |= <API key>; } /* Re-enable gphy autopowerdown. */ if (tp->phy_flags & <API key>) tg3_phy_toggle_apd(tp, true); } err = (data[TG3_MAC_LOOPB_TEST] | data[TG3_PHY_LOOPB_TEST] | data[TG3_EXT_LOOPB_TEST]) ? -EIO : 0; done: tp->phy_flags |= eee_cap; return err; } static void tg3_self_test(struct net_device *dev, struct ethtool_test *etest, u64 *data) { struct tg3 *tp = netdev_priv(dev); bool doextlpbk = etest->flags & <API key>; if (tp->phy_flags & <API key>) { if (tg3_power_up(tp)) { etest->flags |= ETH_TEST_FL_FAILED; memset(data, 1, sizeof(u64) * TG3_NUM_TEST); return; } <API key>(tp, RESET_KIND_INIT); } memset(data, 0, sizeof(u64) * TG3_NUM_TEST); if (tg3_test_nvram(tp) != 0) { etest->flags |= ETH_TEST_FL_FAILED; data[TG3_NVRAM_TEST] = 1; } if (!doextlpbk && tg3_test_link(tp)) { etest->flags |= ETH_TEST_FL_FAILED; data[TG3_LINK_TEST] = 1; } if (etest->flags & ETH_TEST_FL_OFFLINE) { int err, err2 = 0, irq_sync = 0; if (netif_running(dev)) { tg3_phy_stop(tp); tg3_netif_stop(tp); irq_sync = 1; } tg3_full_lock(tp, irq_sync); tg3_halt(tp, RESET_KIND_SUSPEND, 1); err = tg3_nvram_lock(tp); tg3_halt_cpu(tp, RX_CPU_BASE); if (!tg3_flag(tp, 5705_PLUS)) tg3_halt_cpu(tp, TX_CPU_BASE); if (!err) tg3_nvram_unlock(tp); if (tp->phy_flags & <API key>) tg3_phy_reset(tp); if (tg3_test_registers(tp) != 0) { etest->flags |= ETH_TEST_FL_FAILED; data[TG3_REGISTER_TEST] = 1; } if (tg3_test_memory(tp) != 0) { etest->flags |= ETH_TEST_FL_FAILED; data[TG3_MEMORY_TEST] = 1; } if (doextlpbk) etest->flags |= <API key>; if (tg3_test_loopback(tp, data, doextlpbk)) etest->flags |= ETH_TEST_FL_FAILED; tg3_full_unlock(tp); if (tg3_test_interrupt(tp) != 0) { etest->flags |= ETH_TEST_FL_FAILED; data[TG3_INTERRUPT_TEST] = 1; } tg3_full_lock(tp, 0); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); if (netif_running(dev)) { tg3_flag_set(tp, INIT_COMPLETE); err2 = tg3_restart_hw(tp, true); if (!err2) tg3_netif_start(tp); } tg3_full_unlock(tp); if (irq_sync && !err2) tg3_phy_start(tp); } if (tp->phy_flags & <API key>) <API key>(tp); } static int tg3_hwtstamp_set(struct net_device *dev, struct ifreq *ifr) { struct tg3 *tp = netdev_priv(dev); struct hwtstamp_config stmpconf; if (!tg3_flag(tp, PTP_CAPABLE)) return -EOPNOTSUPP; if (copy_from_user(&stmpconf, ifr->ifr_data, sizeof(stmpconf))) return -EFAULT; if (stmpconf.flags) return -EINVAL; if (stmpconf.tx_type != HWTSTAMP_TX_ON && stmpconf.tx_type != HWTSTAMP_TX_OFF) return -ERANGE; switch (stmpconf.rx_filter) { case <API key>: tp->rxptpctl = 0; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; case <API key>: tp->rxptpctl = <API key> | <API key>; break; default: return -ERANGE; } if (netif_running(dev) && tp->rxptpctl) tw32(TG3_RX_PTP_CTL, tp->rxptpctl | <API key>); if (stmpconf.tx_type == HWTSTAMP_TX_ON) tg3_flag_set(tp, TX_TSTAMP_EN); else tg3_flag_clear(tp, TX_TSTAMP_EN); return copy_to_user(ifr->ifr_data, &stmpconf, sizeof(stmpconf)) ? -EFAULT : 0; } static int tg3_hwtstamp_get(struct net_device *dev, struct ifreq *ifr) { struct tg3 *tp = netdev_priv(dev); struct hwtstamp_config stmpconf; if (!tg3_flag(tp, PTP_CAPABLE)) return -EOPNOTSUPP; stmpconf.flags = 0; stmpconf.tx_type = (tg3_flag(tp, TX_TSTAMP_EN) ? HWTSTAMP_TX_ON : HWTSTAMP_TX_OFF); switch (tp->rxptpctl) { case 0: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; case <API key> | <API key>: stmpconf.rx_filter = <API key>; break; default: WARN_ON_ONCE(1); return -ERANGE; } return copy_to_user(ifr->ifr_data, &stmpconf, sizeof(stmpconf)) ? -EFAULT : 0; } static int tg3_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct mii_ioctl_data *data = if_mii(ifr); struct tg3 *tp = netdev_priv(dev); int err; if (tg3_flag(tp, USE_PHYLIB)) { struct phy_device *phydev; if (!(tp->phy_flags & <API key>)) return -EAGAIN; phydev = tp->mdio_bus->phy_map[tp->phy_addr]; return phy_mii_ioctl(phydev, ifr, cmd); } switch (cmd) { case SIOCGMIIPHY: data->phy_id = tp->phy_addr; /* fallthru */ case SIOCGMIIREG: { u32 mii_regval; if (tp->phy_flags & <API key>) break; /* We have no PHY */ if (!netif_running(dev)) return -EAGAIN; spin_lock_bh(&tp->lock); err = __tg3_readphy(tp, data->phy_id & 0x1f, data->reg_num & 0x1f, &mii_regval); spin_unlock_bh(&tp->lock); data->val_out = mii_regval; return err; } case SIOCSMIIREG: if (tp->phy_flags & <API key>) break; /* We have no PHY */ if (!netif_running(dev)) return -EAGAIN; spin_lock_bh(&tp->lock); err = __tg3_writephy(tp, data->phy_id & 0x1f, data->reg_num & 0x1f, data->val_in); spin_unlock_bh(&tp->lock); return err; case SIOCSHWTSTAMP: return tg3_hwtstamp_set(dev, ifr); case SIOCGHWTSTAMP: return tg3_hwtstamp_get(dev, ifr); default: /* do nothing */ break; } return -EOPNOTSUPP; } static int tg3_get_coalesce(struct net_device *dev, struct ethtool_coalesce *ec) { struct tg3 *tp = netdev_priv(dev); memcpy(ec, &tp->coal, sizeof(*ec)); return 0; } static int tg3_set_coalesce(struct net_device *dev, struct ethtool_coalesce *ec) { struct tg3 *tp = netdev_priv(dev); u32 max_rxcoal_tick_int = 0, max_txcoal_tick_int = 0; u32 max_stat_coal_ticks = 0, min_stat_coal_ticks = 0; if (!tg3_flag(tp, 5705_PLUS)) { max_rxcoal_tick_int = MAX_RXCOAL_TICK_INT; max_txcoal_tick_int = MAX_TXCOAL_TICK_INT; max_stat_coal_ticks = MAX_STAT_COAL_TICKS; min_stat_coal_ticks = MIN_STAT_COAL_TICKS; } if ((ec->rx_coalesce_usecs > MAX_RXCOL_TICKS) || (ec->tx_coalesce_usecs > MAX_TXCOL_TICKS) || (ec-><API key> > MAX_RXMAX_FRAMES) || (ec-><API key> > MAX_TXMAX_FRAMES) || (ec-><API key> > max_rxcoal_tick_int) || (ec-><API key> > max_txcoal_tick_int) || (ec-><API key> > MAX_RXCOAL_MAXF_INT) || (ec-><API key> > MAX_TXCOAL_MAXF_INT) || (ec-><API key> > max_stat_coal_ticks) || (ec-><API key> < min_stat_coal_ticks)) return -EINVAL; /* No rx interrupts will be generated if both are zero */ if ((ec->rx_coalesce_usecs == 0) && (ec-><API key> == 0)) return -EINVAL; /* No tx interrupts will be generated if both are zero */ if ((ec->tx_coalesce_usecs == 0) && (ec-><API key> == 0)) return -EINVAL; /* Only copy relevant parameters, ignore all others. */ tp->coal.rx_coalesce_usecs = ec->rx_coalesce_usecs; tp->coal.tx_coalesce_usecs = ec->tx_coalesce_usecs; tp->coal.<API key> = ec-><API key>; tp->coal.<API key> = ec-><API key>; tp->coal.<API key> = ec-><API key>; tp->coal.<API key> = ec-><API key>; tp->coal.<API key> = ec-><API key>; tp->coal.<API key> = ec-><API key>; tp->coal.<API key> = ec-><API key>; if (netif_running(dev)) { tg3_full_lock(tp, 0); __tg3_set_coalesce(tp, &tp->coal); tg3_full_unlock(tp); } return 0; } static int tg3_set_eee(struct net_device *dev, struct ethtool_eee *edata) { struct tg3 *tp = netdev_priv(dev); if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) { netdev_warn(tp->dev, "Board does not support EEE!\n"); return -EOPNOTSUPP; } if (edata->advertised != tp->eee.advertised) { netdev_warn(tp->dev, "Direct manipulation of EEE advertisement is not supported\n"); return -EINVAL; } if (edata->tx_lpi_timer > <API key>) { netdev_warn(tp->dev, "Maximal Tx Lpi timer supported is %#x(u)\n", <API key>); return -EINVAL; } tp->eee = *edata; tp->phy_flags |= <API key>; <API key>(tp); if (netif_running(tp->dev)) { tg3_full_lock(tp, 0); tg3_setup_eee(tp); tg3_phy_reset(tp); tg3_full_unlock(tp); } return 0; } static int tg3_get_eee(struct net_device *dev, struct ethtool_eee *edata) { struct tg3 *tp = netdev_priv(dev); if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) { netdev_warn(tp->dev, "Board does not support EEE!\n"); return -EOPNOTSUPP; } *edata = tp->eee; return 0; } static const struct ethtool_ops tg3_ethtool_ops = { .get_settings = tg3_get_settings, .set_settings = tg3_set_settings, .get_drvinfo = tg3_get_drvinfo, .get_regs_len = tg3_get_regs_len, .get_regs = tg3_get_regs, .get_wol = tg3_get_wol, .set_wol = tg3_set_wol, .get_msglevel = tg3_get_msglevel, .set_msglevel = tg3_set_msglevel, .nway_reset = tg3_nway_reset, .get_link = ethtool_op_get_link, .get_eeprom_len = tg3_get_eeprom_len, .get_eeprom = tg3_get_eeprom, .set_eeprom = tg3_set_eeprom, .get_ringparam = tg3_get_ringparam, .set_ringparam = tg3_set_ringparam, .get_pauseparam = tg3_get_pauseparam, .set_pauseparam = tg3_set_pauseparam, .self_test = tg3_self_test, .get_strings = tg3_get_strings, .set_phys_id = tg3_set_phys_id, .get_ethtool_stats = <API key>, .get_coalesce = tg3_get_coalesce, .set_coalesce = tg3_set_coalesce, .get_sset_count = tg3_get_sset_count, .get_rxnfc = tg3_get_rxnfc, .get_rxfh_indir_size = <API key>, .get_rxfh = tg3_get_rxfh, .set_rxfh = tg3_set_rxfh, .get_channels = tg3_get_channels, .set_channels = tg3_set_channels, .get_ts_info = tg3_get_ts_info, .get_eee = tg3_get_eee, .set_eee = tg3_set_eee, }; static struct rtnl_link_stats64 *tg3_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats) { struct tg3 *tp = netdev_priv(dev); spin_lock_bh(&tp->lock); if (!tp->hw_stats) { spin_unlock_bh(&tp->lock); return &tp->net_stats_prev; } tg3_get_nstats(tp, stats); spin_unlock_bh(&tp->lock); return stats; } static void tg3_set_rx_mode(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); if (!netif_running(dev)) return; tg3_full_lock(tp, 0); __tg3_set_rx_mode(dev); tg3_full_unlock(tp); } static inline void tg3_set_mtu(struct net_device *dev, struct tg3 *tp, int new_mtu) { dev->mtu = new_mtu; if (new_mtu > ETH_DATA_LEN) { if (tg3_flag(tp, 5780_CLASS)) { <API key>(dev); tg3_flag_clear(tp, TSO_CAPABLE); } else { tg3_flag_set(tp, JUMBO_RING_ENABLE); } } else { if (tg3_flag(tp, 5780_CLASS)) { tg3_flag_set(tp, TSO_CAPABLE); <API key>(dev); } tg3_flag_clear(tp, JUMBO_RING_ENABLE); } } static int tg3_change_mtu(struct net_device *dev, int new_mtu) { struct tg3 *tp = netdev_priv(dev); int err; bool reset_phy = false; if (new_mtu < TG3_MIN_MTU || new_mtu > TG3_MAX_MTU(tp)) return -EINVAL; if (!netif_running(dev)) { /* We'll just catch it later when the * device is up'd. */ tg3_set_mtu(dev, tp, new_mtu); return 0; } tg3_phy_stop(tp); tg3_netif_stop(tp); tg3_set_mtu(dev, tp, new_mtu); tg3_full_lock(tp, 1); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); /* Reset PHY, otherwise the read DMA engine will be in a mode that * breaks all requests to 256 bytes. */ if (tg3_asic_rev(tp) == ASIC_REV_57766) reset_phy = true; err = tg3_restart_hw(tp, reset_phy); if (!err) tg3_netif_start(tp); tg3_full_unlock(tp); if (!err) tg3_phy_start(tp); return err; } static const struct net_device_ops tg3_netdev_ops = { .ndo_open = tg3_open, .ndo_stop = tg3_close, .ndo_start_xmit = tg3_start_xmit, .ndo_get_stats64 = tg3_get_stats64, .ndo_validate_addr = eth_validate_addr, .ndo_set_rx_mode = tg3_set_rx_mode, .ndo_set_mac_address = tg3_set_mac_addr, .ndo_do_ioctl = tg3_ioctl, .ndo_tx_timeout = tg3_tx_timeout, .ndo_change_mtu = tg3_change_mtu, .ndo_fix_features = tg3_fix_features, .ndo_set_features = tg3_set_features, #ifdef <API key> .ndo_poll_controller = tg3_poll_controller, #endif }; static void tg3_get_eeprom_size(struct tg3 *tp) { u32 cursize, val, magic; tp->nvram_size = EEPROM_CHIP_SIZE; if (tg3_nvram_read(tp, 0, &magic) != 0) return; if ((magic != TG3_EEPROM_MAGIC) && ((magic & <API key>) != TG3_EEPROM_MAGIC_FW) && ((magic & <API key>) != TG3_EEPROM_MAGIC_HW)) return; /* * Size the chip by reading offsets at increasing powers of two. * When we encounter our validation signature, we know the addressing * has wrapped around, and thus have our chip size. */ cursize = 0x10; while (cursize < tp->nvram_size) { if (tg3_nvram_read(tp, cursize, &val) != 0) return; if (val == magic) break; cursize <<= 1; } tp->nvram_size = cursize; } static void tg3_get_nvram_size(struct tg3 *tp) { u32 val; if (tg3_flag(tp, NO_NVRAM) || tg3_nvram_read(tp, 0, &val) != 0) return; /* Selfboot format */ if (val != TG3_EEPROM_MAGIC) { tg3_get_eeprom_size(tp); return; } if (tg3_nvram_read(tp, 0xf0, &val) == 0) { if (val != 0) { /* This is confusing. We want to operate on the * 16-bit value at offset 0xf2. The tg3_nvram_read() * call will read from NVRAM and byteswap the data * according to the byteswapping settings for all * other register accesses. This ensures the data we * want will always reside in the lower 16-bits. * However, the data in NVRAM is in LE format, which * means the data from the NVRAM read will always be * opposite the endianness of the CPU. The 16-bit * byteswap then brings the data to CPU endianness. */ tp->nvram_size = swab16((u16)(val & 0x0000ffff)) * 1024; return; } } tp->nvram_size = <API key>; } static void tg3_get_nvram_info(struct tg3 *tp) { u32 nvcfg1; nvcfg1 = tr32(NVRAM_CFG1); if (nvcfg1 & <API key>) { tg3_flag_set(tp, FLASH); } else { nvcfg1 &= ~<API key>; tw32(NVRAM_CFG1, nvcfg1); } if (tg3_asic_rev(tp) == ASIC_REV_5750 || tg3_flag(tp, 5780_CLASS)) { switch (nvcfg1 & <API key>) { case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tp->nvram_pagesize = <API key>; tg3_flag_set(tp, NVRAM_BUFFERED); break; case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tp->nvram_pagesize = <API key>; break; case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tp->nvram_pagesize = <API key>; tg3_flag_set(tp, NVRAM_BUFFERED); break; case FLASH_VENDOR_ST: tp->nvram_jedecnum = JEDEC_ST; tp->nvram_pagesize = <API key>; tg3_flag_set(tp, NVRAM_BUFFERED); break; case FLASH_VENDOR_SAIFUN: tp->nvram_jedecnum = JEDEC_SAIFUN; tp->nvram_pagesize = <API key>; break; case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_SST; tp->nvram_pagesize = <API key>; break; } } else { tp->nvram_jedecnum = JEDEC_ATMEL; tp->nvram_pagesize = <API key>; tg3_flag_set(tp, NVRAM_BUFFERED); } } static void <API key>(struct tg3 *tp, u32 nvmcfg1) { switch (nvmcfg1 & <API key>) { case <API key>: tp->nvram_pagesize = 256; break; case <API key>: tp->nvram_pagesize = 512; break; case <API key>: tp->nvram_pagesize = 1024; break; case <API key>: tp->nvram_pagesize = 2048; break; case <API key>: tp->nvram_pagesize = 4096; break; case <API key>: tp->nvram_pagesize = 264; break; case <API key>: tp->nvram_pagesize = 528; break; } } static void <API key>(struct tg3 *tp) { u32 nvcfg1; nvcfg1 = tr32(NVRAM_CFG1); /* NVRAM protection for TPM */ if (nvcfg1 & (1 << 27)) tg3_flag_set(tp, PROTECTED_NVRAM); switch (nvcfg1 & <API key>) { case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); break; case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); break; case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); break; } if (tg3_flag(tp, FLASH)) { <API key>(tp, nvcfg1); } else { /* For eeprom, set pagesize to maximum eeprom size */ tp->nvram_pagesize = <API key>; nvcfg1 &= ~<API key>; tw32(NVRAM_CFG1, nvcfg1); } } static void <API key>(struct tg3 *tp) { u32 nvcfg1, protect = 0; nvcfg1 = tr32(NVRAM_CFG1); /* NVRAM protection for TPM */ if (nvcfg1 & (1 << 27)) { tg3_flag_set(tp, PROTECTED_NVRAM); protect = 1; } nvcfg1 &= <API key>; switch (nvcfg1) { case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tp->nvram_pagesize = 264; if (nvcfg1 == <API key> || nvcfg1 == <API key>) tp->nvram_size = (protect ? 0x3e200 : <API key>); else if (nvcfg1 == <API key>) tp->nvram_size = (protect ? 0x1f200 : <API key>); else tp->nvram_size = (protect ? 0x1f200 : <API key>); break; case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tp->nvram_pagesize = 256; if (nvcfg1 == <API key>) tp->nvram_size = (protect ? TG3_NVRAM_SIZE_64KB : <API key>); else if (nvcfg1 == <API key>) tp->nvram_size = (protect ? TG3_NVRAM_SIZE_64KB : <API key>); else tp->nvram_size = (protect ? <API key> : <API key>); break; } } static void <API key>(struct tg3 *tp) { u32 nvcfg1; nvcfg1 = tr32(NVRAM_CFG1); switch (nvcfg1 & <API key>) { case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tp->nvram_pagesize = <API key>; nvcfg1 &= ~<API key>; tw32(NVRAM_CFG1, nvcfg1); break; case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tp->nvram_pagesize = 264; break; case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tp->nvram_pagesize = 256; break; } } static void <API key>(struct tg3 *tp) { u32 nvcfg1, protect = 0; nvcfg1 = tr32(NVRAM_CFG1); /* NVRAM protection for TPM */ if (nvcfg1 & (1 << 27)) { tg3_flag_set(tp, PROTECTED_NVRAM); protect = 1; } nvcfg1 &= <API key>; switch (nvcfg1) { case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS); tp->nvram_pagesize = 256; break; case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tp->nvram_pagesize = 256; break; } if (protect) { tp->nvram_size = tr32(NVRAM_ADDR_LOCKOUT); } else { switch (nvcfg1) { case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_size = TG3_NVRAM_SIZE_2MB; break; case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_size = TG3_NVRAM_SIZE_1MB; break; case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_size = <API key>; break; case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_size = <API key>; break; } } } static void <API key>(struct tg3 *tp) { tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tp->nvram_pagesize = <API key>; } static void <API key>(struct tg3 *tp) { u32 nvcfg1; nvcfg1 = tr32(NVRAM_CFG1); switch (nvcfg1 & <API key>) { case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tp->nvram_pagesize = <API key>; nvcfg1 &= ~<API key>; tw32(NVRAM_CFG1, nvcfg1); return; case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvcfg1 & <API key>) { case <API key>: case <API key>: case <API key>: tp->nvram_size = <API key>; break; case <API key>: case <API key>: tp->nvram_size = <API key>; break; case <API key>: case <API key>: tp->nvram_size = <API key>; break; } break; case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvcfg1 & <API key>) { case <API key>: tp->nvram_size = <API key>; break; case <API key>: tp->nvram_size = <API key>; break; case <API key>: tp->nvram_size = <API key>; break; } break; default: tg3_flag_set(tp, NO_NVRAM); return; } <API key>(tp, nvcfg1); if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528) tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS); } static void <API key>(struct tg3 *tp) { u32 nvcfg1; nvcfg1 = tr32(NVRAM_CFG1); switch (nvcfg1 & <API key>) { case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tp->nvram_pagesize = <API key>; nvcfg1 &= ~<API key>; tw32(NVRAM_CFG1, nvcfg1); return; case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvcfg1 & <API key>) { case <API key>: /* Detect size with tg3_nvram_get_size() */ break; case <API key>: case <API key>: tp->nvram_size = <API key>; break; default: tp->nvram_size = <API key>; break; } break; case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvcfg1 & <API key>) { case <API key>: case <API key>: /* Detect size with tg3_nvram_get_size() */ break; case <API key>: case <API key>: tp->nvram_size = <API key>; break; default: tp->nvram_size = <API key>; break; } break; default: tg3_flag_set(tp, NO_NVRAM); return; } <API key>(tp, nvcfg1); if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528) tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS); } static void <API key>(struct tg3 *tp) { u32 nvcfg1, nvmpinstrp; nvcfg1 = tr32(NVRAM_CFG1); nvmpinstrp = nvcfg1 & <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5762) { if (!(nvcfg1 & <API key>)) { tg3_flag_set(tp, NO_NVRAM); return; } switch (nvmpinstrp) { case <API key>: nvmpinstrp = <API key>; break; case <API key>: nvmpinstrp = <API key>; break; case <API key>: /* This pinstrap supports multiple sizes, so force it * to read the actual size from location 0xf0. */ nvmpinstrp = <API key>; break; } } switch (nvmpinstrp) { case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); nvcfg1 &= ~<API key>; tw32(NVRAM_CFG1, nvcfg1); if (nvmpinstrp == <API key>) tp->nvram_pagesize = <API key>; else tp->nvram_pagesize = <API key>; return; case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvmpinstrp) { case <API key>: case <API key>: case <API key>: tp->nvram_size = <API key>; break; case <API key>: case <API key>: case <API key>: tp->nvram_size = <API key>; break; case <API key>: case <API key>: tp->nvram_size = TG3_NVRAM_SIZE_1MB; break; default: if (tg3_asic_rev(tp) != ASIC_REV_5762) tp->nvram_size = <API key>; break; } break; case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvmpinstrp) { case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_size = <API key>; break; case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_size = <API key>; break; case <API key>: case <API key>: case <API key>: case <API key>: tp->nvram_size = TG3_NVRAM_SIZE_1MB; break; default: if (tg3_asic_rev(tp) != ASIC_REV_5762) tp->nvram_size = <API key>; break; } break; default: tg3_flag_set(tp, NO_NVRAM); return; } <API key>(tp, nvcfg1); if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528) tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS); if (tg3_asic_rev(tp) == ASIC_REV_5762) { u32 val; if (tg3_nvram_read(tp, 0, &val)) return; if (val != TG3_EEPROM_MAGIC && (val & <API key>) != TG3_EEPROM_MAGIC_FW) tg3_flag_set(tp, NO_NVRAM); } } /* Chips other than 5700/5701 use the NVRAM for fetching info. */ static void tg3_nvram_init(struct tg3 *tp) { if (tg3_flag(tp, IS_SSB_CORE)) { /* No NVRAM and EEPROM on the SSB Broadcom GigE core. */ tg3_flag_clear(tp, NVRAM); tg3_flag_clear(tp, NVRAM_BUFFERED); tg3_flag_set(tp, NO_NVRAM); return; } tw32_f(GRC_EEPROM_ADDR, (<API key> | (<API key> << <API key>))); msleep(1); /* Enable seeprom accesses. */ tw32_f(GRC_LOCAL_CTRL, tr32(GRC_LOCAL_CTRL) | <API key>); udelay(100); if (tg3_asic_rev(tp) != ASIC_REV_5700 && tg3_asic_rev(tp) != ASIC_REV_5701) { tg3_flag_set(tp, NVRAM); if (tg3_nvram_lock(tp)) { netdev_warn(tp->dev, "Cannot get nvram lock, %s failed\n", __func__); return; } <API key>(tp); tp->nvram_size = 0; if (tg3_asic_rev(tp) == ASIC_REV_5752) <API key>(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5755) <API key>(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5787 || tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5785) <API key>(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5761) <API key>(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5906) <API key>(tp); else if (tg3_asic_rev(tp) == ASIC_REV_57780 || tg3_flag(tp, 57765_CLASS)) <API key>(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719) <API key>(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) <API key>(tp); else tg3_get_nvram_info(tp); if (tp->nvram_size == 0) tg3_get_nvram_size(tp); <API key>(tp); tg3_nvram_unlock(tp); } else { tg3_flag_clear(tp, NVRAM); tg3_flag_clear(tp, NVRAM_BUFFERED); tg3_get_eeprom_size(tp); } } struct subsys_tbl_ent { u16 subsys_vendor, subsys_devid; u32 phy_id; }; static struct subsys_tbl_ent subsys_id_to_phy_id[] = { /* Broadcom boards. */ { <API key>, <API key>, TG3_PHY_ID_BCM5401 }, { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, { <API key>, <API key>, TG3_PHY_ID_BCM8002 }, { <API key>, <API key>, 0 }, { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, { <API key>, <API key>, 0 }, { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, { <API key>, <API key>, TG3_PHY_ID_BCM5703 }, { <API key>, <API key>, TG3_PHY_ID_BCM5703 }, /* 3com boards. */ { <API key>, <API key>, TG3_PHY_ID_BCM5401 }, { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, { <API key>, <API key>, 0 }, { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, /* DELL boards. */ { <API key>, <API key>, TG3_PHY_ID_BCM5401 }, { <API key>, <API key>, TG3_PHY_ID_BCM5401 }, { <API key>, <API key>, TG3_PHY_ID_BCM5411 }, { <API key>, <API key>, TG3_PHY_ID_BCM5411 }, /* Compaq boards. */ { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, { <API key>, <API key>, 0 }, { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, { <API key>, <API key>, TG3_PHY_ID_BCM5701 }, /* IBM boards. */ { <API key>, <API key>, 0 } }; static struct subsys_tbl_ent *<API key>(struct tg3 *tp) { int i; for (i = 0; i < ARRAY_SIZE(subsys_id_to_phy_id); i++) { if ((subsys_id_to_phy_id[i].subsys_vendor == tp->pdev->subsystem_vendor) && (subsys_id_to_phy_id[i].subsys_devid == tp->pdev->subsystem_device)) return &subsys_id_to_phy_id[i]; } return NULL; } static void <API key>(struct tg3 *tp) { u32 val; tp->phy_id = TG3_PHY_ID_INVALID; tp->led_ctrl = LED_CTRL_MODE_PHY_1; /* Assume an onboard device and WOL capable by default. */ tg3_flag_set(tp, EEPROM_WRITE_PROT); tg3_flag_set(tp, WOL_CAP); if (tg3_asic_rev(tp) == ASIC_REV_5906) { if (!(tr32(<API key>) & PCIE_TRANS_CFG_LOM)) { tg3_flag_clear(tp, EEPROM_WRITE_PROT); tg3_flag_set(tp, IS_NIC); } val = tr32(VCPU_CFGSHDW); if (val & <API key>) tg3_flag_set(tp, ASPM_WORKAROUND); if ((val & <API key>) && (val & <API key>)) { tg3_flag_set(tp, WOL_ENABLE); <API key>(&tp->pdev->dev, true); } goto done; } tg3_read_mem(tp, NIC_SRAM_DATA_SIG, &val); if (val == <API key>) { u32 nic_cfg, led_cfg; u32 cfg2 = 0, cfg4 = 0, cfg5 = 0; u32 nic_phy_id, ver, eeprom_phy_id; int eeprom_phy_serdes = 0; tg3_read_mem(tp, NIC_SRAM_DATA_CFG, &nic_cfg); tp->nic_sram_data_cfg = nic_cfg; tg3_read_mem(tp, NIC_SRAM_DATA_VER, &ver); ver >>= <API key>; if (tg3_asic_rev(tp) != ASIC_REV_5700 && tg3_asic_rev(tp) != ASIC_REV_5701 && tg3_asic_rev(tp) != ASIC_REV_5703 && (ver > 0) && (ver < 0x100)) tg3_read_mem(tp, NIC_SRAM_DATA_CFG_2, &cfg2); if (tg3_asic_rev(tp) == ASIC_REV_5785) tg3_read_mem(tp, NIC_SRAM_DATA_CFG_4, &cfg4); if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) tg3_read_mem(tp, NIC_SRAM_DATA_CFG_5, &cfg5); if ((nic_cfg & <API key>) == <API key>) eeprom_phy_serdes = 1; tg3_read_mem(tp, <API key>, &nic_phy_id); if (nic_phy_id != 0) { u32 id1 = nic_phy_id & <API key>; u32 id2 = nic_phy_id & <API key>; eeprom_phy_id = (id1 >> 16) << 10; eeprom_phy_id |= (id2 & 0xfc00) << 16; eeprom_phy_id |= (id2 & 0x03ff) << 0; } else eeprom_phy_id = 0; tp->phy_id = eeprom_phy_id; if (eeprom_phy_serdes) { if (!tg3_flag(tp, 5705_PLUS)) tp->phy_flags |= <API key>; else tp->phy_flags |= <API key>; } if (tg3_flag(tp, 5750_PLUS)) led_cfg = cfg2 & (<API key> | <API key>); else led_cfg = nic_cfg & <API key>; switch (led_cfg) { default: case <API key>: tp->led_ctrl = LED_CTRL_MODE_PHY_1; break; case <API key>: tp->led_ctrl = LED_CTRL_MODE_PHY_2; break; case <API key>: tp->led_ctrl = LED_CTRL_MODE_MAC; /* Default to PHY_1_MODE if 0 (MAC_MODE) is * read on some older 5700/5701 bootcode. */ if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) tp->led_ctrl = LED_CTRL_MODE_PHY_1; break; case <API key>: tp->led_ctrl = <API key>; if (tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0 && tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A1) tp->led_ctrl |= (LED_CTRL_MODE_PHY_1 | LED_CTRL_MODE_PHY_2); if (tg3_flag(tp, 5717_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5762) tp->led_ctrl |= <API key> | <API key>; break; case SHASTA_EXT_LED_MAC: tp->led_ctrl = <API key>; break; case <API key>: tp->led_ctrl = LED_CTRL_MODE_COMBO; if (tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0) tp->led_ctrl |= (LED_CTRL_MODE_PHY_1 | LED_CTRL_MODE_PHY_2); break; } if ((tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) && tp->pdev->subsystem_vendor == PCI_VENDOR_ID_DELL) tp->led_ctrl = LED_CTRL_MODE_PHY_2; if (tg3_chip_rev(tp) == CHIPREV_5784_AX) tp->led_ctrl = LED_CTRL_MODE_PHY_1; if (nic_cfg & <API key>) { tg3_flag_set(tp, EEPROM_WRITE_PROT); if ((tp->pdev->subsystem_vendor == PCI_VENDOR_ID_ARIMA) && (tp->pdev->subsystem_device == 0x205a || tp->pdev->subsystem_device == 0x2063)) tg3_flag_clear(tp, EEPROM_WRITE_PROT); } else { tg3_flag_clear(tp, EEPROM_WRITE_PROT); tg3_flag_set(tp, IS_NIC); } if (nic_cfg & <API key>) { tg3_flag_set(tp, ENABLE_ASF); if (tg3_flag(tp, 5750_PLUS)) tg3_flag_set(tp, ASF_NEW_HANDSHAKE); } if ((nic_cfg & <API key>) && tg3_flag(tp, 5750_PLUS)) tg3_flag_set(tp, ENABLE_APE); if (tp->phy_flags & <API key> && !(nic_cfg & <API key>)) tg3_flag_clear(tp, WOL_CAP); if (tg3_flag(tp, WOL_CAP) && (nic_cfg & <API key>)) { tg3_flag_set(tp, WOL_ENABLE); <API key>(&tp->pdev->dev, true); } if (cfg2 & (1 << 17)) tp->phy_flags |= <API key>; /* serdes signal pre-emphasis in register 0x590 set by */ /* bootcode if bit 18 is set */ if (cfg2 & (1 << 18)) tp->phy_flags |= <API key>; if ((tg3_flag(tp, 57765_PLUS) || (tg3_asic_rev(tp) == ASIC_REV_5784 && tg3_chip_rev(tp) != CHIPREV_5784_AX)) && (cfg2 & <API key>)) tp->phy_flags |= <API key>; if (tg3_flag(tp, PCI_EXPRESS)) { u32 cfg3; tg3_read_mem(tp, NIC_SRAM_DATA_CFG_3, &cfg3); if (tg3_asic_rev(tp) != ASIC_REV_5785 && !tg3_flag(tp, 57765_PLUS) && (cfg3 & <API key>)) tg3_flag_set(tp, ASPM_WORKAROUND); if (cfg3 & <API key>) tp->phy_flags |= <API key>; if (cfg3 & <API key>) tp->phy_flags |= <API key>; } if (cfg4 & <API key>) tg3_flag_set(tp, <API key>); if (cfg4 & <API key>) tg3_flag_set(tp, <API key>); if (cfg4 & <API key>) tg3_flag_set(tp, <API key>); if (cfg5 & <API key>) tp->phy_flags |= <API key>; } done: if (tg3_flag(tp, WOL_CAP)) <API key>(&tp->pdev->dev, tg3_flag(tp, WOL_ENABLE)); else <API key>(&tp->pdev->dev, false); } static int tg3_ape_otp_read(struct tg3 *tp, u32 offset, u32 *val) { int i, err; u32 val2, off = offset * 8; err = tg3_nvram_lock(tp); if (err) return err; tg3_ape_write32(tp, TG3_APE_OTP_ADDR, off | <API key>); tg3_ape_write32(tp, TG3_APE_OTP_CTRL, <API key> | APE_OTP_CTRL_CMD_RD | APE_OTP_CTRL_START); tg3_ape_read32(tp, TG3_APE_OTP_CTRL); udelay(10); for (i = 0; i < 100; i++) { val2 = tg3_ape_read32(tp, TG3_APE_OTP_STATUS); if (val2 & <API key>) { *val = tg3_ape_read32(tp, TG3_APE_OTP_RD_DATA); break; } udelay(10); } tg3_ape_write32(tp, TG3_APE_OTP_CTRL, 0); tg3_nvram_unlock(tp); if (val2 & <API key>) return 0; return -EBUSY; } static int <API key>(struct tg3 *tp, u32 cmd) { int i; u32 val; tw32(OTP_CTRL, cmd | <API key>); tw32(OTP_CTRL, cmd); /* Wait for up to 1 ms for command to execute. */ for (i = 0; i < 100; i++) { val = tr32(OTP_STATUS); if (val & OTP_STATUS_CMD_DONE) break; udelay(10); } return (val & OTP_STATUS_CMD_DONE) ? 0 : -EBUSY; } /* Read the gphy configuration from the OTP region of the chip. The gphy * configuration is a 32-bit value that straddles the alignment boundary. * We do two 32-bit reads and then shift and merge the results. */ static u32 tg3_read_otp_phycfg(struct tg3 *tp) { u32 bhalf_otp, thalf_otp; tw32(OTP_MODE, <API key>); if (<API key>(tp, <API key>)) return 0; tw32(OTP_ADDRESS, OTP_ADDRESS_MAGIC1); if (<API key>(tp, <API key>)) return 0; thalf_otp = tr32(OTP_READ_DATA); tw32(OTP_ADDRESS, OTP_ADDRESS_MAGIC2); if (<API key>(tp, <API key>)) return 0; bhalf_otp = tr32(OTP_READ_DATA); return ((thalf_otp & 0x0000ffff) << 16) | (bhalf_otp >> 16); } static void <API key>(struct tg3 *tp) { u32 adv = ADVERTISED_Autoneg; if (!(tp->phy_flags & <API key>)) { if (!(tp->phy_flags & <API key>)) adv |= <API key>; adv |= <API key>; } if (!(tp->phy_flags & <API key>)) adv |= <API key> | <API key> | <API key> | <API key> | ADVERTISED_TP; else adv |= ADVERTISED_FIBRE; tp->link_config.advertising = adv; tp->link_config.speed = SPEED_UNKNOWN; tp->link_config.duplex = DUPLEX_UNKNOWN; tp->link_config.autoneg = AUTONEG_ENABLE; tp->link_config.active_speed = SPEED_UNKNOWN; tp->link_config.active_duplex = DUPLEX_UNKNOWN; tp->old_link = -1; } static int tg3_phy_probe(struct tg3 *tp) { u32 hw_phy_id_1, hw_phy_id_2; u32 hw_phy_id, hw_phy_id_masked; int err; /* flow control autonegotiation is default behavior */ tg3_flag_set(tp, PAUSE_AUTONEG); tp->link_config.flowctrl = FLOW_CTRL_TX | FLOW_CTRL_RX; if (tg3_flag(tp, ENABLE_APE)) { switch (tp->pci_fn) { case 0: tp->phy_ape_lock = TG3_APE_LOCK_PHY0; break; case 1: tp->phy_ape_lock = TG3_APE_LOCK_PHY1; break; case 2: tp->phy_ape_lock = TG3_APE_LOCK_PHY2; break; case 3: tp->phy_ape_lock = TG3_APE_LOCK_PHY3; break; } } if (!tg3_flag(tp, ENABLE_ASF) && !(tp->phy_flags & <API key>) && !(tp->phy_flags & <API key>)) tp->phy_flags &= ~(<API key> | <API key>); if (tg3_flag(tp, USE_PHYLIB)) return tg3_phy_init(tp); /* Reading the PHY ID register can conflict with ASF * firmware access to the PHY hardware. */ err = 0; if (tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE)) { hw_phy_id = hw_phy_id_masked = TG3_PHY_ID_INVALID; } else { /* Now read the physical PHY_ID from the chip and verify * that it is sane. If it doesn't look good, we fall back * to either the hard-coded table based PHY_ID and failing * that the value found in the eeprom area. */ err |= tg3_readphy(tp, MII_PHYSID1, &hw_phy_id_1); err |= tg3_readphy(tp, MII_PHYSID2, &hw_phy_id_2); hw_phy_id = (hw_phy_id_1 & 0xffff) << 10; hw_phy_id |= (hw_phy_id_2 & 0xfc00) << 16; hw_phy_id |= (hw_phy_id_2 & 0x03ff) << 0; hw_phy_id_masked = hw_phy_id & TG3_PHY_ID_MASK; } if (!err && TG3_KNOWN_PHY_ID(hw_phy_id_masked)) { tp->phy_id = hw_phy_id; if (hw_phy_id_masked == TG3_PHY_ID_BCM8002) tp->phy_flags |= <API key>; else tp->phy_flags &= ~<API key>; } else { if (tp->phy_id != TG3_PHY_ID_INVALID) { /* Do nothing, phy ID already set up in * <API key>(). */ } else { struct subsys_tbl_ent *p; /* No eeprom signature? Try the hardcoded * subsys device table. */ p = <API key>(tp); if (p) { tp->phy_id = p->phy_id; } else if (!tg3_flag(tp, IS_SSB_CORE)) { /* For now we saw the IDs 0xbc050cd0, * 0xbc050f80 and 0xbc050c30 on devices * connected to an BCM4785 and there are * probably more. Just assume that the phy is * supported when it is connected to a SSB core * for now. */ return -ENODEV; } if (!tp->phy_id || tp->phy_id == TG3_PHY_ID_BCM8002) tp->phy_flags |= <API key>; } } if (!(tp->phy_flags & <API key>) && (tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_57766 || tg3_asic_rev(tp) == ASIC_REV_5762 || (tg3_asic_rev(tp) == ASIC_REV_5717 && tg3_chip_rev_id(tp) != CHIPREV_ID_5717_A0) || (tg3_asic_rev(tp) == ASIC_REV_57765 && tg3_chip_rev_id(tp) != CHIPREV_ID_57765_A0))) { tp->phy_flags |= TG3_PHYFLG_EEE_CAP; tp->eee.supported = <API key> | <API key>; tp->eee.advertised = <API key> | <API key>; tp->eee.eee_enabled = 1; tp->eee.tx_lpi_enabled = 1; tp->eee.tx_lpi_timer = <API key>; } <API key>(tp); if (!(tp->phy_flags & <API key>) && !(tp->phy_flags & <API key>) && !tg3_flag(tp, ENABLE_APE) && !tg3_flag(tp, ENABLE_ASF)) { u32 bmsr, dummy; tg3_readphy(tp, MII_BMSR, &bmsr); if (!tg3_readphy(tp, MII_BMSR, &bmsr) && (bmsr & BMSR_LSTATUS)) goto skip_phy_reset; err = tg3_phy_reset(tp); if (err) return err; <API key>(tp); if (!<API key>(tp, &dummy)) { tg3_phy_autoneg_cfg(tp, tp->link_config.advertising, tp->link_config.flowctrl); tg3_writephy(tp, MII_BMCR, BMCR_ANENABLE | BMCR_ANRESTART); } } skip_phy_reset: if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) { err = <API key>(tp); if (err) return err; err = <API key>(tp); } return err; } static void tg3_read_vpd(struct tg3 *tp) { u8 *vpd_data; unsigned int block_end, rosize, len; u32 vpdlen; int j, i = 0; vpd_data = (u8 *)tg3_vpd_readblock(tp, &vpdlen); if (!vpd_data) goto out_no_vpd; i = pci_vpd_find_tag(vpd_data, 0, vpdlen, <API key>); if (i < 0) goto out_not_found; rosize = pci_vpd_lrdt_size(&vpd_data[i]); block_end = i + <API key> + rosize; i += <API key>; if (block_end > vpdlen) goto out_not_found; j = <API key>(vpd_data, i, rosize, <API key>); if (j > 0) { len = <API key>(&vpd_data[j]); j += <API key>; if (j + len > block_end || len != 4 || memcmp(&vpd_data[j], "1028", 4)) goto partno; j = <API key>(vpd_data, i, rosize, <API key>); if (j < 0) goto partno; len = <API key>(&vpd_data[j]); j += <API key>; if (j + len > block_end) goto partno; if (len >= sizeof(tp->fw_ver)) len = sizeof(tp->fw_ver) - 1; memset(tp->fw_ver, 0, sizeof(tp->fw_ver)); snprintf(tp->fw_ver, sizeof(tp->fw_ver), "%.*s bc ", len, &vpd_data[j]); } partno: i = <API key>(vpd_data, i, rosize, <API key>); if (i < 0) goto out_not_found; len = <API key>(&vpd_data[i]); i += <API key>; if (len > TG3_BPN_SIZE || (len + i) > vpdlen) goto out_not_found; memcpy(tp->board_part_number, &vpd_data[i], len); out_not_found: kfree(vpd_data); if (tp->board_part_number[0]) return; out_no_vpd: if (tg3_asic_rev(tp) == ASIC_REV_5717) { if (tp->pdev->device == <API key> || tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM5717"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM5718"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57780) { if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57780"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57760"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57790"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57788"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57765) { if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57761"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57765"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57781"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57785"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57791"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57795"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57766) { if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57762"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57766"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57782"); else if (tp->pdev->device == <API key>) strcpy(tp->board_part_number, "BCM57786"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_5906) { strcpy(tp->board_part_number, "BCM95906"); } else { nomatch: strcpy(tp->board_part_number, "none"); } } static int tg3_fw_img_is_valid(struct tg3 *tp, u32 offset) { u32 val; if (tg3_nvram_read(tp, offset, &val) || (val & 0xfc000000) != 0x0c000000 || tg3_nvram_read(tp, offset + 4, &val) || val != 0) return 0; return 1; } static void tg3_read_bc_ver(struct tg3 *tp) { u32 val, offset, start, ver_offset; int i, dst_off; bool newver = false; if (tg3_nvram_read(tp, 0xc, &offset) || tg3_nvram_read(tp, 0x4, &start)) return; offset = <API key>(tp, offset); if (tg3_nvram_read(tp, offset, &val)) return; if ((val & 0xfc000000) == 0x0c000000) { if (tg3_nvram_read(tp, offset + 4, &val)) return; if (val == 0) newver = true; } dst_off = strlen(tp->fw_ver); if (newver) { if (TG3_VER_SIZE - dst_off < 16 || tg3_nvram_read(tp, offset + 8, &ver_offset)) return; offset = offset + ver_offset - start; for (i = 0; i < 16; i += 4) { __be32 v; if (tg3_nvram_read_be32(tp, offset + i, &v)) return; memcpy(tp->fw_ver + dst_off + i, &v, sizeof(v)); } } else { u32 major, minor; if (tg3_nvram_read(tp, TG3_NVM_PTREV_BCVER, &ver_offset)) return; major = (ver_offset & <API key>) >> <API key>; minor = ver_offset & <API key>; snprintf(&tp->fw_ver[dst_off], TG3_VER_SIZE - dst_off, "v%d.%02d", major, minor); } } static void tg3_read_hwsb_ver(struct tg3 *tp) { u32 val, major, minor; /* Use native endian representation */ if (tg3_nvram_read(tp, TG3_NVM_HWSB_CFG1, &val)) return; major = (val & <API key>) >> <API key>; minor = (val & <API key>) >> <API key>; snprintf(&tp->fw_ver[0], 32, "sb v%d.%02d", major, minor); } static void tg3_read_sb_ver(struct tg3 *tp, u32 val) { u32 offset, major, minor, build; strncat(tp->fw_ver, "sb", TG3_VER_SIZE - strlen(tp->fw_ver) - 1); if ((val & <API key>) != <API key>) return; switch (val & <API key>) { case <API key>: offset = <API key>; break; case <API key>: offset = <API key>; break; case <API key>: offset = <API key>; break; case <API key>: offset = <API key>; break; case <API key>: offset = <API key>; break; case <API key>: offset = <API key>; break; default: return; } if (tg3_nvram_read(tp, offset, &val)) return; build = (val & <API key>) >> <API key>; major = (val & <API key>) >> <API key>; minor = val & <API key>; if (minor > 99 || build > 26) return; offset = strlen(tp->fw_ver); snprintf(&tp->fw_ver[offset], TG3_VER_SIZE - offset, " v%d.%02d", major, minor); if (build > 0) { offset = strlen(tp->fw_ver); if (offset < TG3_VER_SIZE - 1) tp->fw_ver[offset] = 'a' + build - 1; } } static void tg3_read_mgmtfw_ver(struct tg3 *tp) { u32 val, offset, start; int i, vlen; for (offset = TG3_NVM_DIR_START; offset < TG3_NVM_DIR_END; offset += TG3_NVM_DIRENT_SIZE) { if (tg3_nvram_read(tp, offset, &val)) return; if ((val >> <API key>) == <API key>) break; } if (offset == TG3_NVM_DIR_END) return; if (!tg3_flag(tp, 5705_PLUS)) start = 0x08000000; else if (tg3_nvram_read(tp, offset - 4, &start)) return; if (tg3_nvram_read(tp, offset + 4, &offset) || !tg3_fw_img_is_valid(tp, offset) || tg3_nvram_read(tp, offset + 8, &val)) return; offset += val - start; vlen = strlen(tp->fw_ver); tp->fw_ver[vlen++] = ','; tp->fw_ver[vlen++] = ' '; for (i = 0; i < 4; i++) { __be32 v; if (tg3_nvram_read_be32(tp, offset, &v)) return; offset += sizeof(v); if (vlen > TG3_VER_SIZE - sizeof(v)) { memcpy(&tp->fw_ver[vlen], &v, TG3_VER_SIZE - vlen); break; } memcpy(&tp->fw_ver[vlen], &v, sizeof(v)); vlen += sizeof(v); } } static void tg3_probe_ncsi(struct tg3 *tp) { u32 apedata; apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG); if (apedata != APE_SEG_SIG_MAGIC) return; apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS); if (!(apedata & APE_FW_STATUS_READY)) return; if (tg3_ape_read32(tp, TG3_APE_FW_FEATURES) & <API key>) tg3_flag_set(tp, APE_HAS_NCSI); } static void tg3_read_dash_ver(struct tg3 *tp) { int vlen; u32 apedata; char *fwtype; apedata = tg3_ape_read32(tp, TG3_APE_FW_VERSION); if (tg3_flag(tp, APE_HAS_NCSI)) fwtype = "NCSI"; else if (tp->pdev->device == <API key>) fwtype = "SMASH"; else fwtype = "DASH"; vlen = strlen(tp->fw_ver); snprintf(&tp->fw_ver[vlen], TG3_VER_SIZE - vlen, " %s v%d.%d.%d.%d", fwtype, (apedata & <API key>) >> <API key>, (apedata & <API key>) >> <API key>, (apedata & <API key>) >> <API key>, (apedata & <API key>)); } static void tg3_read_otp_ver(struct tg3 *tp) { u32 val, val2; if (tg3_asic_rev(tp) != ASIC_REV_5762) return; if (!tg3_ape_otp_read(tp, OTP_ADDRESS_MAGIC0, &val) && !tg3_ape_otp_read(tp, OTP_ADDRESS_MAGIC0 + 4, &val2) && <API key>(val)) { u64 val64 = (u64) val << 32 | val2; u32 ver = 0; int i, vlen; for (i = 0; i < 7; i++) { if ((val64 & 0xff) == 0) break; ver = val64 & 0xff; val64 >>= 8; } vlen = strlen(tp->fw_ver); snprintf(&tp->fw_ver[vlen], TG3_VER_SIZE - vlen, " .%02d", ver); } } static void tg3_read_fw_ver(struct tg3 *tp) { u32 val; bool vpd_vers = false; if (tp->fw_ver[0] != 0) vpd_vers = true; if (tg3_flag(tp, NO_NVRAM)) { strcat(tp->fw_ver, "sb"); tg3_read_otp_ver(tp); return; } if (tg3_nvram_read(tp, 0, &val)) return; if (val == TG3_EEPROM_MAGIC) tg3_read_bc_ver(tp); else if ((val & <API key>) == TG3_EEPROM_MAGIC_FW) tg3_read_sb_ver(tp, val); else if ((val & <API key>) == TG3_EEPROM_MAGIC_HW) tg3_read_hwsb_ver(tp); if (tg3_flag(tp, ENABLE_ASF)) { if (tg3_flag(tp, ENABLE_APE)) { tg3_probe_ncsi(tp); if (!vpd_vers) tg3_read_dash_ver(tp); } else if (!vpd_vers) { tg3_read_mgmtfw_ver(tp); } } tp->fw_ver[TG3_VER_SIZE - 1] = 0; } static inline u32 <API key>(struct tg3 *tp) { if (tg3_flag(tp, LRG_PROD_RING_CAP)) return <API key>; else if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS)) return <API key>; else return <API key>; } static <API key>(<API key>) = { { PCI_DEVICE(PCI_VENDOR_ID_AMD, <API key>) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, <API key>) }, { PCI_DEVICE(PCI_VENDOR_ID_VIA, <API key>) }, { }, }; static struct pci_dev *tg3_find_peer(struct tg3 *tp) { struct pci_dev *peer; unsigned int func, devnr = tp->pdev->devfn & ~7; for (func = 0; func < 8; func++) { peer = pci_get_slot(tp->pdev->bus, devnr | func); if (peer && peer != tp->pdev) break; pci_dev_put(peer); } /* 5704 can be configured in single-port mode, set peer to * tp->pdev in that case. */ if (!peer) { peer = tp->pdev; return peer; } /* * We don't need to keep the refcount elevated; there's no way * to remove one half of this device without removing the other */ pci_dev_put(peer); return peer; } static void tg3_detect_asic_rev(struct tg3 *tp, u32 misc_ctrl_reg) { tp->pci_chip_rev_id = misc_ctrl_reg >> <API key>; if (tg3_asic_rev(tp) == <API key>) { u32 reg; /* All devices that use the alternate * ASIC REV location have a CPMU. */ tg3_flag_set(tp, CPMU_PRESENT); if (tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key>) reg = <API key>; else if (tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key>) reg = <API key>; else reg = <API key>; <API key>(tp->pdev, reg, &tp->pci_chip_rev_id); } /* Wrong chip ID in 5752 A0. This code can be removed later * as A0 is not in production. */ if (tg3_chip_rev_id(tp) == <API key>) tp->pci_chip_rev_id = CHIPREV_ID_5752_A0; if (tg3_chip_rev_id(tp) == CHIPREV_ID_5717_C0) tp->pci_chip_rev_id = CHIPREV_ID_5720_A0; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) tg3_flag_set(tp, 5717_PLUS); if (tg3_asic_rev(tp) == ASIC_REV_57765 || tg3_asic_rev(tp) == ASIC_REV_57766) tg3_flag_set(tp, 57765_CLASS); if (tg3_flag(tp, 57765_CLASS) || tg3_flag(tp, 5717_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5762) tg3_flag_set(tp, 57765_PLUS); /* Intentionally exclude ASIC_REV_5906 */ if (tg3_asic_rev(tp) == ASIC_REV_5755 || tg3_asic_rev(tp) == ASIC_REV_5787 || tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5761 || tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780 || tg3_flag(tp, 57765_PLUS)) tg3_flag_set(tp, 5755_PLUS); if (tg3_asic_rev(tp) == ASIC_REV_5780 || tg3_asic_rev(tp) == ASIC_REV_5714) tg3_flag_set(tp, 5780_CLASS); if (tg3_asic_rev(tp) == ASIC_REV_5750 || tg3_asic_rev(tp) == ASIC_REV_5752 || tg3_asic_rev(tp) == ASIC_REV_5906 || tg3_flag(tp, 5755_PLUS) || tg3_flag(tp, 5780_CLASS)) tg3_flag_set(tp, 5750_PLUS); if (tg3_asic_rev(tp) == ASIC_REV_5705 || tg3_flag(tp, 5750_PLUS)) tg3_flag_set(tp, 5705_PLUS); } static bool <API key>(struct tg3 *tp, const struct pci_device_id *ent) { u32 grc_misc_cfg = tr32(GRC_MISC_CFG) & <API key>; if ((tg3_asic_rev(tp) == ASIC_REV_5703 && (grc_misc_cfg == 0x8000 || grc_misc_cfg == 0x4000)) || (tp->phy_flags & TG3_PHYFLG_IS_FET)) return true; if (ent->driver_data & <API key>) { if (tg3_asic_rev(tp) == ASIC_REV_5705) { if (ent->driver_data & <API key>) return true; } else { return true; } } return false; } static int tg3_get_invariants(struct tg3 *tp, const struct pci_device_id *ent) { u32 misc_ctrl_reg; u32 pci_state_reg, grc_misc_cfg; u32 val; u16 pci_cmd; int err; /* Force memory write invalidate off. If we leave it on, * then on 5700_BX chips we have to enable a workaround. * The workaround is to set the TG3PCI_DMA_RW_CTRL boundary * to match the cacheline size. The Broadcom driver have this * workaround but turns MWI off all the times so never uses * it. This seems to suggest that the workaround is insufficient. */ <API key>(tp->pdev, PCI_COMMAND, &pci_cmd); pci_cmd &= ~<API key>; <API key>(tp->pdev, PCI_COMMAND, pci_cmd); /* Important! -- Make sure register accesses are byteswapped * correctly. Also, for those chips that require it, make * sure that indirect register accesses are enabled before * the first operation. */ <API key>(tp->pdev, <API key>, &misc_ctrl_reg); tp->misc_host_ctrl |= (misc_ctrl_reg & <API key>); <API key>(tp->pdev, <API key>, tp->misc_host_ctrl); tg3_detect_asic_rev(tp, misc_ctrl_reg); /* If we have 5702/03 A1 or A2 on certain ICH chipsets, * we need to disable memory and use config. cycles * only to access all registers. The 5702/03 chips * can mistakenly decode the special cycles from the * ICH chipsets as memory write cycles, causing corruption * of register and memory space. Only certain ICH bridges * will drive special cycles with non-zero data during the * address phase which can fall within the 5703's address * range. This is not an ICH bug as the PCI spec allows * non-zero address during special cycles. However, only * these ICH bridges are known to drive non-zero addresses * during special cycles. * * Since special cycles do not cross PCI bridges, we only * enable this workaround if the 5703 is on the secondary * bus of these ICH bridges. */ if ((tg3_chip_rev_id(tp) == CHIPREV_ID_5703_A1) || (tg3_chip_rev_id(tp) == CHIPREV_ID_5703_A2)) { static struct tg3_dev_id { u32 vendor; u32 device; u32 rev; } ich_chipsets[] = { { PCI_VENDOR_ID_INTEL, <API key>, PCI_ANY_ID }, { PCI_VENDOR_ID_INTEL, <API key>, PCI_ANY_ID }, { PCI_VENDOR_ID_INTEL, <API key>, 0xa }, { PCI_VENDOR_ID_INTEL, <API key>, PCI_ANY_ID }, { }, }; struct tg3_dev_id *pci_id = &ich_chipsets[0]; struct pci_dev *bridge = NULL; while (pci_id->vendor != 0) { bridge = pci_get_device(pci_id->vendor, pci_id->device, bridge); if (!bridge) { pci_id++; continue; } if (pci_id->rev != PCI_ANY_ID) { if (bridge->revision > pci_id->rev) continue; } if (bridge->subordinate && (bridge->subordinate->number == tp->pdev->bus->number)) { tg3_flag_set(tp, ICH_WORKAROUND); pci_dev_put(bridge); break; } } } if (tg3_asic_rev(tp) == ASIC_REV_5701) { static struct tg3_dev_id { u32 vendor; u32 device; } bridge_chipsets[] = { { PCI_VENDOR_ID_INTEL, <API key> }, { PCI_VENDOR_ID_INTEL, <API key> }, { }, }; struct tg3_dev_id *pci_id = &bridge_chipsets[0]; struct pci_dev *bridge = NULL; while (pci_id->vendor != 0) { bridge = pci_get_device(pci_id->vendor, pci_id->device, bridge); if (!bridge) { pci_id++; continue; } if (bridge->subordinate && (bridge->subordinate->number <= tp->pdev->bus->number) && (bridge->subordinate->busn_res.end >= tp->pdev->bus->number)) { tg3_flag_set(tp, 5701_DMA_BUG); pci_dev_put(bridge); break; } } } /* The EPB bridge inside 5714, 5715, and 5780 cannot support * DMA addresses > 40-bit. This bridge may have other additional * 57xx devices behind it in some 4-port NIC designs for example. * Any tg3 device found behind the bridge will also need the 40-bit * DMA workaround. */ if (tg3_flag(tp, 5780_CLASS)) { tg3_flag_set(tp, 40BIT_DMA_BUG); tp->msi_cap = tp->pdev->msi_cap; } else { struct pci_dev *bridge = NULL; do { bridge = pci_get_device(<API key>, <API key>, bridge); if (bridge && bridge->subordinate && (bridge->subordinate->number <= tp->pdev->bus->number) && (bridge->subordinate->busn_res.end >= tp->pdev->bus->number)) { tg3_flag_set(tp, 40BIT_DMA_BUG); pci_dev_put(bridge); break; } } while (bridge); } if (tg3_asic_rev(tp) == ASIC_REV_5704 || tg3_asic_rev(tp) == ASIC_REV_5714) tp->pdev_peer = tg3_find_peer(tp); /* Determine TSO capabilities */ if (tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0) ; /* Do nothing. HW bug. */ else if (tg3_flag(tp, 57765_PLUS)) tg3_flag_set(tp, HW_TSO_3); else if (tg3_flag(tp, 5755_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5906) tg3_flag_set(tp, HW_TSO_2); else if (tg3_flag(tp, 5750_PLUS)) { tg3_flag_set(tp, HW_TSO_1); tg3_flag_set(tp, TSO_BUG); if (tg3_asic_rev(tp) == ASIC_REV_5750 && tg3_chip_rev_id(tp) >= CHIPREV_ID_5750_C2) tg3_flag_clear(tp, TSO_BUG); } else if (tg3_asic_rev(tp) != ASIC_REV_5700 && tg3_asic_rev(tp) != ASIC_REV_5701 && tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) { tg3_flag_set(tp, FW_TSO); tg3_flag_set(tp, TSO_BUG); if (tg3_asic_rev(tp) == ASIC_REV_5705) tp->fw_needed = FIRMWARE_TG3TSO5; else tp->fw_needed = FIRMWARE_TG3TSO; } /* Selectively allow TSO based on operating conditions */ if (tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3) || tg3_flag(tp, FW_TSO)) { /* For firmware TSO, assume ASF is disabled. * We'll disable TSO later if we discover ASF * is enabled in <API key>(). */ tg3_flag_set(tp, TSO_CAPABLE); } else { tg3_flag_clear(tp, TSO_CAPABLE); tg3_flag_clear(tp, TSO_BUG); tp->fw_needed = NULL; } if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0) tp->fw_needed = FIRMWARE_TG3; if (tg3_asic_rev(tp) == ASIC_REV_57766) tp->fw_needed = FIRMWARE_TG357766; tp->irq_max = 1; if (tg3_flag(tp, 5750_PLUS)) { tg3_flag_set(tp, SUPPORT_MSI); if (tg3_chip_rev(tp) == CHIPREV_5750_AX || tg3_chip_rev(tp) == CHIPREV_5750_BX || (tg3_asic_rev(tp) == ASIC_REV_5714 && tg3_chip_rev_id(tp) <= CHIPREV_ID_5714_A2 && tp->pdev_peer == tp->pdev)) tg3_flag_clear(tp, SUPPORT_MSI); if (tg3_flag(tp, 5755_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5906) { tg3_flag_set(tp, 1SHOT_MSI); } if (tg3_flag(tp, 57765_PLUS)) { tg3_flag_set(tp, SUPPORT_MSIX); tp->irq_max = TG3_IRQ_MAX_VECS; } } tp->txq_max = 1; tp->rxq_max = 1; if (tp->irq_max > 1) { tp->rxq_max = TG3_RSS_MAX_NUM_QS; <API key>(tp, TG3_RSS_MAX_NUM_QS); if (tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) tp->txq_max = tp->irq_max - 1; } if (tg3_flag(tp, 5755_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5906) tg3_flag_set(tp, SHORT_DMA_BUG); if (tg3_asic_rev(tp) == ASIC_REV_5719) tp->dma_limit = <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) tg3_flag_set(tp, LRG_PROD_RING_CAP); if (tg3_flag(tp, 57765_PLUS) && tg3_chip_rev_id(tp) != CHIPREV_ID_5719_A0) tg3_flag_set(tp, USE_JUMBO_BDFLAG); if (!tg3_flag(tp, 5705_PLUS) || tg3_flag(tp, 5780_CLASS) || tg3_flag(tp, USE_JUMBO_BDFLAG)) tg3_flag_set(tp, JUMBO_CAPABLE); <API key>(tp->pdev, TG3PCI_PCISTATE, &pci_state_reg); if (pci_is_pcie(tp->pdev)) { u16 lnkctl; tg3_flag_set(tp, PCI_EXPRESS); <API key>(tp->pdev, PCI_EXP_LNKCTL, &lnkctl); if (lnkctl & <API key>) { if (tg3_asic_rev(tp) == ASIC_REV_5906) { tg3_flag_clear(tp, HW_TSO_2); tg3_flag_clear(tp, TSO_CAPABLE); } if (tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5761 || tg3_chip_rev_id(tp) == CHIPREV_ID_57780_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_57780_A1) tg3_flag_set(tp, CLKREQ_BUG); } else if (tg3_chip_rev_id(tp) == CHIPREV_ID_5717_A0) { tg3_flag_set(tp, L1PLLPD_EN); } } else if (tg3_asic_rev(tp) == ASIC_REV_5785) { /* BCM5785 devices are effectively PCIe devices, and should * follow PCIe codepaths, but do not have a PCIe capabilities * section. */ tg3_flag_set(tp, PCI_EXPRESS); } else if (!tg3_flag(tp, 5705_PLUS) || tg3_flag(tp, 5780_CLASS)) { tp->pcix_cap = pci_find_capability(tp->pdev, PCI_CAP_ID_PCIX); if (!tp->pcix_cap) { dev_err(&tp->pdev->dev, "Cannot find PCI-X capability, aborting\n"); return -EIO; } if (!(pci_state_reg & <API key>)) tg3_flag_set(tp, PCIX_MODE); } /* If we have an AMD 762 or VIA K8T800 chipset, write * reordering to the mailbox registers done by the host * controller can cause major troubles. We read back from * every mailbox register write to force the writes to be * posted to the chip in order. */ if (pci_dev_present(<API key>) && !tg3_flag(tp, PCI_EXPRESS)) tg3_flag_set(tp, MBOX_WRITE_REORDER); <API key>(tp->pdev, PCI_CACHE_LINE_SIZE, &tp->pci_cacheline_sz); <API key>(tp->pdev, PCI_LATENCY_TIMER, &tp->pci_lat_timer); if (tg3_asic_rev(tp) == ASIC_REV_5703 && tp->pci_lat_timer < 64) { tp->pci_lat_timer = 64; <API key>(tp->pdev, PCI_LATENCY_TIMER, tp->pci_lat_timer); } /* Important! -- It is critical that the PCI-X hw workaround * situation is decided before the first MMIO register access. */ if (tg3_chip_rev(tp) == CHIPREV_5700_BX) { /* 5700 BX chips need to have their TX producer index * mailboxes written twice to workaround a bug. */ tg3_flag_set(tp, TXD_MBOX_HWBUG); /* If we are in PCI-X mode, enable register write workaround. * * The workaround is to use indirect register accesses * for all chip writes not to mailbox registers. */ if (tg3_flag(tp, PCIX_MODE)) { u32 pm_reg; tg3_flag_set(tp, PCIX_TARGET_HWBUG); /* The chip can have it's power management PCI config * space registers clobbered due to this bug. * So explicitly force the chip into D0 here. */ <API key>(tp->pdev, tp->pdev->pm_cap + PCI_PM_CTRL, &pm_reg); pm_reg &= ~<API key>; pm_reg |= <API key> | 0 ; <API key>(tp->pdev, tp->pdev->pm_cap + PCI_PM_CTRL, pm_reg); /* Also, force SERR#/PERR# in PCI command. */ <API key>(tp->pdev, PCI_COMMAND, &pci_cmd); pci_cmd |= PCI_COMMAND_PARITY | PCI_COMMAND_SERR; <API key>(tp->pdev, PCI_COMMAND, pci_cmd); } } if ((pci_state_reg & <API key>) != 0) tg3_flag_set(tp, PCI_HIGH_SPEED); if ((pci_state_reg & PCISTATE_BUS_32BIT) != 0) tg3_flag_set(tp, PCI_32BIT); /* Chip-specific fixup from Broadcom driver */ if ((tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0) && (!(pci_state_reg & <API key>))) { pci_state_reg |= <API key>; <API key>(tp->pdev, TG3PCI_PCISTATE, pci_state_reg); } /* Default fast path register access methods */ tp->read32 = tg3_read32; tp->write32 = tg3_write32; tp->read32_mbox = tg3_read32; tp->write32_mbox = tg3_write32; tp->write32_tx_mbox = tg3_write32; tp->write32_rx_mbox = tg3_write32; /* Various workaround register access methods */ if (tg3_flag(tp, PCIX_TARGET_HWBUG)) tp->write32 = <API key>; else if (tg3_asic_rev(tp) == ASIC_REV_5701 || (tg3_flag(tp, PCI_EXPRESS) && tg3_chip_rev_id(tp) == CHIPREV_ID_5750_A0)) { /* * Back to back register writes can cause problems on these * chips, the workaround is to read back all reg writes * except those to mailbox regs. * * See <API key>(). */ tp->write32 = <API key>; } if (tg3_flag(tp, TXD_MBOX_HWBUG) || tg3_flag(tp, MBOX_WRITE_REORDER)) { tp->write32_tx_mbox = tg3_write32_tx_mbox; if (tg3_flag(tp, MBOX_WRITE_REORDER)) tp->write32_rx_mbox = <API key>; } if (tg3_flag(tp, ICH_WORKAROUND)) { tp->read32 = <API key>; tp->write32 = <API key>; tp->read32_mbox = <API key>; tp->write32_mbox = <API key>; tp->write32_tx_mbox = <API key>; tp->write32_rx_mbox = <API key>; iounmap(tp->regs); tp->regs = NULL; <API key>(tp->pdev, PCI_COMMAND, &pci_cmd); pci_cmd &= ~PCI_COMMAND_MEMORY; <API key>(tp->pdev, PCI_COMMAND, pci_cmd); } if (tg3_asic_rev(tp) == ASIC_REV_5906) { tp->read32_mbox = <API key>; tp->write32_mbox = <API key>; tp->write32_tx_mbox = <API key>; tp->write32_rx_mbox = <API key>; } if (tp->write32 == <API key> || (tg3_flag(tp, PCIX_MODE) && (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701))) tg3_flag_set(tp, SRAM_USE_CONFIG); /* The memory arbiter has to be enabled in order for SRAM accesses * to succeed. Normally on powerup the tg3 chip firmware will make * sure it is enabled, but other entities such as system netboot * code might disable it. */ val = tr32(MEMARB_MODE); tw32(MEMARB_MODE, val | MEMARB_MODE_ENABLE); tp->pci_fn = PCI_FUNC(tp->pdev->devfn) & 3; if (tg3_asic_rev(tp) == ASIC_REV_5704 || tg3_flag(tp, 5780_CLASS)) { if (tg3_flag(tp, PCIX_MODE)) { <API key>(tp->pdev, tp->pcix_cap + PCI_X_STATUS, &val); tp->pci_fn = val & 0x7; } } else if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) { tg3_read_mem(tp, <API key>, &val); if ((val & <API key>) != <API key>) val = tr32(TG3_CPMU_STATUS); if (tg3_asic_rev(tp) == ASIC_REV_5717) tp->pci_fn = (val & <API key>) ? 1 : 0; else tp->pci_fn = (val & <API key>) >> <API key>; } if (tg3_flag(tp, FLUSH_POSTED_WRITES)) { tp->write32_tx_mbox = <API key>; tp->write32_rx_mbox = <API key>; } /* Get eeprom hw config before calling tg3_set_power_state(). * In particular, the TG3_FLAG_IS_NIC flag must be * determined before calling tg3_set_power_state() so that * we know whether or not to switch out of Vaux power. * When the flag is set, it means that GPIO1 is used for eeprom * write protect and also implies that it is a LOM where GPIOs * are not used to switch power. */ <API key>(tp); if (tg3_flag(tp, FW_TSO) && tg3_flag(tp, ENABLE_ASF)) { tg3_flag_clear(tp, TSO_CAPABLE); tg3_flag_clear(tp, TSO_BUG); tp->fw_needed = NULL; } if (tg3_flag(tp, ENABLE_APE)) { /* Allow reads and writes to the * APE register and memory space. */ pci_state_reg |= <API key> | <API key> | <API key>; <API key>(tp->pdev, TG3PCI_PCISTATE, pci_state_reg); tg3_ape_lock_init(tp); } /* Set up tp->grc_local_ctrl before calling * <API key>(). GPIO1 driven high * will bring 5700's external PHY out of reset. * It is also used as eeprom write protect on LOMs. */ tp->grc_local_ctrl = <API key> | <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_flag(tp, EEPROM_WRITE_PROT)) tp->grc_local_ctrl |= (<API key> | <API key>); /* Unused GPIO3 must be driven as output on 5752 because there * are no pull-up resistors on unused GPIO pins. */ else if (tg3_asic_rev(tp) == ASIC_REV_5752) tp->grc_local_ctrl |= <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5755 || tg3_asic_rev(tp) == ASIC_REV_57780 || tg3_flag(tp, 57765_CLASS)) tp->grc_local_ctrl |= <API key>; if (tp->pdev->device == <API key> || tp->pdev->device == <API key>) { /* Turn off the debug UART. */ tp->grc_local_ctrl |= <API key>; if (tg3_flag(tp, IS_NIC)) /* Keep VMain power. */ tp->grc_local_ctrl |= <API key> | <API key>; } if (tg3_asic_rev(tp) == ASIC_REV_5762) tp->grc_local_ctrl |= tr32(GRC_LOCAL_CTRL) & <API key>; /* Switch out of Vaux if it is a NIC */ <API key>(tp); /* Derive initial jumbo mode from MTU assigned in * ether_setup() via the alloc_etherdev() call */ if (tp->dev->mtu > ETH_DATA_LEN && !tg3_flag(tp, 5780_CLASS)) tg3_flag_set(tp, JUMBO_RING_ENABLE); /* Determine WakeOnLan speed to use. */ if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B2) { tg3_flag_clear(tp, WOL_SPEED_100MB); } else { tg3_flag_set(tp, WOL_SPEED_100MB); } if (tg3_asic_rev(tp) == ASIC_REV_5906) tp->phy_flags |= TG3_PHYFLG_IS_FET; /* A few boards don't want Ethernet@WireSpeed phy feature */ if (tg3_asic_rev(tp) == ASIC_REV_5700 || (tg3_asic_rev(tp) == ASIC_REV_5705 && (tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) && (tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A1)) || (tp->phy_flags & TG3_PHYFLG_IS_FET) || (tp->phy_flags & <API key>)) tp->phy_flags |= <API key>; if (tg3_chip_rev(tp) == CHIPREV_5703_AX || tg3_chip_rev(tp) == CHIPREV_5704_AX) tp->phy_flags |= TG3_PHYFLG_ADC_BUG; if (tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0) tp->phy_flags |= <API key>; if (tg3_flag(tp, 5705_PLUS) && !(tp->phy_flags & TG3_PHYFLG_IS_FET) && tg3_asic_rev(tp) != ASIC_REV_5785 && tg3_asic_rev(tp) != ASIC_REV_57780 && !tg3_flag(tp, 57765_PLUS)) { if (tg3_asic_rev(tp) == ASIC_REV_5755 || tg3_asic_rev(tp) == ASIC_REV_5787 || tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5761) { if (tp->pdev->device != <API key> && tp->pdev->device != <API key>) tp->phy_flags |= <API key>; if (tp->pdev->device == <API key>) tp->phy_flags |= <API key>; } else tp->phy_flags |= TG3_PHYFLG_BER_BUG; } if (tg3_asic_rev(tp) == ASIC_REV_5784 && tg3_chip_rev(tp) != CHIPREV_5784_AX) { tp->phy_otp = tg3_read_otp_phycfg(tp); if (tp->phy_otp == 0) tp->phy_otp = TG3_OTP_DEFAULT; } if (tg3_flag(tp, CPMU_PRESENT)) tp->mi_mode = <API key>; else tp->mi_mode = MAC_MI_MODE_BASE; tp->coalesce_mode = 0; if (tg3_chip_rev(tp) != CHIPREV_5700_AX && tg3_chip_rev(tp) != CHIPREV_5700_BX) tp->coalesce_mode |= HOSTCC_MODE_32BYTE; /* Set these bits to enable statistics workaround. */ if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5762 || tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5720_A0) { tp->coalesce_mode |= HOSTCC_MODE_ATTN; tp->grc_mode |= <API key>; } if (tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780) tg3_flag_set(tp, USE_PHYLIB); err = tg3_mdio_init(tp); if (err) return err; /* Initialize data/descriptor byte/word swapping. */ val = tr32(GRC_MODE); if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) val &= (<API key> | <API key> | <API key> | <API key> | <API key>); else val &= <API key>; tw32(GRC_MODE, val | tp->grc_mode); tg3_switch_clocks(tp); /* Clear this out for sanity. */ tw32(<API key>, 0); /* Clear <API key> to prevent hangs. */ tw32(<API key>, 0); <API key>(tp->pdev, TG3PCI_PCISTATE, &pci_state_reg); if ((pci_state_reg & <API key>) == 0 && !tg3_flag(tp, PCIX_TARGET_HWBUG)) { if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B2 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B5) { void __iomem *sram_base; /* Write some dummy words into the SRAM status block * area, see if it reads back correctly. If the return * value is bad, force enable the PCIX workaround. */ sram_base = tp->regs + NIC_SRAM_WIN_BASE + NIC_SRAM_STATS_BLK; writel(0x00000000, sram_base); writel(0x00000000, sram_base + 4); writel(0xffffffff, sram_base + 4); if (readl(sram_base) != 0x00000000) tg3_flag_set(tp, PCIX_TARGET_HWBUG); } } udelay(50); tg3_nvram_init(tp); /* If the device has an NVRAM, no need to load patch firmware */ if (tg3_asic_rev(tp) == ASIC_REV_57766 && !tg3_flag(tp, NO_NVRAM)) tp->fw_needed = NULL; grc_misc_cfg = tr32(GRC_MISC_CFG); grc_misc_cfg &= <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5705 && (grc_misc_cfg == <API key> || grc_misc_cfg == <API key>)) tg3_flag_set(tp, IS_5788); if (!tg3_flag(tp, IS_5788) && tg3_asic_rev(tp) != ASIC_REV_5700) tg3_flag_set(tp, TAGGED_STATUS); if (tg3_flag(tp, TAGGED_STATUS)) { tp->coalesce_mode |= (<API key> | <API key>); tp->misc_host_ctrl |= <API key>; <API key>(tp->pdev, <API key>, tp->misc_host_ctrl); } /* Preserve the APE MAC_MODE bits */ if (tg3_flag(tp, ENABLE_APE)) tp->mac_mode = MAC_MODE_APE_TX_EN | MAC_MODE_APE_RX_EN; else tp->mac_mode = 0; if (<API key>(tp, ent)) tp->phy_flags |= <API key>; err = tg3_phy_probe(tp); if (err) { dev_err(&tp->pdev->dev, "phy probe failed, err %d\n", err); /* ... but do not return immediately ... */ tg3_mdio_fini(tp); } tg3_read_vpd(tp); tg3_read_fw_ver(tp); if (tp->phy_flags & <API key>) { tp->phy_flags &= ~<API key>; } else { if (tg3_asic_rev(tp) == ASIC_REV_5700) tp->phy_flags |= <API key>; else tp->phy_flags &= ~<API key>; } /* 5700 {AX,BX} chips have a broken status block link * change bit implementation, so we must use the * status register in those cases. */ if (tg3_asic_rev(tp) == ASIC_REV_5700) tg3_flag_set(tp, USE_LINKCHG_REG); else tg3_flag_clear(tp, USE_LINKCHG_REG); /* The led_ctrl is set during tg3_phy_probe, here we might * have to force the link status polling mechanism based * upon subsystem IDs. */ if (tp->pdev->subsystem_vendor == PCI_VENDOR_ID_DELL && tg3_asic_rev(tp) == ASIC_REV_5701 && !(tp->phy_flags & <API key>)) { tp->phy_flags |= <API key>; tg3_flag_set(tp, USE_LINKCHG_REG); } /* For all SERDES we poll the MAC status register. */ if (tp->phy_flags & <API key>) tg3_flag_set(tp, POLL_SERDES); else tg3_flag_clear(tp, POLL_SERDES); if (tg3_flag(tp, ENABLE_APE) && tg3_flag(tp, ENABLE_ASF)) tg3_flag_set(tp, POLL_CPMU_LINK); tp->rx_offset = NET_SKB_PAD + NET_IP_ALIGN; tp->rx_copy_thresh = <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5701 && tg3_flag(tp, PCIX_MODE)) { tp->rx_offset = NET_SKB_PAD; #ifndef <API key> tp->rx_copy_thresh = ~(u16)0; #endif } tp->rx_std_ring_mask = <API key>(tp) - 1; tp->rx_jmb_ring_mask = <API key>(tp) - 1; tp->rx_ret_ring_mask = <API key>(tp) - 1; tp->rx_std_max_post = tp->rx_std_ring_mask + 1; /* Increment the rx prod index on the rx std ring by at most * 8 for these chips to workaround hw errata. */ if (tg3_asic_rev(tp) == ASIC_REV_5750 || tg3_asic_rev(tp) == ASIC_REV_5752 || tg3_asic_rev(tp) == ASIC_REV_5755) tp->rx_std_max_post = 8; if (tg3_flag(tp, ASPM_WORKAROUND)) tp->pwrmgmt_thresh = tr32(<API key>) & <API key>; return err; } #ifdef CONFIG_SPARC static int <API key>(struct tg3 *tp) { struct net_device *dev = tp->dev; struct pci_dev *pdev = tp->pdev; struct device_node *dp = <API key>(pdev); const unsigned char *addr; int len; addr = of_get_property(dp, "local-mac-address", &len); if (addr && len == ETH_ALEN) { memcpy(dev->dev_addr, addr, ETH_ALEN); return 0; } return -ENODEV; } static int <API key>(struct tg3 *tp) { struct net_device *dev = tp->dev; memcpy(dev->dev_addr, idprom->id_ethaddr, ETH_ALEN); return 0; } #endif static int <API key>(struct tg3 *tp) { struct net_device *dev = tp->dev; u32 hi, lo, mac_offset; int addr_ok = 0; int err; #ifdef CONFIG_SPARC if (!<API key>(tp)) return 0; #endif if (tg3_flag(tp, IS_SSB_CORE)) { err = <API key>(tp->pdev, &dev->dev_addr[0]); if (!err && is_valid_ether_addr(&dev->dev_addr[0])) return 0; } mac_offset = 0x7c; if (tg3_asic_rev(tp) == ASIC_REV_5704 || tg3_flag(tp, 5780_CLASS)) { if (tr32(<API key>) & DUAL_MAC_CTRL_ID) mac_offset = 0xcc; if (tg3_nvram_lock(tp)) tw32_f(NVRAM_CMD, NVRAM_CMD_RESET); else tg3_nvram_unlock(tp); } else if (tg3_flag(tp, 5717_PLUS)) { if (tp->pci_fn & 1) mac_offset = 0xcc; if (tp->pci_fn > 1) mac_offset += 0x18c; } else if (tg3_asic_rev(tp) == ASIC_REV_5906) mac_offset = 0x10; /* First try to get it from MAC address mailbox. */ tg3_read_mem(tp, <API key>, &hi); if ((hi >> 16) == 0x484b) { dev->dev_addr[0] = (hi >> 8) & 0xff; dev->dev_addr[1] = (hi >> 0) & 0xff; tg3_read_mem(tp, <API key>, &lo); dev->dev_addr[2] = (lo >> 24) & 0xff; dev->dev_addr[3] = (lo >> 16) & 0xff; dev->dev_addr[4] = (lo >> 8) & 0xff; dev->dev_addr[5] = (lo >> 0) & 0xff; /* Some old bootcode may report a 0 MAC address in SRAM */ addr_ok = is_valid_ether_addr(&dev->dev_addr[0]); } if (!addr_ok) { /* Next, try NVRAM. */ if (!tg3_flag(tp, NO_NVRAM) && !tg3_nvram_read_be32(tp, mac_offset + 0, &hi) && !tg3_nvram_read_be32(tp, mac_offset + 4, &lo)) { memcpy(&dev->dev_addr[0], ((char *)&hi) + 2, 2); memcpy(&dev->dev_addr[2], (char *)&lo, sizeof(lo)); } /* Finally just fetch it out of the MAC control regs. */ else { hi = tr32(MAC_ADDR_0_HIGH); lo = tr32(MAC_ADDR_0_LOW); dev->dev_addr[5] = lo & 0xff; dev->dev_addr[4] = (lo >> 8) & 0xff; dev->dev_addr[3] = (lo >> 16) & 0xff; dev->dev_addr[2] = (lo >> 24) & 0xff; dev->dev_addr[1] = hi & 0xff; dev->dev_addr[0] = (hi >> 8) & 0xff; } } if (!is_valid_ether_addr(&dev->dev_addr[0])) { #ifdef CONFIG_SPARC if (!<API key>(tp)) return 0; #endif return -EINVAL; } return 0; } #define <API key> 1 #define <API key> 2 static u32 tg3_calc_dma_bndry(struct tg3 *tp, u32 val) { int cacheline_size; u8 byte; int goal; <API key>(tp->pdev, PCI_CACHE_LINE_SIZE, &byte); if (byte == 0) cacheline_size = 1024; else cacheline_size = (int) byte * 4; /* On 5703 and later chips, the boundary bits have no * effect. */ if (tg3_asic_rev(tp) != ASIC_REV_5700 && tg3_asic_rev(tp) != ASIC_REV_5701 && !tg3_flag(tp, PCI_EXPRESS)) goto out; #if defined(CONFIG_PPC64) || defined(CONFIG_IA64) || defined(CONFIG_PARISC) goal = <API key>; #else #if defined(CONFIG_SPARC64) || defined(CONFIG_ALPHA) goal = <API key>; #else goal = 0; #endif #endif if (tg3_flag(tp, 57765_PLUS)) { val = goal ? 0 : <API key>; goto out; } if (!goal) goto out; /* PCI controllers on most RISC systems tend to disconnect * when a device tries to burst across a cache-line boundary. * Therefore, letting tg3 do so just wastes PCI bandwidth. * * Unfortunately, for PCI-E there are only limited * write-side controls for this, and thus for reads * we will still get the disconnects. We'll also waste * these PCI cycles for both read and write for chips * other than 5700 and 5701 which do not implement the * boundary bits. */ if (tg3_flag(tp, PCIX_MODE) && !tg3_flag(tp, PCI_EXPRESS)) { switch (cacheline_size) { case 16: case 32: case 64: case 128: if (goal == <API key>) { val |= (<API key> | <API key>); } else { val |= (<API key> | <API key>); } break; case 256: val |= (<API key> | <API key>); break; default: val |= (<API key> | <API key>); break; } } else if (tg3_flag(tp, PCI_EXPRESS)) { switch (cacheline_size) { case 16: case 32: case 64: if (goal == <API key>) { val &= ~<API key>; val |= <API key>; break; } /* fallthrough */ case 128: default: val &= ~<API key>; val |= <API key>; break; } } else { switch (cacheline_size) { case 16: if (goal == <API key>) { val |= (<API key> | <API key>); break; } /* fallthrough */ case 32: if (goal == <API key>) { val |= (<API key> | <API key>); break; } /* fallthrough */ case 64: if (goal == <API key>) { val |= (<API key> | <API key>); break; } /* fallthrough */ case 128: if (goal == <API key>) { val |= (<API key> | <API key>); break; } /* fallthrough */ case 256: val |= (<API key> | <API key>); break; case 512: val |= (<API key> | <API key>); break; case 1024: default: val |= (<API key> | <API key>); break; } } out: return val; } static int tg3_do_test_dma(struct tg3 *tp, u32 *buf, dma_addr_t buf_dma, int size, bool to_device) { struct <API key> test_desc; u32 sram_dma_descs; int i, ret; sram_dma_descs = <API key>; tw32(<API key>, 0); tw32(<API key>, 0); tw32(RDMAC_STATUS, 0); tw32(WDMAC_STATUS, 0); tw32(BUFMGR_MODE, 0); tw32(FTQ_RESET, 0); test_desc.addr_hi = ((u64) buf_dma) >> 32; test_desc.addr_lo = buf_dma & 0xffffffff; test_desc.nic_mbuf = 0x00002100; test_desc.len = size; /* * HP ZX1 was seeing test failures for 5701 cards running at 33Mhz * the *second* time the tg3 driver was getting loaded after an * initial scan. * * Broadcom tells me: * ...the DMA engine is connected to the GRC block and a DMA * reset may affect the GRC block in some unpredictable way... * The behavior of resets to individual blocks has not been tested. * * Broadcom noted the GRC reset will also reset all sub-components. */ if (to_device) { test_desc.cqid_sqid = (13 << 8) | 2; tw32_f(RDMAC_MODE, RDMAC_MODE_ENABLE); udelay(40); } else { test_desc.cqid_sqid = (16 << 8) | 7; tw32_f(WDMAC_MODE, WDMAC_MODE_ENABLE); udelay(40); } test_desc.flags = 0x00000005; for (i = 0; i < (sizeof(test_desc) / sizeof(u32)); i++) { u32 val; val = *(((u32 *)&test_desc) + i); <API key>(tp->pdev, <API key>, sram_dma_descs + (i * sizeof(u32))); <API key>(tp->pdev, TG3PCI_MEM_WIN_DATA, val); } <API key>(tp->pdev, <API key>, 0); if (to_device) tw32(<API key>, sram_dma_descs); else tw32(<API key>, sram_dma_descs); ret = -ENODEV; for (i = 0; i < 40; i++) { u32 val; if (to_device) val = tr32(<API key>); else val = tr32(<API key>); if ((val & 0xffff) == sram_dma_descs) { ret = 0; break; } udelay(100); } return ret; } #define TEST_BUFFER_SIZE 0x2000 static <API key>(<API key>) = { { PCI_DEVICE(PCI_VENDOR_ID_APPLE, <API key>) }, { }, }; static int tg3_test_dma(struct tg3 *tp) { dma_addr_t buf_dma; u32 *buf, saved_dma_rwctrl; int ret = 0; buf = dma_alloc_coherent(&tp->pdev->dev, TEST_BUFFER_SIZE, &buf_dma, GFP_KERNEL); if (!buf) { ret = -ENOMEM; goto out_nofree; } tp->dma_rwctrl = ((0x7 << <API key>) | (0x6 << <API key>)); tp->dma_rwctrl = tg3_calc_dma_bndry(tp, tp->dma_rwctrl); if (tg3_flag(tp, 57765_PLUS)) goto out; if (tg3_flag(tp, PCI_EXPRESS)) { /* DMA read watermark not used on PCIE */ tp->dma_rwctrl |= 0x00180000; } else if (!tg3_flag(tp, PCIX_MODE)) { if (tg3_asic_rev(tp) == ASIC_REV_5705 || tg3_asic_rev(tp) == ASIC_REV_5750) tp->dma_rwctrl |= 0x003f0000; else tp->dma_rwctrl |= 0x003f000f; } else { if (tg3_asic_rev(tp) == ASIC_REV_5703 || tg3_asic_rev(tp) == ASIC_REV_5704) { u32 ccval = (tr32(TG3PCI_CLOCK_CTRL) & 0x1f); u32 read_water = 0x7; /* If the 5704 is behind the EPB bridge, we can * do the less restrictive ONE_DMA workaround for * better performance. */ if (tg3_flag(tp, 40BIT_DMA_BUG) && tg3_asic_rev(tp) == ASIC_REV_5704) tp->dma_rwctrl |= 0x8000; else if (ccval == 0x6 || ccval == 0x7) tp->dma_rwctrl |= DMA_RWCTRL_ONE_DMA; if (tg3_asic_rev(tp) == ASIC_REV_5703) read_water = 4; /* Set bit 23 to enable PCIX hw bug fix */ tp->dma_rwctrl |= (read_water << <API key>) | (0x3 << <API key>) | (1 << 23); } else if (tg3_asic_rev(tp) == ASIC_REV_5780) { /* 5780 always in PCIX mode */ tp->dma_rwctrl |= 0x00144000; } else if (tg3_asic_rev(tp) == ASIC_REV_5714) { /* 5714 always in PCIX mode */ tp->dma_rwctrl |= 0x00148000; } else { tp->dma_rwctrl |= 0x001b000f; } } if (tg3_flag(tp, ONE_DMA_AT_ONCE)) tp->dma_rwctrl |= DMA_RWCTRL_ONE_DMA; if (tg3_asic_rev(tp) == ASIC_REV_5703 || tg3_asic_rev(tp) == ASIC_REV_5704) tp->dma_rwctrl &= 0xfffffff0; if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) { /* Remove this if it causes problems for some boards. */ tp->dma_rwctrl |= <API key>; /* On 5700/5701 chips, we need to set this bit. * Otherwise the chip will issue cacheline transactions * to streamable DMA memory with not all the byte * enables turned on. This is an error on several * RISC PCI controllers, in particular sparc64. * * On 5703/5704 chips, this bit has been reassigned * a different meaning. In particular, it is used * on those chips to enable a PCI-X workaround. */ tp->dma_rwctrl |= <API key>; } tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl); if (tg3_asic_rev(tp) != ASIC_REV_5700 && tg3_asic_rev(tp) != ASIC_REV_5701) goto out; /* It is best to perform DMA test with maximum write burst size * to expose the 5700/5701 write DMA bug. */ saved_dma_rwctrl = tp->dma_rwctrl; tp->dma_rwctrl &= ~<API key>; tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl); while (1) { u32 *p = buf, i; for (i = 0; i < TEST_BUFFER_SIZE / sizeof(u32); i++) p[i] = i; /* Send the buffer to the chip. */ ret = tg3_do_test_dma(tp, buf, buf_dma, TEST_BUFFER_SIZE, true); if (ret) { dev_err(&tp->pdev->dev, "%s: Buffer write failed. err = %d\n", __func__, ret); break; } /* Now read it back. */ ret = tg3_do_test_dma(tp, buf, buf_dma, TEST_BUFFER_SIZE, false); if (ret) { dev_err(&tp->pdev->dev, "%s: Buffer read failed. " "err = %d\n", __func__, ret); break; } /* Verify it. */ for (i = 0; i < TEST_BUFFER_SIZE / sizeof(u32); i++) { if (p[i] == i) continue; if ((tp->dma_rwctrl & <API key>) != <API key>) { tp->dma_rwctrl &= ~<API key>; tp->dma_rwctrl |= <API key>; tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl); break; } else { dev_err(&tp->pdev->dev, "%s: Buffer corrupted on read back! " "(%d != %d)\n", __func__, p[i], i); ret = -ENODEV; goto out; } } if (i == (TEST_BUFFER_SIZE / sizeof(u32))) { /* Success. */ ret = 0; break; } } if ((tp->dma_rwctrl & <API key>) != <API key>) { /* DMA test passed without adjusting DMA boundary, * now look for chipsets that are known to expose the * DMA bug without failing the test. */ if (pci_dev_present(<API key>)) { tp->dma_rwctrl &= ~<API key>; tp->dma_rwctrl |= <API key>; } else { /* Safe to use the calculated DMA boundary. */ tp->dma_rwctrl = saved_dma_rwctrl; } tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl); } out: dma_free_coherent(&tp->pdev->dev, TEST_BUFFER_SIZE, buf, buf_dma); out_nofree: return ret; } static void <API key>(struct tg3 *tp) { if (tg3_flag(tp, 57765_PLUS)) { tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.mbuf_high_water = <API key>; tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.<API key> = <API key>; } else if (tg3_flag(tp, 5705_PLUS)) { tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.mbuf_high_water = <API key>; if (tg3_asic_rev(tp) == ASIC_REV_5906) { tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.mbuf_high_water = <API key>; } tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.<API key> = <API key>; } else { tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.mbuf_high_water = <API key>; tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.<API key> = <API key>; tp->bufmgr_config.<API key> = <API key>; } tp->bufmgr_config.dma_low_water = <API key>; tp->bufmgr_config.dma_high_water = <API key>; } static char *tg3_phy_string(struct tg3 *tp) { switch (tp->phy_id & TG3_PHY_ID_MASK) { case TG3_PHY_ID_BCM5400: return "5400"; case TG3_PHY_ID_BCM5401: return "5401"; case TG3_PHY_ID_BCM5411: return "5411"; case TG3_PHY_ID_BCM5701: return "5701"; case TG3_PHY_ID_BCM5703: return "5703"; case TG3_PHY_ID_BCM5704: return "5704"; case TG3_PHY_ID_BCM5705: return "5705"; case TG3_PHY_ID_BCM5750: return "5750"; case TG3_PHY_ID_BCM5752: return "5752"; case TG3_PHY_ID_BCM5714: return "5714"; case TG3_PHY_ID_BCM5780: return "5780"; case TG3_PHY_ID_BCM5755: return "5755"; case TG3_PHY_ID_BCM5787: return "5787"; case TG3_PHY_ID_BCM5784: return "5784"; case TG3_PHY_ID_BCM5756: return "5722/5756"; case TG3_PHY_ID_BCM5906: return "5906"; case TG3_PHY_ID_BCM5761: return "5761"; case TG3_PHY_ID_BCM5718C: return "5718C"; case TG3_PHY_ID_BCM5718S: return "5718S"; case TG3_PHY_ID_BCM57765: return "57765"; case TG3_PHY_ID_BCM5719C: return "5719C"; case TG3_PHY_ID_BCM5720C: return "5720C"; case TG3_PHY_ID_BCM5762: return "5762C"; case TG3_PHY_ID_BCM8002: return "8002/serdes"; case 0: return "serdes"; default: return "unknown"; } } static char *tg3_bus_string(struct tg3 *tp, char *str) { if (tg3_flag(tp, PCI_EXPRESS)) { strcpy(str, "PCI Express"); return str; } else if (tg3_flag(tp, PCIX_MODE)) { u32 clock_ctrl = tr32(TG3PCI_CLOCK_CTRL) & 0x1f; strcpy(str, "PCIX:"); if ((clock_ctrl == 7) || ((tr32(GRC_MISC_CFG) & <API key>) == <API key>)) strcat(str, "133MHz"); else if (clock_ctrl == 0) strcat(str, "33MHz"); else if (clock_ctrl == 2) strcat(str, "50MHz"); else if (clock_ctrl == 4) strcat(str, "66MHz"); else if (clock_ctrl == 6) strcat(str, "100MHz"); } else { strcpy(str, "PCI:"); if (tg3_flag(tp, PCI_HIGH_SPEED)) strcat(str, "66MHz"); else strcat(str, "33MHz"); } if (tg3_flag(tp, PCI_32BIT)) strcat(str, ":32-bit"); else strcat(str, ":64-bit"); return str; } static void tg3_init_coal(struct tg3 *tp) { struct ethtool_coalesce *ec = &tp->coal; memset(ec, 0, sizeof(*ec)); ec->cmd = ETHTOOL_GCOALESCE; ec->rx_coalesce_usecs = LOW_RXCOL_TICKS; ec->tx_coalesce_usecs = LOW_TXCOL_TICKS; ec-><API key> = LOW_RXMAX_FRAMES; ec-><API key> = LOW_TXMAX_FRAMES; ec-><API key> = <API key>; ec-><API key> = <API key>; ec-><API key> = <API key>; ec-><API key> = <API key>; ec-><API key> = <API key>; if (tp->coalesce_mode & (<API key> | <API key>)) { ec->rx_coalesce_usecs = <API key>; ec-><API key> = <API key>; ec->tx_coalesce_usecs = <API key>; ec-><API key> = <API key>; } if (tg3_flag(tp, 5705_PLUS)) { ec-><API key> = 0; ec-><API key> = 0; ec-><API key> = 0; } } static int tg3_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *dev; struct tg3 *tp; int i, err; u32 sndmbx, rcvmbx, intmbx; char str[40]; u64 dma_mask, persist_dma_mask; netdev_features_t features = 0; printk_once(KERN_INFO "%s\n", version); err = pci_enable_device(pdev); if (err) { dev_err(&pdev->dev, "Cannot enable PCI device, aborting\n"); return err; } err = pci_request_regions(pdev, DRV_MODULE_NAME); if (err) { dev_err(&pdev->dev, "Cannot obtain PCI resources, aborting\n"); goto <API key>; } pci_set_master(pdev); dev = alloc_etherdev_mq(sizeof(*tp), TG3_IRQ_MAX_VECS); if (!dev) { err = -ENOMEM; goto err_out_free_res; } SET_NETDEV_DEV(dev, &pdev->dev); tp = netdev_priv(dev); tp->pdev = pdev; tp->dev = dev; tp->rx_mode = TG3_DEF_RX_MODE; tp->tx_mode = TG3_DEF_TX_MODE; tp->irq_sync = 1; if (tg3_debug > 0) tp->msg_enable = tg3_debug; else tp->msg_enable = TG3_DEF_MSG_ENABLE; if (<API key>(pdev)) { tg3_flag_set(tp, IS_SSB_CORE); if (<API key>(pdev)) tg3_flag_set(tp, FLUSH_POSTED_WRITES); if (<API key>(pdev)) tg3_flag_set(tp, ONE_DMA_AT_ONCE); if (<API key>(pdev)) { tg3_flag_set(tp, USE_PHYLIB); tg3_flag_set(tp, ROBOSWITCH); } if (ssb_gige_is_rgmii(pdev)) tg3_flag_set(tp, RGMII_MODE); } /* The word/byte swap controls here control register access byte * swapping. DMA data byte swapping is controlled in the GRC_MODE * setting below. */ tp->misc_host_ctrl = <API key> | <API key> | <API key> | <API key>; /* The NONFRM (non-frame) byte/word swap controls take effect * on descriptor entries, anything which isn't packet data. * * The StrongARM chips on the board (one for tx, one for rx) * are running in big-endian mode. */ tp->grc_mode = (GRC_MODE_WSWAP_DATA | GRC_MODE_BSWAP_DATA | <API key>); #ifdef __BIG_ENDIAN tp->grc_mode |= <API key>; #endif spin_lock_init(&tp->lock); spin_lock_init(&tp->indirect_lock); INIT_WORK(&tp->reset_task, tg3_reset_task); tp->regs = pci_ioremap_bar(pdev, BAR_0); if (!tp->regs) { dev_err(&pdev->dev, "Cannot map device registers, aborting\n"); err = -ENOMEM; goto err_out_free_dev; } if (tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key> || tp->pdev->device == <API key>) { tg3_flag_set(tp, ENABLE_APE); tp->aperegs = pci_ioremap_bar(pdev, BAR_2); if (!tp->aperegs) { dev_err(&pdev->dev, "Cannot map APE registers, aborting\n"); err = -ENOMEM; goto err_out_iounmap; } } tp->rx_pending = <API key>; tp->rx_jumbo_pending = <API key>; dev->ethtool_ops = &tg3_ethtool_ops; dev->watchdog_timeo = TG3_TX_TIMEOUT; dev->netdev_ops = &tg3_netdev_ops; dev->irq = pdev->irq; err = tg3_get_invariants(tp, ent); if (err) { dev_err(&pdev->dev, "Problem fetching invariants of chip, aborting\n"); goto err_out_apeunmap; } /* The EPB bridge inside 5714, 5715, and 5780 and any * device behind the EPB cannot support DMA addresses > 40-bit. * On 64-bit systems with IOMMU, use 40-bit dma_mask. * On 64-bit systems without IOMMU, use 64-bit dma_mask and * do DMA address check in tg3_start_xmit(). */ if (tg3_flag(tp, IS_5788)) persist_dma_mask = dma_mask = DMA_BIT_MASK(32); else if (tg3_flag(tp, 40BIT_DMA_BUG)) { persist_dma_mask = dma_mask = DMA_BIT_MASK(40); #ifdef CONFIG_HIGHMEM dma_mask = DMA_BIT_MASK(64); #endif } else persist_dma_mask = dma_mask = DMA_BIT_MASK(64); /* Configure DMA attributes. */ if (dma_mask > DMA_BIT_MASK(32)) { err = pci_set_dma_mask(pdev, dma_mask); if (!err) { features |= NETIF_F_HIGHDMA; err = <API key>(pdev, persist_dma_mask); if (err < 0) { dev_err(&pdev->dev, "Unable to obtain 64 bit " "DMA for consistent allocations\n"); goto err_out_apeunmap; } } } if (err || dma_mask == DMA_BIT_MASK(32)) { err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)); if (err) { dev_err(&pdev->dev, "No usable DMA configuration, aborting\n"); goto err_out_apeunmap; } } <API key>(tp); /* 5700 B0 chips do not support checksumming correctly due * to hardware bugs. */ if (tg3_chip_rev_id(tp) != CHIPREV_ID_5700_B0) { features |= NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_RXCSUM; if (tg3_flag(tp, 5755_PLUS)) features |= NETIF_F_IPV6_CSUM; } /* TSO is on by default on chips that support hardware TSO. * Firmware TSO on older chips gives lower performance, so it * is off by default, but can be enabled using ethtool. */ if ((tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) && (features & NETIF_F_IP_CSUM)) features |= NETIF_F_TSO; if (tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) { if (features & NETIF_F_IPV6_CSUM) features |= NETIF_F_TSO6; if (tg3_flag(tp, HW_TSO_3) || tg3_asic_rev(tp) == ASIC_REV_5761 || (tg3_asic_rev(tp) == ASIC_REV_5784 && tg3_chip_rev(tp) != CHIPREV_5784_AX) || tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780) features |= NETIF_F_TSO_ECN; } dev->features |= features | <API key> | <API key>; dev->vlan_features |= features; /* * Add loopback capability only for a subset of devices that support * MAC-LOOPBACK. Eventually this need to be enhanced to allow INT-PHY * loopback for the remaining devices. */ if (tg3_asic_rev(tp) != ASIC_REV_5780 && !tg3_flag(tp, CPMU_PRESENT)) /* Add the loopback capability */ features |= NETIF_F_LOOPBACK; dev->hw_features |= features; dev->priv_flags |= IFF_UNICAST_FLT; if (tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A1 && !tg3_flag(tp, TSO_CAPABLE) && !(tr32(TG3PCI_PCISTATE) & <API key>)) { tg3_flag_set(tp, MAX_RXPEND_64); tp->rx_pending = 63; } err = <API key>(tp); if (err) { dev_err(&pdev->dev, "Could not obtain valid ethernet address, aborting\n"); goto err_out_apeunmap; } /* * Reset chip in case UNDI or EFI driver did not shutdown * DMA self test will enable WDMAC and we'll see (spurious) * pending DMA on the PCI bus at that point. */ if ((tr32(HOSTCC_MODE) & HOSTCC_MODE_ENABLE) || (tr32(WDMAC_MODE) & WDMAC_MODE_ENABLE)) { tw32(MEMARB_MODE, MEMARB_MODE_ENABLE); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); } err = tg3_test_dma(tp); if (err) { dev_err(&pdev->dev, "DMA engine test failed, aborting\n"); goto err_out_apeunmap; } intmbx = MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW; rcvmbx = <API key> + TG3_64BIT_REG_LOW; sndmbx = <API key> + TG3_64BIT_REG_LOW; for (i = 0; i < tp->irq_max; i++) { struct tg3_napi *tnapi = &tp->napi[i]; tnapi->tp = tp; tnapi->tx_pending = <API key>; tnapi->int_mbox = intmbx; if (i <= 4) intmbx += 0x8; else intmbx += 0x4; tnapi->consmbox = rcvmbx; tnapi->prodmbox = sndmbx; if (i) tnapi->coal_now = <API key> << (i - 1); else tnapi->coal_now = HOSTCC_MODE_NOW; if (!tg3_flag(tp, SUPPORT_MSIX)) break; /* * If we support MSIX, we'll be using RSS. If we're using * RSS, the first vector only handles link interrupts and the * remaining vectors handle rx and tx interrupts. Reuse the * mailbox values for the next iteration. The values we setup * above are still useful for the single vectored mode. */ if (!i) continue; rcvmbx += 0x8; if (sndmbx & 0x4) sndmbx -= 0x4; else sndmbx += 0xc; } tg3_init_coal(tp); pci_set_drvdata(pdev, dev); if (tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) tg3_flag_set(tp, PTP_CAPABLE); tg3_timer_init(tp); tg3_carrier_off(tp); err = register_netdev(dev); if (err) { dev_err(&pdev->dev, "Cannot register net device, aborting\n"); goto err_out_apeunmap; } netdev_info(dev, "Tigon3 [partno(%s) rev %04x] (%s) MAC address %pM\n", tp->board_part_number, tg3_chip_rev_id(tp), tg3_bus_string(tp, str), dev->dev_addr); if (tp->phy_flags & <API key>) { struct phy_device *phydev; phydev = tp->mdio_bus->phy_map[tp->phy_addr]; netdev_info(dev, "attached PHY driver [%s] (mii_bus:phy_addr=%s)\n", phydev->drv->name, dev_name(&phydev->dev)); } else { char *ethtype; if (tp->phy_flags & <API key>) ethtype = "10/100Base-TX"; else if (tp->phy_flags & <API key>) ethtype = "1000Base-SX"; else ethtype = "10/100/1000Base-T"; netdev_info(dev, "attached PHY is %s (%s Ethernet) " "(WireSpeed[%d], EEE[%d])\n", tg3_phy_string(tp), ethtype, (tp->phy_flags & <API key>) == 0, (tp->phy_flags & TG3_PHYFLG_EEE_CAP) != 0); } netdev_info(dev, "RXcsums[%d] LinkChgREG[%d] MIirq[%d] ASF[%d] TSOcap[%d]\n", (dev->features & NETIF_F_RXCSUM) != 0, tg3_flag(tp, USE_LINKCHG_REG) != 0, (tp->phy_flags & <API key>) != 0, tg3_flag(tp, ENABLE_ASF) != 0, tg3_flag(tp, TSO_CAPABLE) != 0); netdev_info(dev, "dma_rwctrl[%08x] dma_mask[%d-bit]\n", tp->dma_rwctrl, pdev->dma_mask == DMA_BIT_MASK(32) ? 32 : ((u64)pdev->dma_mask) == DMA_BIT_MASK(40) ? 40 : 64); pci_save_state(pdev); return 0; err_out_apeunmap: if (tp->aperegs) { iounmap(tp->aperegs); tp->aperegs = NULL; } err_out_iounmap: if (tp->regs) { iounmap(tp->regs); tp->regs = NULL; } err_out_free_dev: free_netdev(dev); err_out_free_res: pci_release_regions(pdev); <API key>: if (pci_is_enabled(pdev)) pci_disable_device(pdev); return err; } static void tg3_remove_one(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); if (dev) { struct tg3 *tp = netdev_priv(dev); release_firmware(tp->fw); <API key>(tp); if (tg3_flag(tp, USE_PHYLIB)) { tg3_phy_fini(tp); tg3_mdio_fini(tp); } unregister_netdev(dev); if (tp->aperegs) { iounmap(tp->aperegs); tp->aperegs = NULL; } if (tp->regs) { iounmap(tp->regs); tp->regs = NULL; } free_netdev(dev); pci_release_regions(pdev); pci_disable_device(pdev); } } #ifdef CONFIG_PM_SLEEP static int tg3_suspend(struct device *device) { struct pci_dev *pdev = to_pci_dev(device); struct net_device *dev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(dev); int err = 0; rtnl_lock(); if (!netif_running(dev)) goto unlock; <API key>(tp); tg3_phy_stop(tp); tg3_netif_stop(tp); tg3_timer_stop(tp); tg3_full_lock(tp, 1); tg3_disable_ints(tp); tg3_full_unlock(tp); netif_device_detach(dev); tg3_full_lock(tp, 0); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); tg3_flag_clear(tp, INIT_COMPLETE); tg3_full_unlock(tp); err = <API key>(tp); if (err) { int err2; tg3_full_lock(tp, 0); tg3_flag_set(tp, INIT_COMPLETE); err2 = tg3_restart_hw(tp, true); if (err2) goto out; tg3_timer_start(tp); netif_device_attach(dev); tg3_netif_start(tp); out: tg3_full_unlock(tp); if (!err2) tg3_phy_start(tp); } unlock: rtnl_unlock(); return err; } static int tg3_resume(struct device *device) { struct pci_dev *pdev = to_pci_dev(device); struct net_device *dev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(dev); int err = 0; rtnl_lock(); if (!netif_running(dev)) goto unlock; netif_device_attach(dev); tg3_full_lock(tp, 0); <API key>(tp, RESET_KIND_INIT); tg3_flag_set(tp, INIT_COMPLETE); err = tg3_restart_hw(tp, !(tp->phy_flags & <API key>)); if (err) goto out; tg3_timer_start(tp); tg3_netif_start(tp); out: tg3_full_unlock(tp); if (!err) tg3_phy_start(tp); unlock: rtnl_unlock(); return err; } #endif /* CONFIG_PM_SLEEP */ static SIMPLE_DEV_PM_OPS(tg3_pm_ops, tg3_suspend, tg3_resume); static void tg3_shutdown(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(dev); rtnl_lock(); netif_device_detach(dev); if (netif_running(dev)) dev_close(dev); if (system_state == SYSTEM_POWER_OFF) tg3_power_down(tp); rtnl_unlock(); } /** * <API key> - called when PCI error is detected * @pdev: Pointer to PCI device * @state: The current pci connection state * * This function is called after a PCI bus error affecting * this device has been detected. */ static pci_ers_result_t <API key>(struct pci_dev *pdev, pci_channel_state_t state) { struct net_device *netdev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(netdev); pci_ers_result_t err = <API key>; netdev_info(netdev, "PCI I/O error detected\n"); rtnl_lock(); /* We probably don't have netdev yet */ if (!netdev || !netif_running(netdev)) goto done; tg3_phy_stop(tp); tg3_netif_stop(tp); tg3_timer_stop(tp); /* Want to make sure that the reset task doesn't run */ <API key>(tp); netif_device_detach(netdev); /* Clean up software state, even if MMIO is blocked */ tg3_full_lock(tp, 0); tg3_halt(tp, RESET_KIND_SHUTDOWN, 0); tg3_full_unlock(tp); done: if (state == <API key>) { if (netdev) { tg3_napi_enable(tp); dev_close(netdev); } err = <API key>; } else { pci_disable_device(pdev); } rtnl_unlock(); return err; } /** * tg3_io_slot_reset - called after the pci bus has been reset. * @pdev: Pointer to PCI device * * Restart the card from scratch, as if from a cold-boot. * At this point, the card has exprienced a hard reset, * followed by fixups by BIOS, and has its config space * set up identically to what it was at cold boot. */ static pci_ers_result_t tg3_io_slot_reset(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(netdev); pci_ers_result_t rc = <API key>; int err; rtnl_lock(); if (pci_enable_device(pdev)) { dev_err(&pdev->dev, "Cannot re-enable PCI device after reset.\n"); goto done; } pci_set_master(pdev); pci_restore_state(pdev); pci_save_state(pdev); if (!netdev || !netif_running(netdev)) { rc = <API key>; goto done; } err = tg3_power_up(tp); if (err) goto done; rc = <API key>; done: if (rc != <API key> && netdev && netif_running(netdev)) { tg3_napi_enable(tp); dev_close(netdev); } rtnl_unlock(); return rc; } /** * tg3_io_resume - called when traffic can start flowing again. * @pdev: Pointer to PCI device * * This callback is called when the error recovery driver tells * us that its OK to resume normal operation. */ static void tg3_io_resume(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(netdev); int err; rtnl_lock(); if (!netif_running(netdev)) goto done; tg3_full_lock(tp, 0); <API key>(tp, RESET_KIND_INIT); tg3_flag_set(tp, INIT_COMPLETE); err = tg3_restart_hw(tp, true); if (err) { tg3_full_unlock(tp); netdev_err(netdev, "Cannot restart hardware after reset.\n"); goto done; } netif_device_attach(netdev); tg3_timer_start(tp); tg3_netif_start(tp); tg3_full_unlock(tp); tg3_phy_start(tp); done: rtnl_unlock(); } static const struct pci_error_handlers tg3_err_handler = { .error_detected = <API key>, .slot_reset = tg3_io_slot_reset, .resume = tg3_io_resume }; static struct pci_driver tg3_driver = { .name = DRV_MODULE_NAME, .id_table = tg3_pci_tbl, .probe = tg3_init_one, .remove = tg3_remove_one, .err_handler = &tg3_err_handler, .driver.pm = &tg3_pm_ops, .shutdown = tg3_shutdown, }; module_pci_driver(tg3_driver);
/** * @file config-win32-msvc.h * * $Id: config-win32-msvc.h 82643 2008-08-19 14:02:12Z johnnyw $ * * @brief Microsoft Visual C++ configuration file. * * This file is the ACE configuration file for Microsoft Visual C++ versions * 5.0, 6.0, and 7.0 (.NET) * * @author Darrell Brunsch <brunsch@cs.wustl.edu> */ #ifndef <API key> #define <API key> #include "ace/pre.h" #ifndef ACE_CONFIG_WIN32_H #error Use config-win32.h in config.h instead of this header #endif /* ACE_CONFIG_WIN32_H */ #define ACE_CC_NAME ACE_TEXT ("Visual C++") #ifndef <API key> # define ACE_CC_PREPROCESSOR "CL.EXE" # define <API key> "-nologo -E" #endif #define <API key> (_MSC_VER / 100 - 6) #define <API key> (_MSC_VER % 100) #define ACE_CC_BETA_VERSION (0) #if !defined (<API key>) # if defined (_DEBUG) # define <API key> ACE_TEXT ("d") # endif /* _DEBUG */ #endif /* <API key> */ #if !defined(<API key>) #define <API key> #endif // Win Mobile still does thread exits differently than PC Windows. #if defined (_WIN32_WCE) # define ACE_ENDTHREADEX(STATUS) ExitThread ((DWORD) STATUS) #else # define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) STATUS) #endif /* _WIN32_WCE */ #if (_MSC_VER >= 1500) # include "ace/config-win32-msvc-9.h" #elif (_MSC_VER >= 1400) # include "ace/config-win32-msvc-8.h" #elif (_MSC_VER >= 1310) # include "ace/config-win32-msvc-7.h" #else # error This version of Microsoft Visual C++ is not supported. #endif // MFC changes the behavior of operator new at all MSVC versions from 6 up // by throwing a static CMemoryException* instead of std::bad_alloc // (see ace/OS_Memory.h). This MFC exception object needs to be cleaned up // by calling its Delete() method. #if defined (ACE_HAS_MFC) && (ACE_HAS_MFC == 1) # if !defined (<API key>) # define <API key> # endif # if defined (ACE_bad_alloc) # undef ACE_bad_alloc # endif # define ACE_bad_alloc CMemoryException *e # if defined (ACE_del_bad_alloc) # undef ACE_del_bad_alloc # endif # define ACE_del_bad_alloc e->Delete(); #endif /* ACE_HAS_MFC && ACE_HAS_MFC==1 */ #if defined(ACE_MT_SAFE) && (ACE_MT_SAFE != 0) // must have _MT defined to include multithreading // features from win32 headers # if !defined(_MT) && !defined (ACE_HAS_WINCE) // On MSVC, this is changed by selecting the Multithreaded // DLL or Debug Multithreaded DLL in the Project Settings // under C++ Code Generation. # error You must link against multi-threaded libraries when using ACE (check your project settings) # endif /* !_MT && !ACE_HAS_WINCE */ #endif /* ACE_MT_SAFE && ACE_MT_SAFE != 0 */ #include <malloc.h> // Although ACE does have alloca() on this compiler/platform combination, it is // disabled by default since it can be dangerous. Uncomment the following line // if you ACE to use it. //#define ACE_HAS_ALLOCA 1 #define ACE_LACKS_DIRENT_H #define ACE_LACKS_DLFCN_H #define <API key> #define ACE_LACKS_NETDB_H #define ACE_LACKS_NET_IF_H #define <API key> #define ACE_LACKS_STDINT_H #define ACE_LACKS_STROPTS_H #define <API key> #define ACE_LACKS_SYS_IPC_H #define <API key> #define <API key> #define <API key> #define ACE_LACKS_SYS_SEM_H #define <API key> #define <API key> #define ACE_LACKS_SYS_UIO_H #define <API key> #define <API key> #define <API key> #define ACE_LACKS_STRINGS_H #define ACE_LACKS_PWD_H #define ACE_LACKS_POLL_H #define ACE_LACKS_SYS_SHM_H #define ACE_LACKS_SYS_MSG_H #define <API key> #define ACE_LACKS_TERMIOS_H #define ACE_LACKS_REGEX_H #define <API key> ACE_TEXT ("%I64d") #define <API key> ACE_TEXT ("%I64u") #define <API key> ::_strtoui64 #define <API key> ::_wcstoui64 // Turn off warnings for /W4 // To resume any of these warning: #pragma warning(default: 4xxx) // which should be placed after these defines #if !defined (ALL_WARNINGS) && defined(_MSC_VER) && !defined(ghs) && !defined(__MINGW32__) # pragma warning(disable: 4127) /* constant expression for TRACE/ASSERT */ # pragma warning(disable: 4134) /* message map member fxn casts */ # pragma warning(disable: 4511) /* private copy constructors are good to have */ # pragma warning(disable: 4512) /* private operator= are good to have */ # pragma warning(disable: 4514) /* unreferenced inlines are common */ # pragma warning(disable: 4710) /* private constructors are disallowed */ # pragma warning(disable: 4705) /* statement has no effect in optimized code */ # pragma warning(disable: 4791) /* loss of debugging info in retail version */ # pragma warning(disable: 4275) /* deriving exported class from non-exported */ # pragma warning(disable: 4251) /* using non-exported as public in exported */ # pragma warning(disable: 4786) /* identifier was truncated to '255' characters in the browser information */ # pragma warning(disable: 4097) /* typedef-name used as synonym for class-name */ # pragma warning(disable: 4800) /* converting int to boolean */ # if defined (__INTEL_COMPILER) # pragma warning(disable: 1744) /* field of class type without a DLL interface used in a class with a DLL interface */ # pragma warning(disable: 1738) # endif #endif /* !ALL_WARNINGS && _MSV_VER && !ghs && !__MINGW32__ */ // STRICT type checking in WINDOWS.H enhances type safety for Windows // programs by using distinct types to represent all the different // HANDLES in Windows. So for example, STRICT prevents you from // mistakenly passing an HPEN to a routine expecting an HBITMAP. // Note that we only use this if we # if defined (ACE_HAS_STRICT) && (ACE_HAS_STRICT != 0) # if !defined (STRICT) /* may already be defined */ # define STRICT # endif /* !STRICT */ # endif /* ACE_HAS_STRICT */ #include "ace/post.h" #endif /* <API key> */
<html> <head> <title>Flare Dendrogram</title> <script type="text/javascript" src="../../protovis.js"></script> <script type="text/javascript" src="../flare.js"></script> </head> <body> <script type="text/javascript+protovis"> var vis = new pv.Panel() .height(100) .width(1200); vis.add(pv.Layout.Cluster.Fill) .nodes(pv.dom(flare).root("flare").nodes()) .group(true) .orient("top") .node.add(pv.Bar); vis.render(); </script> </body> </html>
/* PM8921 Charge IC include file */ #ifndef <API key> #define <API key> #include <linux/types.h> #include "axi_charger.h" #include <linux/workqueue.h> #include <linux/param.h> //#define <API key> #if 0 #define HIGH (1) #define LOW (0) #define CHARGE_PIN1_GPIO (MFP_PIN_GPIO57) #define CHARGE_PIN2_GPIO (MFP_PIN_GPIO58) #define CHARGE_DISABLE_GPIO (MFP_PIN_GPIO99) #define CHARGE_PLUG_IN_GPIO (MFP_PIN_GPIO13) #define CHARGE_FAULT_GPIO (MFP_PIN_GPIO20) #define CHARGE_DONE_GPIO (MFP_PIN_GPIO36) #define CHARGE_STATUS_GPIO (MFP_PIN_GPIO19) #define BATTERY_LOW (MFP_PIN_GPIO8) #endif #define <API key> (60*HZ) typedef struct AXC_PM8921Charger { bool mbInited; int mnType; AXE_Charger_Type type; int mnPin1; int mnPin2; int mnChargerDisablePin; int mnChargePlugInPin; int mnChargeFaultPin; int mnChargeDonePin; int mnChargeStatusPin; //int mnBatteryLowPin; bool m_is_bat_valid; <API key> *mpNotifier; AXI_Charger msParentCharger; //struct delayed_work msNotifierWorker; #ifdef <API key> AXI_SelfTest msParentSelfTest; #endif //<API key> }AXC_PM8921Charger; extern void <API key>(AXI_Charger *apCharger,int anType); #endif //<API key>
#include "bladerunner/script/scene_script.h" namespace BladeRunner { enum kCT04Loops { kCT04LoopInshot = 0, kCT04LoopMainLoop = 1 }; void SceneScriptCT04::InitializeScene() { if (Game_Flag_Query(kFlagCT03toCT04)) { <API key>(<API key>, kCT04LoopInshot, false); <API key>(kCT04LoopMainLoop); <API key>(-150.0f, -621.3f, 357.0f, 533); } else { <API key>(kCT04LoopMainLoop); <API key>(-82.86f, -621.3f, 769.03f, 1020); } <API key>(0, 590, 0, 639, 479, 1); <API key>(1, 194, 84, 320, 274, 0); if (_vm->_cutContent) { <API key>(2, 0, 440, 590, 479, 2); } <API key>(kSfxCTRAIN1, 50, 1, 1); <API key>(kSfxCTAMBR1, 15, -100, 1); <API key>(kSfxCTRUNOFF, 34, 100, 1); <API key>(kSfxSPIN2B, 10, 40, 33, 50, 0, 0, -101, -101, 0, 0); <API key>(kSfxSPIN3A, 10, 40, 33, 50, 0, 0, -101, -101, 0, 0); <API key>(kActorBlimpGuy, 0, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1); <API key>(kActorBlimpGuy, 20, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1); <API key>(kActorBlimpGuy, 40, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1); <API key>(kActorBlimpGuy, 50, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1); <API key>(kSfxTHNDER3, 10, 60, 33, 50, -100, 100, -101, -101, 0, 0); <API key>(kSfxTHNDER4, 10, 60, 33, 50, -100, 100, -101, -101, 0, 0); } void SceneScriptCT04::SceneLoaded() { Obstacle_Object("DUMPSTER", true); Obstacle_Object("RIGHTWALL01", true); Obstacle_Object("BACK-BLDNG", true); Clickable_Object("DUMPSTER"); Footstep_Sounds_Set(0, 1); if (Game_Flag_Query(kFlagCT03toCT04)) { Game_Flag_Reset(kFlagCT03toCT04); } if (<API key>(kActorTransient) == <API key>) { <API key>(kActorTransient, 38); } } bool SceneScriptCT04::MouseClick(int x, int y) { return false; } bool SceneScriptCT04::ClickedOn3DObject(const char *objectName, bool a2) { if (objectName) { // this can be only "DUMPSTER" if (!Game_Flag_Query(<API key>) && !Game_Flag_Query(<API key>) && <API key>(kActorTransient) == <API key> ) { Game_Flag_Set(<API key>); <API key>(kActorTransient, <API key>); } if ( Game_Flag_Query(<API key>) && !Game_Flag_Query(<API key>) && !Game_Flag_Query(<API key>) && !Game_Flag_Query(<API key>) && <API key>(kVariableChapter) == 1 ) { if (!<API key>(kActorMcCoy, -147.41f, -621.3f, 724.57f, 0, true, false, false)) { <API key>(); Actor_Face_Heading(kActorMcCoy, 792, false); Actor_Put_In_Set(kActorTransient, kSetFreeSlotI); Actor_Set_At_XYZ(kActorTransient, 0, 0, 0, 0); <API key>(kActorMcCoy, 40); Actor_Voice_Over(320, kActorVoiceOver); Actor_Voice_Over(330, kActorVoiceOver); Actor_Voice_Over(340, kActorVoiceOver); Game_Flag_Set(<API key>); Game_Flag_Set(<API key>); } return false; } if (Game_Flag_Query(<API key>)) { if (Game_Flag_Query(<API key>)) { Actor_Voice_Over(270, kActorVoiceOver); Actor_Voice_Over(280, kActorVoiceOver); } else if (Game_Flag_Query(<API key>)) { Actor_Voice_Over(250, kActorVoiceOver); Actor_Voice_Over(260, kActorVoiceOver); } else { Actor_Voice_Over(230, kActorVoiceOver); Actor_Voice_Over(240, kActorVoiceOver); Game_Flag_Reset(<API key>); } return true; } if (!Game_Flag_Query(<API key>)) { if (!<API key>(kActorMcCoy, 75, 0, true, false)) { Actor_Face_Heading(kActorMcCoy, 707, false); <API key>(kActorMcCoy, 38); Actor_Clue_Acquire(kActorMcCoy, kClueLicensePlate, true, -1); <API key>(<API key>, 392, 225); Game_Flag_Set(<API key>); return true; } } if (!<API key>(kActorMcCoy, 75, 0, true, false)) { Actor_Face_Heading(kActorMcCoy, 707, false); <API key>(kActorMcCoy, 38); <API key>(kSfxGARBAGE, 45, 30, 30, 0); Actor_Voice_Over(1810, kActorVoiceOver); Actor_Voice_Over(1820, kActorVoiceOver); return true; } } return false; } void SceneScriptCT04::<API key>() { <API key>(); if (<API key>(kVariableChinyen) > 10 || <API key>() == kGameDifficultyEasy ) { <API key>(410, 8, 4, -1); // YES } <API key>(420, 2, 6, 8); <API key>(320, 240); int answer = <API key>(); <API key>(); switch (answer) { case 410: // YES Actor_Says(kActorTransient, 10, 14); // Thanks. The big man. He kind of limping. Actor_Says(kActorTransient, 20, 14); // That way. <API key>(kActorTransient, kActorMcCoy, 5); if (<API key>() != kGameDifficultyEasy) { <API key>(kVariableChinyen, 10); } break; case 420: Actor_Says(kActorMcCoy, 430, 3); Actor_Says(kActorTransient, 30, 14); // Hey, that'd work. <API key>(kActorTransient, kActorMcCoy, -5); break; } } bool SceneScriptCT04::ClickedOnActor(int actorId) { if (actorId == kActorTransient) { if (Game_Flag_Query(<API key>)) { if (!<API key>(kActorMcCoy, kActorTransient, 36, true, false)) { Actor_Voice_Over(290, kActorVoiceOver); Actor_Voice_Over(300, kActorVoiceOver); Actor_Voice_Over(310, kActorVoiceOver); } } else { <API key>(kActorTransient, false); if (!<API key>(kActorMcCoy, kActorTransient, 36, true, false)) { Actor_Face_Actor(kActorMcCoy, kActorTransient, true); if (!Game_Flag_Query(<API key>)) { if (Game_Flag_Query(kFlagZubenRetired)) { Actor_Says(kActorMcCoy, 435, kAnimationModeTalk); <API key>(kActorTransient, <API key>); } else { Music_Stop(3); Actor_Says(kActorMcCoy, 425, kAnimationModeTalk); Actor_Says(kActorTransient, 0, 13); // Hey, maybe spare some chinyen? <API key>(); <API key>(kActorTransient, <API key>); } Game_Flag_Set(<API key>); } else { Actor_Face_Actor(kActorMcCoy, kActorTransient, true); Actor_Says(kActorMcCoy, 435, kAnimationModeTalk); } } } return true; } return false; } bool SceneScriptCT04::ClickedOnItem(int itemId, bool a2) { return false; } bool SceneScriptCT04::ClickedOnExit(int exitId) { if (exitId == 1) { if (!<API key>(kActorMcCoy, -82.86f, -621.3f, 769.03f, 0, true, false, false)) { <API key>(true); <API key>(1); if (<API key>(kActorTransient) == <API key>) { <API key>(kActorTransient, <API key>); } Game_Flag_Set(kFlagCT04toCT05); Set_Enter(kSetCT05, kSceneCT05); } return true; } if (exitId == 0) { if (!<API key>(kActorMcCoy, -187.0f, -621.3f, 437.0f, 0, true, false, false)) { <API key>(true); <API key>(1); Game_Flag_Set(kFlagCT04toCT03); Set_Enter(kSetCT03_CT04, kSceneCT03); } return true; } if (_vm->_cutContent) { if (exitId == 2) { if (!<API key>(kActorMcCoy, -106.94f, -619.08f, 429.20f, 0, true, false, false)) { <API key>(true); <API key>(1); Game_Flag_Set(kFlagCT04toCT03); Set_Enter(kSetCT03_CT04, kSceneCT03); } return true; } } return false; } bool SceneScriptCT04::ClickedOn2DRegion(int region) { return false; } void SceneScriptCT04::SceneFrameAdvanced(int frame) { if (Game_Flag_Query(kFlagCT04BodyDumped)) { Game_Flag_Reset(kFlagCT04BodyDumped); Sound_Play(kSfxGARBAGE4, 100, 80, 80, 50); } } void SceneScriptCT04::ActorChangedGoal(int actorId, int newGoal, int oldGoal, bool currentSet) { } void SceneScriptCT04::PlayerWalkedIn() { } void SceneScriptCT04::PlayerWalkedOut() { } void SceneScriptCT04::<API key>(int a1) { } } // End of namespace BladeRunner
package p2; public class c2 { int i; public void method2() { i = 5; System.out.println("c2 method2 called"); } }
/* -*- Mode:C; c-basic-offset:4; tab-width:4; indent-tabs-mode:nil -*- */ #include <xen/config.h> #include <xen/lib.h> #include <xen/errno.h> #include <xen/sched.h> #include <xen/smp.h> #include <asm/ptrace.h> #include <xen/delay.h> #include <linux/efi.h> /* FOR EFI_UNIMPLEMENTED */ #include <asm/sal.h> /* FOR struct ia64_sal_retval */ #include <asm/system.h> #include <asm/io.h> #include <asm/processor.h> #include <asm/desc.h> #include <asm/vlsapic.h> #include <xen/irq.h> #include <xen/event.h> #include <asm/regionreg.h> #include <asm/privop.h> #include <asm/ia64_int.h> #include <asm/debugger.h> #include <asm/dom_fw.h> #include <asm/vmx_vcpu.h> #include <asm/kregs.h> #include <asm/vmx.h> #include <asm/vmmu.h> #include <asm/vmx_mm_def.h> #include <asm/vmx_phy_mode.h> #include <xen/mm.h> #include <asm/vmx_pal.h> #include <asm/shadow.h> #include <asm/sioemu.h> #include <public/arch-ia64/sioemu.h> #include <xen/hvm/irq.h> /* reset all PSR field to 0, except up,mfl,mfh,pk,dt,rt,mc,it */ #define <API key> 0x0000001808028034 extern unsigned long handle_fpu_swa (int fp_fault, struct pt_regs *regs, unsigned long isr); #define DOMN_PAL_REQUEST 0x110000 #define DOMN_SAL_REQUEST 0x110001 static const u16 vec2off[68] = {0x0,0x400,0x800,0xc00,0x1000,0x1400,0x1800, 0x1c00,0x2000,0x2400,0x2800,0x2c00,0x3000,0x3400,0x3800,0x3c00,0x4000, 0x4400,0x4800,0x4c00,0x5000,0x5100,0x5200,0x5300,0x5400,0x5500,0x5600, 0x5700,0x5800,0x5900,0x5a00,0x5b00,0x5c00,0x5d00,0x5e00,0x5f00,0x6000, 0x6100,0x6200,0x6300,0x6400,0x6500,0x6600,0x6700,0x6800,0x6900,0x6a00, 0x6b00,0x6c00,0x6d00,0x6e00,0x6f00,0x7000,0x7100,0x7200,0x7300,0x7400, 0x7500,0x7600,0x7700,0x7800,0x7900,0x7a00,0x7b00,0x7c00,0x7d00,0x7e00, 0x7f00 }; void vmx_lazy_load_fpu(struct vcpu *vcpu) { if (FP_PSR(vcpu) & IA64_PSR_DFH) { FP_PSR(vcpu) = IA64_PSR_MFH; if (__ia64_per_cpu_var(fp_owner) != vcpu) __ia64_load_fpu(vcpu->arch._thread.fph); } } void <API key>(u64 ifa, u64 isr, u64 iim, u64 vec, REGS *regs) { u64 status, vector; VCPU *vcpu = current; u64 vpsr = VCPU(vcpu, vpsr); vector = vec2off[vec]; switch (vec) { case 5: // <API key> break; case 22: // <API key> if (!(vpsr & IA64_PSR_IC)) goto nested_fault; if (<API key>(vcpu, ifa, 0)) return; break; case 25: // <API key> if (!(vpsr & IA64_PSR_IC)) goto nested_fault; vmx_lazy_load_fpu(vcpu); if (!(VCPU(vcpu, vpsr) & IA64_PSR_DFH)) { regs->cr_ipsr &= ~IA64_PSR_DFH; return; } break; case 32: // <API key> if (!(vpsr & IA64_PSR_IC)) goto nested_fault; // handle fpswa emulation // fp fault status = handle_fpu_swa(1, regs, isr); if (!status) { vcpu_increment_iip(vcpu); return; } break; case 33: // IA64_FP_TRAP_VECTOR if (!(vpsr & IA64_PSR_IC)) goto nested_fault; //fp trap status = handle_fpu_swa(0, regs, isr); if (!status) return; break; case 29: // IA64_DEBUG_VECTOR case 35: // <API key> case 36: // <API key> if (<API key>(regs) && current->domain->debugger_attached) { <API key>(); return; } if (!(vpsr & IA64_PSR_IC)) goto nested_fault; break; default: if (!(vpsr & IA64_PSR_IC)) goto nested_fault; break; } VCPU(vcpu,isr) = isr; VCPU(vcpu,iipa) = regs->cr_iip; if (vector == IA64_BREAK_VECTOR || vector == <API key>) VCPU(vcpu,iim) = iim; else set_ifa_itir_iha(vcpu, ifa, 1, 1, 1); <API key>(vcpu, vector); return; nested_fault: panic_domain(regs, "Guest nested fault vector=%lx!\n", vector); } IA64FAULT <API key> (unsigned long ifa, struct pt_regs *regs, unsigned long isr, unsigned long iim) { struct domain *d = current->domain; struct vcpu *v = current; perfc_incr(<API key>); #ifdef CRASH_DEBUG if ((iim == 0 || iim == CDB_BREAK_NUM) && !vmx_user_mode(regs) && IS_VMM_ADDRESS(regs->cr_iip)) { if (iim == 0) show_registers(regs); debugger_trap_fatal(0 /* don't care */, regs); regs_increment_iip(regs); return IA64_NO_FAULT; } #endif if (!vmx_user_mode(regs)) { show_registers(regs); gdprintk(XENLOG_DEBUG, "%s:%d imm %lx\n", __func__, __LINE__, iim); ia64_fault(11 /* break fault */, isr, ifa, iim, 0 /* cr.itir */, 0, 0, 0, (unsigned long)regs); } if (ia64_psr(regs)->cpl == 0) { /* Allow hypercalls only when cpl = 0. */ /* Only common hypercalls are handled by vmx_break_fault. */ if (iim == d->arch.breakimm) { ia64_hypercall(regs); vcpu_increment_iip(v); return IA64_NO_FAULT; } /* normal hypercalls are handled by vmx_break_fault */ BUG_ON(iim == d->arch.breakimm); if (iim == DOMN_PAL_REQUEST) { pal_emul(v); vcpu_increment_iip(v); return IA64_NO_FAULT; } else if (iim == DOMN_SAL_REQUEST) { if (d->arch.is_sioemu) sioemu_sal_assist(v); else { sal_emul(v); vcpu_increment_iip(v); } return IA64_NO_FAULT; } } <API key>(ifa, isr, iim, 11, regs); return IA64_NO_FAULT; } void <API key>(VCPU *v, REGS *regs) { unsigned long i=0UL, * src,* dst, *sunat, *dunat; IA64_PSR vpsr; src = &regs->r16; sunat = &regs->eml_unat; vpsr.val = VCPU(v, vpsr); if (vpsr.bn) { dst = &VCPU(v, vgr[0]); dunat =&VCPU(v, vnat); __asm__ __volatile__ (";;extr.u %0 = %1,%4,16;; \ dep %2 = %0, %2, 0, 16;; \ st8 [%3] = %2;;" ::"r"(i),"r"(*sunat),"r"(*dunat),"r"(dunat),"i"(<API key>):"memory"); } else { dst = &VCPU(v, vbgr[0]); // dunat =&VCPU(v, vbnat); // __asm__ __volatile__ (";;extr.u %0 = %1,%4,16;; // dep %2 = %0, %2, 16, 16;; // st8 [%3] = %2;;" // ::"r"(i),"r"(*sunat),"r"(*dunat),"r"(dunat),"i"(<API key>):"memory"); } for (i = 0; i < 16; i++) *dst++ = *src++; } // ONLY gets called from ia64_leave_kernel // ONLY call with interrupts disabled?? (else might miss one?) // NEVER successful if already reflecting a trap/fault because psr.i==0 void <API key>(void) { struct domain *d = current->domain; struct vcpu *v = current; /* FIXME: can this happen ? */ if (is_idle_domain(current->domain)) return; // A softirq may generate an interrupt. So call softirq early. local_irq_enable(); do_softirq(); local_irq_disable(); // FIXME: Will this work properly if doing an RFI??? if (d->arch.is_sioemu) { if (<API key>()) { <API key>(); } } else if (v->vcpu_id == 0) { unsigned long callback_irq = d->arch.hvm_domain.params[<API key>]; if (v->arch.arch_vmx.pal_init_pending) { /* inject INIT interruption to guest pal */ v->arch.arch_vmx.pal_init_pending = 0; deliver_pal_init(v); return; } /* * val[63:56] == 1: val[55:0] is a delivery PCI INTx line: * Domain = val[47:32], Bus = val[31:16], * DevFn = val[15: 8], IntX = val[ 1: 0] * val[63:56] == 0: val[55:0] is a delivery as GSI */ if (callback_irq != 0 && <API key>()) { /* change level for para-device callback irq */ /* use level irq to send discrete event */ if ((uint8_t)(callback_irq >> 56) == 1) { /* case of using PCI INTx line as callback irq */ int pdev = (callback_irq >> 11) & 0x1f; int pintx = callback_irq & 3; <API key>(d, pdev, pintx, 1); <API key>(d, pdev, pintx, 0); } else { /* case of using GSI as callback irq */ viosapic_set_irq(d, callback_irq, 1); viosapic_set_irq(d, callback_irq, 0); } } } rmb(); if (xchg(&v->arch.irq_new_pending, 0)) { v->arch.irq_new_condition = 0; <API key>(v); } else if (v->arch.irq_new_condition) { v->arch.irq_new_condition = 0; vhpi_detection(v); } } static int vmx_handle_lds(REGS* regs) { regs->cr_ipsr |= IA64_PSR_ED; return IA64_FAULT; } static inline int unimpl_phys_addr (u64 paddr) { return (pa_clear_uc(paddr) >> MAX_PHYS_ADDR_BITS) != 0; } /* We came here because the H/W VHPT walker failed to find an entry */ IA64FAULT vmx_hpw_miss(u64 vadr, u64 vec, REGS* regs) { IA64_PSR vpsr; int type; u64 vhpt_adr, gppa, pteval, rr, itir; ISR misr; PTA vpta; thash_data_t *data; VCPU *v = current; vpsr.val = VCPU(v, vpsr); misr.val = VMX(v,cr_isr); if (vec == 1 || vec == 3) type = ISIDE_TLB; else if (vec == 2 || vec == 4) type = DSIDE_TLB; else panic_domain(regs, "wrong vec:%lx\n", vec); /* Physical mode. */ if (type == ISIDE_TLB) { if (!vpsr.it) { if (unlikely(unimpl_phys_addr(vadr))) { unimpl_iaddr_trap(v, vadr); return IA64_FAULT; } physical_tlb_miss(v, vadr, type); return IA64_FAULT; } } else { /* DTLB miss. */ if (!misr.rs) { if (!vpsr.dt) { u64 pte; if (misr.sp) /* Refer to SDM Vol2 Table 4-11,4-12 */ return vmx_handle_lds(regs); if (unlikely(unimpl_phys_addr(vadr))) { unimpl_daddr(v); return IA64_FAULT; } pte = lookup_domain_mpa(v->domain, pa_clear_uc(vadr), NULL); if (v->domain != dom0 && (pte & _PAGE_IO)) { emulate_io_inst(v, pa_clear_uc(vadr), 4, pte_pfn(__pte(pte))); return IA64_FAULT; } physical_tlb_miss(v, vadr, type); return IA64_FAULT; } } else { /* RSE fault. */ if (!vpsr.rt) { if (unlikely(unimpl_phys_addr(vadr))) { unimpl_daddr(v); return IA64_FAULT; } physical_tlb_miss(v, vadr, type); return IA64_FAULT; } } } try_again: /* Search in VTLB. */ data = vtlb_lookup(v, vadr, type); if (data != 0) { /* Found. */ if (v->domain != dom0 && type == DSIDE_TLB) { u64 pte; if (misr.sp) { /* Refer to SDM Vol2 Table 4-10,4-12 */ if ((data->ma == VA_MATTR_UC) || (data->ma == VA_MATTR_UCE)) return vmx_handle_lds(regs); } gppa = thash_translate(data, vadr); pte = lookup_domain_mpa(v->domain, gppa, NULL); if (pte & _PAGE_IO) { if (misr.sp) panic_domain(NULL, "ld.s on I/O page not with UC attr." " pte=0x%lx\n", data->page_flags); if (data->pl >= ((regs->cr_ipsr >> IA64_PSR_CPL0_BIT) & 3)) emulate_io_inst(v, gppa, data->ma, pte_pfn(__pte(pte))); else { vcpu_set_isr(v, misr.val); data_access_rights(v, vadr); } return IA64_FAULT; } } thash_vhpt_insert(v, data->page_flags, data->itir, vadr, type); return IA64_NO_FAULT; } if (type == DSIDE_TLB) { struct opt_feature* optf = &(v->domain->arch.opt_feature); if (misr.sp) return vmx_handle_lds(regs); vcpu_get_rr(v, vadr, &rr); itir = rr & (RR_RID_MASK | RR_PS_MASK); if (!vhpt_enabled(v, vadr, misr.rs ? RSE_REF : DATA_REF)) { /* windows use region 4 and 5 for identity mapping */ if ((optf->mask & <API key>) && REGION_NUMBER(vadr) == 4 && !(regs->cr_ipsr & IA64_PSR_CPL) && REGION_OFFSET(vadr) <= _PAGE_PPN_MASK) { pteval = PAGEALIGN(REGION_OFFSET(vadr), itir_ps(itir)) | optf->im_reg4.pgprot; if (<API key>(v, pteval, itir, vadr, type)) goto try_again; return IA64_NO_FAULT; } if ((optf->mask & <API key>) && REGION_NUMBER(vadr) == 5 && !(regs->cr_ipsr & IA64_PSR_CPL) && REGION_OFFSET(vadr) <= _PAGE_PPN_MASK) { pteval = PAGEALIGN(REGION_OFFSET(vadr), itir_ps(itir)) | optf->im_reg5.pgprot; if (<API key>(v, pteval, itir, vadr, type)) goto try_again; return IA64_NO_FAULT; } if (vpsr.ic) { vcpu_set_isr(v, misr.val); alt_dtlb(v, vadr); } else { nested_dtlb(v); } return IA64_FAULT; } vpta.val = vmx_vcpu_get_pta(v); if (vpta.vf) { /* Long format is not yet supported. */ goto inject_dtlb_fault; } /* avoid recursively walking (short format) VHPT */ if (!(optf->mask & <API key>) && !(optf->mask & <API key>) && (((vadr ^ vpta.val) << 3) >> (vpta.size + 3)) == 0) { goto inject_dtlb_fault; } vhpt_adr = vmx_vcpu_thash(v, vadr); if (!guest_vhpt_lookup(vhpt_adr, &pteval)) { /* VHPT successfully read. */ if (!(pteval & _PAGE_P)) { goto inject_dtlb_fault; } else if ((pteval & _PAGE_MA_MASK) != _PAGE_MA_ST) { <API key>(v, pteval, itir, vadr, DSIDE_TLB); return IA64_NO_FAULT; } goto inject_dtlb_fault; } else { /* Can't read VHPT. */ if (vpsr.ic) { vcpu_set_isr(v, misr.val); dvhpt_fault(v, vadr); return IA64_FAULT; } else { nested_dtlb(v); return IA64_FAULT; } } } else if (type == ISIDE_TLB) { if (!vpsr.ic) misr.ni = 1; /* Don't bother with PHY_D mode (will require rr0+rr4 switches, and certainly used only within nested TLB handler (hence TR mapped and ic=0). */ if (!vpsr.dt) goto inject_itlb_fault; if (!vhpt_enabled(v, vadr, INST_REF)) { vcpu_set_isr(v, misr.val); alt_itlb(v, vadr); return IA64_FAULT; } vpta.val = vmx_vcpu_get_pta(v); if (vpta.vf) { /* Long format is not yet supported. */ goto inject_itlb_fault; } vhpt_adr = vmx_vcpu_thash(v, vadr); if (!guest_vhpt_lookup(vhpt_adr, &pteval)) { /* VHPT successfully read. */ if (pteval & _PAGE_P) { if ((pteval & _PAGE_MA_MASK) == _PAGE_MA_ST) { goto inject_itlb_fault; } vcpu_get_rr(v, vadr, &rr); itir = rr & (RR_RID_MASK | RR_PS_MASK); <API key>(v, pteval, itir, vadr, ISIDE_TLB); return IA64_NO_FAULT; } else { vcpu_set_isr(v, misr.val); <API key>(v, vadr); return IA64_FAULT; } } else { vcpu_set_isr(v, misr.val); ivhpt_fault(v, vadr); return IA64_FAULT; } } return IA64_NO_FAULT; inject_dtlb_fault: if (vpsr.ic) { vcpu_set_isr(v, misr.val); dtlb_fault(v, vadr); } else nested_dtlb(v); return IA64_FAULT; inject_itlb_fault: vcpu_set_isr(v, misr.val); itlb_fault(v, vadr); return IA64_FAULT; } void <API key>(u64 ifa, u64 isr, u64 mpa, REGS *regs) { struct vcpu *v = current; struct domain *d = v->domain; u64 gpfn, pte; thash_data_t *data; if (!shadow_mode_enabled(d)) goto inject_dirty_bit; gpfn = get_gpfn_from_mfn(mpa >> PAGE_SHIFT); data = vhpt_lookup(ifa); if (data) { pte = data->page_flags; // BUG_ON((pte ^ mpa) & (_PAGE_PPN_MASK & PAGE_MASK)); if (!(pte & _PAGE_VIRT_D)) goto inject_dirty_bit; data->page_flags = pte | _PAGE_D; } else { data = vtlb_lookup(v, ifa, DSIDE_TLB); if (data) { if (!(data->page_flags & _PAGE_VIRT_D)) goto inject_dirty_bit; } pte = 0; } /* Set the dirty bit in the bitmap. */ <API key>(d, gpfn); /* Retry */ atomic64_inc(&d->arch.shadow_fault_count); ia64_ptcl(ifa, PAGE_SHIFT << 2); return; inject_dirty_bit: /* Reflect. no need to purge. */ VCPU(v, isr) = isr; set_ifa_itir_iha (v, ifa, 1, 1, 1); <API key>(v, <API key>); return; }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.10"/> <title>Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="mixerp.png"/></td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.10 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Packages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('<API key>.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="<API key>"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">MixERP.Net.FrontEnd.Services.Office Member List</div> </div> </div><!--header <div class="contents"> <p>This is the complete list of members for <a class="el" href="<API key>.html">MixERP.Net.FrontEnd.Services.Office</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>GetOffices</b>(string catalog) (defined in <a class="el" href="<API key>.html">MixERP.Net.FrontEnd.Services.Office</a>)</td><td class="entry"><a class="el" href="<API key>.html">MixERP.Net.FrontEnd.Services.Office</a></td><td class="entry"></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http: <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li> </ul> </div> </body> </html>
/* $OpenBSD: strdup.c,v 1.6 2005/08/08 08:05:37 espie Exp $ */ #include "sys/types.h" #include "stdlib.h" #include "string.h" char *strdup(const char *str) { size_t siz; char *copy; siz = strlen(str) + 1; if ((copy = malloc(siz)) == NULL) return(NULL); (void)memcpy(copy, str, siz); return(copy); }
; PROLOGUE(mpn_rsh1sub_n) ; AMD64 mpn_rsh1sub_n ; Copyright 2009 Jason Moxham ; Windows Conversion Copyright 2008 Brian Gladman ; ; This file is part of the MPIR Library. ; The MPIR Library is free software; you can redistribute it and/or modify ; it under the terms of the GNU Lesser General Public License as published ; by the Free Software Foundation; either version 2.1 of the License, or (at ; your option) any later version. ; The MPIR Library is distributed in the hope that it will be useful, but ; WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY ; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public ; License for more details. ; You should have received a copy of the GNU Lesser General Public License ; along with the MPIR Library; see the file COPYING.LIB. If not, write ; to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ; Boston, MA 02110-1301, USA. ; ; (rdi,rcx)=((rsi,rcx)-(rdx,rcx))/2 ; return bottom bit of difference ; subtraction treated as two compliment %include "yasm_mac.inc" %define reg_save_list rbx, rsi, rdi, r12 CPU Athlon64 BITS 64 FRAME_PROC mpn_rsh1sub_n, 0, reg_save_list mov rax, r9 lea rdi, [rcx+rax*8-32] lea rsi, [rdx+rax*8-32] lea rdx, [r8+rax*8-32] mov rcx, rax mov r8, 4 sub r8, rcx mov r12, [rsi+r8*8] sub r12, [rdx+r8*8] sbb rbx, rbx mov rax, r12 and rax, 1 cmp r8, 0 jge .2 .1: mov r11, [rsi+r8*8+32] mov r10, [rsi+r8*8+24] add rbx, 1 mov rcx, [rsi+r8*8+8] mov r9, [rsi+r8*8+16] sbb rcx, [rdx+r8*8+8] sbb r9, [rdx+r8*8+16] sbb r10, [rdx+r8*8+24] sbb r11, [rdx+r8*8+32] sbb rbx, rbx bt r11, 0 rcr r10, 1 rcr r9, 1 rcr rcx, 1 rcr r12, 1 mov [rdi+r8*8], r12 mov [rdi+r8*8+8], rcx mov [rdi+r8*8+16], r9 mov [rdi+r8*8+24], r10 mov r12, r11 add r8, 4 jnc .1 .2: cmp r8, 2 ja .6 jz .5 jp .4 .3: mov r10, [rsi+r8*8+24] add rbx, 1 mov rcx, [rsi+r8*8+8] mov r9, [rsi+r8*8+16] sbb rcx, [rdx+r8*8+8] sbb r9, [rdx+r8*8+16] sbb r10, [rdx+r8*8+24] rcr r10, 1 rcr r9, 1 rcr rcx, 1 rcr r12, 1 mov [rdi+r8*8], r12 mov [rdi+r8*8+8], rcx mov [rdi+r8*8+16], r9 mov [rdi+r8*8+24], r10 EXIT_PROC reg_save_list xalign 16 .4: add rbx, 1 mov rcx, [rsi+r8*8+8] mov r9, [rsi+r8*8+16] sbb rcx, [rdx+r8*8+8] sbb r9, [rdx+r8*8+16] rcr r9, 1 rcr rcx, 1 rcr r12, 1 mov [rdi+r8*8], r12 mov [rdi+r8*8+8], rcx mov [rdi+r8*8+16], r9 EXIT_PROC reg_save_list xalign 16 .5: add rbx, 1 mov rcx, [rsi+r8*8+8] sbb rcx, [rdx+r8*8+8] rcr rcx, 1 rcr r12, 1 mov [rdi+r8*8], r12 mov [rdi+r8*8+8], rcx EXIT_PROC reg_save_list xalign 16 .6: add rbx, 1 rcr r12, 1 mov [rdi+r8*8], r12 .7: END_PROC reg_save_list end
#include "inner.h" /* see bearssl_rsa.h */ uint32_t br_rsa_ssl_decrypt(br_rsa_private core, const br_rsa_private_key *sk, unsigned char *data, size_t len) { uint32_t x; size_t u; /* * A first check on length. Since this test works only on the * buffer length, it needs not (and cannot) be constant-time. */ if (len < 59 || len != (sk->n_bitlen + 7) >> 3) { return 0; } x = core(data, sk); x &= EQ(data[0], 0x00); x &= EQ(data[1], 0x02); for (u = 2; u < (len - 49); u ++) { x &= NEQ(data[u], 0); } x &= EQ(data[len - 49], 0x00); memmove(data, data + len - 48, 48); return x; }
// This Source Code Form is subject to the terms of the Mozilla Public package events_test import ( "fmt" "testing" "time" "github.com/syncthing/syncthing/lib/events" ) const timeout = 100 * time.Millisecond func TestNewLogger(t *testing.T) { l := events.NewLogger() if l == nil { t.Fatal("Unexpected nil Logger") } } func TestSubscriber(t *testing.T) { l := events.NewLogger() s := l.Subscribe(0) defer l.Unsubscribe(s) if s == nil { t.Fatal("Unexpected nil Subscription") } } func TestTimeout(t *testing.T) { l := events.NewLogger() s := l.Subscribe(0) defer l.Unsubscribe(s) _, err := s.Poll(timeout) if err != events.ErrTimeout { t.Fatal("Unexpected non-Timeout error:", err) } } func <API key>(t *testing.T) { l := events.NewLogger() l.Log(events.DeviceConnected, "foo") s := l.Subscribe(0) defer l.Unsubscribe(s) _, err := s.Poll(timeout) if err != events.ErrTimeout { t.Fatal("Unexpected non-Timeout error:", err) } } func <API key>(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.AllEvents) defer l.Unsubscribe(s) l.Log(events.DeviceConnected, "foo") ev, err := s.Poll(timeout) if err != nil { t.Fatal("Unexpected error:", err) } if ev.Type != events.DeviceConnected { t.Error("Incorrect event type", ev.Type) } switch v := ev.Data.(type) { case string: if v != "foo" { t.Error("Incorrect Data string", v) } default: t.Errorf("Incorrect Data type %#v", v) } } func <API key>(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.DeviceDisconnected) defer l.Unsubscribe(s) l.Log(events.DeviceConnected, "foo") _, err := s.Poll(timeout) if err != events.ErrTimeout { t.Fatal("Unexpected non-Timeout error:", err) } } func TestBufferOverflow(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.AllEvents) defer l.Unsubscribe(s) t0 := time.Now() for i := 0; i < events.BufferSize*2; i++ { l.Log(events.DeviceConnected, "foo") } if time.Since(t0) > timeout { t.Fatalf("Logging took too long") } } func TestUnsubscribe(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.AllEvents) l.Log(events.DeviceConnected, "foo") _, err := s.Poll(timeout) if err != nil { t.Fatal("Unexpected error:", err) } l.Unsubscribe(s) l.Log(events.DeviceConnected, "foo") _, err = s.Poll(timeout) if err != events.ErrClosed { t.Fatal("Unexpected non-Closed error:", err) } } func TestIDs(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.AllEvents) defer l.Unsubscribe(s) l.Log(events.DeviceConnected, "foo") _ = l.Subscribe(events.AllEvents) l.Log(events.DeviceConnected, "bar") ev, err := s.Poll(timeout) if err != nil { t.Fatal("Unexpected error:", err) } if ev.Data.(string) != "foo" { t.Fatal("Incorrect event:", ev) } id := ev.ID ev, err = s.Poll(timeout) if err != nil { t.Fatal("Unexpected error:", err) } if ev.Data.(string) != "bar" { t.Fatal("Incorrect event:", ev) } if ev.ID != id+1 { t.Fatalf("ID not incremented (%d != %d)", ev.ID, id+1) } } func TestBufferedSub(t *testing.T) { l := events.NewLogger() s := l.Subscribe(events.AllEvents) defer l.Unsubscribe(s) bs := events.<API key>(s, 10*events.BufferSize) go func() { for i := 0; i < 10*events.BufferSize; i++ { l.Log(events.DeviceConnected, fmt.Sprintf("event-%d", i)) if i%30 == 0 { // Give the buffer routine time to pick up the events time.Sleep(20 * time.Millisecond) } } }() recv := 0 for recv < 10*events.BufferSize { evs := bs.Since(recv, nil) for _, ev := range evs { if ev.ID != recv+1 { t.Fatalf("Incorrect ID; %d != %d", ev.ID, recv+1) } recv = ev.ID } } }
# source this file (. devinstall.sh) to get exports in the right place # then you can run graphlab from within the venv and it points to this # development directory # create a virtualenv (if necessary) and activate it virtualenv venv . venv/bin/activate # set the export path for unity server export GRAPHLAB_UNITY=$(pwd)/../server/unity_server # install the package locally in development mode (so the files are symlinked and a make picks up new changes) ARCHFLAGS=-Wno-error=<API key> pip install -e . # install ipython notebook dependencies ARCHFLAGS=-Wno-error=<API key> pip install "ipython[notebook]"
<?php class actionBase { public $id; public function __construct($id = '') { $this->id = $id; } /** * @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead */ public function actionBase($id = '') { $deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code'; if (isset($GLOBALS['log'])) { $GLOBALS['log']->deprecated($deprecatedMessage); } else { trigger_error($deprecatedMessage, E_USER_DEPRECATED); } self::__construct($id); } public function loadJS() { return array(); } public function edit_display($line, SugarBean $bean = null, $params = array()) { return ''; } public function run_action(SugarBean $bean, $params = array(), $in_save=false) { return true; } }
// This file is part of the deal.II library. // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // the top level of the deal.II distribution. // check <API key>::copy constructor with offdiagonals #include "<API key>.h" int main () { std::ofstream logfile("output"); logfile.setf(std::ios::fixed); deallog << std::setprecision(3); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); <API key><<API key>> (); }
// @allowJs: true // @checkJs: true // @noEmit: true // @Filename: <API key>.js /** * @template T * @typedef {(t: T) => T} Id */ /** @template T */ class Foo { /** @typedef {(t: T) => T} Id2 */ /** @param {T} x */ constructor (x) { this.a = x } /** * * @param {T} x * @param {Id<T>} y * @param {Id2} alpha * @return {T} */ foo(x, y, alpha) { return alpha(y(x)) } } var f = new Foo(1) var g = new Foo(false) f.a = g.a
"""Extension argument processing code """ __all__ = ['Message', 'NamespaceMap', 'no_default', '<API key>', 'OPENID_NS', 'BARE_NS', 'OPENID1_NS', 'OPENID2_NS', 'SREG_URI', 'IDENTIFIER_SELECT'] import copy import warnings import urllib from openid import oidutil from openid import kvform try: ElementTree = oidutil.importElementTree() except ImportError: # No elementtree found, so give up, but don't fail to import, # since we have fallbacks. ElementTree = None # This doesn't REALLY belong here, but where is better? IDENTIFIER_SELECT = 'http://specs.openid.net/auth/2.0/identifier_select' # URI for Simple Registration extension, the only commonly deployed # OpenID 1.x extension, and so a special case SREG_URI = 'http://openid.net/sreg/1.0' # The OpenID 1.X namespace URI OPENID1_NS = 'http://openid.net/signon/1.0' <API key> = 'http://openid.net/signon/1.1' OPENID1_NAMESPACES = OPENID1_NS, <API key> # The OpenID 2.0 namespace URI OPENID2_NS = 'http://specs.openid.net/auth/2.0' # The namespace consisting of pairs with keys that are prefixed with # "openid." but not in another namespace. NULL_NAMESPACE = oidutil.Symbol('Null namespace') # The null namespace, when it is an allowed OpenID namespace OPENID_NS = oidutil.Symbol('OpenID namespace') # The top-level namespace, excluding all pairs with keys that start # with "openid." BARE_NS = oidutil.Symbol('Bare namespace') # Limit, in bytes, of identity provider and return_to URLs, including # response payload. See OpenID 1.1 specification, Appendix D. OPENID1_URL_LIMIT = 2047 # All OpenID protocol fields. Used to check namespace aliases. <API key> = [ 'ns', 'mode', 'error', 'return_to', 'contact', 'reference', 'signed', 'assoc_type', 'session_type', 'dh_modulus', 'dh_gen', 'dh_consumer_public', 'claimed_id', 'identity', 'realm', 'invalidate_handle', 'op_endpoint', 'response_nonce', 'sig', 'assoc_handle', 'trust_root', 'openid', ] class <API key>(ValueError): """Raised if the generic OpenID namespace is accessed when there is no OpenID namespace set for this message.""" class <API key>(ValueError): """Raised if openid.ns is not a recognized value. For recognized values, see L{Message.<API key>} """ def __str__(self): s = "Invalid OpenID Namespace" if self.args: s += " %r" % (self.args[0],) return s # Sentinel used for Message implementation to indicate that getArg # should raise an exception instead of returning a default. no_default = object() # Global namespace / alias registration map. See # <API key>. registered_aliases = {} class <API key>(Exception): """ Raised when an alias or namespace URI has already been registered. """ pass def <API key>(namespace_uri, alias): """ Registers a (namespace URI, alias) mapping in a global namespace alias map. Raises <API key> if either the namespace URI or alias has already been registered with a different value. This function is required if you want to use a namespace with an OpenID 1 message. """ global registered_aliases if registered_aliases.get(alias) == namespace_uri: return if namespace_uri in registered_aliases.values(): raise <API key>, \ 'Namespace uri %r already registered' % (namespace_uri,) if alias in registered_aliases: raise <API key>, \ 'Alias %r already registered' % (alias,) registered_aliases[alias] = namespace_uri class Message(object): """ In the implementation of this object, None represents the global namespace as well as a namespace with no key. @cvar namespaces: A dictionary specifying specific namespace-URI to alias mappings that should be used when generating namespace aliases. @ivar ns_args: two-level dictionary of the values in this message, grouped by namespace URI. The first level is the namespace URI. """ <API key> = [OPENID1_NS, <API key>, OPENID2_NS] def __init__(self, openid_namespace=None): """Create an empty Message. @raises <API key>: if openid_namespace is not in L{Message.<API key>} """ self.args = {} self.namespaces = NamespaceMap() if openid_namespace is None: self._openid_ns_uri = None else: implicit = openid_namespace in OPENID1_NAMESPACES self.setOpenIDNamespace(openid_namespace, implicit) def fromPostArgs(cls, args): """Construct a Message containing a set of POST arguments. """ self = cls() # Partition into "openid." args and bare args openid_args = {} for key, value in args.items(): if isinstance(value, list): raise TypeError("query dict must have one value for each key, " "not lists of values. Query is %r" % (args,)) try: prefix, rest = key.split('.', 1) except ValueError: prefix = None if prefix != 'openid': self.args[(BARE_NS, key)] = value else: openid_args[rest] = value self._fromOpenIDArgs(openid_args) return self fromPostArgs = classmethod(fromPostArgs) def fromOpenIDArgs(cls, openid_args): """Construct a Message from a parsed KVForm message. @raises <API key>: if openid.ns is not in L{Message.<API key>} """ self = cls() self._fromOpenIDArgs(openid_args) return self fromOpenIDArgs = classmethod(fromOpenIDArgs) def _fromOpenIDArgs(self, openid_args): ns_args = [] # Resolve namespaces for rest, value in openid_args.iteritems(): try: ns_alias, ns_key = rest.split('.', 1) except ValueError: ns_alias = NULL_NAMESPACE ns_key = rest if ns_alias == 'ns': self.namespaces.addAlias(value, ns_key) elif ns_alias == NULL_NAMESPACE and ns_key == 'ns': # null namespace self.setOpenIDNamespace(value, False) else: ns_args.append((ns_alias, ns_key, value)) # Implicitly set an OpenID namespace definition (OpenID 1) if not self.getOpenIDNamespace(): self.setOpenIDNamespace(OPENID1_NS, True) # Actually put the pairs into the appropriate namespaces for (ns_alias, ns_key, value) in ns_args: ns_uri = self.namespaces.getNamespaceURI(ns_alias) if ns_uri is None: # we found a namespaced arg without a namespace URI defined ns_uri = self.<API key>(ns_alias) if ns_uri is None: ns_uri = self.getOpenIDNamespace() ns_key = '%s.%s' % (ns_alias, ns_key) else: self.namespaces.addAlias(ns_uri, ns_alias, implicit=True) self.setArg(ns_uri, ns_key, value) def <API key>(self, mystery_alias): """OpenID 1 compatibility: look for a default namespace URI to use for this alias.""" global registered_aliases # Only try to map an alias to a default if it's an # OpenID 1.x message. if self.isOpenID1(): return registered_aliases.get(mystery_alias) else: return None def setOpenIDNamespace(self, openid_ns_uri, implicit): """Set the OpenID namespace URI used in this message. @raises <API key>: if the namespace is not in L{Message.<API key>} """ if openid_ns_uri not in self.<API key>: raise <API key>(openid_ns_uri) self.namespaces.addAlias(openid_ns_uri, NULL_NAMESPACE, implicit) self._openid_ns_uri = openid_ns_uri def getOpenIDNamespace(self): return self._openid_ns_uri def isOpenID1(self): return self.getOpenIDNamespace() in OPENID1_NAMESPACES def isOpenID2(self): return self.getOpenIDNamespace() == OPENID2_NS def fromKVForm(cls, kvform_string): """Create a Message from a KVForm string""" return cls.fromOpenIDArgs(kvform.kvToDict(kvform_string)) fromKVForm = classmethod(fromKVForm) def copy(self): return copy.deepcopy(self) def toPostArgs(self): """Return all arguments with openid. in front of namespaced arguments. """ args = {} # Add namespace definitions to the output for ns_uri, alias in self.namespaces.iteritems(): if self.namespaces.isImplicit(ns_uri): continue if alias == NULL_NAMESPACE: ns_key = 'openid.ns' else: ns_key = 'openid.ns.' + alias args[ns_key] = oidutil.toUnicode(ns_uri).encode('UTF-8') for (ns_uri, ns_key), value in self.args.iteritems(): key = self.getKey(ns_uri, ns_key) # Ensure the resulting value is an UTF-8 encoded bytestring. args[key] = oidutil.toUnicode(value).encode('UTF-8') return args def toArgs(self): """Return all namespaced arguments, failing if any non-namespaced arguments exist.""" # FIXME - undocumented exception post_args = self.toPostArgs() kvargs = {} for k, v in post_args.iteritems(): if not k.startswith('openid.'): raise ValueError( 'This message can only be encoded as a POST, because it ' 'contains arguments that are not prefixed with "openid."') else: kvargs[k[7:]] = v return kvargs def toFormMarkup(self, action_url, form_tag_attrs=None, submit_text=u"Continue"): """Generate HTML form markup that contains the values in this message, to be HTTP POSTed as <API key> UTF-8. @param action_url: The URL to which the form will be POSTed @type action_url: str @param form_tag_attrs: Dictionary of attributes to be added to the form tag. 'accept-charset' and 'enctype' have defaults that can be overridden. If a value is supplied for 'action' or 'method', it will be replaced. @type form_tag_attrs: {unicode: unicode} @param submit_text: The text that will appear on the submit button for this form. @type submit_text: unicode @returns: A string containing (X)HTML markup for a form that encodes the values in this Message object. @rtype: str or unicode """ if ElementTree is None: raise RuntimeError('This function requires ElementTree.') assert action_url is not None form = ElementTree.Element(u'form') if form_tag_attrs: for name, attr in form_tag_attrs.iteritems(): form.attrib[name] = attr form.attrib[u'action'] = oidutil.toUnicode(action_url) form.attrib[u'method'] = u'post' form.attrib[u'accept-charset'] = u'UTF-8' form.attrib[u'enctype'] = u'application/<API key>' for name, value in self.toPostArgs().iteritems(): attrs = {u'type': u'hidden', u'name': oidutil.toUnicode(name), u'value': oidutil.toUnicode(value)} form.append(ElementTree.Element(u'input', attrs)) submit = ElementTree.Element(u'input', {u'type':'submit', u'value':oidutil.toUnicode(submit_text)}) form.append(submit) return ElementTree.tostring(form, encoding='utf-8') def toURL(self, base_url): """Generate a GET URL with the parameters in this message attached as query parameters.""" return oidutil.appendArgs(base_url, self.toPostArgs()) def toKVForm(self): """Generate a KVForm string that contains the parameters in this message. This will fail if the message contains arguments outside of the 'openid.' prefix. """ return kvform.dictToKV(self.toArgs()) def toURLEncoded(self): """Generate an x-www-urlencoded string""" args = self.toPostArgs().items() args.sort() return urllib.urlencode(args) def _fixNS(self, namespace): """Convert an input value into the internally used values of this object @param namespace: The string or constant to convert @type namespace: str or unicode or BARE_NS or OPENID_NS """ if namespace == OPENID_NS: if self._openid_ns_uri is None: raise <API key>('OpenID namespace not set') else: namespace = self._openid_ns_uri if namespace != BARE_NS and type(namespace) not in [str, unicode]: raise TypeError( "Namespace must be BARE_NS, OPENID_NS or a string. got %r" % (namespace,)) if namespace != BARE_NS and ':' not in namespace: fmt = 'OpenID 2.0 namespace identifiers SHOULD be URIs. Got %r' warnings.warn(fmt % (namespace,), DeprecationWarning) if namespace == 'sreg': fmt = 'Using %r instead of "sreg" as namespace' warnings.warn(fmt % (SREG_URI,), DeprecationWarning,) return SREG_URI return namespace def hasKey(self, namespace, ns_key): namespace = self._fixNS(namespace) return (namespace, ns_key) in self.args def getKey(self, namespace, ns_key): """Get the key for a particular namespaced argument""" namespace = self._fixNS(namespace) if namespace == BARE_NS: return ns_key ns_alias = self.namespaces.getAlias(namespace) # No alias is defined, so no key can exist if ns_alias is None: return None if ns_alias == NULL_NAMESPACE: tail = ns_key else: tail = '%s.%s' % (ns_alias, ns_key) return 'openid.' + tail def getArg(self, namespace, key, default=None): """Get a value for a namespaced key. @param namespace: The namespace in the message for this key @type namespace: str @param key: The key to get within this namespace @type key: str @param default: The value to use if this key is absent from this message. Using the special value openid.message.no_default will result in this method raising a KeyError instead of returning the default. @rtype: str or the type of default @raises KeyError: if default is no_default @raises <API key>: if the message has not yet had an OpenID namespace set """ namespace = self._fixNS(namespace) args_key = (namespace, key) try: return self.args[args_key] except KeyError: if default is no_default: raise KeyError((namespace, key)) else: return default def getArgs(self, namespace): """Get the arguments that are defined for this namespace URI @returns: mapping from namespaced keys to values @returntype: dict """ namespace = self._fixNS(namespace) return dict([ (ns_key, value) for ((pair_ns, ns_key), value) in self.args.iteritems() if pair_ns == namespace ]) def updateArgs(self, namespace, updates): """Set multiple key/value pairs in one call @param updates: The values to set @type updates: {unicode:unicode} """ namespace = self._fixNS(namespace) for k, v in updates.iteritems(): self.setArg(namespace, k, v) def setArg(self, namespace, key, value): """Set a single argument in this namespace""" assert key is not None assert value is not None namespace = self._fixNS(namespace) self.args[(namespace, key)] = value if not (namespace is BARE_NS): self.namespaces.add(namespace) def delArg(self, namespace, key): namespace = self._fixNS(namespace) del self.args[(namespace, key)] def __repr__(self): return "<%s.%s %r>" % (self.__class__.__module__, self.__class__.__name__, self.args) def __eq__(self, other): return self.args == other.args def __ne__(self, other): return not (self == other) def getAliasedArg(self, aliased_key, default=None): if aliased_key == 'ns': return self.getOpenIDNamespace() if aliased_key.startswith('ns.'): uri = self.namespaces.getNamespaceURI(aliased_key[3:]) if uri is None: if default == no_default: raise KeyError else: return default else: return uri try: alias, key = aliased_key.split('.', 1) except ValueError: # need more than x values to unpack ns = None else: ns = self.namespaces.getNamespaceURI(alias) if ns is None: key = aliased_key ns = self.getOpenIDNamespace() return self.getArg(ns, key, default) class NamespaceMap(object): """Maintains a bijective map between namespace uris and aliases. """ def __init__(self): self.alias_to_namespace = {} self.namespace_to_alias = {} self.implicit_namespaces = [] def getAlias(self, namespace_uri): return self.namespace_to_alias.get(namespace_uri) def getNamespaceURI(self, alias): return self.alias_to_namespace.get(alias) def iterNamespaceURIs(self): """Return an iterator over the namespace URIs""" return iter(self.namespace_to_alias) def iterAliases(self): """Return an iterator over the aliases""" return iter(self.alias_to_namespace) def iteritems(self): """Iterate over the mapping @returns: iterator of (namespace_uri, alias) """ return self.namespace_to_alias.iteritems() def addAlias(self, namespace_uri, desired_alias, implicit=False): """Add an alias from this namespace URI to the desired alias """ # Check that desired_alias is not an openid protocol field as # per the spec. assert desired_alias not in <API key>, \ "%r is not an allowed namespace alias" % (desired_alias,) # Check that desired_alias does not contain a period as per # the spec. if type(desired_alias) in [str, unicode]: assert '.' not in desired_alias, \ "%r must not contain a dot" % (desired_alias,) # Check that there is not a namespace already defined for # the desired alias <API key> = self.alias_to_namespace.get(desired_alias) if (<API key> is not None and <API key> != namespace_uri): fmt = ('Cannot map %r to alias %r. ' '%r is already mapped to alias %r') msg = fmt % ( namespace_uri, desired_alias, <API key>, desired_alias) raise KeyError(msg) # Check that there is not already a (different) alias for # this namespace URI alias = self.namespace_to_alias.get(namespace_uri) if alias is not None and alias != desired_alias: fmt = ('Cannot map %r to alias %r. ' 'It is already mapped to alias %r') raise KeyError(fmt % (namespace_uri, desired_alias, alias)) assert (desired_alias == NULL_NAMESPACE or type(desired_alias) in [str, unicode]), repr(desired_alias) assert namespace_uri not in self.implicit_namespaces self.alias_to_namespace[desired_alias] = namespace_uri self.namespace_to_alias[namespace_uri] = desired_alias if implicit: self.implicit_namespaces.append(namespace_uri) return desired_alias def add(self, namespace_uri): """Add this namespace URI to the mapping, without caring what alias it ends up with""" # See if this namespace is already mapped to an alias alias = self.namespace_to_alias.get(namespace_uri) if alias is not None: return alias # Fall back to generating a numerical alias i = 0 while True: alias = 'ext' + str(i) try: self.addAlias(namespace_uri, alias) except KeyError: i += 1 else: return alias assert False, "Not reached" def isDefined(self, namespace_uri): return namespace_uri in self.namespace_to_alias def __contains__(self, namespace_uri): return self.isDefined(namespace_uri) def isImplicit(self, namespace_uri): return namespace_uri in self.implicit_namespaces
# Apipie DSL functions. module Apipie # DSL is a module that provides #api, #error, #param, #error. module DSL module Base attr_reader :<API key>, :api_params private def _apipie_dsl_data @_apipie_dsl_data ||= <API key> end def <API key> @_apipie_dsl_data = nil end def <API key> @_apipie_dsl_data = { :api => false, :api_args => [], :api_from_routes => nil, :errors => [], :params => [], :headers => [], :resouce_id => nil, :short_description => nil, :description => nil, :examples => [], :see => [], :formats => nil, :api_versions => [], :meta => nil, :show => true } end end module Resource # by default, the resource id is derived from controller_name # it can be overwritten with. # resource_id "my_own_resource_id" def resource_id(resource_id) Apipie.set_resource_id(@controller, resource_id) end def name(name) _apipie_dsl_data[:resource_name] = name end def api_base_url(url) _apipie_dsl_data[:api_base_url] = url end def short(short) _apipie_dsl_data[:short_description] = short end alias :short_description :short def path(path) _apipie_dsl_data[:path] = path end def app_info(app_info) _apipie_dsl_data[:app_info] = app_info end end module Action def def_param_group(name, &block) Apipie.add_param_group(self, name, &block) end # # load paths from routes and don't provide description # api def api(method, path, desc = nil, options={}) #:doc: return unless Apipie.active_dsl? _apipie_dsl_data[:api] = true _apipie_dsl_data[:api_args] << [method, path, desc, options] end # # load paths from routes # api! "short description", def api!(desc = nil, options={}) #:doc: return unless Apipie.active_dsl? _apipie_dsl_data[:api] = true _apipie_dsl_data[:api_from_routes] = { :desc => desc, :options =>options } end # Reference other similar method # api :PUT, '/articles/:id' # see "articles#create" # def update; end def see(*args) return unless Apipie.active_dsl? _apipie_dsl_data[:see] << args end # Show some example of what does the described # method return. def example(example) #:doc: return unless Apipie.active_dsl? _apipie_dsl_data[:examples] << example.strip_heredoc end # Determine if the method should be included # in the documentation def show(show) return unless Apipie.active_dsl? _apipie_dsl_data[:show] = show end # Describe whole resource # Example: # api :desc => "Show user profile", :path => "/users/", :version => '1.0 - 3.4.2012' # param :id, Fixnum, :desc => "User ID", :required => true # desc <<-EOS # Long description... # EOS def <API key>(options = {}, &block) #:doc: return unless Apipie.active_dsl? raise ArgumentError, "Block expected" unless block_given? dsl_data = <API key>.eval_dsl(self, &block) versions = dsl_data[:api_versions] @<API key> = versions.map do |version| Apipie.<API key>(self, version, dsl_data) end Apipie.<API key>(self, versions) end end module Common def api_versions(*versions) _apipie_dsl_data[:api_versions].concat(versions) end alias :api_version :api_versions # Describe the next method. # Example: # desc "print hello world" # def hello_world # puts "hello world" # end def desc(description) #:doc: return unless Apipie.active_dsl? if _apipie_dsl_data[:description] raise "Double method description." end _apipie_dsl_data[:description] = description end alias :description :desc alias :full_description :desc # describe next method with document in given path # in convension, these doc located under "#{Rails.root}/doc" # Example: # document "hello_world.md" # def hello_world # puts "hello world" # end def document path content = File.open(File.join(Rails.root, Apipie.configuration.doc_path, path)).read desc content end # Describe available request/response formats # formats ['json', 'jsonp', 'xml'] def formats(formats) #:doc: return unless Apipie.active_dsl? _apipie_dsl_data[:formats] = formats end # Describe additional metadata # meta :author => { :name => 'John', :surname => 'Doe' } def meta(meta) #:doc: _apipie_dsl_data[:meta] = meta end # Describe possible errors # Example: # error :desc => "speaker is sleeping", :code => 500, :meta => [:some, :more, :data] # error 500, "speaker is sleeping" # def hello_world # return 500 if self.speaker.sleeping? # puts "hello world" # end def error(code_or_options, desc=nil, options={}) #:doc: return unless Apipie.active_dsl? _apipie_dsl_data[:errors] << [code_or_options, desc, options] end def <API key>(description) # [re]define method only if validation is turned on if description && (Apipie.configuration.validate == true || Apipie.configuration.validate == :implicitly || Apipie.configuration.validate == :explicitly) <API key>(description.method, description.params) unless instance_methods.include?(:apipie_validations) define_method(:apipie_validations) do method_params = self.class.<API key>(action_name) if Apipie.configuration.validate_presence? method_params.each do |_, param| # check if required parameters are present raise ParamMissing.new(param.name) if param.required && !params.has_key?(param.name) end end if Apipie.configuration.validate_value? method_params.each do |_, param| # params validations param.validate(params[:"#{param.name}"]) if params.has_key?(param.name) end end # Only allow params passed in that are defined keys in the api # Auto skip the default params (format, controller, action) if Apipie.configuration.validate_key? params.reject{|k,_| %w[format controller action].include?(k.to_s) }.each_key do |param| # params allowed raise UnknownParam.new(param) if method_params.select {|_,p| p.name.to_s == param.to_s}.empty? end end if Apipie.configuration.process_value? @api_params ||= {} method_params.each do |_, param| # params processing @api_params[param.as] = param.process_value(params[:"#{param.name}"]) if params.has_key?(param.name) end end end end if (Apipie.configuration.validate == :implicitly || Apipie.configuration.validate == true) old_method = instance_method(description.method) define_method(description.method) do |*args| apipie_validations # run the original method code old_method.bind(self).call(*args) end end end end def <API key>(method, params) @method_params ||= {} @method_params[method] = params end def <API key>(method) @method_params[method] end # Describe request header. # Headers can't be validated with config.validate_presence = true # Example: # header 'ClientId', "client-id" # def show # render :text => headers['HTTP_CLIENT_ID'] # end def header(header_name, description, options = {}) #:doc return unless Apipie.active_dsl? _apipie_dsl_data[:headers] << { name: header_name, description: description, options: options } end end # this describes the params, it's in separate module because it's # used in Validators as well module Param # Describe method's parameter # Example: # param :greeting, String, :desc => "arbitrary text", :required => true # def hello_world(greeting) # puts greeting # end def param(param_name, validator, desc_or_options = nil, options = {}, &block) #:doc: return unless Apipie.active_dsl? _apipie_dsl_data[:params] << [param_name, validator, desc_or_options, options.merge(:param_group => @<API key>), block] end # Reuses param group for this method. The definition is looked up # in scope of this controller. If the group was defined in # different controller, the second param can be used to specify it. # when using action_aware parmas, you can specify :as => # :create or :update to explicitly say how it should behave def param_group(name, scope_or_options = nil, options = {}) if scope_or_options.is_a? Hash options.merge!(scope_or_options) scope = options[:scope] else scope = scope_or_options end scope ||= <API key> @<API key> = { :scope => scope, :name => name, :options => options, :from_concern => scope.apipie_concern? } self.instance_exec(&Apipie.get_param_group(scope, name)) ensure @<API key> = nil end # where the group definition should be looked up when no scope # given. This is expected to return a controller. def <API key> self end end module Controller include Apipie::DSL::Base include Apipie::DSL::Common include Apipie::DSL::Action include Apipie::DSL::Param # defines the substitutions to be made in the API paths deifned # in concerns included. For example: # There is this method defined in concern: # api GET ':controller_path/:id' # def show # end # If you include the concern into some controller, you can # specify the value for :controller_path like this: # <API key>(:controller_path => '/users') # include ::Concerns::SampleController # The resulting path will be '/users/:id'. # It has to be specified before the concern is included. # If not specified, the default predefined substitions are # {:conroller_path => controller.controller_path, # :resource_id => `<API key>` } def <API key>(subst_hash) <API key>.merge!(subst_hash) end def <API key> @<API key> ||= {:controller_path => self.controller_path, :resource_id => Apipie.get_resource_name(self)} end def <API key>(string) return <API key>.reduce(string) do |ret, (key, val)| ret.gsub(":#{key}", val) end end def apipie_concern? false end # create method api and redefine newly added method def method_added(method_name) #:doc: super return if !Apipie.active_dsl? || !_apipie_dsl_data[:api] return if _apipie_dsl_data[:api_args].blank? && _apipie_dsl_data[:api_from_routes].blank? # remove method description if exists and create new one Apipie.<API key>(self, _apipie_dsl_data[:api_versions], method_name) description = Apipie.<API key>(self, method_name, _apipie_dsl_data) <API key> <API key>(description) ensure <API key> end end module Concern include Apipie::DSL::Base include Apipie::DSL::Common include Apipie::DSL::Action include Apipie::DSL::Param # the concern was included into a controller def included(controller) super <API key>.each do |method_name, _apipie_dsl_data| # remove method description if exists and create new one description = Apipie.<API key>(controller, method_name, _apipie_dsl_data) controller.<API key>(description) end end def <API key> @<API key> ||= [] end def apipie_concern? true end # create method api and redefine newly added method def method_added(method_name) #:doc: super return if ! Apipie.active_dsl? || !_apipie_dsl_data[:api] <API key> << [method_name, _apipie_dsl_data.merge(:from_concern => true)] ensure <API key> end end class <API key> include Apipie::DSL::Base include Apipie::DSL::Common include Apipie::DSL::Resource include Apipie::DSL::Param def initialize(controller) @controller = controller end def _eval_dsl(&block) instance_eval(&block) return _apipie_dsl_data end # evaluates resource description DSL and returns results def self.eval_dsl(controller, &block) dsl_data = self.new(controller)._eval_dsl(&block) if dsl_data[:api_versions].empty? dsl_data[:api_versions] = Apipie.controller_versions(controller) end dsl_data end end end # module DSL end # module Apipie
isClear = true; function context(description, spec) { describe(description, spec); }; function build() { $('body').append('<div id="element"></div>'); }; function buildDivTarget() { $('body').append('<div id="hint"></div>'); }; function buildComboboxTarget() { $('body').append( '<select id="hint">' + '<option value="Cancel this rating!">cancel hint default</option>' + '<option value="cancel-hint-custom">cancel hint custom</option>' + '<option value="">cancel number default</option>' + '<option value="0">cancel number custom</option>' + '<option value="bad">bad hint imutable</option>' + '<option value="1">bad number imutable</option>' + '<option value="targetText">targetText is setted without targetKeep</option>' + '<option value="score: bad">targetFormat</option>' + '</select>' ); }; function buildTextareaTarget() { $('body').append('<textarea id="hint"></textarea>'); }; function buildTextTarget() { $('body').append('<input id="hint" type="text" />'); }; function clear() { if (isClear) { $('#element').remove(); $('#hint').remove(); } }; describe('Raty', function() { beforeEach(function() { build(); }); afterEach(function() { clear(); }); it ('has the right values', function() { // given var raty = $.fn.raty // when var opt = raty.defaults // then expect(opt.cancel).toBeFalsy(); expect(opt.cancelHint).toEqual('Cancel this rating!'); expect(opt.cancelOff).toEqual('cancel-off.png'); expect(opt.cancelOn).toEqual('cancel-on.png'); expect(opt.cancelPlace).toEqual('left'); expect(opt.click).toBeUndefined(); expect(opt.half).toBeFalsy(); expect(opt.halfShow).toBeTruthy(); expect(opt.hints).toContain('bad', 'poor', 'regular', 'good', 'gorgeous'); expect(opt.iconRange).toBeUndefined(); expect(opt.mouseover).toBeUndefined(); expect(opt.noRatedMsg).toEqual('Not rated yet!'); expect(opt.number).toBe(5); expect(opt.path).toEqual(''); expect(opt.precision).toBeFalsy(); expect(opt.readOnly).toBeFalsy(); expect(opt.round.down).toEqual(.25); expect(opt.round.full).toEqual(.6); expect(opt.round.up).toEqual(.76); expect(opt.score).toBeUndefined(); expect(opt.scoreName).toEqual('score'); expect(opt.single).toBeFalsy(); expect(opt.size).toBe(16); expect(opt.space).toBeTruthy(); expect(opt.starHalf).toEqual('star-half.png'); expect(opt.starOff).toEqual('star-off.png'); expect(opt.starOn).toEqual('star-on.png'); expect(opt.target).toBeUndefined(); expect(opt.targetFormat).toEqual('{score}'); expect(opt.targetKeep).toBeFalsy(); expect(opt.targetText).toEqual(''); expect(opt.targetType).toEqual('hint'); expect(opt.width).toBeUndefined(); }); describe('common features', function() { it ('is chainable', function() { // given var self = $('#element'); // when var ref = self.raty(); // then expect(ref).toBe(self); }); it ('creates the default markup', function() { // given var self = $('#element'); // when self.raty(); // then var imgs = self.children('img'), score = self.children('input'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); expect(imgs).toHaveAttr('src', 'star-off.png'); expect(score).toHaveAttr('type', 'hidden'); expect(score).toHaveAttr('name', 'score'); expect(score.val()).toEqual(''); }); }); describe('#star', function() { it ('starts all off', function() { // given var self = $('#element'); // when self.raty(); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); context('on :mouseover', function() { it ('turns on the stars', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(4).mouseover(); // then expect(imgs).toHaveAttr('src', 'star-on.png'); }); context('and :mouseout', function() { it ('clears all stars', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(4).mouseover().mouseout(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); }); }); context('on rating', function() { it ('changes the score', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(1).mouseover().click(); // then expect(self.children('input')).toHaveValue(2); }); context('on :mouseout', function() { it ('keeps the stars on', function() { // given var self = $('#element').raty(), imgs = self.children('img'); // when imgs.eq(4).mouseover().click().mouseout(); // then expect(imgs).toHaveAttr('src', 'star-on.png'); }); }); }); }); describe('options', function() { describe('#numberMax', function() { it ('limits to 20 stars', function() { // given var self = $('#element').raty({ number: 50, score: 50 }); // when var score = self.raty('score'); // then expect(self.children('img').length).toEqual(20); expect(self.children('input')).toHaveValue(20); }); context('with custom numberMax', function() { it ('chages the limit', function() { // given var self = $('#element').raty({ numberMax: 10, number: 50, score: 50 }); // when var score = self.raty('score'); // then expect(self.children('img').length).toEqual(10); expect(self.children('input')).toHaveValue(10); }); }); }); describe('#starOff', function() { it ('changes the icons', function() { // given var self = $('#element'); // when self.raty({ starOff: 'icon.png' }); // then expect(self.children('img')).toHaveAttr('src', 'icon.png'); }); }); describe('#starOn', function() { it ('changes the icons', function() { // given var self = $('#element').raty({ starOn: 'icon.png' }), imgs = self.children('img'); // when imgs.eq(3).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(1)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(2)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(3)).toHaveAttr('src', 'icon.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); }); describe('#iconRange', function() { it ('uses icon intervals', function() { // given var self = $('#element'); // when self.raty({ iconRange: [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); context('when off icon is not especified', function() { it ('uses the :starOff icon', function() { // given var self = $('#element'); // when self.raty({ iconRange: [ { range: 2, on: 'on.png', off: 'off.png' }, { range: 3, on: 'on.png', off: 'off.png' }, { range: 4, on: 'on.png', off: 'off.png' }, { range: 5, on: 'on.png' } ] }); // then expect(self.children('img').eq(4)).toHaveAttr('src', 'star-off.png'); }); }); context('on mouseover', function() { it ('uses the on icon', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }), imgs = self.children('img'); // when imgs.eq(4).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd.png'); }); context('when on icon is not especified', function() { it ('uses the :starOn icon', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, off: 'off.png', on: 'on.png' }, { range: 3, off: 'off.png', on: 'on.png' }, { range: 4, off: 'off.png', on: 'on.png' }, { range: 5, off: 'off.png' } ] }), imgs = self.children('img'); // when imgs.eq(4).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'on.png'); expect(imgs.eq(1)).toHaveAttr('src', 'on.png'); expect(imgs.eq(2)).toHaveAttr('src', 'on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'on.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-on.png'); }); }); }); context('on mouseout', function() { it ('changes to off icons', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' }, ] }), imgs = self.children('img'); // when imgs.eq(4).mouseover(); self.mouseleave(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); it ('keeps the score value', function() { // given var self = $('#element').raty({ iconRange : [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ], score : 1 }); // when self.children('img').eq(4).mouseover(); self.mouseleave(); // then expect(self.children('input')).toHaveValue(1); }); context('when off icon is not especified', function() { it ('uses the :starOff icon', function() { // given var self = $('#element').raty({ iconRange: [ { range: 2, on: 'on.png', off: 'off.png' }, { range: 3, on: 'on.png', off: 'off.png' }, { range: 4, on: 'on.png', off: 'off.png' }, { range: 5, on: 'on.png' } ] }), img = self.children('img').eq(4); // when img.mouseover(); self.mouseleave(); // then expect(img).toHaveAttr('src', 'star-off.png'); }); }); }); }); describe('#click', function() { it ('has `this` as the self element', function() { // given var self = $('#element').raty({ click: function() { $(this).data('self', this); } }); // when self.children('img:first').mouseover().click(); // then expect(self.data('self')).toBe(self); }); it ('is called on star click', function() { // given var self = $('#element').raty({ click: function() { $(this).data('clicked', true); } }); // when self.children('img:first').mouseover().click(); // then expect(self.data('clicked')).toBeTruthy(); }); it ('receives the score', function() { // given var self = $('#element').raty({ click: function(score) { $(this).data('score', score); } }); // when self.children('img:first').mouseover().click(); // then expect(self.data('score')).toEqual(1); }); context('with :cancel', function() { it ('executes cancel click callback', function() { // given var self = $('#element').raty({ cancel: true, click : function(score) { $(this).data('score', null); } }); // when self.children('.raty-cancel').mouseover().click().mouseleave(); // then expect(self.data('score')).toBeNull(); }); }); }); describe('#score', function() { it ('starts with value', function() { // given var self = $('#element'); // when self.raty({ score: 1 }); // then expect(self.children('input')).toHaveValue(1); }); it ('turns on 1 stars', function() { // given var self = $('#element'); // when self.raty({ score: 1 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ score: function() { return 1; } }); // then expect(self.raty('score')).toEqual(1); }); context('with negative number', function() { it ('gets none score', function() { // given var self = $('#element'); // when self.raty({ score: -1 }); // then expect(self.children('input').val()).toEqual(''); }); }); context('with :readOnly', function() { it ('becomes readOnly too', function() { // given var self = $('#element'); // when self.raty({ readOnly: true }); // then expect(self.children('input')).toHaveAttr('readonly', 'readonly'); }); }); }); describe('#scoreName', function() { it ('changes the score field name', function() { // given var self = $('#element'); // when self.raty({ scoreName: 'entity.score' }); // then expect(self.children('input')).toHaveAttr('name', 'entity.score'); }); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ scoreName: function() { return 'custom'; } }); // then expect(self.data('settings').scoreName).toEqual('custom'); }); describe('#readOnly', function() { it ('Applies "Not rated yet!" on stars', function() { // given var self = $('#element'); // when self.raty({ readOnly: true }); // then expect(self.children('img')).toHaveAttr('title', 'Not rated yet!'); }); it ('removes the pointer cursor', function() { // given var self = $('#element'); // when self.raty({ readOnly: true }); // then expect(self).not.toHaveCss({ cursor: 'pointer' }); expect(self).not.toHaveCss({ cursor: 'default' }); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ readOnly: function() { return true; } }); // then expect(self.data('settings').readOnly).toEqual(true); }); it ('avoids trigger mouseover', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); // when imgs.eq(1).mouseover(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); it ('avoids trigger click', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); // when imgs.eq(1).mouseover().click().mouseleave(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); }); it ('avoids trigger mouseleave', function() { // given var self = $('#element').raty({ readOnly: true, mouseout: function() { $(this).data('mouseleave', true); } }), imgs = self.children('img'); imgs.eq(1).mouseover(); // when self.mouseleave(); // then expect(self.data('mouseleave')).toBeFalsy(); }); context('with :score', function() { context('as integer', function() { it ('applies the score title on stars', function() { // given var self = $('#element'); // when self.raty({ readOnly: true, score: 3 }); // then expect(self.children('img')).toHaveAttr('title', 'regular'); }); }); context('as float', function() { it ('applies the integer score title on stars', function() { // given var self = $('#element'); // when self.raty({ readOnly: true, score: 3.1 }); // then expect(self.children('img')).toHaveAttr('title', 'regular'); }); }); }); context('with :cancel', function() { it ('hides the button', function() { // given var self = $('#element'); // when self.raty({ cancel: true, readOnly: true, path: '../lib/img' }); // then expect(self.children('.raty-cancel')).toBeHidden(); }); }); }); describe('#hints', function() { it ('changes the hints', function() { // given var self = $('#element'); // when self.raty({ hints: ['1', '/', 'c', '-', ' // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 1); expect(imgs.eq(1)).toHaveAttr('title', '/'); expect(imgs.eq(2)).toHaveAttr('title', 'c'); expect(imgs.eq(3)).toHaveAttr('title', '-'); expect(imgs.eq(4)).toHaveAttr('title', ' }); it ('receives the number of the star when is undefined', function() { // given var self = $('#element'); // when self.raty({ hints: [undefined, 'a', 'b', 'c', 'd'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'a'); expect(imgs.eq(2)).toHaveAttr('title', 'b'); expect(imgs.eq(3)).toHaveAttr('title', 'c'); expect(imgs.eq(4)).toHaveAttr('title', 'd'); }); it ('receives empty when is empty string', function() { // given var self = $('#element'); // when self.raty({ hints: ['', 'a', 'b', 'c', 'd'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', ''); expect(imgs.eq(1)).toHaveAttr('title', 'a'); expect(imgs.eq(2)).toHaveAttr('title', 'b'); expect(imgs.eq(3)).toHaveAttr('title', 'c'); expect(imgs.eq(4)).toHaveAttr('title', 'd'); }); it ('receives the number of the star when is null', function() { // given var self = $('#element'); // when self.raty({ hints: [null, 'a', 'b', 'c', 'd'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 1); expect(imgs.eq(1)).toHaveAttr('title', 'a'); expect(imgs.eq(2)).toHaveAttr('title', 'b'); expect(imgs.eq(3)).toHaveAttr('title', 'c'); expect(imgs.eq(4)).toHaveAttr('title', 'd'); }); context('whe has less hint than stars', function() { it ('receives the default hint index', function() { // given var self = $('#element'); // when self.raty({ hints: ['1', '2', '3', '4'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 1); expect(imgs.eq(1)).toHaveAttr('title', 2); expect(imgs.eq(2)).toHaveAttr('title', 3); expect(imgs.eq(3)).toHaveAttr('title', 4); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); }); }); context('whe has more stars than hints', function() { it ('sets star number', function() { // given var self = $('#element'); // when self.raty({ number: 6, hints: ['a', 'b', 'c', 'd', 'e'] }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('title', 'a'); expect(imgs.eq(1)).toHaveAttr('title', 'b'); expect(imgs.eq(2)).toHaveAttr('title', 'c'); expect(imgs.eq(3)).toHaveAttr('title', 'd'); expect(imgs.eq(4)).toHaveAttr('title', 'e'); expect(imgs.eq(5)).toHaveAttr('title', 6); }); }); }); describe('#mouseover', function() { it ('receives the score as int', function() { // given var self = $('#element').raty({ mouseover: function(score) { $(this).data('score', score); } }); // when self.children('img:first').mouseover(); // then expect(self.data('score')).toEqual(1); }); it ('receives the event', function() { // given var self = $('#element').raty({ mouseover: function(score, evt) { $(this).data('evt', evt); } }); // when self.children('img:first').mouseover(); // then expect(self.data('evt').type).toEqual('mouseover'); }); context('with :cancel', function() { it ('receives null as score', function() { // given var self = $('#element').raty({ cancel : true, mouseover : function(score) { self.data('null', score); } }); // when self.children('.raty-cancel').mouseover(); // then expect(self.data('null')).toBeNull(); }); }); }); describe('#mouseout', function() { it ('receives the score as int', function() { // given var self = $('#element').raty({ mouseout: function(score) { $(this).data('score', score); } }); // when self.children('img:first').mouseover().click().mouseout(); // then expect(self.data('score')).toEqual(1); }); it ('receives the event', function() { // given var self = $('#element').raty({ mouseout: function(score, evt) { $(this).data('evt', evt); } }); // when self.children('img:first').mouseover().click().mouseout(); // then expect(self.data('evt').type).toEqual('mouseout'); }); context('without score setted', function() { it ('pass undefined on callback', function() { // given var self = $('#element').raty({ cancel : true, mouseout: function(score) { self.data('undefined', score === undefined); } }); // when self.children('img:first').mouseenter().mouseleave(); // then expect(self.data('undefined')).toBeTruthy(); }); }); context('with :score rated', function() { it ('pass the score on callback', function() { // given var self = $('#element').raty({ score : 1, mouseout: function(score) { self.data('score', score); } }); // when self.children('img:first').mouseenter().mouseleave(); // then expect(self.data('score')).toEqual(1); }); }); context('with :cancel', function() { it ('receives the event', function() { // given var self = $('#element').raty({ cancel : true, mouseout: function(score, evt) { $(this).data('evt', evt); } }); // when self.children('.raty-cancel').mouseover().click().mouseout(); // then expect(self.data('evt').type).toEqual('mouseout'); }); context('without score setted', function() { it ('pass undefined on callback', function() { // given var self = $('#element').raty({ mouseout: function(score) { self.data('undefined', score === undefined); }, cancel : true }); // when self.children('.raty-cancel').mouseenter().mouseleave(); // then expect(self.data('undefined')).toBeTruthy(); }); }); context('with :score rated', function() { it ('pass the score on callback', function() { // given var self = $('#element').raty({ mouseout: function(score) { self.data('score', score); }, cancel : true, score : 1 }); // when self.children('.raty-cancel').mouseenter().mouseleave(); // then expect(self.data('score')).toEqual(1); }); }); }); }); describe('#number', function() { it ('changes the number of stars', function() { // given var self = $('#element'); // when self.raty({ number: 1 }); // then expect(self.children('img').length).toEqual(1); }); it ('accepts number as string', function() { // given var self = $('#element'); // when self.raty({ number: '10' }); // then expect(self.children('img').length).toEqual(10); }); it ('accepts callback', function() { // given var self = $('#element'); // when self.raty({ number: function() { return 1; } }); // then expect(self.children('img').length).toEqual(1); }); }); describe('#path', function() { context('without last slash', function() { it ('receives the slash', function() { // given var self = $('#element'); // when self.raty({ path: 'path' }); // then expect(self[0].opt.path).toEqual('path/'); }); }); context('with last slash', function() { it ('keeps it', function() { // given var self = $('#element'); // when self.raty({ path: 'path/' }); // then expect(self[0].opt.path).toEqual('path/'); }); }); it ('changes the path', function() { // given var self = $('#element'); // when self.raty({ path: 'path' }); // then expect(self.children('img')).toHaveAttr('src', 'path/star-off.png'); }); context('without path', function() { it ('sets receives empty', function() { // given var self = $('#element'); // when self.raty({ path: null }); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); }); context('with :cancel', function() { it ('changes the path', function() { // given var self = $('#element'); // when self.raty({ cancel: true, path: 'path' }) // then expect(self.children('.raty-cancel')).toHaveAttr('src', 'path/cancel-off.png'); }); }); context('with :iconRange', function() { it ('changes the path', function() { // given var self = $('#element'); // when self.raty({ path : 'path', iconRange: [{ range: 5 }] }); // then expect(self.children('img')).toHaveAttr('src', 'path/star-off.png'); }); }); }); describe('#cancelOff', function() { it ('changes the icon', function() { // given var self = $('#element'); // when self.raty({ cancel: true, cancelOff: 'off.png' }); // then expect(self.children('.raty-cancel')).toHaveAttr('src', 'off.png'); }); }); describe('#cancelOn', function() { it ('changes the icon', function() { // given var self = $('#element').raty({ cancel: true, cancelOn: 'icon.png' }); // when var cancel = self.children('.raty-cancel').mouseover(); // then expect(cancel).toHaveAttr('src', 'icon.png'); }); }); describe('#cancelHint', function() { it ('changes the cancel hint', function() { // given var self = $('#element'); // when self.raty({ cancel: true, cancelHint: 'hint' }); // then expect(self.children('.raty-cancel')).toHaveAttr('title', 'hint'); }); }); describe('#cancelPlace', function() { it ('changes the place off cancel button', function() { // given var self = $('#element'); // when self.raty({ cancel: true, cancelPlace: 'right' }); // then var cancel = self.children('img:last'); expect(cancel).toHaveClass('raty-cancel'); expect(cancel).toHaveAttr('title', 'Cancel this rating!'); expect(cancel).toHaveAttr('alt', 'x'); expect(cancel).toHaveAttr('src', 'cancel-off.png'); }); }); describe('#cancel', function() { it ('creates the element', function() { // given var self = $('#element'); // when self.raty({ cancel: true }); // then var cancel = self.children('.raty-cancel'); expect(cancel).toHaveClass('raty-cancel'); expect(cancel).toHaveAttr('title', 'Cancel this rating!'); expect(cancel).toHaveAttr('alt', 'x'); expect(cancel).toHaveAttr('src', 'cancel-off.png'); }); context('on mouseover', function() { it ('turns on', function() { // given var self = $('#element').raty({ cancel: true }); // when var cancel = self.children('.raty-cancel').mouseover(); // then expect(cancel).toHaveAttr('src', 'cancel-on.png'); }); context('with :score', function() { it ('turns off the stars', function() { // given var self = $('#element').raty({ score: 3, cancel: true }), imgs = self.children('img:not(.raty-cancel)'); // when self.children('.raty-cancel').mouseover(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); }); }); context('when :mouseout', function() { it ('turns on', function() { // given var self = $('#element').raty({ cancel: true }); // when var cancel = self.children('.raty-cancel').mouseover().mouseout(); // then expect(cancel).toHaveAttr('src', 'cancel-off.png'); }); context('with :score', function() { it ('turns the star on again', function() { // given var self = $('#element').raty({ score: 4, cancel: true }), imgs = self.children('img:not(.raty-cancel)'); // when self.children('.raty-cancel').mouseover().mouseout(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); }); }); context('on click', function() { it ('cancel the rating', function() { // given var self = $('#element').raty({ cancel: true, score: 1 }); // when self.children('.raty-cancel').click().mouseout(); // then var stars = self.children('img:not(.raty-cancel)'); expect(stars).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); }); }); context('when starts :readOnly', function() { it ('starts hidden', function() { // given var self = $('#element').raty({ cancel: true, readOnly: true, path: '../img' }); // when self.raty('readOnly', true); // then expect(self.children('.raty-cancel')).toBeHidden(); }); context('on click', function() { it ('does not cancel the rating', function() { // given var self = $('#element').raty({ cancel: true, readOnly: true, score: 5 }); // when self.children('.raty-cancel').click().mouseout(); // then var stars = self.children('img:not(.raty-cancel)'); expect(stars).toHaveAttr('src', 'star-on.png'); expect(self.children('input').val()).toEqual('5'); }); }); }); context('when become :readOnly', function() { it ('becomes hidden', function() { // given var self = $('#element').raty({ cancel: true, path: '../img' }); // when self.raty('readOnly', true); // then expect(self.children('.raty-cancel')).toBeHidden(); }); }); }); describe('#targetType', function() { beforeEach(function() { buildDivTarget(); }); context('with missing target', function() { it ('throws error', function() { // given var self = $('#element'); // when var lambda = function() { self.raty({ target: 'missing' }); }; // then expect(lambda).toThrow(new Error('Target selector invalid or missing!')); }); }); context('as hint', function() { it ('receives the hint', function() { // given var self = $('#element').raty({ target: '#hint', targetType: 'hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml('bad'); }); context('with :cancel', function() { it ('receives the :cancelHint', function() { // given var self = $('#element').raty({ cancel: true, target: '#hint', targetType: 'hint' }); // when self.children('.raty-cancel').mouseover(); // then expect($('#hint')).toHaveHtml('Cancel this rating!'); }); }); }); context('as score', function() { it ('receives the score', function() { // given var self = $('#element').raty({ target: '#hint', targetType: 'score' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml(1); }); context('with :cancel', function() { it ('receives the :cancelHint', function() { // given var self = $('#element').raty({ cancel: true, target: '#hint', targetType: 'score' }); // when self.children('.raty-cancel').mouseover(); // then expect($('#hint')).toHaveHtml('Cancel this rating!'); }); }); }); }); describe('#targetText', function() { beforeEach(function() { buildDivTarget(); }); it ('set target with none value', function() { // given var self = $('#element'); // when self.raty({ target: '#hint', targetText: 'none' }); // then expect($('#hint')).toHaveHtml('none'); }); }); describe('#targetFormat', function() { context('with :target', function() { beforeEach(function() { buildDivTarget(); }); it ('stars empty', function() { // given var self = $('#element'); // when self.raty({ target: '#hint', targetFormat: 'score: {score}' }); // then expect($('#hint')).toBeEmpty(); }); context('with missing score key', function() { it ('throws error', function() { // given var self = $('#element'); // when var lambda = function() { self.raty({ target: '#hint', targetFormat: '' }); }; // then expect(lambda).toThrow(new Error('Template "{score}" missing!')); }); }); context('on mouseover', function() { it ('set target with format on mouseover', function() { // given var self = $('#element').raty({ target: '#hint', targetFormat: 'score: {score}' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml('score: bad'); }); }); context('on mouseout', function() { it ('clears the target', function() { // given var self = $('#element').raty({ target : '#hint', targetFormat: 'score: {score}' }); // when self.children('img:first').mouseover().mouseout(); // then expect($('#hint')).toBeEmpty(); }); context('with :targetKeep', function() { context('without score', function() { it ('clears the target', function() { // given var self = $('#element').raty({ target : '#hint', targetFormat: 'score: {score}', targetKeep : true }); // when self.children('img:first').mouseover().mouseleave(); // then expect($('#hint')).toBeEmpty(); }); }); context('with score', function() { it ('keeps the template', function() { // given var self = $('#element').raty({ score : 1, target : '#hint', targetFormat: 'score: {score}', targetKeep : true }); // when self.children('img:first').mouseover().mouseleave(); // then expect($('#hint')).toHaveHtml('score: bad'); }); }); }); }); }); }); describe('#precision', function() { beforeEach(function() { buildDivTarget(); }); it ('enables the :half options', function() { // given var self = $('#element'); // when self.raty({ precision: true }); // then expect(self.data('settings').half).toBeTruthy(); }); it ('changes the :targetType to score', function() { // given var self = $('#element'); // when self.raty({ precision: true }); // then expect(self.data('settings').targetType).toEqual('score'); }); context('with :target', function() { context('with :targetKeep', function() { context('with :score', function() { it ('sets the float with one fractional number', function() { // given var self = $('#element'); // when self.raty({ precision : true, score : 1.23, target : '#hint', targetKeep: true, targetType: 'score' }); // then expect($('#hint')).toHaveHtml('1.2'); }); }); }); }); }); describe('#target', function() { context('on mouseover', function() { context('as div', function() { beforeEach(function() { buildDivTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveHtml('bad'); }); }); context('as text field', function() { beforeEach(function() { buildTextTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveValue('bad'); }); }); context('as textarea', function() { beforeEach(function() { buildTextareaTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveValue('bad'); }); }); context('as combobox', function() { beforeEach(function() { buildComboboxTarget(); }); it ('sets the hint', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover(); // then expect($('#hint')).toHaveValue('bad'); }); }); }); context('on mouseout', function() { context('as div', function() { beforeEach(function() { buildDivTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').mouseover().click().mouseleave(); // then expect($('#hint')).toBeEmpty(); }); }); context('as textarea', function() { beforeEach(function() { buildTextareaTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').click().mouseover().mouseleave(); // then expect($('#hint')).toHaveValue(''); }); }); context('as text field', function() { beforeEach(function() { buildTextTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').click().mouseover().mouseleave(); // then expect($('#hint')).toHaveValue(''); }); }); context('as combobox', function() { beforeEach(function() { buildComboboxTarget(); }); it ('gets clear', function() { // given var self = $('#element').raty({ target: '#hint' }); // when self.children('img:first').click().mouseover().mouseleave(); // then expect($('#hint')).toHaveValue(''); }); }); }); }); describe('#size', function() { it ('calculate the right icon size', function() { // given var self = $('#element'), size = 24, stars = 5, space = 4; // when self.raty({ size: size }); // then expect(self.width()).toEqual((stars * size) + (stars * space)); }); context('with :cancel', function() { it ('addes the cancel and space witdh', function() { // given var self = $('#element'), size = 24, stars = 5, cancel = size, space = 4; // when self.raty({ cancel: true, size: size }); // then expect(self.width()).toEqual(cancel + space + (stars * size) + (stars * space)); }); }); }); describe('#space', function() { context('when off', function() { it ('takes off the space', function() { // given var self = $('#element'); size = 16, stars = 5; // when self.raty({ space: false }); // then expect(self.width()).toEqual(size * stars); }); context('with :cancel', function() { it ('takes off the space', function() { // given var self = $('#element'); size = 16, stars = 5, cancel = size; // when self.raty({ cancel: true, space: false }); // then expect(self.width()).toEqual(cancel + (size * stars)); }); }); }); }); describe('#single', function() { context('on mouseover', function() { it ('turns on just one icon', function() { // given var self = $('#element').raty({ single: true }), imgs = self.children('img'); // when imgs.eq(2).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); context('with :iconRange', function() { it ('shows just on icon', function() { // given var self = $('#element').raty({ single : true, iconRange : [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }), imgs = self.children('img'); // when imgs.eq(3).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); }); }); context('on click', function() { context('on mouseout', function() { it ('keeps the score', function() { // given var self = $('#element').raty({ single: true }) imgs = self.children('img'); // when imgs.eq(2).mouseover().click().mouseleave(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png'); expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png'); }); context('and :iconRange', function() { it ('keeps the score', function() { // given var self = $('#element').raty({ single : true, iconRange : [ { range: 2, on: 'a.png', off: 'a-off.png' }, { range: 3, on: 'b.png', off: 'b-off.png' }, { range: 4, on: 'c.png', off: 'c-off.png' }, { range: 5, on: 'd.png', off: 'd-off.png' } ] }), imgs = self.children('img'); // when imgs.eq(3).mouseover().click().mouseleave(); // then expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png'); expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png'); expect(imgs.eq(3)).toHaveAttr('src', 'c.png'); expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png'); }); }); }); }); }); describe('#width', function() { it ('set custom width', function() { // given var self = $('#element'); // when self.raty({ width: 200 }); // then expect(self.width()).toEqual(200); }); describe('when it is false', function() { it ('does not apply the style', function() { // given var self = $('#element'); // when self.raty({ width: false }); // then expect(self).not.toHaveCss({ width: '100px' }); }); }); describe('when :readOnly', function() { it ('set custom width when readOnly', function() { // given var self = $('#element'); // when self.raty({ readOnly: true, width: 200 }); // then expect(self.width()).toEqual(200); }); }); }); describe('#half', function() { context('as false', function() { context('#halfShow', function() { context('as false', function() { it ('rounds down while less the full limit', function() { // given var self = $('#element'); // when self.raty({ half : false, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .5 }); var imgs = self.children('img'); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png'); }); it ('rounds full when equal the full limit', function() { // given var self = $('#element'); // when self.raty({ half : false, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .6 }); var imgs = self.children('img'); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); }); }); }); context('as true', function() { context('#halfShow', function() { context('as false', function() { it ('ignores round down while less down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .24 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual('0.24'); }); it ('ignores half while greater then down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .26 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual('0.26'); }); it ('ignores half while equal full limit, ignoring it', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .6 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(self.children('input').val()).toEqual('0.6'); }); it ('ignores half while greater than down limit and less than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .75 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); expect(self.children('input').val()).toEqual('0.75'); }); it ('ignores full while equal or greater than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: false, round : { down: .25, full: .6, up: .76 }, score : .76 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); }); context('as true', function() { it ('rounds down while less down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .24 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png'); }); it ('receives half while greater then down limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .26 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png'); }); it ('receives half while equal full limit, ignoring it', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .6 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png'); }); it ('receives half while greater than down limit and less than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .75 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png'); }); it ('receives full while equal or greater than up limit', function() { // given var self = $('#element'); // when self.raty({ half : true, halfShow: true, round : { down: .25, full: .6, up: .76 }, score : .76 }); // then var imgs = self.children('img'); expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); }); }); context('with :target', function() { beforeEach(function() { buildDivTarget(); }); context('and :precision', function() { context('and :targetType as score', function() { context('and :targetKeep', function() { context('and :targetType as score', function() { it ('set .5 increment value target with half option and no precision', function() { // given var self = $('#element'); // when self.raty({ half : true, precision : false, score : 1.5, target : '#hint', targetKeep: true, targetType: 'score' }); // then expect($('#hint')).toHaveHtml('1.5'); }); }); }); }); }); }); }); }); }); describe('class bind', function() { beforeEach(function() { $('body').append('<div class="element"></div><div class="element"></div>'); }); afterEach(function() { $('.element').remove(); }); it ('is chainable', function() { // given var self = $('.element'); // when var refs = self.raty(); // then expect(refs.eq(0)).toBe(self.eq(0)); expect(refs.eq(1)).toBe(self.eq(1)); }); it ('creates the default markup', function() { // given var self = $('.element'); // when self.raty(); // then var imgs = self.eq(0).children('img'), score = self.eq(0).children('input'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); expect(imgs).toHaveAttr('src', 'star-off.png'); expect(score).toHaveAttr('type', 'hidden'); expect(score).toHaveAttr('name', 'score'); expect(score.val()).toEqual(''); imgs = self.eq(1).children('img'); score = self.eq(0).children('input'); expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); expect(imgs).toHaveAttr('src', 'star-off.png'); expect(score).toHaveAttr('type', 'hidden'); expect(score).toHaveAttr('name', 'score'); expect(score.val()).toEqual(''); }); }); describe('functions', function() { describe('GET #score', function() { it ('accepts number as string', function() { // given var self = $('#element'); // when self.raty({ score: '1' }); // then expect(self.children('input')).toHaveValue(1); }); it ('accepts float string', function() { // given var self = $('#element'); // when self.raty({ score: '1.5' }); // then expect(self.children('input')).toHaveValue(1.5); }); context('with integer score', function() { it ('gets as int', function() { // given var self = $('#element').raty({ score: 1 }); // when var score = self.raty('score'); // then expect(score).toEqual(1); }); }); context('with float score', function() { it ('gets as float', function() { // given var self = $('#element').raty({ score: 1.5 }); // when var score = self.raty('score'); // then expect(score).toEqual(1.5); }); }); context('with score zero', function() { it ('gets null to emulate cancel', function() { // given var self = $('#element').raty({ score: 0 }); // when var score = self.raty('score'); // then expect(score).toEqual(null); }); }); context('with score greater than :numberMax', function() { it ('gets the max', function() { // given var self = $('#element').raty({ number: 50, score: 50 }); // when var score = self.raty('score'); // then expect(score).toEqual(self.data('settings').numberMax); }); }); }); describe('SET #score', function() { it ('sets the score', function() { // given var self = $('#element'); // when self.raty({ score: 1 }); // then expect(self.raty('score')).toEqual(1); }); describe('with :click', function() { it ('calls the click callback', function() { // given var self = $('#element').raty({ click: function(score) { $(this).data('score', score); } }); // when self.raty('score', 5); // then expect(self.children('img')).toHaveAttr('src', 'star-on.png'); }); }); describe('without :click', function() { it ('does not throw exception', function() { // given var self = $('#element').raty(); // when var lambda = function() { self.raty('score', 1); }; // then expect(lambda).not.toThrow(new Error('You must add the "click: function(score, evt) { }" callback.')); }); }); describe('with :readOnly', function() { it ('does not set the score', function() { // given var self = $('#element').raty({ readOnly: true }); // when self.raty('score', 5); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); }); }); describe('#set', function() { it ('is chainable', function() { // given var self = $('#element').raty(); // when var ref = self.raty('set', { number: 1 }); // then expect(ref).toBe(self); }); it ('changes the declared options', function() { // given var self = $('#element').raty(); // when var ref = self.raty('set', { scoreName: 'change-just-it' }); // then expect(ref.children('input')).toHaveAttr('name', 'change-just-it'); }); it ('does not change other none declared options', function() { // given var self = $('#element').raty({ number: 6 }); // when var ref = self.raty('set', { scoreName: 'change-just-it' }); // then expect(ref.children('img').length).toEqual(6); }); context('with external bind on wrapper', function() { it ('keeps it', function() { // given var self = $('#element').on('click', function() { $(this).data('externalClick', true); }).raty(); // when self.raty('set', {}).click(); // then expect(self.data('externalClick')).toBeTruthy(); }); }); context('when :readOnly by function', function() { it ('is removes the readonly data info', function() { // given var self = $('#element').raty().raty('readOnly', true); // when var ref = self.raty('set', { readOnly: false }); // then expect(self).not.toHaveData('readonly'); }); }); }); describe('#readOnly', function() { context('changes to true', function() { it ('sets score as readonly', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', true); // then expect(self.children('input')).toHaveAttr('readonly', 'readonly'); }); it ('removes the pointer cursor', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', true); // then expect(self).not.toHaveCss({ cursor: 'pointer' }); expect(self).not.toHaveCss({ cursor: 'default' }); }); it ('Applies "Not rated yet!" on stars', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', true); // then expect(self.children('img')).toHaveAttr('title', 'Not rated yet!'); }); it ('avoids trigger mouseover', function() { // given var self = $('#element').raty(), imgs = self.children('img'); self.raty('readOnly', true); // when imgs.eq(0).mouseover(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); it ('avoids trigger click', function() { // given var self = $('#element').raty(), imgs = self.children('img'); self.raty('readOnly', true); // when imgs.eq(0).mouseover().click().mouseleave(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); }); context('with :score', function() { it ('applies the score title on stars', function() { // given var self = $('#element').raty({ score: 1 }); // when self.raty('readOnly', true); // then expect(self.children('img')).toHaveAttr('title', 'bad'); }); }); context('with :cancel', function() { it ('hides the button', function() { // given var self = $('#element').raty({ cancel: true, path: '../lib/img' }); // when self.raty('readOnly', true); // then expect(self.children('.raty-cancel')).toBeHidden(); }); }); context('with external bind on wrapper', function() { it ('keeps it', function() { // given var self = $('#element').on('click', function() { $(this).data('externalClick', true); }).raty(); // when self.raty('readOnly', true).click(); // then expect(self.data('externalClick')).toBeTruthy(); }); }); context('with external bind on stars', function() { it ('keeps it', function() { // given var self = $('#element').raty(), star = self.children('img').first(); star.on('click', function() { self.data('externalClick', true); }); // when self.raty('readOnly', true); star.click(); // then expect(self.data('externalClick')).toBeTruthy(); }); }); }); context('changes to false', function() { it ('removes the :readOnly of the score', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', false); // then expect(self.children('input')).not.toHaveAttr('readonly', 'readonly'); }); it ('applies the pointer cursor on wrapper', function() { // given var self = $('#element').raty(); // when self.raty('readOnly', false); // then expect(self).toHaveCss({ cursor: 'pointer' }); }); it ('Removes the "Not rated yet!" off the stars', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); // when self.raty('readOnly', false); // then expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); }); it ('triggers mouseover', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); self.raty('readOnly', false); // when imgs.eq(0).mouseover(); // then expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png'); }); it ('triggers click', function() { // given var self = $('#element').raty({ readOnly: true }), imgs = self.children('img'); self.raty('readOnly', false); // when imgs.eq(0).mouseover().click().mouseleave(); // then expect(imgs).toHaveAttr('src', 'star-on.png'); expect(self.children('input')).toHaveValue('1'); }); context('with :score', function() { it ('removes the score title off the stars', function() { // given var self = $('#element').raty({ readOnly: true, score: 3 }); // when self.raty('readOnly', false); // then var imgs = self.children('img') expect(imgs.eq(0)).toHaveAttr('title', 'bad'); expect(imgs.eq(1)).toHaveAttr('title', 'poor'); expect(imgs.eq(2)).toHaveAttr('title', 'regular'); expect(imgs.eq(3)).toHaveAttr('title', 'good'); expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous'); }); }); context('with :cancel', function() { it ('shows the button', function() { // given var self = $('#element').raty({ readOnly: true, cancel: true, path: '../lib/img' }); // when self.raty('readOnly', false); // then expect(self.children('.raty-cancel')).toBeVisible(); expect(self.children('.raty-cancel')).not.toHaveCss({ display: 'block' }); }); it ('rebinds the mouseover', function() { // given var self = $('#element').raty({ readOnly: true, cancel: true }), cancel = self.children('.raty-cancel'), imgs = self.children('img:not(.raty-cancel)'); // when self.raty('readOnly', false); cancel.mouseover(); // then expect(cancel).toHaveAttr('src', 'cancel-on.png'); expect(imgs).toHaveAttr('src', 'star-off.png'); }); it ('rebinds the click', function() { // given var self = $('#element').raty({ readOnly: true, cancel: true, score: 5 }), imgs = self.children('img:not(.raty-cancel)'); // when self.raty('readOnly', false); self.children('.raty-cancel').click().mouseout(); // then expect(imgs).toHaveAttr('src', 'star-off.png'); }); }); }); }); describe('#cancel', function() { describe('with :readOnly', function() { it ('does not cancel', function() { // given var self = $('#element').raty({ readOnly: true, score: 5 }); // when self.raty('cancel'); // then expect(self.children('img')).toHaveAttr('src', 'star-on.png'); }); }); context('without click trigger', function() { it ('cancel the rating', function() { // given var self = $('#element').raty({ score: 1, click: function() { $(this).data('clicked', true); } }); // when self.raty('cancel'); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); expect(self.data('clicked')).toBeFalsy(); }); }); context('with click trigger', function() { it ('cancel the rating', function() { // given var self = $('#element').raty({ score: 1, click: function() { $(this).data('clicked', true); } }); // when self.raty('cancel', true); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); expect(self.children('input').val()).toEqual(''); expect(self.data('clicked')).toBeTruthy(); }); }); context('with :target', function() { beforeEach(function() { buildDivTarget(); }); context('and :targetKeep', function() { it ('sets the :targetText on target', function() { // given var hint = $('#hint').html('dirty'), self = $('#element').raty({ cancel : true, target : '#hint', targetKeep: true, targetText: 'targetText' }); // when self.raty('cancel'); // then expect(hint).toHaveHtml('targetText'); }); }); }); }); describe('#click', function() { it ('clicks on star', function() { // given var self = $('#element').raty({ click: function() { $(this).data('clicked', true); } }); // when self.raty('click', 1); // then expect(self.children('img')).toHaveAttr('src', 'star-on.png'); expect(self.data('clicked')).toBeTruthy(); }); it ('receives the score', function() { // given var self = $('#element').raty({ click: function(score) { $(this).data('score', score); } }); // when self.raty('click', 1); // then expect(self.data('score')).toEqual(1); }); it ('receives the event', function() { // given var self = $('#element').raty({ click: function(score, evt) { $(this).data('evt', evt); } }); // when self.raty('click', 1); // then expect(self.data('evt').type).toEqual('click'); }); describe('with :readOnly', function() { it ('does not set the score', function() { // given var self = $('#element').raty({ readOnly: true }); // when self.raty('click', 1); // then expect(self.children('img')).toHaveAttr('src', 'star-off.png'); }); }); context('without :click', function() { it ('throws error', function() { // given var self = $('#element').raty(); // when var lambda = function() { self.raty('click', 1); }; // then expect(lambda).toThrow(new Error('You must add the "click: function(score, evt) { }" callback.')); }); }); context('with :target', function() { beforeEach(function() { buildDivTarget(); }); context('and :targetKeep', function() { it ('sets the score on target', function() { // given var self = $('#element').raty({ target : '#hint', targetKeep: true, click : function() { } }); // when self.raty('click', 1); // then expect($('#hint')).toHaveHtml('bad'); }); }); }); }); describe('#reload', function() { it ('is chainable', function() { // given var self = $('#element').raty(); // when var ref = self.raty('reload'); // then expect(ref).toBe(self); }); it ('reloads with the same configuration', function() { // given var self = $('#element').raty({ number: 6 }); // when var ref = self.raty('reload'); // then expect(ref.children('img').length).toEqual(6); }); context('when :readOnly by function', function() { it ('is removes the readonly data info', function() { // given var self = $('#element').raty().raty('readOnly', true); // when var ref = self.raty('reload'); // then expect(self).not.toHaveData('readonly'); }); }); }); describe('#destroy', function() { it ('is chainable', function() { // given var self = $('#element').raty(); // when var ref = self.raty('destroy'); // then expect(ref).toBe(self); }); it ('clear the content', function() { // given var self = $('#element').raty(); // when self.raty('destroy'); // then expect(self).toBeEmpty(); }); it ('removes the trigger mouseleave', function() { // given var self = $('#element').raty({ mouseout: function() { console.log(this); $(this).data('mouseleave', true); } }); self.raty('destroy'); // when self.mouseleave(); // then expect(self.data('mouseleave')).toBeFalsy(); }); it ('resets the style attributes', function() { // given var self = $('#element').css({ cursor: 'help', width: 10 }).raty(); // when self.raty('destroy'); // then expect(self[0].style.cursor).toEqual('help'); expect(self[0].style.width).toEqual('10px'); }); }); }); });
#include "config-host.h" #include "qemu-common.h" #include "trace.h" #include "block/block_int.h" #include "block/blockjob.h" #include "qemu/module.h" #include "qapi/qmp/qjson.h" #include "sysemu/block-backend.h" #include "sysemu/sysemu.h" #include "qemu/notify.h" #include "block/coroutine.h" #include "block/qapi.h" #include "qmp-commands.h" #include "qemu/timer.h" #include "qapi-event.h" #ifdef CONFIG_BSD #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/queue.h> #ifndef __DragonFly__ #include <sys/disk.h> #endif #endif #ifdef _WIN32 #include <windows.h> #endif struct BdrvDirtyBitmap { HBitmap *bitmap; QLIST_ENTRY(BdrvDirtyBitmap) list; }; #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */ static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, BlockCompletionFunc *cb, void *opaque); static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, BlockCompletionFunc *cb, void *opaque); static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *iov); static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *iov); static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs, int64_t offset, unsigned int bytes, QEMUIOVector *qiov, BdrvRequestFlags flags); static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs, int64_t offset, unsigned int bytes, QEMUIOVector *qiov, BdrvRequestFlags flags); static BlockAIOCB *<API key>(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, BdrvRequestFlags flags, BlockCompletionFunc *cb, void *opaque, bool is_write); static void coroutine_fn bdrv_co_do_rw(void *opaque); static int coroutine_fn <API key>(BlockDriverState *bs, int64_t sector_num, int nb_sectors, BdrvRequestFlags flags); static QTAILQ_HEAD(, BlockDriverState) bdrv_states = <API key>(bdrv_states); static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states = <API key>(graph_bdrv_states); static QLIST_HEAD(, BlockDriver) bdrv_drivers = <API key>(bdrv_drivers); /* If non-zero, use only whitelisted block drivers */ static int use_bdrv_whitelist; #ifdef _WIN32 static int <API key>(const char *filename) { return (((filename[0] >= 'a' && filename[0] <= 'z') || (filename[0] >= 'A' && filename[0] <= 'Z')) && filename[1] == ':'); } int is_windows_drive(const char *filename) { if (<API key>(filename) && filename[2] == '\0') return 1; if (strstart(filename, "\\\\.\\", NULL) || strstart(filename, "//./", NULL)) return 1; return 0; } #endif /* throttling disk I/O limits */ void bdrv_set_io_limits(BlockDriverState *bs, ThrottleConfig *cfg) { int i; throttle_config(&bs->throttle_state, cfg); for (i = 0; i < 2; i++) { qemu_co_enter_next(&bs->throttled_reqs[i]); } } /* this function drain all the throttled IOs */ static bool <API key>(BlockDriverState *bs) { bool drained = false; bool enabled = bs->io_limits_enabled; int i; bs->io_limits_enabled = false; for (i = 0; i < 2; i++) { while (qemu_co_enter_next(&bs->throttled_reqs[i])) { drained = true; } } bs->io_limits_enabled = enabled; return drained; } void <API key>(BlockDriverState *bs) { bs->io_limits_enabled = false; <API key>(bs); throttle_destroy(&bs->throttle_state); } static void <API key>(void *opaque) { BlockDriverState *bs = opaque; qemu_co_enter_next(&bs->throttled_reqs[0]); } static void <API key>(void *opaque) { BlockDriverState *bs = opaque; qemu_co_enter_next(&bs->throttled_reqs[1]); } /* should be called before bdrv_set_io_limits if a limit is set */ void <API key>(BlockDriverState *bs) { assert(!bs->io_limits_enabled); throttle_init(&bs->throttle_state, <API key>(bs), QEMU_CLOCK_VIRTUAL, <API key>, <API key>, bs); bs->io_limits_enabled = true; } /* This function makes an IO wait if needed * * @nb_sectors: the number of sectors of the IO * @is_write: is the IO a write */ static void <API key>(BlockDriverState *bs, unsigned int bytes, bool is_write) { /* does this io must wait */ bool must_wait = <API key>(&bs->throttle_state, is_write); /* if must wait or any request of this type throttled queue the IO */ if (must_wait || !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) { qemu_co_queue_wait(&bs->throttled_reqs[is_write]); } /* the IO will be executed, do the accounting */ throttle_account(&bs->throttle_state, is_write, bytes); /* if the next request must wait -> do nothing */ if (<API key>(&bs->throttle_state, is_write)) { return; } /* else queue next request for execution */ qemu_co_queue_next(&bs->throttled_reqs[is_write]); } size_t bdrv_opt_mem_align(BlockDriverState *bs) { if (!bs || !bs->drv) { /* 4k should be on the safe side */ return 4096; } return bs->bl.opt_mem_alignment; } /* check if the path starts with "<protocol>:" */ static int path_has_protocol(const char *path) { const char *p; #ifdef _WIN32 if (is_windows_drive(path) || <API key>(path)) { return 0; } p = path + strcspn(path, ":/\\"); #else p = path + strcspn(path, ":/"); #endif return *p == ':'; } int path_is_absolute(const char *path) { #ifdef _WIN32 /* specific case for names like: "\\.\d:" */ if (is_windows_drive(path) || <API key>(path)) { return 1; } return (*path == '/' || *path == '\\'); #else return (*path == '/'); #endif } /* if filename is absolute, just copy it to dest. Otherwise, build a path to it by considering it is relative to base_path. URL are supported. */ void path_combine(char *dest, int dest_size, const char *base_path, const char *filename) { const char *p, *p1; int len; if (dest_size <= 0) return; if (path_is_absolute(filename)) { pstrcpy(dest, dest_size, filename); } else { p = strchr(base_path, ':'); if (p) p++; else p = base_path; p1 = strrchr(base_path, '/'); #ifdef _WIN32 { const char *p2; p2 = strrchr(base_path, '\\'); if (!p1 || p2 > p1) p1 = p2; } #endif if (p1) p1++; else p1 = base_path; if (p1 > p) p = p1; len = p - base_path; if (len > dest_size - 1) len = dest_size - 1; memcpy(dest, base_path, len); dest[len] = '\0'; pstrcat(dest, dest_size, filename); } } void <API key>(BlockDriverState *bs, char *dest, size_t sz) { if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) { pstrcpy(dest, sz, bs->backing_file); } else { path_combine(dest, sz, bs->filename, bs->backing_file); } } void bdrv_register(BlockDriver *bdrv) { /* Block drivers without coroutine functions need emulation */ if (!bdrv->bdrv_co_readv) { bdrv->bdrv_co_readv = bdrv_co_readv_em; bdrv->bdrv_co_writev = bdrv_co_writev_em; /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if * the block driver lacks aio we need to emulate that too. */ if (!bdrv->bdrv_aio_readv) { /* add AIO emulation layer */ bdrv->bdrv_aio_readv = bdrv_aio_readv_em; bdrv->bdrv_aio_writev = bdrv_aio_writev_em; } } QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list); } BlockDriverState *bdrv_new_root(void) { BlockDriverState *bs = bdrv_new(); QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list); return bs; } BlockDriverState *bdrv_new(void) { BlockDriverState *bs; int i; bs = g_new0(BlockDriverState, 1); QLIST_INIT(&bs->dirty_bitmaps); for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { QLIST_INIT(&bs->op_blockers[i]); } <API key>(bs); notifier_list_init(&bs->close_notifiers); <API key>(&bs-><API key>); qemu_co_queue_init(&bs->throttled_reqs[0]); qemu_co_queue_init(&bs->throttled_reqs[1]); bs->refcnt = 1; bs->aio_context = <API key>(); return bs; } void <API key>(BlockDriverState *bs, Notifier *notify) { notifier_list_add(&bs->close_notifiers, notify); } BlockDriver *bdrv_find_format(const char *format_name) { BlockDriver *drv1; QLIST_FOREACH(drv1, &bdrv_drivers, list) { if (!strcmp(drv1->format_name, format_name)) { return drv1; } } return NULL; } static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only) { static const char *whitelist_rw[] = { <API key> }; static const char *whitelist_ro[] = { <API key> }; const char **p; if (!whitelist_rw[0] && !whitelist_ro[0]) { return 1; /* no whitelist, anything goes */ } for (p = whitelist_rw; *p; p++) { if (!strcmp(drv->format_name, *p)) { return 1; } } if (read_only) { for (p = whitelist_ro; *p; p++) { if (!strcmp(drv->format_name, *p)) { return 1; } } } return 0; } BlockDriver *<API key>(const char *format_name, bool read_only) { BlockDriver *drv = bdrv_find_format(format_name); return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL; } typedef struct CreateCo { BlockDriver *drv; char *filename; QemuOpts *opts; int ret; Error *err; } CreateCo; static void coroutine_fn <API key>(void *opaque) { Error *local_err = NULL; int ret; CreateCo *cco = opaque; assert(cco->drv); ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err); if (local_err) { error_propagate(&cco->err, local_err); } cco->ret = ret; } int bdrv_create(BlockDriver *drv, const char* filename, QemuOpts *opts, Error **errp) { int ret; Coroutine *co; CreateCo cco = { .drv = drv, .filename = g_strdup(filename), .opts = opts, .ret = NOT_DONE, .err = NULL, }; if (!drv->bdrv_create) { error_setg(errp, "Driver '%s' does not support image creation", drv->format_name); ret = -ENOTSUP; goto out; } if (qemu_in_coroutine()) { /* Fast-path if already in coroutine context */ <API key>(&cco); } else { co = <API key>(<API key>); <API key>(co, &cco); while (cco.ret == NOT_DONE) { aio_poll(<API key>(), true); } } ret = cco.ret; if (ret < 0) { if (cco.err) { error_propagate(errp, cco.err); } else { error_setg_errno(errp, -ret, "Could not create image"); } } out: g_free(cco.filename); return ret; } int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp) { BlockDriver *drv; Error *local_err = NULL; int ret; drv = bdrv_find_protocol(filename, true); if (drv == NULL) { error_setg(errp, "Could not find protocol for file '%s'", filename); return -ENOENT; } ret = bdrv_create(drv, filename, opts, &local_err); if (local_err) { error_propagate(errp, local_err); } return ret; } void bdrv_refresh_limits(BlockDriverState *bs, Error **errp) { BlockDriver *drv = bs->drv; Error *local_err = NULL; memset(&bs->bl, 0, sizeof(bs->bl)); if (!drv) { return; } /* Take some limits from the children as a default */ if (bs->file) { bdrv_refresh_limits(bs->file, &local_err); if (local_err) { error_propagate(errp, local_err); return; } bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length; bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment; } else { bs->bl.opt_mem_alignment = 512; } if (bs->backing_hd) { bdrv_refresh_limits(bs->backing_hd, &local_err); if (local_err) { error_propagate(errp, local_err); return; } bs->bl.opt_transfer_length = MAX(bs->bl.opt_transfer_length, bs->backing_hd->bl.opt_transfer_length); bs->bl.opt_mem_alignment = MAX(bs->bl.opt_mem_alignment, bs->backing_hd->bl.opt_mem_alignment); } /* Then let the driver override it */ if (drv->bdrv_refresh_limits) { drv->bdrv_refresh_limits(bs, errp); } } /* * Create a uniquely-named empty temporary file. * Return 0 upon success, otherwise a negative errno value. */ int get_tmp_filename(char *filename, int size) { #ifdef _WIN32 char temp_dir[MAX_PATH]; /* GetTempFileName requires that its output buffer (4th param) have length MAX_PATH or greater. */ assert(size >= MAX_PATH); return (GetTempPath(MAX_PATH, temp_dir) && GetTempFileName(temp_dir, "qem", 0, filename) ? 0 : -GetLastError()); #else int fd; const char *tmpdir; tmpdir = getenv("TMPDIR"); if (!tmpdir) { tmpdir = "/var/tmp"; } if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) { return -EOVERFLOW; } fd = mkstemp(filename); if (fd < 0) { return -errno; } if (close(fd) != 0) { unlink(filename); return -errno; } return 0; #endif } /* * Detect host devices. By convention, /dev/cdrom[N] is always * recognized as a host CDROM. */ static BlockDriver *find_hdev_driver(const char *filename) { int score_max = 0, score; BlockDriver *drv = NULL, *d; QLIST_FOREACH(d, &bdrv_drivers, list) { if (d->bdrv_probe_device) { score = d->bdrv_probe_device(filename); if (score > score_max) { score_max = score; drv = d; } } } return drv; } BlockDriver *bdrv_find_protocol(const char *filename, bool <API key>) { BlockDriver *drv1; char protocol[128]; int len; const char *p; /* TODO Drivers without bdrv_file_open must be specified explicitly */ /* * XXX(hch): we really should not let host device detection * override an explicit protocol specification, but moving this * later breaks access to device names with colons in them. * Thanks to the brain-dead persistent naming schemes on udev- * based Linux systems those actually are quite common. */ drv1 = find_hdev_driver(filename); if (drv1) { return drv1; } if (!path_has_protocol(filename) || !<API key>) { return bdrv_find_format("file"); } p = strchr(filename, ':'); assert(p != NULL); len = p - filename; if (len > sizeof(protocol) - 1) len = sizeof(protocol) - 1; memcpy(protocol, filename, len); protocol[len] = '\0'; QLIST_FOREACH(drv1, &bdrv_drivers, list) { if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) { return drv1; } } return NULL; } static int find_image_format(BlockDriverState *bs, const char *filename, BlockDriver **pdrv, Error **errp) { int score, score_max; BlockDriver *drv1, *drv; uint8_t buf[2048]; int ret = 0; /* Return the raw BlockDriver * to scsi-generic devices or empty drives */ if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) { drv = bdrv_find_format("raw"); if (!drv) { error_setg(errp, "Could not find raw image format"); ret = -ENOENT; } *pdrv = drv; return ret; } ret = bdrv_pread(bs, 0, buf, sizeof(buf)); if (ret < 0) { error_setg_errno(errp, -ret, "Could not read image for determining its " "format"); *pdrv = NULL; return ret; } score_max = 0; drv = NULL; QLIST_FOREACH(drv1, &bdrv_drivers, list) { if (drv1->bdrv_probe) { score = drv1->bdrv_probe(buf, ret, filename); if (score > score_max) { score_max = score; drv = drv1; } } } if (!drv) { error_setg(errp, "Could not determine image format: No compatible " "driver found"); ret = -ENOENT; } *pdrv = drv; return ret; } /** * Set the current 'total_sectors' value * Return 0 on success, -errno on error. */ static int <API key>(BlockDriverState *bs, int64_t hint) { BlockDriver *drv = bs->drv; /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */ if (bs->sg) return 0; /* query actual device if possible, otherwise just trust the hint */ if (drv->bdrv_getlength) { int64_t length = drv->bdrv_getlength(bs); if (length < 0) { return length; } hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE); } bs->total_sectors = hint; return 0; } /** * Set open flags for a given discard mode * * Return 0 on success, -1 if the discard mode was invalid. */ int <API key>(const char *mode, int *flags) { *flags &= ~BDRV_O_UNMAP; if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) { /* do nothing */ } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) { *flags |= BDRV_O_UNMAP; } else { return -1; } return 0; } /** * Set open flags for a given cache mode * * Return 0 on success, -1 if the cache mode was invalid. */ int <API key>(const char *mode, int *flags) { *flags &= ~BDRV_O_CACHE_MASK; if (!strcmp(mode, "off") || !strcmp(mode, "none")) { *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB; } else if (!strcmp(mode, "directsync")) { *flags |= BDRV_O_NOCACHE; } else if (!strcmp(mode, "writeback")) { *flags |= BDRV_O_CACHE_WB; } else if (!strcmp(mode, "unsafe")) { *flags |= BDRV_O_CACHE_WB; *flags |= BDRV_O_NO_FLUSH; } else if (!strcmp(mode, "writethrough")) { /* this is the default */ } else { return -1; } return 0; } /** * The copy-on-read flag is actually a reference count so multiple users may * use the feature without worrying about clobbering its previous state. * Copy-on-read stays enabled until all users have called to disable it. */ void <API key>(BlockDriverState *bs) { bs->copy_on_read++; } void <API key>(BlockDriverState *bs) { assert(bs->copy_on_read > 0); bs->copy_on_read } /* * Returns the flags that a temporary snapshot should get, based on the * originally requested flags (the originally requested image will have flags * like a backing file) */ static int <API key>(int flags) { return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY; } /* * Returns the flags that bs->file should get, based on the given flags for * the parent BDS */ static int <API key>(int flags) { /* Enable protocol handling, disable format probing for bs->file */ flags |= BDRV_O_PROTOCOL; /* Our block drivers take care to send flushes and respect unmap policy, * so we can enable both unconditionally on lower layers. */ flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP; /* Clear flags that only apply to the top layer */ flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ); return flags; } /* * Returns the flags that bs->backing_hd should get, based on the given flags * for the parent BDS */ static int bdrv_backing_flags(int flags) { /* backing files always opened read-only */ flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ); /* snapshot=on is handled on the top layer */ flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY); return flags; } static int bdrv_open_flags(BlockDriverState *bs, int flags) { int open_flags = flags | BDRV_O_CACHE_WB; /* * Clear flags that are internal to the block layer before opening the * image. */ open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL); /* * Snapshots should be writable. */ if (flags & BDRV_O_TEMPORARY) { open_flags |= BDRV_O_RDWR; } return open_flags; } static void <API key>(BlockDriverState *bs, const char *node_name, Error **errp) { if (!node_name) { return; } /* Check for empty string or invalid characters */ if (!id_wellformed(node_name)) { error_setg(errp, "Invalid node name"); return; } /* takes care of avoiding namespaces collisions */ if (blk_by_name(node_name)) { error_setg(errp, "node-name=%s is conflicting with a device id", node_name); return; } /* takes care of avoiding duplicates node names */ if (bdrv_find_node(node_name)) { error_setg(errp, "Duplicate node name"); return; } /* copy node name into the bs and insert it into the graph list */ pstrcpy(bs->node_name, sizeof(bs->node_name), node_name); QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list); } /* * Common part for opening disk images and files * * Removes all processed options from *options. */ static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file, QDict *options, int flags, BlockDriver *drv, Error **errp) { int ret, open_flags; const char *filename; const char *node_name = NULL; Error *local_err = NULL; assert(drv != NULL); assert(bs->file == NULL); assert(options != NULL && bs->options != options); if (file != NULL) { filename = file->filename; } else { filename = qdict_get_try_str(options, "filename"); } if (drv->bdrv_needs_filename && !filename) { error_setg(errp, "The '%s' block driver requires a file name", drv->format_name); return -EINVAL; } <API key>(bs, filename ?: "", flags, drv->format_name); node_name = qdict_get_try_str(options, "node-name"); <API key>(bs, node_name, &local_err); if (local_err) { error_propagate(errp, local_err); return -EINVAL; } qdict_del(options, "node-name"); /* bdrv_open() with directly using a protocol as drv. This layer is already * opened, so assign it to bs (while file becomes a closed BlockDriverState) * and return immediately. */ if (file != NULL && drv->bdrv_file_open) { bdrv_swap(file, bs); return 0; } bs->open_flags = flags; bs->guest_block_size = 512; bs->request_alignment = 512; bs->zero_beyond_eof = true; open_flags = bdrv_open_flags(bs, flags); bs->read_only = !(open_flags & BDRV_O_RDWR); bs->growable = !!(flags & BDRV_O_PROTOCOL); if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) { error_setg(errp, !bs->read_only && bdrv_is_whitelisted(drv, true) ? "Driver '%s' can only be used for read-only devices" : "Driver '%s' is not whitelisted", drv->format_name); return -ENOTSUP; } assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */ if (flags & BDRV_O_COPY_ON_READ) { if (!bs->read_only) { <API key>(bs); } else { error_setg(errp, "Can't use copy-on-read on read-only device"); return -EINVAL; } } if (filename != NULL) { pstrcpy(bs->filename, sizeof(bs->filename), filename); } else { bs->filename[0] = '\0'; } pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename); bs->drv = drv; bs->opaque = g_malloc0(drv->instance_size); bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB); /* Open the image, either directly or using a protocol */ if (drv->bdrv_file_open) { assert(file == NULL); assert(!drv->bdrv_needs_filename || filename != NULL); ret = drv->bdrv_file_open(bs, options, open_flags, &local_err); } else { if (file == NULL) { error_setg(errp, "Can't use '%s' as a block driver for the " "protocol level", drv->format_name); ret = -EINVAL; goto free_and_fail; } bs->file = file; ret = drv->bdrv_open(bs, options, open_flags, &local_err); } if (ret < 0) { if (local_err) { error_propagate(errp, local_err); } else if (bs->filename[0]) { error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename); } else { error_setg_errno(errp, -ret, "Could not open image"); } goto free_and_fail; } ret = <API key>(bs, bs->total_sectors); if (ret < 0) { error_setg_errno(errp, -ret, "Could not refresh total sector count"); goto free_and_fail; } bdrv_refresh_limits(bs, &local_err); if (local_err) { error_propagate(errp, local_err); ret = -EINVAL; goto free_and_fail; } assert(bdrv_opt_mem_align(bs) != 0); assert((bs->request_alignment != 0) || bs->sg); return 0; free_and_fail: bs->file = NULL; g_free(bs->opaque); bs->opaque = NULL; bs->drv = NULL; return ret; } static QDict *parse_json_filename(const char *filename, Error **errp) { QObject *options_obj; QDict *options; int ret; ret = strstart(filename, "json:", &filename); assert(ret); options_obj = qobject_from_json(filename); if (!options_obj) { error_setg(errp, "Could not parse the JSON options"); return NULL; } if (qobject_type(options_obj) != QTYPE_QDICT) { qobject_decref(options_obj); error_setg(errp, "Invalid JSON object given"); return NULL; } options = qobject_to_qdict(options_obj); qdict_flatten(options); return options; } /* * Fills in default options for opening images and converts the legacy * filename/flags pair to option QDict entries. */ static int bdrv_fill_options(QDict **options, const char **pfilename, int flags, BlockDriver *drv, Error **errp) { const char *filename = *pfilename; const char *drvname; bool protocol = flags & BDRV_O_PROTOCOL; bool parse_filename = false; Error *local_err = NULL; /* Parse json: pseudo-protocol */ if (filename && g_str_has_prefix(filename, "json:")) { QDict *json_options = parse_json_filename(filename, &local_err); if (local_err) { error_propagate(errp, local_err); return -EINVAL; } /* Options given in the filename have lower priority than options * specified directly */ qdict_join(*options, json_options, false); QDECREF(json_options); *pfilename = filename = NULL; } /* Fetch the file name from the options QDict if necessary */ if (protocol && filename) { if (!qdict_haskey(*options, "filename")) { qdict_put(*options, "filename", qstring_from_str(filename)); parse_filename = true; } else { error_setg(errp, "Can't specify 'file' and 'filename' options at " "the same time"); return -EINVAL; } } /* Find the right block driver */ filename = qdict_get_try_str(*options, "filename"); drvname = qdict_get_try_str(*options, "driver"); if (drv) { if (drvname) { error_setg(errp, "Driver specified twice"); return -EINVAL; } drvname = drv->format_name; qdict_put(*options, "driver", qstring_from_str(drvname)); } else { if (!drvname && protocol) { if (filename) { drv = bdrv_find_protocol(filename, parse_filename); if (!drv) { error_setg(errp, "Unknown protocol"); return -EINVAL; } drvname = drv->format_name; qdict_put(*options, "driver", qstring_from_str(drvname)); } else { error_setg(errp, "Must specify either driver or file"); return -EINVAL; } } else if (drvname) { drv = bdrv_find_format(drvname); if (!drv) { error_setg(errp, "Unknown driver '%s'", drvname); return -ENOENT; } } } assert(drv || !protocol); /* Driver-specific filename parsing */ if (drv && drv->bdrv_parse_filename && parse_filename) { drv->bdrv_parse_filename(filename, *options, &local_err); if (local_err) { error_propagate(errp, local_err); return -EINVAL; } if (!drv->bdrv_needs_filename) { qdict_del(*options, "filename"); } } return 0; } void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd) { if (bs->backing_hd) { assert(bs->backing_blocker); bdrv_op_unblock_all(bs->backing_hd, bs->backing_blocker); } else if (backing_hd) { error_setg(&bs->backing_blocker, "device is used as backing hd of '%s'", <API key>(bs)); } bs->backing_hd = backing_hd; if (!backing_hd) { error_free(bs->backing_blocker); bs->backing_blocker = NULL; goto out; } bs->open_flags &= ~BDRV_O_NO_BACKING; pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename); pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_hd->drv ? backing_hd->drv->format_name : ""); bdrv_op_block_all(bs->backing_hd, bs->backing_blocker); /* Otherwise we won't be able to commit due to check in bdrv_commit */ bdrv_op_unblock(bs->backing_hd, <API key>, bs->backing_blocker); out: bdrv_refresh_limits(bs, NULL); } /* * Opens the backing file for a BlockDriverState if not yet open * * options is a QDict of options to pass to the block drivers, or NULL for an * empty set of options. The reference to the QDict is transferred to this * function (even on failure), so if the caller intends to reuse the dictionary, * it needs to use QINCREF() before calling bdrv_file_open. */ int <API key>(BlockDriverState *bs, QDict *options, Error **errp) { char *backing_filename = g_malloc0(PATH_MAX); int ret = 0; BlockDriver *back_drv = NULL; BlockDriverState *backing_hd; Error *local_err = NULL; if (bs->backing_hd != NULL) { QDECREF(options); goto free_exit; } /* NULL means an empty set of options */ if (options == NULL) { options = qdict_new(); } bs->open_flags &= ~BDRV_O_NO_BACKING; if (qdict_haskey(options, "file.filename")) { backing_filename[0] = '\0'; } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) { QDECREF(options); goto free_exit; } else { <API key>(bs, backing_filename, PATH_MAX); } if (!bs->drv || !bs->drv->supports_backing) { ret = -EINVAL; error_setg(errp, "Driver doesn't support backing files"); QDECREF(options); goto free_exit; } backing_hd = bdrv_new(); if (bs->backing_format[0] != '\0') { back_drv = bdrv_find_format(bs->backing_format); } assert(bs->backing_hd == NULL); ret = bdrv_open(&backing_hd, *backing_filename ? backing_filename : NULL, NULL, options, bdrv_backing_flags(bs->open_flags), back_drv, &local_err); if (ret < 0) { bdrv_unref(backing_hd); backing_hd = NULL; bs->open_flags |= BDRV_O_NO_BACKING; error_setg(errp, "Could not open backing file: %s", error_get_pretty(local_err)); error_free(local_err); goto free_exit; } bdrv_set_backing_hd(bs, backing_hd); free_exit: g_free(backing_filename); return ret; } /* * Opens a disk image whose options are given as BlockdevRef in another block * device's options. * * If allow_none is true, no image will be opened if filename is false and no * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned. * * bdrev_key specifies the key for the image's BlockdevRef in the options QDict. * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict * itself, all options starting with "${bdref_key}." are considered part of the * BlockdevRef. * * The BlockdevRef will be removed from the options QDict. * * To conform with the behavior of bdrv_open(), *pbs has to be NULL. */ int bdrv_open_image(BlockDriverState **pbs, const char *filename, QDict *options, const char *bdref_key, int flags, bool allow_none, Error **errp) { QDict *image_options; int ret; char *bdref_key_dot; const char *reference; assert(pbs); assert(*pbs == NULL); bdref_key_dot = g_strdup_printf("%s.", bdref_key); <API key>(options, &image_options, bdref_key_dot); g_free(bdref_key_dot); reference = qdict_get_try_str(options, bdref_key); if (!filename && !reference && !qdict_size(image_options)) { if (allow_none) { ret = 0; } else { error_setg(errp, "A block device must be specified for \"%s\"", bdref_key); ret = -EINVAL; } QDECREF(image_options); goto done; } ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp); done: qdict_del(options, bdref_key); return ret; } int <API key>(BlockDriverState *bs, int flags, Error **errp) { /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */ char *tmp_filename = g_malloc0(PATH_MAX + 1); int64_t total_size; BlockDriver *bdrv_qcow2; QemuOpts *opts = NULL; QDict *snapshot_options; BlockDriverState *bs_snapshot; Error *local_err; int ret; /* if snapshot, we create a temporary backing file and open it instead of opening 'filename' directly */ /* Get the required size from the image */ total_size = bdrv_getlength(bs); if (total_size < 0) { ret = total_size; error_setg_errno(errp, -total_size, "Could not get image size"); goto out; } /* Create the temporary image */ ret = get_tmp_filename(tmp_filename, PATH_MAX + 1); if (ret < 0) { error_setg_errno(errp, -ret, "Could not get temporary filename"); goto out; } bdrv_qcow2 = bdrv_find_format("qcow2"); opts = qemu_opts_create(bdrv_qcow2->create_opts, NULL, 0, &error_abort); qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size); ret = bdrv_create(bdrv_qcow2, tmp_filename, opts, &local_err); qemu_opts_del(opts); if (ret < 0) { error_setg_errno(errp, -ret, "Could not create temporary overlay " "'%s': %s", tmp_filename, error_get_pretty(local_err)); error_free(local_err); goto out; } /* Prepare a new options QDict for the temporary file */ snapshot_options = qdict_new(); qdict_put(snapshot_options, "file.driver", qstring_from_str("file")); qdict_put(snapshot_options, "file.filename", qstring_from_str(tmp_filename)); bs_snapshot = bdrv_new(); ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options, flags, bdrv_qcow2, &local_err); if (ret < 0) { error_propagate(errp, local_err); goto out; } bdrv_append(bs_snapshot, bs); out: g_free(tmp_filename); return ret; } /* * Opens a disk image (raw, qcow2, vmdk, ...) * * options is a QDict of options to pass to the block drivers, or NULL for an * empty set of options. The reference to the QDict belongs to the block layer * after the call (even on failure), so if the caller intends to reuse the * dictionary, it needs to use QINCREF() before calling bdrv_open. * * If *pbs is NULL, a new BDS will be created with a pointer to it stored there. * If it is not NULL, the referenced BDS will be reused. * * The reference parameter may be used to specify an existing block device which * should be opened. If specified, neither options nor a filename may be given, * nor can an existing BDS be reused (that is, *pbs has to be NULL). */ int bdrv_open(BlockDriverState **pbs, const char *filename, const char *reference, QDict *options, int flags, BlockDriver *drv, Error **errp) { int ret; BlockDriverState *file = NULL, *bs; const char *drvname; Error *local_err = NULL; int snapshot_flags = 0; assert(pbs); if (reference) { bool options_non_empty = options ? qdict_size(options) : false; QDECREF(options); if (*pbs) { error_setg(errp, "Cannot reuse an existing BDS when referencing " "another block device"); return -EINVAL; } if (filename || options_non_empty) { error_setg(errp, "Cannot reference an existing block device with " "additional options or a new filename"); return -EINVAL; } bs = bdrv_lookup_bs(reference, reference, errp); if (!bs) { return -ENODEV; } bdrv_ref(bs); *pbs = bs; return 0; } if (*pbs) { bs = *pbs; } else { bs = bdrv_new(); } /* NULL means an empty set of options */ if (options == NULL) { options = qdict_new(); } ret = bdrv_fill_options(&options, &filename, flags, drv, &local_err); if (local_err) { goto fail; } /* Find the right image format driver */ drv = NULL; drvname = qdict_get_try_str(options, "driver"); if (drvname) { drv = bdrv_find_format(drvname); qdict_del(options, "driver"); if (!drv) { error_setg(errp, "Unknown driver: '%s'", drvname); ret = -EINVAL; goto fail; } } assert(drvname || !(flags & BDRV_O_PROTOCOL)); if (drv && !drv->bdrv_file_open) { /* If the user explicitly wants a format driver here, we'll need to add * another layer for the protocol in bs->file */ flags &= ~BDRV_O_PROTOCOL; } bs->options = options; options = qdict_clone_shallow(options); /* Open image file without format layer */ if ((flags & BDRV_O_PROTOCOL) == 0) { if (flags & BDRV_O_RDWR) { flags |= BDRV_O_ALLOW_RDWR; } if (flags & BDRV_O_SNAPSHOT) { snapshot_flags = <API key>(flags); flags = bdrv_backing_flags(flags); } assert(file == NULL); ret = bdrv_open_image(&file, filename, options, "file", <API key>(flags), true, &local_err); if (ret < 0) { goto fail; } } /* Image format probing */ if (!drv && file) { ret = find_image_format(file, filename, &drv, &local_err); if (ret < 0) { goto fail; } } else if (!drv) { error_setg(errp, "Must specify either driver or file"); ret = -EINVAL; goto fail; } /* Open the image */ ret = bdrv_open_common(bs, file, options, flags, drv, &local_err); if (ret < 0) { goto fail; } if (file && (bs->file != file)) { bdrv_unref(file); file = NULL; } /* If there is a backing file, use it */ if ((flags & BDRV_O_NO_BACKING) == 0) { QDict *backing_options; <API key>(options, &backing_options, "backing."); ret = <API key>(bs, backing_options, &local_err); if (ret < 0) { goto close_and_fail; } } <API key>(bs); /* For snapshot=on, create a temporary qcow2 overlay. bs points to the * temporary snapshot afterwards. */ if (snapshot_flags) { ret = <API key>(bs, snapshot_flags, &local_err); if (local_err) { goto close_and_fail; } } /* Check if any unknown options were used */ if (options && (qdict_size(options) != 0)) { const QDictEntry *entry = qdict_first(options); if (flags & BDRV_O_PROTOCOL) { error_setg(errp, "Block protocol '%s' doesn't support the option " "'%s'", drv->format_name, entry->key); } else { error_setg(errp, "Block format '%s' used by device '%s' doesn't " "support the option '%s'", drv->format_name, <API key>(bs), entry->key); } ret = -EINVAL; goto close_and_fail; } if (!bdrv_key_required(bs)) { if (bs->blk) { <API key>(bs->blk, true); } } else if (!runstate_check(RUN_STATE_PRELAUNCH) && !runstate_check(RUN_STATE_INMIGRATE) && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */ error_setg(errp, "Guest must be stopped for opening of encrypted image"); ret = -EBUSY; goto close_and_fail; } QDECREF(options); *pbs = bs; return 0; fail: if (file != NULL) { bdrv_unref(file); } QDECREF(bs->options); QDECREF(options); bs->options = NULL; if (!*pbs) { /* If *pbs is NULL, a new BDS has been created in this function and needs to be freed now. Otherwise, it does not need to be closed, since it has not really been opened yet. */ bdrv_unref(bs); } if (local_err) { error_propagate(errp, local_err); } return ret; close_and_fail: /* See fail path, but now the BDS has to be always closed */ if (*pbs) { bdrv_close(bs); } else { bdrv_unref(bs); } QDECREF(options); if (local_err) { error_propagate(errp, local_err); } return ret; } typedef struct <API key> { bool prepared; BDRVReopenState state; QSIMPLEQ_ENTRY(<API key>) entry; } <API key>; /* * Adds a BlockDriverState to a simple queue for an atomic, transactional * reopen of multiple devices. * * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT * already performed, or alternatively may be NULL a new BlockReopenQueue will * be created and initialized. This newly created BlockReopenQueue should be * passed back in for subsequent calls that are intended to be of the same * atomic 'set'. * * bs is the BlockDriverState to add to the reopen queue. * * flags contains the open flags for the associated bs * * returns a pointer to bs_queue, which is either the newly allocated * bs_queue, or the existing bs_queue being used. * */ BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue, BlockDriverState *bs, int flags) { assert(bs != NULL); <API key> *bs_entry; if (bs_queue == NULL) { bs_queue = g_new0(BlockReopenQueue, 1); QSIMPLEQ_INIT(bs_queue); } /* bdrv_open() masks this flag out */ flags &= ~BDRV_O_PROTOCOL; if (bs->file) { bdrv_reopen_queue(bs_queue, bs->file, <API key>(flags)); } bs_entry = g_new0(<API key>, 1); <API key>(bs_queue, bs_entry, entry); bs_entry->state.bs = bs; bs_entry->state.flags = flags; return bs_queue; } /* * Reopen multiple BlockDriverStates atomically & transactionally. * * The queue passed in (bs_queue) must have been built up previous * via bdrv_reopen_queue(). * * Reopens all BDS specified in the queue, with the appropriate * flags. All devices are prepared for reopen, and failure of any * device will cause all device changes to be abandonded, and intermediate * data cleaned up. * * If all devices prepare successfully, then the changes are committed * to all devices. * */ int <API key>(BlockReopenQueue *bs_queue, Error **errp) { int ret = -1; <API key> *bs_entry, *next; Error *local_err = NULL; assert(bs_queue != NULL); bdrv_drain_all(); QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) { if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) { error_propagate(errp, local_err); goto cleanup; } bs_entry->prepared = true; } /* If we reach this point, we have success and just need to apply the * changes */ QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) { bdrv_reopen_commit(&bs_entry->state); } ret = 0; cleanup: <API key>(bs_entry, bs_queue, entry, next) { if (ret && bs_entry->prepared) { bdrv_reopen_abort(&bs_entry->state); } g_free(bs_entry); } g_free(bs_queue); return ret; } /* Reopen a single BlockDriverState with the specified flags. */ int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp) { int ret = -1; Error *local_err = NULL; BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags); ret = <API key>(queue, &local_err); if (local_err != NULL) { error_propagate(errp, local_err); } return ret; } /* * Prepares a BlockDriverState for reopen. All changes are staged in the * 'opaque' field of the BDRVReopenState, which is used and allocated by * the block driver layer .bdrv_reopen_prepare() * * bs is the BlockDriverState to reopen * flags are the new open flags * queue is the reopen queue * * Returns 0 on success, non-zero on error. On error errp will be set * as well. * * On failure, bdrv_reopen_abort() will be called to clean up any data. * It is the responsibility of the caller to then call the abort() or * commit() for any other BDS that have been left in a prepare() state * */ int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue, Error **errp) { int ret = -1; Error *local_err = NULL; BlockDriver *drv; assert(reopen_state != NULL); assert(reopen_state->bs->drv != NULL); drv = reopen_state->bs->drv; if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) && reopen_state->flags & BDRV_O_RDWR) { error_set(errp, <API key>, <API key>(reopen_state->bs)); goto error; } ret = bdrv_flush(reopen_state->bs); if (ret) { error_set(errp, <API key>, "Error (%s) flushing drive", strerror(-ret)); goto error; } if (drv->bdrv_reopen_prepare) { ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err); if (ret) { if (local_err != NULL) { error_propagate(errp, local_err); } else { error_setg(errp, "failed while preparing to reopen image '%s'", reopen_state->bs->filename); } goto error; } } else { /* It is currently mandatory to have a bdrv_reopen_prepare() * handler for each supported drv. */ error_set(errp, <API key>, drv->format_name, <API key>(reopen_state->bs), "reopening of file"); ret = -1; goto error; } ret = 0; error: return ret; } /* * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and * makes them final by swapping the staging BlockDriverState contents into * the active BlockDriverState contents. */ void bdrv_reopen_commit(BDRVReopenState *reopen_state) { BlockDriver *drv; assert(reopen_state != NULL); drv = reopen_state->bs->drv; assert(drv != NULL); /* If there are any driver level actions to take */ if (drv->bdrv_reopen_commit) { drv->bdrv_reopen_commit(reopen_state); } /* set BDS specific flags now */ reopen_state->bs->open_flags = reopen_state->flags; reopen_state->bs->enable_write_cache = !!(reopen_state->flags & BDRV_O_CACHE_WB); reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR); bdrv_refresh_limits(reopen_state->bs, NULL); } /* * Abort the reopen, and delete and free the staged changes in * reopen_state */ void bdrv_reopen_abort(BDRVReopenState *reopen_state) { BlockDriver *drv; assert(reopen_state != NULL); drv = reopen_state->bs->drv; assert(drv != NULL); if (drv->bdrv_reopen_abort) { drv->bdrv_reopen_abort(reopen_state); } } void bdrv_close(BlockDriverState *bs) { BdrvAioNotifier *ban, *ban_next; if (bs->job) { <API key>(bs->job); } bdrv_drain_all(); /* complete I/O */ bdrv_flush(bs); bdrv_drain_all(); /* in case flush left pending I/O */ <API key>(&bs->close_notifiers, bs); if (bs->drv) { if (bs->backing_hd) { BlockDriverState *backing_hd = bs->backing_hd; bdrv_set_backing_hd(bs, NULL); bdrv_unref(backing_hd); } bs->drv->bdrv_close(bs); g_free(bs->opaque); bs->opaque = NULL; bs->drv = NULL; bs->copy_on_read = 0; bs->backing_file[0] = '\0'; bs->backing_format[0] = '\0'; bs->total_sectors = 0; bs->encrypted = 0; bs->valid_key = 0; bs->sg = 0; bs->growable = 0; bs->zero_beyond_eof = false; QDECREF(bs->options); bs->options = NULL; QDECREF(bs->full_open_options); bs->full_open_options = NULL; if (bs->file != NULL) { bdrv_unref(bs->file); bs->file = NULL; } } if (bs->blk) { <API key>(bs->blk, false); } /*throttling disk I/O limits*/ if (bs->io_limits_enabled) { <API key>(bs); } QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) { g_free(ban); } QLIST_INIT(&bs->aio_notifiers); } void bdrv_close_all(void) { BlockDriverState *bs; QTAILQ_FOREACH(bs, &bdrv_states, device_list) { AioContext *aio_context = <API key>(bs); aio_context_acquire(aio_context); bdrv_close(bs); aio_context_release(aio_context); } } /* Check if any requests are in-flight (including throttled requests) */ static bool <API key>(BlockDriverState *bs) { if (!QLIST_EMPTY(&bs->tracked_requests)) { return true; } if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) { return true; } if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) { return true; } if (bs->file && <API key>(bs->file)) { return true; } if (bs->backing_hd && <API key>(bs->backing_hd)) { return true; } return false; } void bdrv_drain_all(void) { /* Always run first iteration so any pending completion BHs run */ bool busy = true; BlockDriverState *bs; while (busy) { busy = false; QTAILQ_FOREACH(bs, &bdrv_states, device_list) { AioContext *aio_context = <API key>(bs); bool bs_busy; aio_context_acquire(aio_context); bdrv_flush_io_queue(bs); <API key>(bs); bs_busy = <API key>(bs); bs_busy |= aio_poll(aio_context, bs_busy); aio_context_release(aio_context); busy |= bs_busy; } } } /* make a BlockDriverState anonymous by removing from bdrv_state and * graph_bdrv_state list. Also, NULL terminate the device_name to prevent double remove */ void bdrv_make_anon(BlockDriverState *bs) { /* * Take care to remove bs from bdrv_states only when it's actually * in it. Note that bs->device_list.tqe_prev is initially null, * and gets set to non-null by QTAILQ_INSERT_TAIL(). Establish * the useful invariant "bs in bdrv_states iff bs->tqe_prev" by * resetting it to null on remove. */ if (bs->device_list.tqe_prev) { QTAILQ_REMOVE(&bdrv_states, bs, device_list); bs->device_list.tqe_prev = NULL; } if (bs->node_name[0] != '\0') { QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list); } bs->node_name[0] = '\0'; } static void bdrv_rebind(BlockDriverState *bs) { if (bs->drv && bs->drv->bdrv_rebind) { bs->drv->bdrv_rebind(bs); } } static void <API key>(BlockDriverState *bs_dest, BlockDriverState *bs_src) { /* move some fields that need to stay attached to the device */ /* dev info */ bs_dest->guest_block_size = bs_src->guest_block_size; bs_dest->copy_on_read = bs_src->copy_on_read; bs_dest->enable_write_cache = bs_src->enable_write_cache; /* i/o throttled req */ memcpy(&bs_dest->throttle_state, &bs_src->throttle_state, sizeof(ThrottleState)); bs_dest->throttled_reqs[0] = bs_src->throttled_reqs[0]; bs_dest->throttled_reqs[1] = bs_src->throttled_reqs[1]; bs_dest->io_limits_enabled = bs_src->io_limits_enabled; /* r/w error */ bs_dest->on_read_error = bs_src->on_read_error; bs_dest->on_write_error = bs_src->on_write_error; /* i/o status */ bs_dest->iostatus_enabled = bs_src->iostatus_enabled; bs_dest->iostatus = bs_src->iostatus; /* dirty bitmap */ bs_dest->dirty_bitmaps = bs_src->dirty_bitmaps; /* reference count */ bs_dest->refcnt = bs_src->refcnt; /* job */ bs_dest->job = bs_src->job; /* keep the same entry in bdrv_states */ bs_dest->device_list = bs_src->device_list; bs_dest->blk = bs_src->blk; memcpy(bs_dest->op_blockers, bs_src->op_blockers, sizeof(bs_dest->op_blockers)); } /* * Swap bs contents for two image chains while they are live, * while keeping required fields on the BlockDriverState that is * actually attached to a device. * * This will modify the BlockDriverState fields, and swap contents * between bs_new and bs_old. Both bs_new and bs_old are modified. * * bs_new must not be attached to a BlockBackend. * * This function does not create any image files. */ void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old) { BlockDriverState tmp; /* The code needs to swap the node_name but simply swapping node_list won't * work so first remove the nodes from the graph list, do the swap then * insert them back if needed. */ if (bs_new->node_name[0] != '\0') { QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list); } if (bs_old->node_name[0] != '\0') { QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list); } /* bs_new must be unattached and shouldn't have anything fancy enabled */ assert(!bs_new->blk); assert(QLIST_EMPTY(&bs_new->dirty_bitmaps)); assert(bs_new->job == NULL); assert(bs_new->io_limits_enabled == false); assert(!throttle_have_timer(&bs_new->throttle_state)); tmp = *bs_new; *bs_new = *bs_old; *bs_old = tmp; /* there are some fields that should not be swapped, move them back */ <API key>(&tmp, bs_old); <API key>(bs_old, bs_new); <API key>(bs_new, &tmp); /* bs_new must remain unattached */ assert(!bs_new->blk); /* Check a few fields that should remain attached to the device */ assert(bs_new->job == NULL); assert(bs_new->io_limits_enabled == false); assert(!throttle_have_timer(&bs_new->throttle_state)); /* insert the nodes back into the graph node list if needed */ if (bs_new->node_name[0] != '\0') { QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list); } if (bs_old->node_name[0] != '\0') { QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list); } bdrv_rebind(bs_new); bdrv_rebind(bs_old); } /* * Add new bs contents at the top of an image chain while the chain is * live, while keeping required fields on the top layer. * * This will modify the BlockDriverState fields, and swap contents * between bs_new and bs_top. Both bs_new and bs_top are modified. * * bs_new must not be attached to a BlockBackend. * * This function does not create any image files. */ void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top) { bdrv_swap(bs_new, bs_top); /* The contents of 'tmp' will become bs_top, as we are * swapping bs_new and bs_top contents. */ bdrv_set_backing_hd(bs_top, bs_new); } static void bdrv_delete(BlockDriverState *bs) { assert(!bs->job); assert(<API key>(bs)); assert(!bs->refcnt); assert(QLIST_EMPTY(&bs->dirty_bitmaps)); bdrv_close(bs); /* remove from list, if necessary */ bdrv_make_anon(bs); g_free(bs); } /* * Run consistency checks on an image * * Returns 0 if the check could be completed (it doesn't mean that the image is * free of errors) or -errno when an internal error occurred. The results of the * check are stored in res. */ int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix) { if (bs->drv == NULL) { return -ENOMEDIUM; } if (bs->drv->bdrv_check == NULL) { return -ENOTSUP; } memset(res, 0, sizeof(*res)); return bs->drv->bdrv_check(bs, res, fix); } #define COMMIT_BUF_SECTORS 2048 /* commit COW file into the raw image */ int bdrv_commit(BlockDriverState *bs) { BlockDriver *drv = bs->drv; int64_t sector, total_sectors, length, backing_length; int n, ro, open_flags; int ret = 0; uint8_t *buf = NULL; char filename[PATH_MAX]; if (!drv) return -ENOMEDIUM; if (!bs->backing_hd) { return -ENOTSUP; } if (bdrv_op_is_blocked(bs, <API key>, NULL) || bdrv_op_is_blocked(bs->backing_hd, <API key>, NULL)) { return -EBUSY; } ro = bs->backing_hd->read_only; /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */ pstrcpy(filename, sizeof(filename), bs->backing_hd->filename); open_flags = bs->backing_hd->open_flags; if (ro) { if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) { return -EACCES; } } length = bdrv_getlength(bs); if (length < 0) { ret = length; goto ro_cleanup; } backing_length = bdrv_getlength(bs->backing_hd); if (backing_length < 0) { ret = backing_length; goto ro_cleanup; } /* If our top snapshot is larger than the backing file image, * grow the backing file image if possible. If not possible, * we must return an error */ if (length > backing_length) { ret = bdrv_truncate(bs->backing_hd, length); if (ret < 0) { goto ro_cleanup; } } total_sectors = length >> BDRV_SECTOR_BITS; /* qemu_try_blockalign() for bs will choose an alignment that works for * bs->backing_hd as well, so no need to compare the alignment manually. */ buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE); if (buf == NULL) { ret = -ENOMEM; goto ro_cleanup; } for (sector = 0; sector < total_sectors; sector += n) { ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n); if (ret < 0) { goto ro_cleanup; } if (ret) { ret = bdrv_read(bs, sector, buf, n); if (ret < 0) { goto ro_cleanup; } ret = bdrv_write(bs->backing_hd, sector, buf, n); if (ret < 0) { goto ro_cleanup; } } } if (drv->bdrv_make_empty) { ret = drv->bdrv_make_empty(bs); if (ret < 0) { goto ro_cleanup; } bdrv_flush(bs); } /* * Make sure all data we wrote to the backing device is actually * stable on disk. */ if (bs->backing_hd) { bdrv_flush(bs->backing_hd); } ret = 0; ro_cleanup: qemu_vfree(buf); if (ro) { /* ignoring error return here */ bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL); } return ret; } int bdrv_commit_all(void) { BlockDriverState *bs; QTAILQ_FOREACH(bs, &bdrv_states, device_list) { AioContext *aio_context = <API key>(bs); aio_context_acquire(aio_context); if (bs->drv && bs->backing_hd) { int ret = bdrv_commit(bs); if (ret < 0) { aio_context_release(aio_context); return ret; } } aio_context_release(aio_context); } return 0; } /** * Remove an active request from the tracked requests list * * This function should be called when a tracked request is completing. */ static void tracked_request_end(BdrvTrackedRequest *req) { if (req->serialising) { req->bs-><API key> } QLIST_REMOVE(req, list); <API key>(&req->wait_queue); } /** * Add an active request to the tracked requests list */ static void <API key>(BdrvTrackedRequest *req, BlockDriverState *bs, int64_t offset, unsigned int bytes, bool is_write) { *req = (BdrvTrackedRequest){ .bs = bs, .offset = offset, .bytes = bytes, .is_write = is_write, .co = qemu_coroutine_self(), .serialising = false, .overlap_offset = offset, .overlap_bytes = bytes, }; qemu_co_queue_init(&req->wait_queue); QLIST_INSERT_HEAD(&bs->tracked_requests, req, list); } static void <API key>(BdrvTrackedRequest *req, uint64_t align) { int64_t overlap_offset = req->offset & ~(align - 1); unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align) - overlap_offset; if (!req->serialising) { req->bs-><API key>++; req->serialising = true; } req->overlap_offset = MIN(req->overlap_offset, overlap_offset); req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes); } /** * Round a region to cluster boundaries */ void <API key>(BlockDriverState *bs, int64_t sector_num, int nb_sectors, int64_t *cluster_sector_num, int *cluster_nb_sectors) { BlockDriverInfo bdi; if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) { *cluster_sector_num = sector_num; *cluster_nb_sectors = nb_sectors; } else { int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE; *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c); *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num + nb_sectors, c); } } static int <API key>(BlockDriverState *bs) { BlockDriverInfo bdi; int ret; ret = bdrv_get_info(bs, &bdi); if (ret < 0 || bdi.cluster_size == 0) { return bs->request_alignment; } else { return bdi.cluster_size; } } static bool <API key>(BdrvTrackedRequest *req, int64_t offset, unsigned int bytes) { /* aaaa bbbb */ if (offset >= req->overlap_offset + req->overlap_bytes) { return false; } /* bbbb aaaa */ if (req->overlap_offset >= offset + bytes) { return false; } return true; } static bool coroutine_fn <API key>(BdrvTrackedRequest *self) { BlockDriverState *bs = self->bs; BdrvTrackedRequest *req; bool retry; bool waited = false; if (!bs-><API key>) { return false; } do { retry = false; QLIST_FOREACH(req, &bs->tracked_requests, list) { if (req == self || (!req->serialising && !self->serialising)) { continue; } if (<API key>(req, self->overlap_offset, self->overlap_bytes)) { /* Hitting this means there was a reentrant request, for * example, a block driver issuing nested requests. This must * never happen since it means deadlock. */ assert(qemu_coroutine_self() != req->co); /* If the request is already (indirectly) waiting for us, or * will wait for us as soon as it wakes up, then just go on * (instead of producing a deadlock in the former case). */ if (!req->waiting_for) { self->waiting_for = req; qemu_co_queue_wait(&req->wait_queue); self->waiting_for = NULL; retry = true; waited = true; break; } } } } while (retry); return waited; } /* * Return values: * 0 - success * -EINVAL - backing format specified, but no file * -ENOSPC - can't update the backing file because no space is left in the * image file header * -ENOTSUP - format driver doesn't support changing the backing file */ int <API key>(BlockDriverState *bs, const char *backing_file, const char *backing_fmt) { BlockDriver *drv = bs->drv; int ret; /* Backing file format doesn't make sense without a backing file */ if (backing_fmt && !backing_file) { return -EINVAL; } if (drv-><API key> != NULL) { ret = drv-><API key>(bs, backing_file, backing_fmt); } else { ret = -ENOTSUP; } if (ret == 0) { pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: ""); pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: ""); } return ret; } /* * Finds the image layer in the chain that has 'bs' as its backing file. * * active is the current topmost image. * * Returns NULL if bs is not found in active's image chain, * or if active == bs. * * Returns the bottommost base image if bs == NULL. */ BlockDriverState *bdrv_find_overlay(BlockDriverState *active, BlockDriverState *bs) { while (active && bs != active->backing_hd) { active = active->backing_hd; } return active; } /* Given a BDS, searches for the base layer. */ BlockDriverState *bdrv_find_base(BlockDriverState *bs) { return bdrv_find_overlay(bs, NULL); } typedef struct <API key> { BlockDriverState *bs; QSIMPLEQ_ENTRY(<API key>) entry; } <API key>; /* * Drops images above 'base' up to and including 'top', and sets the image * above 'top' to have base as its backing file. * * Requires that the overlay to 'top' is opened r/w, so that the backing file * information in 'bs' can be properly updated. * * E.g., this will convert the following chain: * bottom <- base <- intermediate <- top <- active * * to * * bottom <- base <- active * * It is allowed for bottom==base, in which case it converts: * * base <- intermediate <- top <- active * * to * * base <- active * * If backing_file_str is non-NULL, it will be used when modifying top's * overlay image metadata. * * Error conditions: * if active == top, that is considered an error * */ int <API key>(BlockDriverState *active, BlockDriverState *top, BlockDriverState *base, const char *backing_file_str) { BlockDriverState *intermediate; BlockDriverState *base_bs = NULL; BlockDriverState *new_top_bs = NULL; <API key> *intermediate_state, *next; int ret = -EIO; QSIMPLEQ_HEAD(states_to_delete, <API key>) states_to_delete; QSIMPLEQ_INIT(&states_to_delete); if (!top->drv || !base->drv) { goto exit; } new_top_bs = bdrv_find_overlay(active, top); if (new_top_bs == NULL) { /* we could not find the image above 'top', this is an error */ goto exit; } /* special case of new_top_bs->backing_hd already pointing to base - nothing * to do, no intermediate images */ if (new_top_bs->backing_hd == base) { ret = 0; goto exit; } intermediate = top; /* now we will go down through the list, and add each BDS we find * into our deletion queue, until we hit the 'base' */ while (intermediate) { intermediate_state = g_new0(<API key>, 1); intermediate_state->bs = intermediate; <API key>(&states_to_delete, intermediate_state, entry); if (intermediate->backing_hd == base) { base_bs = intermediate->backing_hd; break; } intermediate = intermediate->backing_hd; } if (base_bs == NULL) { /* something went wrong, we did not end at the base. safely * unravel everything, and exit with error */ goto exit; } /* success - we can delete the intermediate states, and link top->base */ backing_file_str = backing_file_str ? backing_file_str : base_bs->filename; ret = <API key>(new_top_bs, backing_file_str, base_bs->drv ? base_bs->drv->format_name : ""); if (ret) { goto exit; } bdrv_set_backing_hd(new_top_bs, base_bs); <API key>(intermediate_state, &states_to_delete, entry, next) { /* so that bdrv_close() does not recursively close the chain */ bdrv_set_backing_hd(intermediate_state->bs, NULL); bdrv_unref(intermediate_state->bs); } ret = 0; exit: <API key>(intermediate_state, &states_to_delete, entry, next) { g_free(intermediate_state); } return ret; } static int <API key>(BlockDriverState *bs, int64_t offset, size_t size) { int64_t len; if (size > INT_MAX) { return -EIO; } if (!bdrv_is_inserted(bs)) return -ENOMEDIUM; if (bs->growable) return 0; len = bdrv_getlength(bs); if (offset < 0) return -EIO; if ((offset > len) || (len - offset < size)) return -EIO; return 0; } static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num, int nb_sectors) { if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { return -EIO; } return <API key>(bs, sector_num * BDRV_SECTOR_SIZE, nb_sectors * BDRV_SECTOR_SIZE); } typedef struct RwCo { BlockDriverState *bs; int64_t offset; QEMUIOVector *qiov; bool is_write; int ret; BdrvRequestFlags flags; } RwCo; static void coroutine_fn bdrv_rw_co_entry(void *opaque) { RwCo *rwco = opaque; if (!rwco->is_write) { rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset, rwco->qiov->size, rwco->qiov, rwco->flags); } else { rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset, rwco->qiov->size, rwco->qiov, rwco->flags); } } /* * Process a vectored synchronous request using coroutines */ static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov, bool is_write, BdrvRequestFlags flags) { Coroutine *co; RwCo rwco = { .bs = bs, .offset = offset, .qiov = qiov, .is_write = is_write, .ret = NOT_DONE, .flags = flags, }; /** * In sync call context, when the vcpu is blocked, this throttling timer * will not fire; so the I/O throttling function has to be disabled here * if it has been enabled. */ if (bs->io_limits_enabled) { fprintf(stderr, "Disabling I/O throttling on '%s' due " "to synchronous I/O.\n", <API key>(bs)); <API key>(bs); } if (qemu_in_coroutine()) { /* Fast-path if already in coroutine context */ bdrv_rw_co_entry(&rwco); } else { AioContext *aio_context = <API key>(bs); co = <API key>(bdrv_rw_co_entry); <API key>(co, &rwco); while (rwco.ret == NOT_DONE) { aio_poll(aio_context, true); } } return rwco.ret; } /* * Process a synchronous request using coroutines */ static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf, int nb_sectors, bool is_write, BdrvRequestFlags flags) { QEMUIOVector qiov; struct iovec iov = { .iov_base = (void *)buf, .iov_len = nb_sectors * BDRV_SECTOR_SIZE, }; if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { return -EINVAL; } <API key>(&qiov, &iov, 1); return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS, &qiov, is_write, flags); } /* return < 0 if error. See bdrv_write() for the return codes */ int bdrv_read(BlockDriverState *bs, int64_t sector_num, uint8_t *buf, int nb_sectors) { return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0); } /* Just like bdrv_read(), but with I/O throttling temporarily disabled */ int <API key>(BlockDriverState *bs, int64_t sector_num, uint8_t *buf, int nb_sectors) { bool enabled; int ret; enabled = bs->io_limits_enabled; bs->io_limits_enabled = false; ret = bdrv_read(bs, sector_num, buf, nb_sectors); bs->io_limits_enabled = enabled; return ret; } /* Return < 0 if error. Important errors are: -EIO generic I/O error (may happen for all errors) -ENOMEDIUM No media inserted. -EINVAL Invalid sector number or nb_sectors -EACCES Trying to write a read-only device */ int bdrv_write(BlockDriverState *bs, int64_t sector_num, const uint8_t *buf, int nb_sectors) { return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0); } int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num, int nb_sectors, BdrvRequestFlags flags) { return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true, BDRV_REQ_ZERO_WRITE | flags); } /* * Completely zero out a block device with the help of bdrv_write_zeroes. * The operation is sped up by checking the block status and only writing * zeroes to the device if they currently do not return zeroes. Optional * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP). * * Returns < 0 on error, 0 on success. For error codes see bdrv_write(). */ int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags) { int64_t target_sectors, ret, nb_sectors, sector_num = 0; int n; target_sectors = bdrv_nb_sectors(bs); if (target_sectors < 0) { return target_sectors; } for (;;) { nb_sectors = target_sectors - sector_num; if (nb_sectors <= 0) { return 0; } if (nb_sectors > INT_MAX) { nb_sectors = INT_MAX; } ret = <API key>(bs, sector_num, nb_sectors, &n); if (ret < 0) { error_report("error getting block status at sector %" PRId64 ": %s", sector_num, strerror(-ret)); return ret; } if (ret & BDRV_BLOCK_ZERO) { sector_num += n; continue; } ret = bdrv_write_zeroes(bs, sector_num, n, flags); if (ret < 0) { error_report("error writing zeroes at sector %" PRId64 ": %s", sector_num, strerror(-ret)); return ret; } sector_num += n; } } int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes) { QEMUIOVector qiov; struct iovec iov = { .iov_base = (void *)buf, .iov_len = bytes, }; int ret; if (bytes < 0) { return -EINVAL; } <API key>(&qiov, &iov, 1); ret = bdrv_prwv_co(bs, offset, &qiov, false, 0); if (ret < 0) { return ret; } return bytes; } int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov) { int ret; ret = bdrv_prwv_co(bs, offset, qiov, true, 0); if (ret < 0) { return ret; } return qiov->size; } int bdrv_pwrite(BlockDriverState *bs, int64_t offset, const void *buf, int bytes) { QEMUIOVector qiov; struct iovec iov = { .iov_base = (void *) buf, .iov_len = bytes, }; if (bytes < 0) { return -EINVAL; } <API key>(&qiov, &iov, 1); return bdrv_pwritev(bs, offset, &qiov); } /* * Writes to the file and ensures that no writes are reordered across this * request (acts as a barrier) * * Returns 0 on success, -errno in error cases. */ int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset, const void *buf, int count) { int ret; ret = bdrv_pwrite(bs, offset, buf, count); if (ret < 0) { return ret; } /* No flush needed for cache modes that already do it */ if (bs->enable_write_cache) { bdrv_flush(bs); } return 0; } static int coroutine_fn <API key>(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) { /* Perform I/O through a temporary buffer so that users who scribble over * their read buffer while the operation is in progress do not end up * modifying the image file. This is critical for zero-copy guest I/O * where anything might happen inside guest memory. */ void *bounce_buffer; BlockDriver *drv = bs->drv; struct iovec iov; QEMUIOVector bounce_qiov; int64_t cluster_sector_num; int cluster_nb_sectors; size_t skip_bytes; int ret; /* Cover entire cluster so no additional backing file I/O is required when * allocating cluster in the image file. */ <API key>(bs, sector_num, nb_sectors, &cluster_sector_num, &cluster_nb_sectors); <API key>(bs, sector_num, nb_sectors, cluster_sector_num, cluster_nb_sectors); iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE; iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len); if (bounce_buffer == NULL) { ret = -ENOMEM; goto err; } <API key>(&bounce_qiov, &iov, 1); ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors, &bounce_qiov); if (ret < 0) { goto err; } if (drv-><API key> && buffer_is_zero(bounce_buffer, iov.iov_len)) { ret = <API key>(bs, cluster_sector_num, cluster_nb_sectors, 0); } else { /* This does not change the data on the disk, it is not necessary * to flush even in cache=writethrough mode. */ ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors, &bounce_qiov); } if (ret < 0) { /* It might be okay to ignore write errors for guest requests. If this * is a deliberate copy-on-read then we don't want to ignore the error. * Simply report it in all cases. */ goto err; } skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE; qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes, nb_sectors * BDRV_SECTOR_SIZE); err: qemu_vfree(bounce_buffer); return ret; } /* * Forwards an already correctly aligned request to the BlockDriver. This * handles copy on read and zeroing after EOF; any other features must be * implemented by the caller. */ static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs, BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, int64_t align, QEMUIOVector *qiov, int flags) { BlockDriver *drv = bs->drv; int ret; int64_t sector_num = offset >> BDRV_SECTOR_BITS; unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS; assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); assert(!qiov || bytes == qiov->size); /* Handle Copy on Read and associated serialisation */ if (flags & <API key>) { /* If we touch the same cluster it counts as an overlap. This * guarantees that allocating writes will be serialized and not race * with each other for the same cluster. For example, in copy-on-read * it ensures that the CoR read and write operations are atomic and * guest writes cannot interleave between them. */ <API key>(req, <API key>(bs)); } <API key>(req); if (flags & <API key>) { int pnum; ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum); if (ret < 0) { goto out; } if (!ret || pnum != nb_sectors) { ret = <API key>(bs, sector_num, nb_sectors, qiov); goto out; } } /* Forward the request to the BlockDriver */ if (!(bs->zero_beyond_eof && bs->growable)) { ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov); } else { /* Read zeros after EOF of growable BDSes */ int64_t total_sectors, max_nb_sectors; total_sectors = bdrv_nb_sectors(bs); if (total_sectors < 0) { ret = total_sectors; goto out; } max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num), align >> BDRV_SECTOR_BITS); if (max_nb_sectors > 0) { QEMUIOVector local_qiov; size_t local_sectors; max_nb_sectors = MIN(max_nb_sectors, SIZE_MAX / BDRV_SECTOR_BITS); local_sectors = MIN(max_nb_sectors, nb_sectors); qemu_iovec_init(&local_qiov, qiov->niov); qemu_iovec_concat(&local_qiov, qiov, 0, local_sectors * BDRV_SECTOR_SIZE); ret = drv->bdrv_co_readv(bs, sector_num, local_sectors, &local_qiov); qemu_iovec_destroy(&local_qiov); } else { ret = 0; } /* Reading beyond end of file is supposed to produce zeroes */ if (ret == 0 && total_sectors < sector_num + nb_sectors) { uint64_t offset = MAX(0, total_sectors - sector_num); uint64_t bytes = (sector_num + nb_sectors - offset) * BDRV_SECTOR_SIZE; qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes); } } out: return ret; } /* * Handle a read request in coroutine context */ static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs, int64_t offset, unsigned int bytes, QEMUIOVector *qiov, BdrvRequestFlags flags) { BlockDriver *drv = bs->drv; BdrvTrackedRequest req; /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */ uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment); uint8_t *head_buf = NULL; uint8_t *tail_buf = NULL; QEMUIOVector local_qiov; bool use_local_qiov = false; int ret; if (!drv) { return -ENOMEDIUM; } if (<API key>(bs, offset, bytes)) { return -EIO; } if (bs->copy_on_read) { flags |= <API key>; } /* throttling disk I/O */ if (bs->io_limits_enabled) { <API key>(bs, bytes, false); } /* Align read if necessary by padding qiov */ if (offset & (align - 1)) { head_buf = qemu_blockalign(bs, align); qemu_iovec_init(&local_qiov, qiov->niov + 2); qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); use_local_qiov = true; bytes += offset & (align - 1); offset = offset & ~(align - 1); } if ((offset + bytes) & (align - 1)) { if (!use_local_qiov) { qemu_iovec_init(&local_qiov, qiov->niov + 1); qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); use_local_qiov = true; } tail_buf = qemu_blockalign(bs, align); qemu_iovec_add(&local_qiov, tail_buf, align - ((offset + bytes) & (align - 1))); bytes = ROUND_UP(bytes, align); } <API key>(&req, bs, offset, bytes, false); ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align, use_local_qiov ? &local_qiov : qiov, flags); tracked_request_end(&req); if (use_local_qiov) { qemu_iovec_destroy(&local_qiov); qemu_vfree(head_buf); qemu_vfree(tail_buf); } return ret; } static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, BdrvRequestFlags flags) { if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) { return -EINVAL; } return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS, nb_sectors << BDRV_SECTOR_BITS, qiov, flags); } int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) { trace_bdrv_co_readv(bs, sector_num, nb_sectors); return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0); } int coroutine_fn <API key>(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) { <API key>(bs, sector_num, nb_sectors); return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, <API key>); } /* if no limit is specified in the BlockLimits use a default * of 32768 512-byte sectors (16 MiB) per request. */ #define <API key> 32768 static int coroutine_fn <API key>(BlockDriverState *bs, int64_t sector_num, int nb_sectors, BdrvRequestFlags flags) { BlockDriver *drv = bs->drv; QEMUIOVector qiov; struct iovec iov = {0}; int ret = 0; int max_write_zeroes = bs->bl.max_write_zeroes ? bs->bl.max_write_zeroes : <API key>; while (nb_sectors > 0 && !ret) { int num = nb_sectors; /* Align request. Block drivers can expect the "bulk" of the request * to be aligned. */ if (bs->bl.<API key> && num > bs->bl.<API key>) { if (sector_num % bs->bl.<API key> != 0) { /* Make a small request up to the first aligned sector. */ num = bs->bl.<API key>; num -= sector_num % bs->bl.<API key>; } else if ((sector_num + num) % bs->bl.<API key> != 0) { /* Shorten the request to the last aligned sector. num cannot * underflow because num > bs->bl.<API key>. */ num -= (sector_num + num) % bs->bl.<API key>; } } /* limit request size */ if (num > max_write_zeroes) { num = max_write_zeroes; } ret = -ENOTSUP; /* First try the efficient write zeroes operation */ if (drv-><API key>) { ret = drv-><API key>(bs, sector_num, num, flags); } if (ret == -ENOTSUP) { /* Fall back to bounce buffer if write zeroes is unsupported */ iov.iov_len = num * BDRV_SECTOR_SIZE; if (iov.iov_base == NULL) { iov.iov_base = qemu_try_blockalign(bs, num * BDRV_SECTOR_SIZE); if (iov.iov_base == NULL) { ret = -ENOMEM; goto fail; } memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE); } <API key>(&qiov, &iov, 1); ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov); /* Keep bounce buffer around if it is big enough for all * all future requests. */ if (num < max_write_zeroes) { qemu_vfree(iov.iov_base); iov.iov_base = NULL; } } sector_num += num; nb_sectors -= num; } fail: qemu_vfree(iov.iov_base); return ret; } /* * Forwards an already correctly aligned write request to the BlockDriver. */ static int coroutine_fn <API key>(BlockDriverState *bs, BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, QEMUIOVector *qiov, int flags) { BlockDriver *drv = bs->drv; bool waited; int ret; int64_t sector_num = offset >> BDRV_SECTOR_BITS; unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS; assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); assert(!qiov || bytes == qiov->size); waited = <API key>(req); assert(!waited || !req->serialising); assert(req->overlap_offset <= offset); assert(offset + bytes <= req->overlap_offset + req->overlap_bytes); ret = <API key>(&bs-><API key>, req); if (!ret && bs->detect_zeroes != <API key> && !(flags & BDRV_REQ_ZERO_WRITE) && drv-><API key> && qemu_iovec_is_zero(qiov)) { flags |= BDRV_REQ_ZERO_WRITE; if (bs->detect_zeroes == <API key>) { flags |= BDRV_REQ_MAY_UNMAP; } } if (ret < 0) { /* Do nothing, write notifier decided to fail this request */ } else if (flags & BDRV_REQ_ZERO_WRITE) { BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO); ret = <API key>(bs, sector_num, nb_sectors, flags); } else { BLKDBG_EVENT(bs, BLKDBG_PWRITEV); ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov); } BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE); if (ret == 0 && !bs->enable_write_cache) { ret = bdrv_co_flush(bs); } bdrv_set_dirty(bs, sector_num, nb_sectors); <API key>(&bs->stats, sector_num, nb_sectors); if (bs->growable && ret >= 0) { bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors); } return ret; } /* * Handle a write request in coroutine context */ static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs, int64_t offset, unsigned int bytes, QEMUIOVector *qiov, BdrvRequestFlags flags) { BdrvTrackedRequest req; /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */ uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment); uint8_t *head_buf = NULL; uint8_t *tail_buf = NULL; QEMUIOVector local_qiov; bool use_local_qiov = false; int ret; if (!bs->drv) { return -ENOMEDIUM; } if (bs->read_only) { return -EACCES; } if (<API key>(bs, offset, bytes)) { return -EIO; } /* throttling disk I/O */ if (bs->io_limits_enabled) { <API key>(bs, bytes, true); } /* * Align write if necessary by performing a read-modify-write cycle. * Pad qiov with the read parts and be sure to have a tracked request not * only for <API key>, but also for the reads of the RMW cycle. */ <API key>(&req, bs, offset, bytes, true); if (offset & (align - 1)) { QEMUIOVector head_qiov; struct iovec head_iov; <API key>(&req, align); <API key>(&req); head_buf = qemu_blockalign(bs, align); head_iov = (struct iovec) { .iov_base = head_buf, .iov_len = align, }; <API key>(&head_qiov, &head_iov, 1); BLKDBG_EVENT(bs, <API key>); ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align, align, &head_qiov, 0); if (ret < 0) { goto fail; } BLKDBG_EVENT(bs, <API key>); qemu_iovec_init(&local_qiov, qiov->niov + 2); qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); use_local_qiov = true; bytes += offset & (align - 1); offset = offset & ~(align - 1); } if ((offset + bytes) & (align - 1)) { QEMUIOVector tail_qiov; struct iovec tail_iov; size_t tail_bytes; bool waited; <API key>(&req, align); waited = <API key>(&req); assert(!waited || !use_local_qiov); tail_buf = qemu_blockalign(bs, align); tail_iov = (struct iovec) { .iov_base = tail_buf, .iov_len = align, }; <API key>(&tail_qiov, &tail_iov, 1); BLKDBG_EVENT(bs, <API key>); ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align, align, &tail_qiov, 0); if (ret < 0) { goto fail; } BLKDBG_EVENT(bs, <API key>); if (!use_local_qiov) { qemu_iovec_init(&local_qiov, qiov->niov + 1); qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); use_local_qiov = true; } tail_bytes = (offset + bytes) & (align - 1); qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes); bytes = ROUND_UP(bytes, align); } ret = <API key>(bs, &req, offset, bytes, use_local_qiov ? &local_qiov : qiov, flags); fail: tracked_request_end(&req); if (use_local_qiov) { qemu_iovec_destroy(&local_qiov); } qemu_vfree(head_buf); qemu_vfree(tail_buf); return ret; } static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, BdrvRequestFlags flags) { if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) { return -EINVAL; } return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS, nb_sectors << BDRV_SECTOR_BITS, qiov, flags); } int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) { <API key>(bs, sector_num, nb_sectors); return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0); } int coroutine_fn <API key>(BlockDriverState *bs, int64_t sector_num, int nb_sectors, BdrvRequestFlags flags) { <API key>(bs, sector_num, nb_sectors, flags); if (!(bs->open_flags & BDRV_O_UNMAP)) { flags &= ~BDRV_REQ_MAY_UNMAP; } return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL, BDRV_REQ_ZERO_WRITE | flags); } /** * Truncate file to 'offset' bytes (needed only for file protocols) */ int bdrv_truncate(BlockDriverState *bs, int64_t offset) { BlockDriver *drv = bs->drv; int ret; if (!drv) return -ENOMEDIUM; if (!drv->bdrv_truncate) return -ENOTSUP; if (bs->read_only) return -EACCES; ret = drv->bdrv_truncate(bs, offset); if (ret == 0) { ret = <API key>(bs, offset >> BDRV_SECTOR_BITS); if (bs->blk) { blk_dev_resize_cb(bs->blk); } } return ret; } /** * Length of a allocated file in bytes. Sparse files are counted by actual * allocated space. Return < 0 if error or unknown. */ int64_t <API key>(BlockDriverState *bs) { BlockDriver *drv = bs->drv; if (!drv) { return -ENOMEDIUM; } if (drv-><API key>) { return drv-><API key>(bs); } if (bs->file) { return <API key>(bs->file); } return -ENOTSUP; } /** * Return number of sectors on success, -errno on error. */ int64_t bdrv_nb_sectors(BlockDriverState *bs) { BlockDriver *drv = bs->drv; if (!drv) return -ENOMEDIUM; if (drv->has_variable_length) { int ret = <API key>(bs, bs->total_sectors); if (ret < 0) { return ret; } } return bs->total_sectors; } /** * Return length in bytes on success, -errno on error. * The length is always a multiple of BDRV_SECTOR_SIZE. */ int64_t bdrv_getlength(BlockDriverState *bs) { int64_t ret = bdrv_nb_sectors(bs); return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE; } /* return 0 as number of sectors if no device present or error */ void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr) { int64_t nb_sectors = bdrv_nb_sectors(bs); *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors; } void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error, BlockdevOnError on_write_error) { bs->on_read_error = on_read_error; bs->on_write_error = on_write_error; } BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read) { return is_read ? bs->on_read_error : bs->on_write_error; } BlockErrorAction <API key>(BlockDriverState *bs, bool is_read, int error) { BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error; switch (on_err) { case <API key>: return (error == ENOSPC) ? <API key> : <API key>; case <API key>: return <API key>; case <API key>: return <API key>; case <API key>: return <API key>; default: abort(); } } static void <API key>(BlockDriverState *bs, BlockErrorAction action, bool is_read, int error) { BlockErrorAction ac; ac = is_read ? <API key> : <API key>; <API key>(<API key>(bs), ac, action, <API key>(bs), error == ENOSPC, strerror(error), &error_abort); } /* This is done by device models because, while the block layer knows * about the error, it does not know whether an operation comes from * the device or the block layer (from a job, for example). */ void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action, bool is_read, int error) { assert(error >= 0); if (action == <API key>) { /* First set the iostatus, so that "info block" returns an iostatus * that matches the events raised so far (an additional error iostatus * is fine, but not a lost one). */ <API key>(bs, error); /* Then raise the request to stop the VM and the event. * <API key> has two effects. First, * it ensures that the STOP event always comes after the * BLOCK_IO_ERROR event. Second, it ensures that even if management * can observe the STOP event and do a "cont" before the STOP * event is issued, the VM will not stop. In this case, vm_start() * also ensures that the STOP/RESUME pair of events is emitted. */ <API key>(); <API key>(bs, action, is_read, error); <API key>(RUN_STATE_IO_ERROR); } else { <API key>(bs, action, is_read, error); } } int bdrv_is_read_only(BlockDriverState *bs) { return bs->read_only; } int bdrv_is_sg(BlockDriverState *bs) { return bs->sg; } int <API key>(BlockDriverState *bs) { return bs->enable_write_cache; } void <API key>(BlockDriverState *bs, bool wce) { bs->enable_write_cache = wce; /* so a reopen() will preserve wce */ if (wce) { bs->open_flags |= BDRV_O_CACHE_WB; } else { bs->open_flags &= ~BDRV_O_CACHE_WB; } } int bdrv_is_encrypted(BlockDriverState *bs) { if (bs->backing_hd && bs->backing_hd->encrypted) return 1; return bs->encrypted; } int bdrv_key_required(BlockDriverState *bs) { BlockDriverState *backing_hd = bs->backing_hd; if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key) return 1; return (bs->encrypted && !bs->valid_key); } int bdrv_set_key(BlockDriverState *bs, const char *key) { int ret; if (bs->backing_hd && bs->backing_hd->encrypted) { ret = bdrv_set_key(bs->backing_hd, key); if (ret < 0) return ret; if (!bs->encrypted) return 0; } if (!bs->encrypted) { return -EINVAL; } else if (!bs->drv || !bs->drv->bdrv_set_key) { return -ENOMEDIUM; } ret = bs->drv->bdrv_set_key(bs, key); if (ret < 0) { bs->valid_key = 0; } else if (!bs->valid_key) { bs->valid_key = 1; if (bs->blk) { /* call the change callback now, we skipped it on open */ <API key>(bs->blk, true); } } return ret; } const char *<API key>(BlockDriverState *bs) { return bs->drv ? bs->drv->format_name : NULL; } static int qsort_strcmp(const void *a, const void *b) { return strcmp(a, b); } void bdrv_iterate_format(void (*it)(void *opaque, const char *name), void *opaque) { BlockDriver *drv; int count = 0; int i; const char **formats = NULL; QLIST_FOREACH(drv, &bdrv_drivers, list) { if (drv->format_name) { bool found = false; int i = count; while (formats && i && !found) { found = !strcmp(formats[--i], drv->format_name); } if (!found) { formats = g_renew(const char *, formats, count + 1); formats[count++] = drv->format_name; } } } qsort(formats, count, sizeof(formats[0]), qsort_strcmp); for (i = 0; i < count; i++) { it(opaque, formats[i]); } g_free(formats); } /* This function is to find block backend bs */ /* TODO convert callers to blk_by_name(), then remove */ BlockDriverState *bdrv_find(const char *name) { BlockBackend *blk = blk_by_name(name); return blk ? blk_bs(blk) : NULL; } /* This function is to find a node in the bs graph */ BlockDriverState *bdrv_find_node(const char *node_name) { BlockDriverState *bs; assert(node_name); QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) { if (!strcmp(node_name, bs->node_name)) { return bs; } } return NULL; } /* Put this QMP function here so it can access the static graph_bdrv_states. */ BlockDeviceInfoList *<API key>(void) { BlockDeviceInfoList *list, *entry; BlockDriverState *bs; list = NULL; QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) { entry = g_malloc0(sizeof(*entry)); entry->value = <API key>(bs); entry->next = list; list = entry; } return list; } BlockDriverState *bdrv_lookup_bs(const char *device, const char *node_name, Error **errp) { BlockBackend *blk; BlockDriverState *bs; if (device) { blk = blk_by_name(device); if (blk) { return blk_bs(blk); } } if (node_name) { bs = bdrv_find_node(node_name); if (bs) { return bs; } } error_setg(errp, "Cannot find device=%s nor node_name=%s", device ? device : "", node_name ? node_name : ""); return NULL; } /* If 'base' is in the same chain as 'top', return true. Otherwise, * return false. If either argument is NULL, return false. */ bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base) { while (top && top != base) { top = top->backing_hd; } return top != NULL; } BlockDriverState *bdrv_next(BlockDriverState *bs) { if (!bs) { return QTAILQ_FIRST(&bdrv_states); } return QTAILQ_NEXT(bs, device_list); } /* TODO check what callers really want: bs->node_name or blk_name() */ const char *<API key>(const BlockDriverState *bs) { return bs->blk ? blk_name(bs->blk) : ""; } int bdrv_get_flags(BlockDriverState *bs) { return bs->open_flags; } int bdrv_flush_all(void) { BlockDriverState *bs; int result = 0; QTAILQ_FOREACH(bs, &bdrv_states, device_list) { AioContext *aio_context = <API key>(bs); int ret; aio_context_acquire(aio_context); ret = bdrv_flush(bs); if (ret < 0 && !result) { result = ret; } aio_context_release(aio_context); } return result; } int <API key>(BlockDriverState *bs) { return 1; } int bdrv_has_zero_init(BlockDriverState *bs) { assert(bs->drv); /* If BS is a copy on write image, it is initialized to the contents of the base image, which may not be zeroes. */ if (bs->backing_hd) { return 0; } if (bs->drv->bdrv_has_zero_init) { return bs->drv->bdrv_has_zero_init(bs); } /* safe default */ return 0; } bool <API key>(BlockDriverState *bs) { BlockDriverInfo bdi; if (bs->backing_hd) { return false; } if (bdrv_get_info(bs, &bdi) == 0) { return bdi.<API key>; } return false; } bool <API key>(BlockDriverState *bs) { BlockDriverInfo bdi; if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) { return false; } if (bdrv_get_info(bs, &bdi) == 0) { return bdi.<API key>; } return false; } typedef struct <API key> { BlockDriverState *bs; BlockDriverState *base; int64_t sector_num; int nb_sectors; int *pnum; int64_t ret; bool done; } <API key>; /* * Returns true iff the specified sector is present in the disk image. Drivers * not implementing the functionality are assumed to not support backing files, * hence all their sectors are reported as allocated. * * If 'sector_num' is beyond the end of the disk image the return value is 0 * and 'pnum' is set to 0. * * 'pnum' is set to the number of sectors (including and immediately following * the specified sector) that are known to be in the same * allocated/unallocated state. * * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes * beyond the end of the disk image it will be clamped. */ static int64_t coroutine_fn <API key>(BlockDriverState *bs, int64_t sector_num, int nb_sectors, int *pnum) { int64_t total_sectors; int64_t n; int64_t ret, ret2; total_sectors = bdrv_nb_sectors(bs); if (total_sectors < 0) { return total_sectors; } if (sector_num >= total_sectors) { *pnum = 0; return 0; } n = total_sectors - sector_num; if (n < nb_sectors) { nb_sectors = n; } if (!bs->drv-><API key>) { *pnum = nb_sectors; ret = BDRV_BLOCK_DATA | <API key>; if (bs->drv->protocol_name) { ret |= <API key> | (sector_num * BDRV_SECTOR_SIZE); } return ret; } ret = bs->drv-><API key>(bs, sector_num, nb_sectors, pnum); if (ret < 0) { *pnum = 0; return ret; } if (ret & BDRV_BLOCK_RAW) { assert(ret & <API key>); return <API key>(bs->file, ret >> BDRV_SECTOR_BITS, *pnum, pnum); } if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) { ret |= <API key>; } if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) { if (<API key>(bs)) { ret |= BDRV_BLOCK_ZERO; } else if (bs->backing_hd) { BlockDriverState *bs2 = bs->backing_hd; int64_t nb_sectors2 = bdrv_nb_sectors(bs2); if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) { ret |= BDRV_BLOCK_ZERO; } } } if (bs->file && (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) && (ret & <API key>)) { int file_pnum; ret2 = <API key>(bs->file, ret >> BDRV_SECTOR_BITS, *pnum, &file_pnum); if (ret2 >= 0) { /* Ignore errors. This is just providing extra information, it * is useful but not necessary. */ if (!file_pnum) { /* !file_pnum indicates an offset at or beyond the EOF; it is * perfectly valid for the format block driver to point to such * offsets, so catch it and mark everything as zero */ ret |= BDRV_BLOCK_ZERO; } else { /* Limit request to the range reported by the protocol driver */ *pnum = file_pnum; ret |= (ret2 & BDRV_BLOCK_ZERO); } } } return ret; } /* Coroutine wrapper for <API key>() */ static void coroutine_fn <API key>(void *opaque) { <API key> *data = opaque; BlockDriverState *bs = data->bs; data->ret = <API key>(bs, data->sector_num, data->nb_sectors, data->pnum); data->done = true; } /* * Synchronous wrapper around <API key>(). * * See <API key>() for details. */ int64_t <API key>(BlockDriverState *bs, int64_t sector_num, int nb_sectors, int *pnum) { Coroutine *co; <API key> data = { .bs = bs, .sector_num = sector_num, .nb_sectors = nb_sectors, .pnum = pnum, .done = false, }; if (qemu_in_coroutine()) { /* Fast-path if already in coroutine context */ <API key>(&data); } else { AioContext *aio_context = <API key>(bs); co = <API key>(<API key>); <API key>(co, &data); while (!data.done) { aio_poll(aio_context, true); } } return data.ret; } int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors, int *pnum) { int64_t ret = <API key>(bs, sector_num, nb_sectors, pnum); if (ret < 0) { return ret; } return !!(ret & <API key>); } /* * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP] * * Return true if the given sector is allocated in any image between * BASE and TOP (inclusive). BASE can be NULL to check if the given * sector is allocated in any image of the chain. Return false otherwise. * * 'pnum' is set to the number of sectors (including and immediately following * the specified sector) that are known to be in the same * allocated/unallocated state. * */ int <API key>(BlockDriverState *top, BlockDriverState *base, int64_t sector_num, int nb_sectors, int *pnum) { BlockDriverState *intermediate; int ret, n = nb_sectors; intermediate = top; while (intermediate && intermediate != base) { int pnum_inter; ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors, &pnum_inter); if (ret < 0) { return ret; } else if (ret) { *pnum = pnum_inter; return 1; } /* * [sector_num, nb_sectors] is unallocated on top but intermediate * might have * * [sector_num+x, nr_sectors] allocated. */ if (n > pnum_inter && (intermediate == top || sector_num + pnum_inter < intermediate->total_sectors)) { n = pnum_inter; } intermediate = intermediate->backing_hd; } *pnum = n; return 0; } const char *<API key>(BlockDriverState *bs) { if (bs->backing_hd && bs->backing_hd->encrypted) return bs->backing_file; else if (bs->encrypted) return bs->filename; else return NULL; } void <API key>(BlockDriverState *bs, char *filename, int filename_size) { pstrcpy(filename, filename_size, bs->backing_file); } int <API key>(BlockDriverState *bs, int64_t sector_num, const uint8_t *buf, int nb_sectors) { BlockDriver *drv = bs->drv; if (!drv) return -ENOMEDIUM; if (!drv-><API key>) return -ENOTSUP; if (bdrv_check_request(bs, sector_num, nb_sectors)) return -EIO; assert(QLIST_EMPTY(&bs->dirty_bitmaps)); return drv-><API key>(bs, sector_num, buf, nb_sectors); } int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi) { BlockDriver *drv = bs->drv; if (!drv) return -ENOMEDIUM; if (!drv->bdrv_get_info) return -ENOTSUP; memset(bdi, 0, sizeof(*bdi)); return drv->bdrv_get_info(bs, bdi); } ImageInfoSpecific *<API key>(BlockDriverState *bs) { BlockDriver *drv = bs->drv; if (drv && drv-><API key>) { return drv-><API key>(bs); } return NULL; } int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf, int64_t pos, int size) { QEMUIOVector qiov; struct iovec iov = { .iov_base = (void *) buf, .iov_len = size, }; <API key>(&qiov, &iov, 1); return bdrv_writev_vmstate(bs, &qiov, pos); } int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos) { BlockDriver *drv = bs->drv; if (!drv) { return -ENOMEDIUM; } else if (drv->bdrv_save_vmstate) { return drv->bdrv_save_vmstate(bs, qiov, pos); } else if (bs->file) { return bdrv_writev_vmstate(bs->file, qiov, pos); } return -ENOTSUP; } int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf, int64_t pos, int size) { BlockDriver *drv = bs->drv; if (!drv) return -ENOMEDIUM; if (drv->bdrv_load_vmstate) return drv->bdrv_load_vmstate(bs, buf, pos, size); if (bs->file) return bdrv_load_vmstate(bs->file, buf, pos, size); return -ENOTSUP; } void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event) { if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) { return; } bs->drv->bdrv_debug_event(bs, event); } int <API key>(BlockDriverState *bs, const char *event, const char *tag) { while (bs && bs->drv && !bs->drv-><API key>) { bs = bs->file; } if (bs && bs->drv && bs->drv-><API key>) { return bs->drv-><API key>(bs, event, tag); } return -ENOTSUP; } int <API key>(BlockDriverState *bs, const char *tag) { while (bs && bs->drv && !bs->drv-><API key>) { bs = bs->file; } if (bs && bs->drv && bs->drv-><API key>) { return bs->drv-><API key>(bs, tag); } return -ENOTSUP; } int bdrv_debug_resume(BlockDriverState *bs, const char *tag) { while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) { bs = bs->file; } if (bs && bs->drv && bs->drv->bdrv_debug_resume) { return bs->drv->bdrv_debug_resume(bs, tag); } return -ENOTSUP; } bool <API key>(BlockDriverState *bs, const char *tag) { while (bs && bs->drv && !bs->drv-><API key>) { bs = bs->file; } if (bs && bs->drv && bs->drv-><API key>) { return bs->drv-><API key>(bs, tag); } return false; } int bdrv_is_snapshot(BlockDriverState *bs) { return !!(bs->open_flags & BDRV_O_SNAPSHOT); } /* backing_file can either be relative, or absolute, or a protocol. If it is * relative, it must be relative to the chain. So, passing in bs->filename * from a BDS as backing_file should not be done, as that may be relative to * the CWD rather than the chain. */ BlockDriverState *<API key>(BlockDriverState *bs, const char *backing_file) { char *filename_full = NULL; char *backing_file_full = NULL; char *filename_tmp = NULL; int is_protocol = 0; BlockDriverState *curr_bs = NULL; BlockDriverState *retval = NULL; if (!bs || !bs->drv || !backing_file) { return NULL; } filename_full = g_malloc(PATH_MAX); backing_file_full = g_malloc(PATH_MAX); filename_tmp = g_malloc(PATH_MAX); is_protocol = path_has_protocol(backing_file); for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) { /* If either of the filename paths is actually a protocol, then * compare unmodified paths; otherwise make paths relative */ if (is_protocol || path_has_protocol(curr_bs->backing_file)) { if (strcmp(backing_file, curr_bs->backing_file) == 0) { retval = curr_bs->backing_hd; break; } } else { /* If not an absolute filename path, make it relative to the current * image's filename path */ path_combine(filename_tmp, PATH_MAX, curr_bs->filename, backing_file); /* We are going to compare absolute pathnames */ if (!realpath(filename_tmp, filename_full)) { continue; } /* We need to make sure the backing filename we are comparing against * is relative to the current image filename (or absolute) */ path_combine(filename_tmp, PATH_MAX, curr_bs->filename, curr_bs->backing_file); if (!realpath(filename_tmp, backing_file_full)) { continue; } if (strcmp(backing_file_full, filename_full) == 0) { retval = curr_bs->backing_hd; break; } } } g_free(filename_full); g_free(backing_file_full); g_free(filename_tmp); return retval; } int <API key>(BlockDriverState *bs) { if (!bs->drv) { return 0; } if (!bs->backing_hd) { return 0; } return 1 + <API key>(bs->backing_hd); } /* async I/Os */ BlockAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, BlockCompletionFunc *cb, void *opaque) { <API key>(bs, sector_num, nb_sectors, opaque); return <API key>(bs, sector_num, qiov, nb_sectors, 0, cb, opaque, false); } BlockAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, BlockCompletionFunc *cb, void *opaque) { <API key>(bs, sector_num, nb_sectors, opaque); return <API key>(bs, sector_num, qiov, nb_sectors, 0, cb, opaque, true); } BlockAIOCB *<API key>(BlockDriverState *bs, int64_t sector_num, int nb_sectors, BdrvRequestFlags flags, BlockCompletionFunc *cb, void *opaque) { <API key>(bs, sector_num, nb_sectors, flags, opaque); return <API key>(bs, sector_num, NULL, nb_sectors, BDRV_REQ_ZERO_WRITE | flags, cb, opaque, true); } typedef struct MultiwriteCB { int error; int num_requests; int num_callbacks; struct { BlockCompletionFunc *cb; void *opaque; QEMUIOVector *free_qiov; } callbacks[]; } MultiwriteCB; static void multiwrite_user_cb(MultiwriteCB *mcb) { int i; for (i = 0; i < mcb->num_callbacks; i++) { mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error); if (mcb->callbacks[i].free_qiov) { qemu_iovec_destroy(mcb->callbacks[i].free_qiov); } g_free(mcb->callbacks[i].free_qiov); } } static void multiwrite_cb(void *opaque, int ret) { MultiwriteCB *mcb = opaque; trace_multiwrite_cb(mcb, ret); if (ret < 0 && !mcb->error) { mcb->error = ret; } mcb->num_requests if (mcb->num_requests == 0) { multiwrite_user_cb(mcb); g_free(mcb); } } static int <API key>(const void *a, const void *b) { const BlockRequest *req1 = a, *req2 = b; /* * Note that we can't simply subtract req2->sector from req1->sector * here as that could overflow the return value. */ if (req1->sector > req2->sector) { return 1; } else if (req1->sector < req2->sector) { return -1; } else { return 0; } } /* * Takes a bunch of requests and tries to merge them. Returns the number of * requests that remain after merging. */ static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs, int num_reqs, MultiwriteCB *mcb) { int i, outidx; // Sort requests by start sector qsort(reqs, num_reqs, sizeof(*reqs), &<API key>); // Check if adjacent requests touch the same clusters. If so, combine them, // filling up gaps with zero sectors. outidx = 0; for (i = 1; i < num_reqs; i++) { int merge = 0; int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors; // Handle exactly sequential writes and overlapping writes. if (reqs[i].sector <= oldreq_last) { merge = 1; } if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) { merge = 0; } if (merge) { size_t size; QEMUIOVector *qiov = g_malloc0(sizeof(*qiov)); qemu_iovec_init(qiov, reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1); // Add the first request to the merged one. If the requests are // overlapping, drop the last sectors of the first request. size = (reqs[i].sector - reqs[outidx].sector) << 9; qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size); // We should need to add any zeros between the two requests assert (reqs[i].sector <= oldreq_last); // Add the second request qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size); // Add tail of first request, if necessary if (qiov->size < reqs[outidx].qiov->size) { qemu_iovec_concat(qiov, reqs[outidx].qiov, qiov->size, reqs[outidx].qiov->size - qiov->size); } reqs[outidx].nb_sectors = qiov->size >> 9; reqs[outidx].qiov = qiov; mcb->callbacks[i].free_qiov = reqs[outidx].qiov; } else { outidx++; reqs[outidx].sector = reqs[i].sector; reqs[outidx].nb_sectors = reqs[i].nb_sectors; reqs[outidx].qiov = reqs[i].qiov; } } return outidx + 1; } /* * Submit multiple AIO write requests at once. * * On success, the function returns 0 and all requests in the reqs array have * been submitted. In error case this function returns -1, and any of the * requests may or may not be submitted yet. In particular, this means that the * callback will be called for some of the requests, for others it won't. The * caller must check the error field of the BlockRequest to wait for the right * callbacks (if error != 0, no callback will be called). * * The implementation may modify the contents of the reqs array, e.g. to merge * requests. However, the fields opaque and error are left unmodified as they * are used to signal failure for a single request to the caller. */ int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs) { MultiwriteCB *mcb; int i; /* don't submit writes if we don't have a medium */ if (bs->drv == NULL) { for (i = 0; i < num_reqs; i++) { reqs[i].error = -ENOMEDIUM; } return -1; } if (num_reqs == 0) { return 0; } // Create MultiwriteCB structure mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks)); mcb->num_requests = 0; mcb->num_callbacks = num_reqs; for (i = 0; i < num_reqs; i++) { mcb->callbacks[i].cb = reqs[i].cb; mcb->callbacks[i].opaque = reqs[i].opaque; } // Check for mergable requests num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb); <API key>(mcb, mcb->num_callbacks, num_reqs); /* Run the aio requests. */ mcb->num_requests = num_reqs; for (i = 0; i < num_reqs; i++) { <API key>(bs, reqs[i].sector, reqs[i].qiov, reqs[i].nb_sectors, reqs[i].flags, multiwrite_cb, mcb, true); } return 0; } void bdrv_aio_cancel(BlockAIOCB *acb) { qemu_aio_ref(acb); <API key>(acb); while (acb->refcnt > 1) { if (acb->aiocb_info->get_aio_context) { aio_poll(acb->aiocb_info->get_aio_context(acb), true); } else if (acb->bs) { aio_poll(<API key>(acb->bs), true); } else { abort(); } } qemu_aio_unref(acb); } /* Async version of aio cancel. The caller is not blocked if the acb implements * cancel_async, otherwise we do nothing and let the request normally complete. * In either case the completion callback must be called. */ void <API key>(BlockAIOCB *acb) { if (acb->aiocb_info->cancel_async) { acb->aiocb_info->cancel_async(acb); } } /* async block device emulation */ typedef struct BlockAIOCBSync { BlockAIOCB common; QEMUBH *bh; int ret; /* vector translation state */ QEMUIOVector *qiov; uint8_t *bounce; int is_write; } BlockAIOCBSync; static const AIOCBInfo bdrv_em_aiocb_info = { .aiocb_size = sizeof(BlockAIOCBSync), }; static void bdrv_aio_bh_cb(void *opaque) { BlockAIOCBSync *acb = opaque; if (!acb->is_write && acb->ret >= 0) { qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size); } qemu_vfree(acb->bounce); acb->common.cb(acb->common.opaque, acb->ret); qemu_bh_delete(acb->bh); acb->bh = NULL; qemu_aio_unref(acb); } static BlockAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, BlockCompletionFunc *cb, void *opaque, int is_write) { BlockAIOCBSync *acb; acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque); acb->is_write = is_write; acb->qiov = qiov; acb->bounce = qemu_try_blockalign(bs, qiov->size); acb->bh = aio_bh_new(<API key>(bs), bdrv_aio_bh_cb, acb); if (acb->bounce == NULL) { acb->ret = -ENOMEM; } else if (is_write) { qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size); acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors); } else { acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors); } qemu_bh_schedule(acb->bh); return &acb->common; } static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, BlockCompletionFunc *cb, void *opaque) { return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0); } static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, BlockCompletionFunc *cb, void *opaque) { return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1); } typedef struct BlockAIOCBCoroutine { BlockAIOCB common; BlockRequest req; bool is_write; bool *done; QEMUBH* bh; } BlockAIOCBCoroutine; static const AIOCBInfo <API key> = { .aiocb_size = sizeof(BlockAIOCBCoroutine), }; static void bdrv_co_em_bh(void *opaque) { BlockAIOCBCoroutine *acb = opaque; acb->common.cb(acb->common.opaque, acb->req.error); qemu_bh_delete(acb->bh); qemu_aio_unref(acb); } /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */ static void coroutine_fn bdrv_co_do_rw(void *opaque) { BlockAIOCBCoroutine *acb = opaque; BlockDriverState *bs = acb->common.bs; if (!acb->is_write) { acb->req.error = bdrv_co_do_readv(bs, acb->req.sector, acb->req.nb_sectors, acb->req.qiov, acb->req.flags); } else { acb->req.error = bdrv_co_do_writev(bs, acb->req.sector, acb->req.nb_sectors, acb->req.qiov, acb->req.flags); } acb->bh = aio_bh_new(<API key>(bs), bdrv_co_em_bh, acb); qemu_bh_schedule(acb->bh); } static BlockAIOCB *<API key>(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, BdrvRequestFlags flags, BlockCompletionFunc *cb, void *opaque, bool is_write) { Coroutine *co; BlockAIOCBCoroutine *acb; acb = qemu_aio_get(&<API key>, bs, cb, opaque); acb->req.sector = sector_num; acb->req.nb_sectors = nb_sectors; acb->req.qiov = qiov; acb->req.flags = flags; acb->is_write = is_write; co = <API key>(bdrv_co_do_rw); <API key>(co, acb); return &acb->common; } static void coroutine_fn <API key>(void *opaque) { BlockAIOCBCoroutine *acb = opaque; BlockDriverState *bs = acb->common.bs; acb->req.error = bdrv_co_flush(bs); acb->bh = aio_bh_new(<API key>(bs), bdrv_co_em_bh, acb); qemu_bh_schedule(acb->bh); } BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs, BlockCompletionFunc *cb, void *opaque) { <API key>(bs, opaque); Coroutine *co; BlockAIOCBCoroutine *acb; acb = qemu_aio_get(&<API key>, bs, cb, opaque); co = <API key>(<API key>); <API key>(co, acb); return &acb->common; } static void coroutine_fn <API key>(void *opaque) { BlockAIOCBCoroutine *acb = opaque; BlockDriverState *bs = acb->common.bs; acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors); acb->bh = aio_bh_new(<API key>(bs), bdrv_co_em_bh, acb); qemu_bh_schedule(acb->bh); } BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors, BlockCompletionFunc *cb, void *opaque) { Coroutine *co; BlockAIOCBCoroutine *acb; <API key>(bs, sector_num, nb_sectors, opaque); acb = qemu_aio_get(&<API key>, bs, cb, opaque); acb->req.sector = sector_num; acb->req.nb_sectors = nb_sectors; co = <API key>(<API key>); <API key>(co, acb); return &acb->common; } void bdrv_init(void) { module_call_init(MODULE_INIT_BLOCK); } void <API key>(void) { use_bdrv_whitelist = 1; bdrv_init(); } void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs, BlockCompletionFunc *cb, void *opaque) { BlockAIOCB *acb; acb = g_slice_alloc(aiocb_info->aiocb_size); acb->aiocb_info = aiocb_info; acb->bs = bs; acb->cb = cb; acb->opaque = opaque; acb->refcnt = 1; return acb; } void qemu_aio_ref(void *p) { BlockAIOCB *acb = p; acb->refcnt++; } void qemu_aio_unref(void *p) { BlockAIOCB *acb = p; assert(acb->refcnt > 0); if (--acb->refcnt == 0) { g_slice_free1(acb->aiocb_info->aiocb_size, acb); } } /* Coroutine block device emulation */ typedef struct <API key> { Coroutine *coroutine; int ret; } <API key>; static void <API key>(void *opaque, int ret) { <API key> *co = opaque; co->ret = ret; <API key>(co->coroutine, NULL); } static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *iov, bool is_write) { <API key> co = { .coroutine = qemu_coroutine_self(), }; BlockAIOCB *acb; if (is_write) { acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors, <API key>, &co); } else { acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors, <API key>, &co); } trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb); if (!acb) { return -EIO; } <API key>(); return co.ret; } static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *iov) { return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false); } static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *iov) { return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true); } static void coroutine_fn bdrv_flush_co_entry(void *opaque) { RwCo *rwco = opaque; rwco->ret = bdrv_co_flush(rwco->bs); } int coroutine_fn bdrv_co_flush(BlockDriverState *bs) { int ret; if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) { return 0; } /* Write back cached data to the OS even with cache=unsafe */ BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS); if (bs->drv->bdrv_co_flush_to_os) { ret = bs->drv->bdrv_co_flush_to_os(bs); if (ret < 0) { return ret; } } /* But don't actually force it to the disk with cache=unsafe */ if (bs->open_flags & BDRV_O_NO_FLUSH) { goto flush_parent; } BLKDBG_EVENT(bs->file, <API key>); if (bs->drv-><API key>) { ret = bs->drv-><API key>(bs); } else if (bs->drv->bdrv_aio_flush) { BlockAIOCB *acb; <API key> co = { .coroutine = qemu_coroutine_self(), }; acb = bs->drv->bdrv_aio_flush(bs, <API key>, &co); if (acb == NULL) { ret = -EIO; } else { <API key>(); ret = co.ret; } } else { /* * Some block drivers always operate in either writethrough or unsafe * mode and don't support bdrv_flush therefore. Usually qemu doesn't * know how the server works (because the behaviour is hardcoded or * depends on server-side configuration), so we can't ensure that * everything is safe on disk. Returning an error doesn't work because * that would break guests even if the server operates in writethrough * mode. * * Let's hope the user knows what he's doing. */ ret = 0; } if (ret < 0) { return ret; } /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH * in the case of cache=unsafe, so there are no useless flushes. */ flush_parent: return bdrv_co_flush(bs->file); } void <API key>(BlockDriverState *bs, Error **errp) { Error *local_err = NULL; int ret; if (!bs->drv) { return; } if (!(bs->open_flags & BDRV_O_INCOMING)) { return; } bs->open_flags &= ~BDRV_O_INCOMING; if (bs->drv-><API key>) { bs->drv-><API key>(bs, &local_err); } else if (bs->file) { <API key>(bs->file, &local_err); } if (local_err) { error_propagate(errp, local_err); return; } ret = <API key>(bs, bs->total_sectors); if (ret < 0) { error_setg_errno(errp, -ret, "Could not refresh total sector count"); return; } } void <API key>(Error **errp) { BlockDriverState *bs; Error *local_err = NULL; QTAILQ_FOREACH(bs, &bdrv_states, device_list) { AioContext *aio_context = <API key>(bs); aio_context_acquire(aio_context); <API key>(bs, &local_err); aio_context_release(aio_context); if (local_err) { error_propagate(errp, local_err); return; } } } int bdrv_flush(BlockDriverState *bs) { Coroutine *co; RwCo rwco = { .bs = bs, .ret = NOT_DONE, }; if (qemu_in_coroutine()) { /* Fast-path if already in coroutine context */ bdrv_flush_co_entry(&rwco); } else { AioContext *aio_context = <API key>(bs); co = <API key>(bdrv_flush_co_entry); <API key>(co, &rwco); while (rwco.ret == NOT_DONE) { aio_poll(aio_context, true); } } return rwco.ret; } typedef struct DiscardCo { BlockDriverState *bs; int64_t sector_num; int nb_sectors; int ret; } DiscardCo; static void coroutine_fn <API key>(void *opaque) { DiscardCo *rwco = opaque; rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors); } /* if no limit is specified in the BlockLimits use a default * of 32768 512-byte sectors (16 MiB) per request. */ #define MAX_DISCARD_DEFAULT 32768 int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors) { int max_discard; if (!bs->drv) { return -ENOMEDIUM; } else if (bdrv_check_request(bs, sector_num, nb_sectors)) { return -EIO; } else if (bs->read_only) { return -EROFS; } bdrv_reset_dirty(bs, sector_num, nb_sectors); /* Do nothing if disabled. */ if (!(bs->open_flags & BDRV_O_UNMAP)) { return 0; } if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) { return 0; } max_discard = bs->bl.max_discard ? bs->bl.max_discard : MAX_DISCARD_DEFAULT; while (nb_sectors > 0) { int ret; int num = nb_sectors; /* align request */ if (bs->bl.discard_alignment && num >= bs->bl.discard_alignment && sector_num % bs->bl.discard_alignment) { if (num > bs->bl.discard_alignment) { num = bs->bl.discard_alignment; } num -= sector_num % bs->bl.discard_alignment; } /* limit request size */ if (num > max_discard) { num = max_discard; } if (bs->drv->bdrv_co_discard) { ret = bs->drv->bdrv_co_discard(bs, sector_num, num); } else { BlockAIOCB *acb; <API key> co = { .coroutine = qemu_coroutine_self(), }; acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors, <API key>, &co); if (acb == NULL) { return -EIO; } else { <API key>(); ret = co.ret; } } if (ret && ret != -ENOTSUP) { return ret; } sector_num += num; nb_sectors -= num; } return 0; } int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors) { Coroutine *co; DiscardCo rwco = { .bs = bs, .sector_num = sector_num, .nb_sectors = nb_sectors, .ret = NOT_DONE, }; if (qemu_in_coroutine()) { /* Fast-path if already in coroutine context */ <API key>(&rwco); } else { AioContext *aio_context = <API key>(bs); co = <API key>(<API key>); <API key>(co, &rwco); while (rwco.ret == NOT_DONE) { aio_poll(aio_context, true); } } return rwco.ret; } /* removable device support */ /** * Return TRUE if the media is present */ int bdrv_is_inserted(BlockDriverState *bs) { BlockDriver *drv = bs->drv; if (!drv) return 0; if (!drv->bdrv_is_inserted) return 1; return drv->bdrv_is_inserted(bs); } /** * Return whether the media changed since the last call to this * function, or -ENOTSUP if we don't know. Most drivers don't know. */ int bdrv_media_changed(BlockDriverState *bs) { BlockDriver *drv = bs->drv; if (drv && drv->bdrv_media_changed) { return drv->bdrv_media_changed(bs); } return -ENOTSUP; } /** * If eject_flag is TRUE, eject the media. Otherwise, close the tray */ void bdrv_eject(BlockDriverState *bs, bool eject_flag) { BlockDriver *drv = bs->drv; const char *device_name; if (drv && drv->bdrv_eject) { drv->bdrv_eject(bs, eject_flag); } device_name = <API key>(bs); if (device_name[0] != '\0') { <API key>(device_name, eject_flag, &error_abort); } } /** * Lock or unlock the media (if it is locked, the user won't be able * to eject it manually). */ void bdrv_lock_medium(BlockDriverState *bs, bool locked) { BlockDriver *drv = bs->drv; <API key>(bs, locked); if (drv && drv->bdrv_lock_medium) { drv->bdrv_lock_medium(bs, locked); } } /* needed for generic scsi interface */ int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf) { BlockDriver *drv = bs->drv; if (drv && drv->bdrv_ioctl) return drv->bdrv_ioctl(bs, req, buf); return -ENOTSUP; } BlockAIOCB *bdrv_aio_ioctl(BlockDriverState *bs, unsigned long int req, void *buf, BlockCompletionFunc *cb, void *opaque) { BlockDriver *drv = bs->drv; if (drv && drv->bdrv_aio_ioctl) return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque); return NULL; } void <API key>(BlockDriverState *bs, int align) { bs->guest_block_size = align; } void *qemu_blockalign(BlockDriverState *bs, size_t size) { return qemu_memalign(bdrv_opt_mem_align(bs), size); } void *qemu_blockalign0(BlockDriverState *bs, size_t size) { return memset(qemu_blockalign(bs, size), 0, size); } void *qemu_try_blockalign(BlockDriverState *bs, size_t size) { size_t align = bdrv_opt_mem_align(bs); /* Ensure that NULL is never returned on success */ assert(align > 0); if (size == 0) { size = align; } return qemu_try_memalign(align, size); } void *<API key>(BlockDriverState *bs, size_t size) { void *mem = qemu_try_blockalign(bs, size); if (mem) { memset(mem, 0, size); } return mem; } /* * Check if all memory in this vector is sector aligned. */ bool <API key>(BlockDriverState *bs, QEMUIOVector *qiov) { int i; size_t alignment = bdrv_opt_mem_align(bs); for (i = 0; i < qiov->niov; i++) { if ((uintptr_t) qiov->iov[i].iov_base % alignment) { return false; } if (qiov->iov[i].iov_len % alignment) { return false; } } return true; } BdrvDirtyBitmap *<API key>(BlockDriverState *bs, int granularity, Error **errp) { int64_t bitmap_size; BdrvDirtyBitmap *bitmap; assert((granularity & (granularity - 1)) == 0); granularity >>= BDRV_SECTOR_BITS; assert(granularity); bitmap_size = bdrv_nb_sectors(bs); if (bitmap_size < 0) { error_setg_errno(errp, -bitmap_size, "could not get length of device"); errno = -bitmap_size; return NULL; } bitmap = g_new0(BdrvDirtyBitmap, 1); bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1); QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list); return bitmap; } void <API key>(BlockDriverState *bs, BdrvDirtyBitmap *bitmap) { BdrvDirtyBitmap *bm, *next; QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) { if (bm == bitmap) { QLIST_REMOVE(bitmap, list); hbitmap_free(bitmap->bitmap); g_free(bitmap); return; } } } BlockDirtyInfoList *<API key>(BlockDriverState *bs) { BdrvDirtyBitmap *bm; BlockDirtyInfoList *list = NULL; BlockDirtyInfoList **plist = &list; QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) { BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1); BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1); info->count = <API key>(bs, bm); info->granularity = ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap)); entry->value = info; *plist = entry; plist = &entry->next; } return list; } int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector) { if (bitmap) { return hbitmap_get(bitmap->bitmap, sector); } else { return 0; } } void <API key>(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, HBitmapIter *hbi) { hbitmap_iter_init(hbi, bitmap->bitmap, 0); } void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors) { BdrvDirtyBitmap *bitmap; QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) { hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors); } } void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors) { BdrvDirtyBitmap *bitmap; QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) { hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors); } } int64_t <API key>(BlockDriverState *bs, BdrvDirtyBitmap *bitmap) { return hbitmap_count(bitmap->bitmap); } /* Get a reference to bs */ void bdrv_ref(BlockDriverState *bs) { bs->refcnt++; } /* Release a previously grabbed reference to bs. * If after releasing, reference count is zero, the BlockDriverState is * deleted. */ void bdrv_unref(BlockDriverState *bs) { if (!bs) { return; } assert(bs->refcnt > 0); if (--bs->refcnt == 0) { bdrv_delete(bs); } } struct BdrvOpBlocker { Error *reason; QLIST_ENTRY(BdrvOpBlocker) list; }; bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp) { BdrvOpBlocker *blocker; assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); if (!QLIST_EMPTY(&bs->op_blockers[op])) { blocker = QLIST_FIRST(&bs->op_blockers[op]); if (errp) { error_setg(errp, "Device '%s' is busy: %s", <API key>(bs), error_get_pretty(blocker->reason)); } return true; } return false; } void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason) { BdrvOpBlocker *blocker; assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); blocker = g_new0(BdrvOpBlocker, 1); blocker->reason = reason; QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list); } void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason) { BdrvOpBlocker *blocker, *next; assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) { if (blocker->reason == reason) { QLIST_REMOVE(blocker, list); g_free(blocker); } } } void bdrv_op_block_all(BlockDriverState *bs, Error *reason) { int i; for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { bdrv_op_block(bs, i, reason); } } void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason) { int i; for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { bdrv_op_unblock(bs, i, reason); } } bool <API key>(BlockDriverState *bs) { int i; for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { if (!QLIST_EMPTY(&bs->op_blockers[i])) { return false; } } return true; } void <API key>(BlockDriverState *bs) { bs->iostatus_enabled = true; bs->iostatus = <API key>; } /* The I/O status is only enabled if the drive explicitly * enables it _and_ the VM is configured to stop on errors */ bool <API key>(const BlockDriverState *bs) { return (bs->iostatus_enabled && (bs->on_write_error == <API key> || bs->on_write_error == <API key> || bs->on_read_error == <API key>)); } void <API key>(BlockDriverState *bs) { bs->iostatus_enabled = false; } void bdrv_iostatus_reset(BlockDriverState *bs) { if (<API key>(bs)) { bs->iostatus = <API key>; if (bs->job) { <API key>(bs->job); } } } void <API key>(BlockDriverState *bs, int error) { assert(<API key>(bs)); if (bs->iostatus == <API key>) { bs->iostatus = error == ENOSPC ? <API key> : <API key>; } } void bdrv_img_create(const char *filename, const char *fmt, const char *base_filename, const char *base_fmt, char *options, uint64_t img_size, int flags, Error **errp, bool quiet) { QemuOptsList *create_opts = NULL; QemuOpts *opts = NULL; const char *backing_fmt, *backing_file; int64_t size; BlockDriver *drv, *proto_drv; BlockDriver *backing_drv = NULL; Error *local_err = NULL; int ret = 0; /* Find driver and parse its options */ drv = bdrv_find_format(fmt); if (!drv) { error_setg(errp, "Unknown file format '%s'", fmt); return; } proto_drv = bdrv_find_protocol(filename, true); if (!proto_drv) { error_setg(errp, "Unknown protocol '%s'", filename); return; } create_opts = qemu_opts_append(create_opts, drv->create_opts); create_opts = qemu_opts_append(create_opts, proto_drv->create_opts); /* Create parameter list with default values */ opts = qemu_opts_create(create_opts, NULL, 0, &error_abort); qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size); /* Parse -o options */ if (options) { if (qemu_opts_do_parse(opts, options, NULL) != 0) { error_setg(errp, "Invalid options for file format '%s'", fmt); goto out; } } if (base_filename) { if (qemu_opt_set(opts, <API key>, base_filename)) { error_setg(errp, "Backing file not supported for file format '%s'", fmt); goto out; } } if (base_fmt) { if (qemu_opt_set(opts, <API key>, base_fmt)) { error_setg(errp, "Backing file format not supported for file " "format '%s'", fmt); goto out; } } backing_file = qemu_opt_get(opts, <API key>); if (backing_file) { if (!strcmp(filename, backing_file)) { error_setg(errp, "Error: Trying to create an image with the " "same filename as the backing file"); goto out; } } backing_fmt = qemu_opt_get(opts, <API key>); if (backing_fmt) { backing_drv = bdrv_find_format(backing_fmt); if (!backing_drv) { error_setg(errp, "Unknown backing file format '%s'", backing_fmt); goto out; } } // The size for the image must always be specified, with one exception: // If we are using a backing file, we can obtain the size from there size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0); if (size == -1) { if (backing_file) { BlockDriverState *bs; int64_t size; int back_flags; /* backing files always opened read-only */ back_flags = flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING); bs = NULL; ret = bdrv_open(&bs, backing_file, NULL, NULL, back_flags, backing_drv, &local_err); if (ret < 0) { error_setg_errno(errp, -ret, "Could not open '%s': %s", backing_file, error_get_pretty(local_err)); error_free(local_err); local_err = NULL; goto out; } size = bdrv_getlength(bs); if (size < 0) { error_setg_errno(errp, -size, "Could not get size of '%s'", backing_file); bdrv_unref(bs); goto out; } qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size); bdrv_unref(bs); } else { error_setg(errp, "Image creation needs a size parameter"); goto out; } } if (!quiet) { printf("Formatting '%s', fmt=%s ", filename, fmt); qemu_opts_print(opts); puts(""); } ret = bdrv_create(drv, filename, opts, &local_err); if (ret == -EFBIG) { /* This is generally a better message than whatever the driver would * deliver (especially because of the cluster_size_hint), since that * is most probably not much different from "image too large". */ const char *cluster_size_hint = ""; if (qemu_opt_get_size(opts, <API key>, 0)) { cluster_size_hint = " (try using a larger cluster size)"; } error_setg(errp, "The image size is too large for file format '%s'" "%s", fmt, cluster_size_hint); error_free(local_err); local_err = NULL; } out: qemu_opts_del(opts); qemu_opts_free(create_opts); if (local_err) { error_propagate(errp, local_err); } } AioContext *<API key>(BlockDriverState *bs) { return bs->aio_context; } void <API key>(BlockDriverState *bs) { BdrvAioNotifier *baf; if (!bs->drv) { return; } QLIST_FOREACH(baf, &bs->aio_notifiers, list) { baf->detach_aio_context(baf->opaque); } if (bs->io_limits_enabled) { <API key>(&bs->throttle_state); } if (bs->drv-><API key>) { bs->drv-><API key>(bs); } if (bs->file) { <API key>(bs->file); } if (bs->backing_hd) { <API key>(bs->backing_hd); } bs->aio_context = NULL; } void <API key>(BlockDriverState *bs, AioContext *new_context) { BdrvAioNotifier *ban; if (!bs->drv) { return; } bs->aio_context = new_context; if (bs->backing_hd) { <API key>(bs->backing_hd, new_context); } if (bs->file) { <API key>(bs->file, new_context); } if (bs->drv-><API key>) { bs->drv-><API key>(bs, new_context); } if (bs->io_limits_enabled) { <API key>(&bs->throttle_state, new_context); } QLIST_FOREACH(ban, &bs->aio_notifiers, list) { ban-><API key>(new_context, ban->opaque); } } void <API key>(BlockDriverState *bs, AioContext *new_context) { bdrv_drain_all(); /* ensure there are no in-flight requests */ <API key>(bs); /* This function executes in the old AioContext so acquire the new one in * case it runs in a different thread. */ aio_context_acquire(new_context); <API key>(bs, new_context); aio_context_release(new_context); } void <API key>(BlockDriverState *bs, void (*<API key>)(AioContext *new_context, void *opaque), void (*detach_aio_context)(void *opaque), void *opaque) { BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1); *ban = (BdrvAioNotifier){ .<API key> = <API key>, .detach_aio_context = detach_aio_context, .opaque = opaque }; QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list); } void <API key>(BlockDriverState *bs, void (*<API key>)(AioContext *, void *), void (*detach_aio_context)(void *), void *opaque) { BdrvAioNotifier *ban, *ban_next; QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) { if (ban-><API key> == <API key> && ban->detach_aio_context == detach_aio_context && ban->opaque == opaque) { QLIST_REMOVE(ban, list); g_free(ban); return; } } abort(); } void <API key>(BlockDriverState *bs, NotifierWithReturn *notifier) { <API key>(&bs-><API key>, notifier); } int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts) { if (!bs->drv->bdrv_amend_options) { return -ENOTSUP; } return bs->drv->bdrv_amend_options(bs, opts); } /* This function will be called by the <API key> method * of block filter and by <API key>. * It is used to test if the given bs is the candidate or recurse more in the * node graph. */ bool <API key>(BlockDriverState *bs, BlockDriverState *candidate) { /* return false if basic checks fails */ if (!bs || !bs->drv) { return false; } /* the code reached a non block filter driver -> check if the bs is * the same as the candidate. It's the recursion termination condition. */ if (!bs->drv->is_filter) { return bs == candidate; } /* Down this path the driver is a block filter driver */ /* If the block filter recursion method is defined use it to recurse down * the node graph. */ if (bs->drv-><API key>) { return bs->drv-><API key>(bs, candidate); } /* the driver is a block filter but don't allow to recurse -> return false */ return false; } /* This function checks if the candidate is the first non filter bs down it's * bs chain. Since we don't have pointers to parents it explore all bs chains * from the top. Some filters can choose not to pass down the recursion. */ bool <API key>(BlockDriverState *candidate) { BlockDriverState *bs; /* walk down the bs forest recursively */ QTAILQ_FOREACH(bs, &bdrv_states, device_list) { bool perm; /* try to recurse in this top level bs */ perm = <API key>(bs, candidate); /* candidate is the first non filter */ if (perm) { return true; } } return false; } BlockDriverState *<API key>(const char *node_name, Error **errp) { BlockDriverState *to_replace_bs = bdrv_find_node(node_name); if (!to_replace_bs) { error_setg(errp, "Node name '%s' not found", node_name); return NULL; } if (bdrv_op_is_blocked(to_replace_bs, <API key>, errp)) { return NULL; } /* We don't want arbitrary node of the BDS chain to be replaced only the top * most non filter in order to prevent data corruption. * Another benefit is that this tests exclude backing files which are * blocked by the backing blockers. */ if (!<API key>(to_replace_bs)) { error_setg(errp, "Only top most non filter can be replaced"); return NULL; } return to_replace_bs; } void bdrv_io_plug(BlockDriverState *bs) { BlockDriver *drv = bs->drv; if (drv && drv->bdrv_io_plug) { drv->bdrv_io_plug(bs); } else if (bs->file) { bdrv_io_plug(bs->file); } } void bdrv_io_unplug(BlockDriverState *bs) { BlockDriver *drv = bs->drv; if (drv && drv->bdrv_io_unplug) { drv->bdrv_io_unplug(bs); } else if (bs->file) { bdrv_io_unplug(bs->file); } } void bdrv_flush_io_queue(BlockDriverState *bs) { BlockDriver *drv = bs->drv; if (drv && drv->bdrv_flush_io_queue) { drv->bdrv_flush_io_queue(bs); } else if (bs->file) { bdrv_flush_io_queue(bs->file); } } static bool append_open_options(QDict *d, BlockDriverState *bs) { const QDictEntry *entry; bool found_any = false; for (entry = qdict_first(bs->options); entry; entry = qdict_next(bs->options, entry)) { /* Only take options for this level and exclude all non-driver-specific * options */ if (!strchr(qdict_entry_key(entry), '.') && strcmp(qdict_entry_key(entry), "node-name")) { qobject_incref(qdict_entry_value(entry)); qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry)); found_any = true; } } return found_any; } /* Updates the following BDS fields: * - exact_filename: A filename which may be used for opening a block device * which (mostly) equals the given BDS (even without any * other options; so reading and writing must return the same * results, but caching etc. may be different) * - full_open_options: Options which, when given when opening a block device * (without a filename), result in a BDS (mostly) * equalling the given one * - filename: If exact_filename is set, it is copied here. Otherwise, * full_open_options is converted to a JSON object, prefixed with * "json:" (for use through the JSON pseudo protocol) and put here. */ void <API key>(BlockDriverState *bs) { BlockDriver *drv = bs->drv; QDict *opts; if (!drv) { return; } /* This BDS's file name will most probably depend on its file's name, so * refresh that first */ if (bs->file) { <API key>(bs->file); } if (drv-><API key>) { /* Obsolete information is of no use here, so drop the old file name * information before refreshing it */ bs->exact_filename[0] = '\0'; if (bs->full_open_options) { QDECREF(bs->full_open_options); bs->full_open_options = NULL; } drv-><API key>(bs); } else if (bs->file) { /* Try to reconstruct valid information from the underlying file */ bool has_open_options; bs->exact_filename[0] = '\0'; if (bs->full_open_options) { QDECREF(bs->full_open_options); bs->full_open_options = NULL; } opts = qdict_new(); has_open_options = append_open_options(opts, bs); /* If no specific options have been given for this BDS, the filename of * the underlying file should suffice for this one as well */ if (bs->file->exact_filename[0] && !has_open_options) { strcpy(bs->exact_filename, bs->file->exact_filename); } /* Reconstructing the full options QDict is simple for most format block * drivers, as long as the full options are known for the underlying * file BDS. The full options QDict of that file BDS should somehow * contain a representation of the filename, therefore the following * suffices without querying the (exact_)filename of this BDS. */ if (bs->file->full_open_options) { qdict_put_obj(opts, "driver", QOBJECT(qstring_from_str(drv->format_name))); QINCREF(bs->file->full_open_options); qdict_put_obj(opts, "file", QOBJECT(bs->file->full_open_options)); bs->full_open_options = opts; } else { QDECREF(opts); } } else if (!bs->full_open_options && qdict_size(bs->options)) { /* There is no underlying file BDS (at least referenced by BDS.file), * so the full options QDict should be equal to the options given * specifically for this block device when it was opened (plus the * driver specification). * Because those options don't change, there is no need to update * full_open_options when it's already set. */ opts = qdict_new(); append_open_options(opts, bs); qdict_put_obj(opts, "driver", QOBJECT(qstring_from_str(drv->format_name))); if (bs->exact_filename[0]) { /* This may not work for all block protocol drivers (some may * require this filename to be parsed), but we have to find some * default solution here, so just include it. If some block driver * does not support pure options without any filename at all or * needs some special format of the options QDict, it needs to * implement the driver-specific <API key>() function. */ qdict_put_obj(opts, "filename", QOBJECT(qstring_from_str(bs->exact_filename))); } bs->full_open_options = opts; } if (bs->exact_filename[0]) { pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename); } else if (bs->full_open_options) { QString *json = qobject_to_json(QOBJECT(bs->full_open_options)); snprintf(bs->filename, sizeof(bs->filename), "json:%s", qstring_get_str(json)); QDECREF(json); } } /* This accessor function purpose is to allow the device models to access the * BlockAcctStats structure embedded inside a BlockDriverState without being * aware of the BlockDriverState structure layout. * It will go away when the BlockAcctStats structure will be moved inside * the device models. */ BlockAcctStats *bdrv_get_stats(BlockDriverState *bs) { return &bs->stats; }