ULONG STDMETHODCALLTYPE DirectWriteFontFileLoader::AddRef() { return InterlockedIncrement(&m_referenceCount); }
STDMETHODIMP_(ULONG) WCEnumFormatEtc::AddRef(void) { return InterlockedIncrement(&m_ref); }
ULONG STDMETHODCALLTYPE FileStream::AddRef(void) { return (ULONG)InterlockedIncrement(&_refcount); }
NTSTATUS NdasDluIoctlDeviceLock( IN PNDAS_LOGICALUNIT_EXTENSION LogicalUnitExtension, IN PNDAS_DLU_EXTENSION DluLuExtension, IN PNDSCIOCTL_DEVICELOCK DeviceLockControl, IN PSCSI_REQUEST_BLOCK Srb ){ NTSTATUS status; PLURN_DEVLOCK_CONTROL lurnDeviceLock; PCCB ccb; PNDAS_DLU_EXTENSION ndasDluExtension = NdasDluGetExtension(LogicalUnitExtension); // // Create a CCB // status = LsCcbAllocate(&ccb); if(!NT_SUCCESS(status)) { Srb->SrbStatus = SRB_STATUS_INVALID_REQUEST; KDPrint(1,("LsCcbAllocate() failed.\n")); return status; } lurnDeviceLock = (PLURN_DEVLOCK_CONTROL)ExAllocatePoolWithTag(NonPagedPool, sizeof(LURN_DEVLOCK_CONTROL), NDAS_DLU_PTAG_IOCTL); if(!lurnDeviceLock) { Srb->SrbStatus = SRB_STATUS_INVALID_REQUEST; KDPrint(1,("ExAllocatePoolWithTag() failed.\n")); return STATUS_INSUFFICIENT_RESOURCES; } LSCCB_INITIALIZE(ccb); ccb->OperationCode = CCB_OPCODE_DEVLOCK; ccb->DataBuffer = lurnDeviceLock; ccb->DataBufferLength = sizeof(LURN_DEVLOCK_CONTROL); LsCcbSetFlag(ccb, CCB_FLAG_ALLOCATED|CCB_FLAG_DATABUF_ALLOCATED); // Ioctl Srb will complete asynchronously. ccb->Srb = Srb; InterlockedIncrement(&DluLuExtension->RequestExecuting); // // Increment in-progress count // LsuIncrementTdiClientInProgress(); LsCcbSetCompletionRoutine(ccb, NdasDluCcbCompletion, LogicalUnitExtension); // // Set up request // lurnDeviceLock->LockId = DeviceLockControl->LockId; lurnDeviceLock->LockOpCode = DeviceLockControl->LockOpCode; lurnDeviceLock->AdvancedLock = DeviceLockControl->AdvancedLock; lurnDeviceLock->AddressRangeValid = DeviceLockControl->AddressRangeValid; lurnDeviceLock->RequireLockAcquisition = DeviceLockControl->RequireLockAcquisition; lurnDeviceLock->StartingAddress = DeviceLockControl->StartingAddress; lurnDeviceLock->ContentionTimeOut = DeviceLockControl->ContentionTimeOut; RtlCopyMemory(lurnDeviceLock->LockData, DeviceLockControl->LockData, NDSCLOCK_LOCKDATA_LENGTH); ASSERT(NDSCLOCK_LOCKDATA_LENGTH == LURNDEVLOCK_LOCKDATA_LENGTH); // // Send the request // status = LurRequest( ndasDluExtension->LUR, ccb ); if(!NT_SUCCESS(status)) { KDPrint(1,("LurnRequest() failed.\n")); LsCcbFree(ccb); ExFreePoolWithTag(lurnDeviceLock, NDSC_PTAG_IOCTL); status = STATUS_SUCCESS; Srb->SrbStatus = SRB_STATUS_INVALID_REQUEST; } else { status = STATUS_PENDING; } return status; }
STDMETHODIMP_(ULONG32) HXCloakedV2TCPSocket::AddRef() { return InterlockedIncrement(&m_lRefCount); }
void Main_OnRemindTimer (void) { Main_RepopulateTabs (TRUE); // See if anything is close to expiring; if so, display a warning // dialog. Make sure we never display a warning more than once. // size_t iExpired; if ((iExpired = Main_FindExpiredCreds()) != -1) { if (InterlockedIncrement (&g.fShowingMessage) != 1) { InterlockedDecrement (&g.fShowingMessage); } else { char * rootcell = NULL; char password[PROBE_PASSWORD_LEN+1]; struct afsconf_cell cellconfig; BOOL serverReachable = FALSE; DWORD code; rootcell = (char *)GlobalAlloc(GPTR,MAXCELLCHARS+1); if (!rootcell) goto cleanup; code = KFW_AFS_get_cellconfig(g.aCreds[ iExpired ].szCell, (afsconf_cell*)&cellconfig, rootcell); if (code) goto cleanup; if (KFW_is_available()) { // If we can't use the FSProbe interface we can attempt to forge // a kinit and if we can back an invalid user error we know the // kdc is at least reachable serverReachable = KFW_probe_kdc(&cellconfig); } else { int i; for ( i=0 ; i<PROBE_PASSWORD_LEN ; i++ ) password[i] = 'x'; code = ObtainNewCredentials(rootcell, PROBE_USERNAME, password, TRUE); switch ( code ) { case INTK_BADPW: case KERB_ERR_PRINCIPAL_UNKNOWN: case KERB_ERR_SERVICE_EXP: case RD_AP_TIME: serverReachable = TRUE; break; default: serverReachable = FALSE; } } cleanup: if (rootcell) GlobalFree(rootcell); if (serverReachable) ShowObtainCreds (TRUE, g.aCreds[ iExpired ].szCell); else InterlockedDecrement (&g.fShowingMessage); } } }
//------------------------------------------------------------------------------ // CSimpleThermostatDevice::AddRef //------------------------------------------------------------------------------ ULONG CSimpleThermostatDevice::AddRef() { return InterlockedIncrement( &m_cRef ); }// CSimpleThermostatDevice::AddRef
void MyAssertDumpToFile(const wchar_t* pszFile, int nLine, const wchar_t* pszTest) { wchar_t dmpfile[MAX_PATH+64] = L"", szVer4[8] = L"", szLine[64]; typedef HRESULT (WINAPI* SHGetFolderPath_t)(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath); HMODULE hShell = LoadLibrary(L"shell32.dll"); SHGetFolderPath_t shGetFolderPath = hShell ? (SHGetFolderPath_t)GetProcAddress(hShell, "SHGetFolderPathW") : NULL; HRESULT hrc = shGetFolderPath ? shGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL, 0/*SHGFP_TYPE_CURRENT*/, dmpfile) : E_FAIL; if (hShell) FreeLibrary(hShell); if (FAILED(hrc)) { memset(dmpfile, 0, sizeof(dmpfile)); if (!GetTempPath(MAX_PATH, dmpfile) || !*dmpfile) { //pszError = L"CreateDumpForReport called, get desktop or temp folder failed"; return; } } wcscat_c(dmpfile, (*dmpfile && dmpfile[lstrlen(dmpfile)-1] != L'\\') ? L"\\ConEmuTrap" : L"ConEmuTrap"); CreateDirectory(dmpfile, NULL); int nLen = lstrlen(dmpfile); lstrcpyn(szVer4, _T(MVV_4a), countof(szVer4)); static LONG snAutoIndex = 0; LONG nAutoIndex = InterlockedIncrement(&snAutoIndex); msprintf(dmpfile+nLen, countof(dmpfile)-nLen, L"\\Assert-%02u%02u%02u%s-%u-%u.txt", MVV_1, MVV_2, MVV_3, szVer4, GetCurrentProcessId(), nAutoIndex); HANDLE hFile = CreateFile(dmpfile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) { //pszError = L"Failed to create dump file"; return; } DWORD nWrite; msprintf(szLine, countof(szLine), L"CEAssert PID=%u TID=%u\r\nAssertion in ", GetCurrentProcessId(), GetCurrentThreadId()); WriteFile(hFile, szLine, (nWrite = lstrlen(szLine)*2), &nWrite, NULL); if (!GetModuleFileNameW(NULL, dmpfile, countof(dmpfile)-2)) lstrcpyn(dmpfile, L"<unknown>\r\n", countof(dmpfile)); else wcscat_c(dmpfile, L"\r\n"); WriteFile(hFile, dmpfile, (nWrite = lstrlen(dmpfile)*2), &nWrite, NULL); // File.cpp: 123\r\n if (pszFile) { WriteFile(hFile, pszFile, (nWrite = lstrlen(pszFile)*2), &nWrite, NULL); msprintf(szLine, countof(szLine), L": %i\r\n\r\n", nLine); WriteFile(hFile, szLine, (nWrite = lstrlen(szLine)*2), &nWrite, NULL); } if (pszTest) { WriteFile(hFile, pszTest, (nWrite = lstrlen(pszTest)*2), &nWrite, NULL); WriteFile(hFile, L"\r\n", 4, &nWrite, NULL); } CloseHandle(hFile); }
int MyAssertProc(const wchar_t* pszFile, int nLine, const wchar_t* pszTest, bool abNoPipe) { HooksUnlocker; #ifdef _DEBUG if (MyAssertSkip(pszFile, nLine, pszTest, abNoPipe)) return 1; #endif MyAssertDumpToFile(pszFile, nLine, pszTest); HANDLE hHeap = GetProcessHeap(); MyAssertInfo* pa = (MyAssertInfo*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(MyAssertInfo)); if (!pa) return -1; wchar_t *szExeName = (wchar_t*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, (MAX_PATH+1)*sizeof(wchar_t)); if (szExeName && !GetModuleFileNameW(NULL, szExeName, MAX_PATH+1)) szExeName[0] = 0; pa->bNoPipe = abNoPipe; msprintf(pa->szTitle, countof(pa->szTitle), L"CEAssert PID=%u TID=%u", GetCurrentProcessId(), GetCurrentThreadId()); wchar_t szVer4[2] = WSTRING(MVV_4a); msprintf(pa->szDebugInfo, countof(pa->szDebugInfo), L"Assertion in %s [%02u%02u%02u%s]\n%s\n\n%s: %i\n\nPress 'Retry' to trap.", szExeName ? szExeName : L"<HeapAllocFailed>", MVV_1, MVV_2, MVV_3, szVer4, pszTest ? pszTest : L"", pszFile, nLine); DWORD dwCode = 0; if (gAllowAssertThread == am_Thread) { DWORD dwTID; HANDLE hThread = apiCreateThread(MyAssertThread, pa, &dwTID, "MyAssertThread"); if (hThread == NULL) { dwCode = IDRETRY; goto wrap; } WaitForSingleObject(hThread, INFINITE); GetExitCodeThread(hThread, &dwCode); CloseHandle(hThread); goto wrap; } #ifdef ASSERT_PIPE_ALLOWED #ifdef _DEBUG if (!abNoPipe && (gAllowAssertThread == am_Pipe)) { HWND hConWnd = GetConEmuHWND(2); HWND hGuiWnd = ghConEmuWnd; // -- искать - нельзя. Если мы НЕ в ConEmu - нельзя стучаться в другие копии!!! //#ifndef CONEMU_MINIMAL //if (hGuiWnd == NULL) //{ // hGuiWnd = FindWindowEx(NULL, NULL, VirtualConsoleClassMain, NULL); //} //#endif if (hGuiWnd && gnInMyAssertTrap <= 0) { InterlockedIncrement(&gnInMyAssertTrap); InterlockedIncrement(&gnInMyAssertPipe); gnInMyAssertThread = GetCurrentThreadId(); ResetEvent(ghInMyAssertTrap); dwCode = GuiMessageBox(abNoPipe ? NULL : hGuiWnd, pa->szDebugInfo, pa->szTitle, MB_SETFOREGROUND|MB_SYSTEMMODAL|MB_RETRYCANCEL); InterlockedDecrement(&gnInMyAssertTrap); InterlockedDecrement(&gnInMyAssertPipe); SetEvent(ghInMyAssertTrap); gnInMyAssertThread = 0; goto wrap; } } while (gnInMyAssertPipe>0 && (gnInMyAssertThread != GetCurrentThreadId())) { Sleep(250); } #endif #endif // В консольных приложениях попытка запустить CreateThread(MyAssertThread) может зависать dwCode = MyAssertThread(pa); wrap: if (pa) HeapFree(hHeap, 0, pa); if (szExeName) HeapFree(hHeap, 0, szExeName); return (dwCode == IDRETRY) ? -1 : 1; }
int gettimeofday(struct timeval* tp, int* /*tz*/) { static LARGE_INTEGER tickFrequency, epochOffset; static Boolean isInitialized = False; LARGE_INTEGER tickNow; #if !defined(_WIN32_WCE) QueryPerformanceCounter(&tickNow); #else tickNow.QuadPart = GetTickCount(); #endif if (!isInitialized) { if(1 == InterlockedIncrement(&initializeLock_gettimeofday)) { #if !defined(_WIN32_WCE) // For our first call, use "ftime()", so that we get a time with a proper epoch. // For subsequent calls, use "QueryPerformanceCount()", because it's more fine-grain. struct timeb tb; ftime(&tb); tp->tv_sec = tb.time; tp->tv_usec = 1000*tb.millitm; // Also get our counter frequency: QueryPerformanceFrequency(&tickFrequency); #else /* FILETIME of Jan 1 1970 00:00:00. */ const LONGLONG epoch = 116444736000000000LL; FILETIME fileTime; LARGE_INTEGER time; GetSystemTimeAsFileTime(&fileTime); time.HighPart = fileTime.dwHighDateTime; time.LowPart = fileTime.dwLowDateTime; // convert to from 100ns time to unix timestamp in seconds, 1000*1000*10 tp->tv_sec = (long)((time.QuadPart - epoch) / 10000000L); /* GetSystemTimeAsFileTime has just a seconds resolution, thats why wince-version of gettimeofday is not 100% accurate, usec accuracy would be calculated like this: // convert 100 nanoseconds to usec tp->tv_usec= (long)((time.QuadPart - epoch)%10000000L) / 10L; */ tp->tv_usec = 0; // resolution of GetTickCounter() is always milliseconds tickFrequency.QuadPart = 1000; #endif // compute an offset to add to subsequent counter times, so we get a proper epoch: epochOffset.QuadPart = tp->tv_sec * tickFrequency.QuadPart + (tp->tv_usec * tickFrequency.QuadPart) / 1000000L - tickNow.QuadPart; // next caller can use ticks for time calculation isInitialized = True; return 0; } else { InterlockedDecrement(&initializeLock_gettimeofday); // wait until first caller has initialized static values while(!isInitialized){ Sleep(1); } } } // adjust our tick count so that we get a proper epoch: tickNow.QuadPart += epochOffset.QuadPart; tp->tv_sec = (long)(tickNow.QuadPart / tickFrequency.QuadPart); tp->tv_usec = (long)(((tickNow.QuadPart % tickFrequency.QuadPart) * 1000000L) / tickFrequency.QuadPart); return 0; }
void DllAddRef(void) { InterlockedIncrement(&g_cRefDll); }
//operator ++ 函数 int osm_atomic32::operator++() { return static_cast<int>(InterlockedIncrement( reinterpret_cast<volatile LONG*>(&value_))); }
static ssize_t ofi_nd_ep_readv(struct fid_ep *pep, const struct iovec *iov, void **desc, size_t count, fi_addr_t src_addr, uint64_t addr, uint64_t key, void *context) { struct fi_rma_iov rma_iov = { .addr = addr, .len = iov[0].iov_len, .key = key }; struct fi_msg_rma msg = { .msg_iov = iov, .desc = desc, .iov_count = count, .addr = src_addr, .rma_iov = &rma_iov, .rma_iov_count = 1, .context = context, .data = 0 }; assert(pep->fid.fclass == FI_CLASS_EP); if (pep->fid.fclass != FI_CLASS_EP) return -FI_EINVAL; struct nd_ep *ep = container_of(pep, struct nd_ep, fid); return ofi_nd_ep_readmsg(pep, &msg, ep->info->rx_attr->op_flags); } static ssize_t ofi_nd_ep_readmsg(struct fid_ep *pep, const struct fi_msg_rma *msg, uint64_t flags) { assert(pep->fid.fclass == FI_CLASS_EP); assert(msg); if (pep->fid.fclass != FI_CLASS_EP) return -FI_EINVAL; size_t msg_len = 0, rma_len = 0, i; HRESULT hr; struct nd_ep *ep = container_of(pep, struct nd_ep, fid); if (!ep->qp) return -FI_EOPBADSTATE; for (i = 0; i < msg->iov_count; i++) { if (msg->msg_iov[i].iov_len && !msg->msg_iov[i].iov_base) return -FI_EINVAL; msg_len += msg->msg_iov[i].iov_len; } for (i = 0; i < msg->rma_iov_count; i++) { if (msg->rma_iov[i].len && !msg->rma_iov[i].addr) return -FI_EINVAL; rma_len += msg->rma_iov[i].len; } /* Check the following: */ if ((msg_len != rma_len) || /* - msg and rma len are correlated */ /* - iov counts are less or equal than supported */ (msg->iov_count > ND_MSG_IOV_LIMIT || msg->rma_iov_count > ND_MSG_IOV_LIMIT) || /* - transmitted length is less or equal than max possible */ (msg_len > ep->domain->info->ep_attr->max_msg_size)) return -FI_EINVAL; struct nd_cq_entry *main_entry = ofi_nd_buf_alloc_nd_cq_entry(); if (!main_entry) return -FI_ENOMEM; memset(main_entry, 0, sizeof(*main_entry)); main_entry->data = msg->data; main_entry->flags = flags; main_entry->domain = ep->domain; main_entry->context = msg->context; main_entry->seq = InterlockedAdd64(&ep->domain->msg_cnt, 1); /* since write operation can't be canceled, set NULL into * the 1st byte of internal data of context */ if (msg->context) ND_FI_CONTEXT(msg->context) = 0; struct fi_rma_iov rma_iovecs[ND_MSG_INTERNAL_IOV_LIMIT]; size_t rma_count = 0; size_t from_split_map[ND_MSG_INTERNAL_IOV_LIMIT]; size_t to_split_map[ND_MSG_INTERNAL_IOV_LIMIT]; uint64_t remote_addr[ND_MSG_INTERNAL_IOV_LIMIT]; ofi_nd_split_msg_iov_2_rma_iov(msg->rma_iov, msg->rma_iov_count, msg->msg_iov, msg->iov_count, rma_iovecs, &rma_count, from_split_map, to_split_map, remote_addr); assert(rma_count <= ND_MSG_INTERNAL_IOV_LIMIT); main_entry->wait_completion.comp_count = 0; main_entry->wait_completion.total_count = rma_count; InitializeCriticalSection(&main_entry->wait_completion.comp_lock); struct nd_cq_entry *entries[ND_MSG_IOV_LIMIT]; for (i = 0; i < rma_count; i++) { entries[i] = ofi_nd_buf_alloc_nd_cq_entry(); if (!entries[i]) goto fn_fail; memset(entries[i], 0, sizeof(*entries[i])); entries[i]->data = msg->data; entries[i]->flags = flags; entries[i]->domain = ep->domain; entries[i]->context = msg->context; entries[i]->seq = main_entry->seq; entries[i]->aux_entry = main_entry; hr = ep->domain->adapter->lpVtbl->CreateMemoryRegion( ep->domain->adapter, &IID_IND2MemoryRegion, ep->domain->adapter_file, (void**)&entries[i]->mr[0]); if (FAILED(hr)) goto fn_fail; entries[i]->mr_count = 1; hr = ofi_nd_util_register_mr( entries[i]->mr[0], (const void *)remote_addr[i], rma_iovecs[i].len, ND_MR_FLAG_ALLOW_LOCAL_WRITE | ND_MR_FLAG_ALLOW_REMOTE_READ | ND_MR_FLAG_ALLOW_REMOTE_WRITE); if (FAILED(hr)) goto fn_fail; ND2_SGE sge = { .Buffer = (void *)remote_addr[i], .BufferLength = (ULONG)rma_iovecs[i].len, .MemoryRegionToken = (UINT32)(uintptr_t)msg->desc[to_split_map[i]] }; hr = ep->qp->lpVtbl->Read(ep->qp, entries[i], &sge, 1, (UINT64)rma_iovecs[i].addr, (UINT32)rma_iovecs[i].key, 0); if (FAILED(hr)) goto fn_fail; } return FI_SUCCESS; fn_fail: while (i-- > 0) ofi_nd_free_cq_entry(entries[i]); ND_LOG_WARN(FI_LOG_EP_DATA, ofi_nd_strerror((DWORD)hr, NULL)); return H2F(hr); } static ssize_t ofi_nd_ep_write(struct fid_ep *ep, const void *buf, size_t len, void *desc, fi_addr_t dest_addr, uint64_t addr, uint64_t key, void *context) { struct iovec iov = { .iov_base = (void*)buf, .iov_len = len }; return ofi_nd_ep_writev(ep, &iov, &desc, 1, dest_addr, addr, key, context); } static ssize_t ofi_nd_ep_writev(struct fid_ep *pep, const struct iovec *iov, void **desc, size_t count, fi_addr_t dest_addr, uint64_t addr, uint64_t key, void *context) { struct fi_rma_iov rma_iov = { .addr = addr, .len = iov[0].iov_len, .key = key }; struct fi_msg_rma msg = { .msg_iov = iov, .desc = desc, .iov_count = count, .addr = dest_addr, .rma_iov = &rma_iov, .rma_iov_count = 1, .context = context, .data = 0 }; assert(pep->fid.fclass == FI_CLASS_EP); if (pep->fid.fclass != FI_CLASS_EP) return -FI_EINVAL; struct nd_ep *ep = container_of(pep, struct nd_ep, fid); return ofi_nd_ep_writemsg(pep, &msg, ep->info->tx_attr->op_flags); } static ssize_t ofi_nd_ep_writemsg(struct fid_ep *pep, const struct fi_msg_rma *msg, uint64_t flags) { assert(pep->fid.fclass == FI_CLASS_EP); assert(msg); if (pep->fid.fclass != FI_CLASS_EP) return -FI_EINVAL; size_t msg_len = 0, rma_len = 0, i; HRESULT hr; struct nd_cq_entry *entries[ND_MSG_IOV_LIMIT]; struct nd_ep *ep = container_of(pep, struct nd_ep, fid); if (!ep->qp) return -FI_EOPBADSTATE; for (i = 0; i < msg->iov_count; i++) { if (msg->msg_iov[i].iov_len && !msg->msg_iov[i].iov_base) return -FI_EINVAL; msg_len += msg->msg_iov[i].iov_len; } if ((msg_len > ep->domain->info->ep_attr->max_msg_size) && (flags & FI_INJECT)) return -FI_EINVAL; for (i = 0; i < msg->rma_iov_count; i++) { if (msg->rma_iov[i].len && !msg->rma_iov[i].addr) return -FI_EINVAL; rma_len += msg->rma_iov[i].len; } /* Check the following: */ if ((msg_len != rma_len) || /* - msg and rma len are correlated */ /* - iov counts are less or equal than supported */ ((msg->iov_count > ND_MSG_IOV_LIMIT || msg->rma_iov_count > ND_MSG_IOV_LIMIT)) || /* - transmitted length is less or equal than max possible */ (msg_len > ep->domain->info->ep_attr->max_msg_size) || /* - if INJECT, data should be inlined */ ((flags & FI_INJECT) && (msg_len > ep->domain->info->tx_attr->inject_size))) return -FI_EINVAL; struct nd_cq_entry *main_entry = ofi_nd_buf_alloc_nd_cq_entry(); if (!main_entry) return -FI_ENOMEM; memset(main_entry, 0, sizeof(*main_entry)); main_entry->data = msg->data; main_entry->flags = flags; main_entry->domain = ep->domain; main_entry->context = msg->context; main_entry->seq = InterlockedAdd64(&ep->domain->msg_cnt, 1); /* since write operation can't be canceled, set NULL into * the 1st byte of internal data of context */ if (msg->context) ND_FI_CONTEXT(msg->context) = 0; /* TODO */ if (msg_len > (size_t)gl_data.inline_thr) { struct fi_rma_iov rma_iovecs[ND_MSG_INTERNAL_IOV_LIMIT]; size_t rma_count = 0; size_t from_split_map[ND_MSG_INTERNAL_IOV_LIMIT]; size_t to_split_map[ND_MSG_INTERNAL_IOV_LIMIT]; uint64_t remote_addr[ND_MSG_INTERNAL_IOV_LIMIT]; ofi_nd_split_msg_iov_2_rma_iov(msg->rma_iov, msg->rma_iov_count, msg->msg_iov, msg->iov_count, rma_iovecs, &rma_count, from_split_map, to_split_map, remote_addr); assert(rma_count <= ND_MSG_INTERNAL_IOV_LIMIT); main_entry->wait_completion.comp_count = 0; main_entry->wait_completion.total_count = rma_count; InitializeCriticalSection(&main_entry->wait_completion.comp_lock); for (i = 0; i < rma_count; i++) { entries[i] = ofi_nd_buf_alloc_nd_cq_entry(); if (!entries[i]) goto fn_fail; memset(entries[i], 0, sizeof(*entries[i])); entries[i]->data = msg->data; entries[i]->flags = flags; entries[i]->domain = ep->domain; entries[i]->context = msg->context; entries[i]->seq = main_entry->seq; entries[i]->aux_entry = main_entry; ND2_SGE sge = { .Buffer = (void *)remote_addr[i], .BufferLength = (ULONG)rma_iovecs[i].len, .MemoryRegionToken = (UINT32)(uintptr_t)msg->desc[to_split_map[i]] }; hr = ep->qp->lpVtbl->Write(ep->qp, entries[i], &sge, 1, (UINT64)rma_iovecs[i].addr, (UINT32)rma_iovecs[i].key, 0); if (FAILED(hr)) goto fn_fail; } return FI_SUCCESS; } else { if (msg_len) { main_entry->inline_buf = __ofi_nd_buf_alloc_nd_inlinebuf(&ep->domain->inlinebuf); if (!main_entry->inline_buf) return -FI_ENOMEM; char *buf = (char*)main_entry->inline_buf->buffer; for (i = 0; i < msg->iov_count; i++) { memcpy(buf, msg->msg_iov[i].iov_base, msg->msg_iov[i].iov_len); buf += msg->msg_iov[i].iov_len; } } for (i = 0; i < msg->rma_iov_count; i++) { char *buf = (char *)main_entry->inline_buf->buffer; entries[i] = ofi_nd_buf_alloc_nd_cq_entry(); if (!entries[i]) goto fn_fail; memset(entries[i], 0, sizeof(*entries[i])); entries[i]->data = msg->data; entries[i]->flags = flags; entries[i]->domain = ep->domain; entries[i]->context = msg->context; entries[i]->seq = main_entry->seq; entries[i]->aux_entry = main_entry; ND2_SGE sge = { .Buffer = (void *)(buf + msg->rma_iov[i].len), .BufferLength = (ULONG)msg->rma_iov[i].len, .MemoryRegionToken = main_entry->inline_buf->token }; hr = ep->qp->lpVtbl->Write(ep->qp, entries[i], &sge, 1, (UINT64)msg->rma_iov[i].addr, (UINT32)msg->rma_iov[i].key, 0); if (FAILED(hr)) goto fn_fail; } return FI_SUCCESS; } fn_fail: while (i-- > 0) ofi_nd_free_cq_entry(entries[i]); ND_LOG_WARN(FI_LOG_EP_DATA, ofi_nd_strerror((DWORD)hr, NULL)); return H2F(hr); } static ssize_t ofi_nd_ep_inject(struct fid_ep *pep, const void *buf, size_t len, fi_addr_t dest_addr, uint64_t addr, uint64_t key) { struct iovec iov = { .iov_base = (void*)buf, .iov_len = len }; struct fi_rma_iov rma_iov = { .addr = addr, .len = len, .key = key }; struct fi_msg_rma msg = { .msg_iov = &iov, .desc = 0, .iov_count = 1, .addr = dest_addr, .rma_iov = &rma_iov, .rma_iov_count = 1, .context = 0, .data = 0 }; return ofi_nd_ep_writemsg(pep, &msg, FI_INJECT); } static ssize_t ofi_nd_ep_writedata(struct fid_ep *pep, const void *buf, size_t len, void *desc, uint64_t data, fi_addr_t dest_addr, uint64_t addr, uint64_t key, void *context) { struct iovec iov = { .iov_base = (void*)buf, .iov_len = len }; struct fi_rma_iov rma_iov = { .addr = addr, .len = len, .key = key }; struct fi_msg_rma msg = { .msg_iov = &iov, .desc = &desc, .iov_count = 1, .addr = dest_addr, .rma_iov = &rma_iov, .rma_iov_count = 1, .context = context, .data = data }; assert(pep->fid.fclass == FI_CLASS_EP); if (pep->fid.fclass != FI_CLASS_EP) return -FI_EINVAL; struct nd_ep *ep = container_of(pep, struct nd_ep, fid); return ofi_nd_ep_writemsg(pep, &msg, ep->info->tx_attr->op_flags | FI_REMOTE_CQ_DATA); } static ssize_t ofi_nd_ep_writeinjectdata(struct fid_ep *ep, const void *buf, size_t len, uint64_t data, fi_addr_t dest_addr, uint64_t addr, uint64_t key) { struct iovec iov = { .iov_base = (void*)buf, .iov_len = len }; struct fi_rma_iov rma_iov = { .addr = addr, .len = len, .key = key }; struct fi_msg_rma msg = { .msg_iov = &iov, .desc = 0, .iov_count = 1, .addr = dest_addr, .rma_iov = &rma_iov, .rma_iov_count = 1, .context = 0, .data = data }; return ofi_nd_ep_writemsg(ep, &msg, FI_INJECT | FI_REMOTE_CQ_DATA); } void ofi_nd_read_event(ND2_RESULT *result) { assert(result); assert(result->RequestType == Nd2RequestTypeRead); nd_cq_entry *entry = (nd_cq_entry*)result->RequestContext; assert(entry); ND_LOG_EVENT_INFO(entry); /* Check whether the operation is complex, i.e. read operation * may consists from several subtasks of read */ if (entry->aux_entry) { EnterCriticalSection(&entry->aux_entry->wait_completion.comp_lock); entry->aux_entry->wait_completion.comp_count++; ND_LOG_DEBUG(FI_LOG_EP_DATA, "READ Event comp_count = %d, total_count = %d\n", entry->aux_entry->wait_completion.comp_count, entry->aux_entry->wait_completion.total_count); if (entry->aux_entry->wait_completion.comp_count < entry->aux_entry->wait_completion.total_count) { /* Should wait some remaining completion events about read operation */ LeaveCriticalSection(&entry->aux_entry->wait_completion.comp_lock); entry->aux_entry = NULL; ofi_nd_free_cq_entry(entry); return; } LeaveCriticalSection(&entry->aux_entry->wait_completion.comp_lock); } /*TODO: Handle erroneous case "result->Status != S_OK" */ ofi_nd_dispatch_cq_event(entry->state == LARGE_MSG_RECV_REQ ? LARGE_MSG_REQ : NORMAL_EVENT, entry, result); } void ofi_nd_write_event(ND2_RESULT *result) { assert(result); assert(result->RequestType == Nd2RequestTypeWrite); nd_cq_entry *entry = (nd_cq_entry*)result->RequestContext; assert(entry); struct nd_ep *ep = (struct nd_ep*)result->QueuePairContext; assert(ep); assert(ep->fid.fid.fclass == FI_CLASS_EP); ND_LOG_EVENT_INFO(entry); /* Check whether the operation is complex, i.e. write operation * may consist from several subtasks of write */ if (entry->aux_entry) { EnterCriticalSection(&entry->aux_entry->wait_completion.comp_lock); entry->aux_entry->wait_completion.comp_count++; if (entry->aux_entry->wait_completion.comp_count < entry->aux_entry->wait_completion.total_count) { /* Should wait some remaining completion events about write operation */ LeaveCriticalSection(&entry->aux_entry->wait_completion.comp_lock); entry->aux_entry = NULL; ofi_nd_free_cq_entry(entry); return; } LeaveCriticalSection(&entry->aux_entry->wait_completion.comp_lock); } if (!entry->context) { /* This means that this write was an internal event, * just release it */ ofi_nd_free_cq_entry(entry); return; } if (entry->flags & FI_REMOTE_CQ_DATA) { if (ofi_nd_ep_injectdata( &ep->fid, 0, 0, entry->data, FI_ADDR_UNSPEC) != FI_SUCCESS) ND_LOG_WARN(FI_LOG_CQ, "failed to write-inject"); } if (ep->cntr_write) { if (result->Status != S_OK) { InterlockedIncrement64(&ep->cntr_write->err); } InterlockedIncrement64(&ep->cntr_write->counter); WakeByAddressAll((void*)&ep->cntr_write->counter); } int notify = ofi_nd_util_completion_blackmagic( ep->info->tx_attr->op_flags, ep->send_flags, entry->flags) || result->Status != S_OK; if (notify) { PostQueuedCompletionStatus( entry->result.Status == S_OK ? ep->cq_send->iocp : ep->cq_send->err, 0, 0, &entry->base.ov); InterlockedIncrement(&ep->cq_send->count); WakeByAddressAll((void*)&ep->cq_send->count); } else { /* if notification is not requested - just free entry */ ofi_nd_free_cq_entry(entry); } } void ofi_nd_split_msg_iov_2_rma_iov(const struct fi_rma_iov *rma_iovecs, const size_t rma_count, const struct iovec *msg_iovecs, const size_t msg_count, struct fi_rma_iov res_iovecs[ND_MSG_INTERNAL_IOV_LIMIT], size_t *res_count, size_t from_split_map[ND_MSG_INTERNAL_IOV_LIMIT], size_t to_split_map[ND_MSG_INTERNAL_IOV_LIMIT], uint64_t remote_addr[ND_MSG_INTERNAL_IOV_LIMIT]) { size_t i; struct iovec from_rma_iovecs[ND_MSG_IOV_LIMIT]; size_t from_rma_count = rma_count; struct iovec res_msg_iovecs[ND_MSG_IOV_LIMIT]; size_t res_msg_count = 0; /* Convert RMA iovecs to MSG iovecs to be able to reuse * them in @ofi_nd_repack_iovecs */ for (i = 0; i < rma_count; i++) { from_rma_iovecs[i].iov_base = (void *)rma_iovecs[i].addr; from_rma_iovecs[i].iov_len = rma_iovecs[i].len; } ofi_nd_repack_iovecs(from_rma_iovecs, from_rma_count, msg_iovecs, msg_count, res_msg_iovecs, &res_msg_count, from_split_map, to_split_map, remote_addr); /* Extract MSG iov to RMA iovecs and returns them */ for (i = 0; i < res_msg_count; i++) { res_iovecs[i].addr = remote_addr[i]; res_iovecs[i].len = res_msg_iovecs[i].iov_len; res_iovecs[i].key = rma_iovecs[from_split_map[i]].key; remote_addr[i] = (uint64_t)res_msg_iovecs[i].iov_base; } *res_count = res_msg_count; }
int main (int argc, char *argv[]) { int i = 0; CRITICAL_SECTION cs; old_mutex_t ox; pthread_mutexattr_init(&ma); printf( "=============================================================================\n"); printf( "\nLock plus unlock on an unlocked mutex.\n%ld iterations\n\n", ITERATIONS); printf( "%-45s %15s %15s\n", "Test", "Total(msec)", "average(usec)"); printf( "-----------------------------------------------------------------------------\n"); /* * Time the loop overhead so we can subtract it from the actual test times. */ TESTSTART assert(1 == one); assert(1 == one); TESTSTOP durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; overHeadMilliSecs = durationMilliSecs; TESTSTART assert((dummy_call(&i), 1) == one); assert((dummy_call(&i), 1) == one); TESTSTOP durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Dummy call x 2", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); TESTSTART assert((interlocked_inc_with_conditionals(&i), 1) == one); assert((interlocked_dec_with_conditionals(&i), 1) == one); TESTSTOP durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Dummy call -> Interlocked with cond x 2", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); TESTSTART assert((InterlockedIncrement((LPLONG)&i), 1) == (LONG)one); assert((InterlockedDecrement((LPLONG)&i), 1) == (LONG)one); TESTSTOP durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "InterlockedOp x 2", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); InitializeCriticalSection(&cs); TESTSTART assert((EnterCriticalSection(&cs), 1) == one); assert((LeaveCriticalSection(&cs), 1) == one); TESTSTOP DeleteCriticalSection(&cs); durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Simple Critical Section", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); old_mutex_use = OLD_WIN32CS; assert(old_mutex_init(&ox, NULL) == 0); TESTSTART assert(old_mutex_lock(&ox) == zero); assert(old_mutex_unlock(&ox) == zero); TESTSTOP assert(old_mutex_destroy(&ox) == 0); durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Old PT Mutex using a Critical Section (WNT)", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); old_mutex_use = OLD_WIN32MUTEX; assert(old_mutex_init(&ox, NULL) == 0); TESTSTART assert(old_mutex_lock(&ox) == zero); assert(old_mutex_unlock(&ox) == zero); TESTSTOP assert(old_mutex_destroy(&ox) == 0); durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Old PT Mutex using a Win32 Mutex (W9x)", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); printf( ".............................................................................\n"); /* * Now we can start the actual tests */ #ifdef PTW32_MUTEX_TYPES runTest("PTHREAD_MUTEX_DEFAULT (W9x,WNT)", PTHREAD_MUTEX_DEFAULT); runTest("PTHREAD_MUTEX_NORMAL (W9x,WNT)", PTHREAD_MUTEX_NORMAL); runTest("PTHREAD_MUTEX_ERRORCHECK (W9x,WNT)", PTHREAD_MUTEX_ERRORCHECK); runTest("PTHREAD_MUTEX_RECURSIVE (W9x,WNT)", PTHREAD_MUTEX_RECURSIVE); #else runTest("Non-blocking lock", 0); #endif printf( "=============================================================================\n"); /* * End of tests. */ pthread_mutexattr_destroy(&ma); one = i; /* Dummy assignment to avoid 'variable unused' warning */ return 0; }
static ULONG WINAPI RecycleBin_AddRef(IShellFolder2 *iface) { RecycleBin *This = (RecycleBin *)iface; TRACE("(%p)\n", This); return InterlockedIncrement(&This->refCount); }
// IUnknown ULONG DX11VideoRenderer::CActivate::AddRef(void) { return InterlockedIncrement(&m_lRefCount); }
ULONG STDMETHODCALLTYPE CiTunesEventHandler::AddRef() { InterlockedIncrement(&m_dwRefCount); return m_dwRefCount; }
LONG CEventManager::AddRef() { return InterlockedIncrement(&m_nRef); }
BOOL CALLBACK Main_DlgProc (HWND hDlg, UINT msg, WPARAM wp, LPARAM lp) { static UINT msgCheckTerminate = 0; if (msgCheckTerminate == 0) msgCheckTerminate = RegisterWindowMessage (TEXT("AfsCredsCheckTerminate")); if (msg == msgCheckTerminate) { Main_OnCheckTerminate(); } else switch (msg) { case WM_INITDIALOG: g.hMain = hDlg; Main_OnInitDialog (hDlg); break; case WM_DESTROY: Creds_CloseLibraries(); ChangeTrayIcon (NIM_DELETE); break; case WM_ACTIVATEAPP: if (wp) { Main_RepopulateTabs (FALSE); } break; case WM_COMMAND: switch (LOWORD(wp)) { case IDOK: case IDCANCEL: Main_Show (FALSE); break; case M_ACTIVATE: if (g.fIsWinNT || IsServiceRunning()) { if (!lp) // Got here from "/show" parameter? switch tabs. { HWND hTab = GetDlgItem (g.hMain, IDC_TABS); TabCtrl_SetCurSel (hTab, 0); Main_OnSelectTab(); } Main_Show (TRUE); } else { Message (MB_ICONHAND, IDS_UNCONFIG_TITLE_95, IDS_UNCONFIG_DESC_95); } break; case M_TERMINATE: if (g.fIsWinNT && IsServiceRunning()) ModalDialog (IDD_TERMINATE, NULL, (DLGPROC)Terminate_DlgProc); else if (g.fIsWinNT) ModalDialog (IDD_TERMINATE_SMALL, NULL, (DLGPROC)Terminate_DlgProc); else // (!g.fIsWinNT) ModalDialog (IDD_TERMINATE_SMALL_95, NULL, (DLGPROC)Terminate_DlgProc); break; case M_TERMINATE_NOW: Quit(); break; case M_REMIND: Main_OnCheckMenuRemind(); break; } break; case WM_TIMER: Main_OnRemindTimer(); break; case WM_NOTIFY: switch (((NMHDR*)lp)->code) { case TCN_SELCHANGE: Main_OnSelectTab(); break; } break; case WM_TRAYICON: switch (lp) { case WM_LBUTTONDOWN: if (IsServiceRunning() || !IsServiceConfigured()) Main_Show (TRUE); else if (!g.fIsWinNT) Message (MB_ICONHAND, IDS_UNCONFIG_TITLE_95, IDS_UNCONFIG_DESC_95); else ShowStartupWizard(); break; case WM_RBUTTONDOWN: HMENU hm; if ((hm = TaLocale_LoadMenu (MENU_TRAYICON)) != 0) { POINT pt; GetCursorPos(&pt); HMENU hmDummy = CreateMenu(); InsertMenu (hmDummy, 0, MF_POPUP, (UINT)hm, NULL); BOOL fRemind = FALSE; lock_ObtainMutex(&g.credsLock); for (size_t iCreds = 0; iCreds < g.cCreds; ++iCreds) { if (g.aCreds[ iCreds ].fRemind) fRemind = TRUE; } lock_ReleaseMutex(&g.credsLock); CheckMenuItem (hm, M_REMIND, MF_BYCOMMAND | ((fRemind) ? MF_CHECKED : MF_UNCHECKED)); SetForegroundWindow(hDlg); TrackPopupMenu (GetSubMenu (hmDummy, 0), TPM_RIGHTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, NULL, hDlg, NULL); PostMessage(hDlg, WM_NULL, 0, 0); DestroyMenu (hmDummy); } break; case WM_MOUSEMOVE: Main_OnMouseOver(); break; } break; case WM_OBTAIN_TOKENS: if ( InterlockedIncrement (&g.fShowingMessage) != 1 ) InterlockedDecrement (&g.fShowingMessage); else ShowObtainCreds (wp, (char *)lp); GlobalFree((void *)lp); break; case WM_START_SERVICE: { SC_HANDLE hManager; if ((hManager = OpenSCManager ( NULL, NULL, SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_QUERY_LOCK_STATUS)) != NULL) { SC_HANDLE hService; if ((hService = OpenService ( hManager, TEXT("TransarcAFSDaemon"), SERVICE_QUERY_STATUS | SERVICE_START)) != NULL) { if (StartService (hService, 0, 0)) TestAndDoMapShare(SERVICE_START_PENDING); if ( KFW_is_available() && KFW_AFS_wait_for_service_start() ) { #ifdef USE_MS2MIT KFW_import_windows_lsa(); #endif /* USE_MS2MIT */ KFW_AFS_renew_tokens_for_all_cells(); } CloseServiceHandle (hService); } CloseServiceHandle (hManager); } if (KFW_AFS_wait_for_service_start()) ObtainTokensFromUserIfNeeded(g.hMain); } break; } return FALSE; }
static ULONG WINAPI RegistrarCF_AddRef(IClassFactory *iface) { InterlockedIncrement(&dll_count); return 2; }
NTSTATUS NdasDluSrbIoctlQueryInfo( PNDAS_LOGICALUNIT_EXTENSION LogicalUnitExtension, PNDAS_DLU_EXTENSION DluLuExtension, PSCSI_REQUEST_BLOCK Srb, PNDASSCSI_QUERY_INFO_DATA QueryInfo, ULONG OutputBufferLength, PUCHAR OutputBuffer, PULONG SrbIoctlReturnCode, PUCHAR SrbStatus ) { NTSTATUS status; PCCB Ccb; // KIRQL oldIrql; UNREFERENCED_PARAMETER(LogicalUnitExtension); UNREFERENCED_PARAMETER(DluLuExtension); *SrbIoctlReturnCode = SRB_STATUS_SUCCESS; *SrbStatus = SRB_STATUS_SUCCESS; status = STATUS_SUCCESS; switch(QueryInfo->InfoClass) { case NdscPrimaryUnitDiskInformation: { PNDSCIOCTL_PRIMUNITDISKINFO primUnitDisk = (PNDSCIOCTL_PRIMUNITDISKINFO)OutputBuffer; PLUR_QUERY lurQuery; PLURN_PRIMARYINFORMATION lurPrimaryInfo; PBYTE lurBuffer; KDPrint(1,("NdscPrimaryUnitDiskInformation\n")); if(OutputBufferLength < sizeof(NDSCIOCTL_PRIMUNITDISKINFO)) { KDPrint(1,("Too small output buffer\n")); *SrbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_BUFFER_TOO_SMALL; if (OutputBufferLength > sizeof(UINT32)) primUnitDisk->Length = sizeof(NDSCIOCTL_PRIMUNITDISKINFO); break; } // // Query to the LUR // status = LsCcbAllocate(&Ccb); if(!NT_SUCCESS(status)) { KDPrint(1,("LsCcbAllocate() failed.\n")); *SrbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INSUFFICIENT_RESOURCES; break; } lurBuffer = ExAllocatePoolWithTag( NonPagedPool, SIZE_OF_LURQUERY(0, sizeof(LURN_PRIMARYINFORMATION)), LURN_IOCTL_POOL_TAG); if(lurBuffer == NULL) { KDPrint(1,("LsCcbAllocate() failed.\n")); *SrbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INSUFFICIENT_RESOURCES; break; } // // Set up asynchronous CCB // LSCCB_INITIALIZE(Ccb); Ccb->Srb = Srb; Ccb->OperationCode = CCB_OPCODE_QUERY; LsCcbSetFlag(Ccb, CCB_FLAG_ALLOCATED|CCB_FLAG_DATABUF_ALLOCATED); Ccb->DataBuffer = lurBuffer; Ccb->DataBufferLength = sizeof(LURN_PRIMARYINFORMATION); LsCcbSetCompletionRoutine(Ccb, NdasDluCcbCompletion, DluLuExtension); InterlockedIncrement(&DluLuExtension->RequestExecuting); LsuIncrementTdiClientInProgress(); lurQuery = (PLUR_QUERY)lurBuffer; lurQuery->InfoClass = LurPrimaryLurnInformation; lurQuery->Length = SIZE_OF_LURQUERY(0, sizeof(LURN_PRIMARYINFORMATION)); lurQuery->QueryDataLength = 0; lurPrimaryInfo = (PLURN_PRIMARYINFORMATION)LUR_QUERY_INFORMATION(lurQuery); if(DluLuExtension->LUR == NULL) { LsuDecrementTdiClientInProgress(); InterlockedDecrement(&DluLuExtension->RequestExecuting); ExFreePoolWithTag(lurBuffer, LURN_IOCTL_POOL_TAG); LsCcbFree(Ccb); *SrbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INVALID_PARAMETER; break; } status = LurRequest( DluLuExtension->LUR, Ccb ); if(!NT_SUCCESS(status)) { LsuDecrementTdiClientInProgress(); InterlockedDecrement(&DluLuExtension->RequestExecuting); ExFreePoolWithTag(lurBuffer, LURN_IOCTL_POOL_TAG); LsCcbFree(Ccb); KDPrint(1,("LurRequest() failed.\n")); *SrbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INVALID_PARAMETER; break; } status = STATUS_PENDING; break; } case NdscLurInformation: { PNDSCIOCTL_LURINFO info = (PNDSCIOCTL_LURINFO)OutputBuffer; PLUR_QUERY lurQuery; UINT32 lurnEnumInfoLen; UINT32 nodeCount; KDPrint(1,("NdscLurInformation\n")); if(OutputBufferLength < FIELD_OFFSET(NDSCIOCTL_LURINFO, Lurns)) { KDPrint(2,("LurInfo: Buffer size %d is less than required %d bytes\n", OutputBufferLength, FIELD_OFFSET(NDSCIOCTL_LURINFO, Lurns))); *SrbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INVALID_PARAMETER; break; } // // allocate a CCB // status = LsCcbAllocate(&Ccb); if(!NT_SUCCESS(status)) { KDPrint(1,("LsCcbAllocate() failed.\n")); *SrbStatus = SRB_STATUS_INVALID_REQUEST; break; } // // initialize query CCB // LSCCB_INITIALIZE(Ccb); Ccb->Srb = Srb; Ccb->OperationCode = CCB_OPCODE_QUERY; LsCcbSetFlag(Ccb, CCB_FLAG_ALLOCATED|CCB_FLAG_DATABUF_ALLOCATED); if (DluLuExtension->LUR) { nodeCount = DluLuExtension->LUR->NodeCount; } else { nodeCount = 0; ASSERT(FALSE); } lurnEnumInfoLen = FIELD_OFFSET(LURN_ENUM_INFORMATION, Lurns) + sizeof(LURN_INFORMATION) * nodeCount; // Allocate memory and initialize it. LUR_QUERY_INITIALIZE(lurQuery, LurEnumerateLurn, 0, lurnEnumInfoLen); if(!lurQuery) { LsCcbFree(Ccb); KDPrint(1,("allocating DataBuffer failed.\n")); *SrbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INSUFFICIENT_RESOURCES; break; } Ccb->DataBuffer = lurQuery; Ccb->DataBufferLength = lurQuery->Length; // // Set completion routine // LsCcbSetCompletionRoutine(Ccb, NdasDluCcbCompletion, DluLuExtension); InterlockedIncrement(&DluLuExtension->RequestExecuting); LsuIncrementTdiClientInProgress(); // // send the CCB down // status = LurRequest( DluLuExtension->LUR, Ccb ); if(!NT_SUCCESS(status)) { InterlockedDecrement(&DluLuExtension->RequestExecuting); LsuDecrementTdiClientInProgress(); LsCcbFree(Ccb); KDPrint(1,("LurRequest() failed.\n")); ExFreePoolWithTag(lurQuery, NDSC_PTAG_IOCTL); *SrbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INVALID_PARAMETER; break; } status = STATUS_PENDING; break; } case NdscSystemBacl: case NdscUserBacl: { ULONG requiredBufLen; PNDAS_BLOCK_ACL ndasBacl = (PNDAS_BLOCK_ACL)OutputBuffer; PLSU_BLOCK_ACL targetBacl; KDPrint(1,("NdscSystemBacl/UserBacl: going to default LuExtention 0.\n")); if(DluLuExtension->LUR == NULL) { *SrbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INVALID_PARAMETER; break; } if(QueryInfo->InfoClass == NdscSystemBacl) targetBacl = &DluLuExtension->LUR->SystemBacl; else targetBacl = &DluLuExtension->LUR->UserBacl; status = LsuConvertLsuBaclToNdasBacl( ndasBacl, OutputBufferLength, &requiredBufLen, targetBacl); if(status == STATUS_BUFFER_TOO_SMALL) { // // Set required field. // if(OutputBufferLength >= FIELD_OFFSET(NDAS_BLOCK_ACL, BlockACECnt)) { ndasBacl->Length = requiredBufLen; } // // Set error code to the srb ioctl, but return success // *SrbIoctlReturnCode = SRB_STATUS_DATA_OVERRUN; } else if(!NT_SUCCESS(status)) { *SrbStatus = SRB_STATUS_ERROR; break; } *SrbStatus = SRB_STATUS_SUCCESS; status = STATUS_SUCCESS; break; } default: KDPrint(1,("Invalid Information Class!!\n")); *SrbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INVALID_PARAMETER; } return status; }
STDMETHODIMP_(ULONG) MessageEvents::AddRef() { return InterlockedIncrement(&m_ulRef); }
NTSTATUS NdasDluSrbControl( IN PNDAS_LOGICALUNIT_EXTENSION LogicalUnitExtension, IN PSCSI_REQUEST_BLOCK Srb ) { PSRB_IO_CONTROL srbIoControl; PUCHAR srbIoctlBuffer; LONG srbIoctlBufferLength; ULONG controlCode; NTSTATUS status; UCHAR srbStatus; PNDAS_DLU_EXTENSION ndasDluExtension = NdasDluGetExtension(LogicalUnitExtension); // // Start off being paranoid. // if (Srb->DataBuffer == NULL) { KDPrint(1,("DataBuffer is NULL\n")); Srb->SrbStatus = SRB_STATUS_INVALID_REQUEST; return STATUS_INVALID_PARAMETER; } status = STATUS_MORE_PROCESSING_REQUIRED; srbStatus = SRB_STATUS_SUCCESS; // // Extract the io_control // srbIoControl = (PSRB_IO_CONTROL)Srb->DataBuffer; // // Based on the signature, determine if this is Disk class ioctl or our own's those. // if (strncmp(srbIoControl->Signature, NDASSCSI_IOCTL_SIGNATURE, 8) == 0) { // // NDAS MINIPORT own's. // Continue to the parsing and execution in this function. // } else if(strncmp(srbIoControl->Signature, "SCSIDISK", 8) == 0) { #if 1 // // Disk class request // Complete the SRB in the disk class ioctl function. // return NdasDluDiskClassControl(LogicalUnitExtension, ndasDluExtension, Srb); #else KDPrint(1,("Disk class control disabled.\n")); Srb->SrbStatus = SRB_STATUS_INVALID_REQUEST; return STATUS_INVALID_PARAMETER; #endif } else { KDPrint(1,("Signature mismatch %8s, %8s\n", srbIoControl->Signature, NDASSCSI_IOCTL_SIGNATURE)); Srb->SrbStatus = SRB_STATUS_INVALID_REQUEST; return STATUS_INVALID_PARAMETER; } // // Get the control code. // controlCode = srbIoControl->ControlCode; // // Get the Ioctl buffer. If this is a send message request, it gets // fixed up to be an I2O message later. // srbIoctlBuffer = ((PUCHAR)Srb->DataBuffer) + sizeof(SRB_IO_CONTROL); srbIoctlBufferLength = srbIoControl->Length; // // Based on the control code, figure out what to do. // switch (controlCode) { case NDASSCSI_IOCTL_GET_DVD_STATUS: { srbStatus = NdasDluSrbIoctlGetDVDSTatus( LogicalUnitExtension, ndasDluExtension, srbIoctlBufferLength, srbIoctlBuffer, &srbIoControl->ReturnCode ); if(srbStatus == SRB_STATUS_SUCCESS) { KDPrint(4,("NDASSCSI_IOCTL_QUERYINFO_EX: Successful.\n")); status = STATUS_SUCCESS; } else { status = STATUS_UNSUCCESSFUL; } } break; case NDASSCSI_IOCTL_GET_SLOT_NO: KDPrint(2,("Get Slot No. Slot number is %d\n", ndasDluExtension->LogicalUnitAddress)); if(srbIoctlBufferLength < sizeof(ULONG)) { srbIoControl->ReturnCode = SRB_STATUS_DATA_OVERRUN; srbStatus = SRB_STATUS_DATA_OVERRUN; status = STATUS_UNSUCCESSFUL; break; } *(PULONG)srbIoctlBuffer = ndasDluExtension->LogicalUnitAddress; srbIoControl->ReturnCode = SRB_STATUS_SUCCESS; srbStatus = SRB_STATUS_SUCCESS; status = STATUS_SUCCESS; break; case NDASSCSI_IOCTL_QUERYINFO_EX: { PNDASSCSI_QUERY_INFO_DATA QueryInfo; PUCHAR tmpBuffer; KDPrint(5, ("Query information EX.\n")); QueryInfo = (PNDASSCSI_QUERY_INFO_DATA)srbIoctlBuffer; tmpBuffer = ExAllocatePoolWithTag(NonPagedPool, srbIoctlBufferLength, NDAS_DLU_PTAG_IOCTL); if(tmpBuffer == NULL) { ASSERT(FALSE); KDPrint(1,("NDASSCSI_IOCTL_QUERYINFO_EX: SRB_STATUS_DATA_OVERRUN. BufferLength:%d\n", srbIoctlBufferLength)); srbStatus = SRB_STATUS_DATA_OVERRUN; break; } status = NdasDluSrbIoctlQueryInfo( LogicalUnitExtension, ndasDluExtension, Srb, QueryInfo, srbIoctlBufferLength, tmpBuffer, &srbIoControl->ReturnCode, &srbStatus ); // if(NT_SUCCESS(status)) { // KDPrint(4,("NDASSCSI_IOCTL_QUERYINFO_EX: Successful.\n")); // Need to fill structure anyway. RtlCopyMemory(srbIoctlBuffer, tmpBuffer, srbIoctlBufferLength); // } ExFreePoolWithTag(tmpBuffer, NDSC_PTAG_IOCTL); break; } case NDASSCSI_IOCTL_UPGRADETOWRITE: { PLURN_UPDATE LurnUpdate; PCCB Ccb; // // Set a CCB // status = LsCcbAllocate(&Ccb); if(!NT_SUCCESS(status)) { srbStatus = SRB_STATUS_INVALID_REQUEST; KDPrint(1,("NDASSCSI_IOCTL_UPGRADETOWRITE: LsCcbAllocate() failed.\n")); break; } LurnUpdate = (PLURN_UPDATE)ExAllocatePoolWithTag(NonPagedPool, sizeof(LURN_UPDATE), NDAS_DLU_PTAG_IOCTL); if(!LurnUpdate) { srbStatus = SRB_STATUS_INVALID_REQUEST; KDPrint(1,("NDASSCSI_IOCTL_UPGRADETOWRITE: ExAllocatePoolWithTag() failed.\n")); status = STATUS_INSUFFICIENT_RESOURCES; break; } LSCCB_INITIALIZE(Ccb); Ccb->OperationCode = CCB_OPCODE_UPDATE; Ccb->DataBuffer = LurnUpdate; Ccb->DataBufferLength = sizeof(LURN_UPDATE); LsCcbSetFlag(Ccb, CCB_FLAG_ALLOCATED|CCB_FLAG_DATABUF_ALLOCATED); // Ioctl Srb will complete asynchronously. Ccb->Srb = Srb; InterlockedIncrement(&ndasDluExtension->RequestExecuting); LsuIncrementTdiClientInProgress(); LsCcbSetCompletionRoutine(Ccb, NdasDluCcbCompletion, LogicalUnitExtension); LurnUpdate->UpdateClass = LURN_UPDATECLASS_WRITEACCESS_USERID; status = LurRequest( ndasDluExtension->LUR, Ccb ); if(!NT_SUCCESS(status)) { KDPrint(1,("NDASSCSI_IOCTL_UPGRADETOWRITE: LurnRequest() failed.\n")); NdasDluLogError( LogicalUnitExtension, Srb, Srb->PathId, Srb->TargetId, Srb->Lun, NDASSCSI_IO_UPGRADEIOCTL_FAIL, EVTLOG_UNIQUEID(EVTLOG_MODULE_IOCTL, EVTLOG_FAIL_UPGRADEIOCTL, 0) ); LsuDecrementTdiClientInProgress(); LsCcbFree(Ccb); ExFreePoolWithTag(LurnUpdate, NDSC_PTAG_IOCTL); status = STATUS_SUCCESS; srbStatus = SRB_STATUS_INVALID_REQUEST; } else { status = STATUS_PENDING; } break; } case NDASSCSI_IOCTL_NOOP: { PCCB Ccb; // // Query to the LUR // status = LsCcbAllocate(&Ccb); if(!NT_SUCCESS(status)) { srbStatus = SRB_STATUS_ERROR; status = STATUS_SUCCESS; KDPrint(1,("LsCcbAllocate() failed.\n")); break; } LSCCB_INITIALIZE(Ccb); Ccb->OperationCode = CCB_OPCODE_NOOP; LsCcbSetFlag(Ccb, CCB_FLAG_ALLOCATED); Ccb->Srb = Srb; LsCcbSetCompletionRoutine(Ccb, NdasDluCcbCompletion, LogicalUnitExtension); InterlockedIncrement(&ndasDluExtension->RequestExecuting); LsuIncrementTdiClientInProgress(); status = LurRequest( ndasDluExtension->LUR, Ccb ); if(!NT_SUCCESS(status)) { LsuDecrementTdiClientInProgress(); LsCcbFree(Ccb); srbStatus = SRB_STATUS_ERROR; status = STATUS_SUCCESS; KDPrint(1,("LurRequest() failed.\n")); break; } srbStatus = SRB_STATUS_SUCCESS; status = STATUS_PENDING; break; } case NDASSCSI_IOCTL_ADD_USERBACL: { PNDAS_BLOCK_ACE bace = (PNDAS_BLOCK_ACE)srbIoctlBuffer; // input PBLOCKACE_ID blockAceId = (PBLOCKACE_ID)srbIoctlBuffer; // output UCHAR lsuAccessMode; PLSU_BLOCK_ACE lsuBace; UINT64 blockStartAddr; UINT64 blockEndAddr; if(srbIoctlBufferLength < sizeof(NDAS_BLOCK_ACE)) { srbStatus = SRB_STATUS_DATA_OVERRUN; status = STATUS_UNSUCCESSFUL; break; } if(ndasDluExtension->LUR == NULL) { srbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INVALID_PARAMETER; break; } lsuAccessMode = 0; if(bace->AccessMode & NBACE_ACCESS_READ) { lsuAccessMode |= LSUBACE_ACCESS_READ; } if(bace->AccessMode & NBACE_ACCESS_WRITE) { lsuAccessMode |= LSUBACE_ACCESS_WRITE; } if (bace->IsByteAddress) { blockStartAddr = bace->StartingOffset / ndasDluExtension->LUR->BlockBytes; blockEndAddr = (bace->StartingOffset + bace->Length) / ndasDluExtension->LUR->BlockBytes - 1; } else { blockStartAddr = bace->BlockStartAddr; blockEndAddr = bace->BlockEndAddr; } lsuBace = LsuCreateBlockAce( lsuAccessMode, blockStartAddr, blockEndAddr ); if(lsuBace == NULL) { srbStatus = SRB_STATUS_DATA_OVERRUN; status = STATUS_UNSUCCESSFUL; break; } // Set returned BACE ID. *blockAceId = lsuBace->BlockAceId; LsuInsertAce(&ndasDluExtension->LUR->UserBacl, lsuBace); srbStatus = SRB_STATUS_SUCCESS; status = STATUS_SUCCESS; break; } case NDASSCSI_IOCTL_REMOVE_USERBACL: { PNDSCIOCTL_REMOVE_USERBACL ioctlRemoveUserAcl = (PNDSCIOCTL_REMOVE_USERBACL)srbIoctlBuffer; BLOCKACE_ID blockAceId; PLSU_BLOCK_ACE lsuBacl; if(srbIoctlBufferLength < sizeof(NDSCIOCTL_REMOVE_USERBACL)) { srbStatus = SRB_STATUS_DATA_OVERRUN; status = STATUS_UNSUCCESSFUL; break; } blockAceId = ioctlRemoveUserAcl->NdasBlockAceId; // input if(ndasDluExtension->LUR == NULL) { srbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INVALID_PARAMETER; break; } if(blockAceId == 0) { KDPrint(1,("REMOVE_USERBACL: Zero block ACE ID.\n")); srbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INVALID_PARAMETER; break; } lsuBacl = LsuRemoveAceById(&ndasDluExtension->LUR->UserBacl, blockAceId); if(lsuBacl == NULL) { KDPrint(1,("REMOVE_USERBACL: Invalid block ACE ID.\n")); srbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INVALID_PARAMETER; break; } LsuFreeBlockAce(lsuBacl); srbStatus = SRB_STATUS_SUCCESS; status = STATUS_SUCCESS; break; } case NDASSCSI_IOCTL_DEVICE_LOCK: { if(srbIoctlBufferLength < sizeof(NDSCIOCTL_DEVICELOCK)) { srbStatus = SRB_STATUS_DATA_OVERRUN; status = STATUS_UNSUCCESSFUL; break; } if(ndasDluExtension->LUR == NULL) { srbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_INVALID_PARAMETER; break; } status = NdasDluIoctlDeviceLock( LogicalUnitExtension, ndasDluExtension, (PNDSCIOCTL_DEVICELOCK)srbIoctlBuffer, Srb); srbStatus = Srb->SrbStatus; break; } default: KDPrint(2,("Control Code (%x)\n", controlCode)); srbStatus = SRB_STATUS_INVALID_REQUEST; status = STATUS_MORE_PROCESSING_REQUIRED; } Srb->SrbStatus = srbStatus; return status; }
// // Add fault to Lurn fault list for future analysys // // ErrorCode is dependent on fault type. It can be custom error code. // // Param is Type dependent parameter. // Param is CCB if / Ccb is valid only for fault type LURN_ERR_IO, LURN_ERR_LOCK // NTSTATUS LurnRecordFault(PLURELATION_NODE Lurn, LURN_FAULT_TYPE Type, UINT32 ErrorCode, PVOID Param) { PLURN_FAULT_INFO fInfo = &Lurn->FaultInfo; LONG count; LURN_FAULT_TYPE LastFaultType; LONG LastErrorCode; PLURN_FAULT_IO pLfi= (PLURN_FAULT_IO) Param; LastFaultType = fInfo->LastFaultType; LastErrorCode = fInfo->LastErrorCode[LastFaultType]; // // To do: Recognize some indirect error patterns. // #if 0 // // Check accesing same range failed. // if ((Type == LURN_ERR_READ || Type == LURN_ERR_WRITE || Type == LURN_ERR_VERIFY) && pLfi && (ErrorCode == LURN_FAULT_COMMUNICATION)) { if (fInfo->LastIoOperation) { // // Check accesing same range failed and error occured multiple times. // if (fInfo->LastIoAddr + fInfo->LastIoLength > pLfi->Address && pLfi->Address+pLfi->Length > fInfo->LastIoAddr && fInfo->ErrorCount[Type] > 5) { KDPrintM(NDASSCSI_DBG_LUR_ERROR, ("IO failed on same location. Marking error\n")); ErrorCode = LURN_FAULT_BAD_SECTOR; } } else { // no previous IO error recorded. } } #endif // // to do: handle disk hang after bad sector.. // // // Update internal fault record. // switch(Type) { case LURN_ERR_SUCCESS: count = InterlockedIncrement(&fInfo->ErrorCount[Type]); if (count == 128) { KDPrintM(NDASSCSI_DBG_LUR_TRACE, ("Resetting error count\n")); // // If some IO operation completed without any error, clear all other errors. // LurnResetFaultInfo(Lurn); InterlockedExchange(&fInfo->ErrorCount[Type], count); } break; case LURN_ERR_CONNECT: case LURN_ERR_LOGIN: case LURN_ERR_NDAS_OP: case LURN_ERR_DISK_OP: case LURN_ERR_READ: case LURN_ERR_WRITE: case LURN_ERR_VERIFY: case LURN_ERR_UNKNOWN: case LURN_ERR_FLUSH: default: // Error occured. Reset success count InterlockedExchange(&fInfo->ErrorCount[LURN_ERR_SUCCESS], 0); InterlockedIncrement(&fInfo->ErrorCount[Type]); InterlockedExchange(&fInfo->LastErrorCode[Type], ErrorCode); fInfo->LastFaultType = Type; KeQuerySystemTime(&fInfo->LastFaultTime); break; } if (Type == LURN_ERR_READ || Type == LURN_ERR_WRITE) { if (pLfi) { fInfo->LastIoOperation = Type; fInfo->LastIoAddr = pLfi->Address; fInfo->LastIoLength = pLfi->Length; } } // // Update error causes. // // // Guess error cause. Be cautious when setting error because this can mark a disk as defective permanently. // if (Type == LURN_ERR_CONNECT) { fInfo->FaultCause |= LURN_FCAUSE_TARGET_DOWN; } else { // At least target is not down fInfo->FaultCause &= ~LURN_FCAUSE_TARGET_DOWN; } if ((Type == LURN_ERR_READ || Type == LURN_ERR_WRITE || Type == LURN_ERR_VERIFY) && ErrorCode == LURN_FAULT_BAD_SECTOR) { fInfo->FaultCause |= LURN_FCAUSE_BAD_SECTOR; } if (Type == LURN_ERR_DISK_OP) { if (fInfo->ErrorCount[LURN_ERR_DISK_OP] > 5 && ErrorCode == LURN_FAULT_IDENTIFY) { NDAS_ASSERT(FALSE); // // If HDD's board is broken, identify may not work. // // To do: mark LURN_FAULT_IDENTIFY fault only when this is just communication problem. (Need support from lpx) // fInfo->FaultCause |= LURN_FCAUSE_BAD_DISK; } else if (ErrorCode == LURN_FAULT_NOT_EXIST){ // // NDAS chip cannot detect HDD. HDD may be removed or dead // fInfo->FaultCause |= LURN_FAULT_NO_TARGET; } } // // to do: handle more error cases: LURN_ERR_FLUSH, LURN_ERR_LOGIN, LURN_ERR_NDAS_OP // return STATUS_SUCCESS; }
STDMETHODIMP_(ULONG) WCDataObject::AddRef( void) { return InterlockedIncrement(&m_ref); }
void khm_cred_process_startup_actions(void) { khm_handle defident = NULL; if (!khm_startup.processing) return; if (khm_startup.init || khm_startup.renew || khm_startup.destroy || khm_startup.autoinit) { kcdb_identity_get_default(&defident); } /* For asynchronous actions, we trigger the action and then exit the loop. Once the action completes, the completion handler will trigger a continuation message which will result in this function getting called again. Then we can proceed with the rest of the startup actions. */ do { if (khm_startup.init) { khm_cred_obtain_new_creds_for_ident(defident, NULL); khm_startup.init = FALSE; break; } if (khm_startup.import) { khm_cred_import(); khm_startup.import = FALSE; /* we also set the renew command to false here because we trigger a renewal for all the identities at the end of the import operation anyway. */ khm_startup.renew = FALSE; break; } if (khm_startup.renew) { LONG pending_renewals; /* if there are no credentials, we just skip over the renew action. */ khm_startup.renew = FALSE; InterlockedIncrement(&khm_startup.pending_renewals); khm_cred_renew_all_identities(); pending_renewals = InterlockedDecrement(&khm_startup.pending_renewals); if (pending_renewals != 0) break; /* if there were no pending renewals, then we just fall through. This means that either there were no identities to renew, or all the renewals completed. If all the renewals completed, then the commandline contiuation message wasn't triggered. Either way, we must fall through if the count is zero. */ } if (khm_startup.destroy) { khm_startup.destroy = FALSE; if (defident) { khm_cred_destroy_identity(defident); break; } } if (khm_startup.autoinit) { khm_size count = 0; khm_handle credset = NULL; khm_int32 ctype_ident = KCDB_CREDTYPE_INVALID; khm_int32 delta = 0; khm_startup.autoinit = FALSE; kcdb_credset_create(&credset); kcdb_identity_get_type(&ctype_ident); kcdb_credset_collect(credset, NULL, defident, ctype_ident, &delta); kcdb_credset_get_size(credset, &count); kcdb_credset_delete(credset); if (count == 0) { if (defident) khui_context_set(KHUI_SCOPE_IDENT, defident, KCDB_CREDTYPE_INVALID, NULL, NULL, 0, NULL); else khui_context_reset(); khm_cred_obtain_new_creds(NULL); break; } } if (khm_startup.exit) { PostMessage(khm_hwnd_main, WM_COMMAND, MAKEWPARAM(KHUI_ACTION_EXIT, 0), 0); khm_startup.exit = FALSE; break; } if (khm_startup.display & SOPTS_DISPLAY_HIDE) { khm_hide_main_window(); } else if (khm_startup.display & SOPTS_DISPLAY_SHOW) { khm_show_main_window(); } khm_startup.display = 0; /* when we get here, then we are all done with the command line stuff */ khm_startup.processing = FALSE; khm_startup.remote = FALSE; kmq_post_message(KMSG_ACT, KMSG_ACT_END_CMDLINE, 0, 0); } while(FALSE); if (defident) kcdb_identity_release(defident); }
static ULONG WINAPI NoStatStreamImpl_AddRef( IStream* iface) { NoStatStreamImpl* const This=(NoStatStreamImpl*)iface; return InterlockedIncrement(&This->ref); }
/* Completion handler for KMSG_CRED messages. We control the overall logic of credentials acquisition and other operations here. Once a credentials operation is triggered, each successive message completion notification will be used to dispatch the messages for the next step in processing the operation. */ void KHMAPI kmsg_cred_completion(kmq_message *m) { khui_new_creds * nc; #ifdef DEBUG assert(m->type == KMSG_CRED); #else if(m->type != KMSG_CRED) return; /* huh? */ #endif switch(m->subtype) { case KMSG_CRED_PASSWORD: /* fallthrough */ case KMSG_CRED_NEW_CREDS: /* Cred types have attached themselves. Trigger the next phase. */ kmq_post_message(KMSG_CRED, KMSG_CRED_DIALOG_SETUP, 0, m->vparam); break; case KMSG_CRED_RENEW_CREDS: nc = (khui_new_creds *) m->vparam; /* khm_cred_dispatch_process_message() deals with the case where there are no credential types that wants to participate in this operation. */ khm_cred_dispatch_process_message(nc); break; case KMSG_CRED_DIALOG_SETUP: nc = (khui_new_creds *) m->vparam; khm_prep_newcredwnd(nc->hwnd); /* all the controls have been created. Now initialize them */ if (nc->n_types > 0) { kmq_post_subs_msg(nc->type_subs, nc->n_types, KMSG_CRED, KMSG_CRED_DIALOG_PRESTART, 0, m->vparam); } else { PostMessage(nc->hwnd, KHUI_WM_NC_NOTIFY, MAKEWPARAM(0, WMNC_DIALOG_PROCESS_COMPLETE), 0); } break; case KMSG_CRED_DIALOG_PRESTART: /* all prestart stuff is done. Now to activate the dialog */ nc = (khui_new_creds *) m->vparam; khm_show_newcredwnd(nc->hwnd); kmq_post_subs_msg(nc->type_subs, nc->n_types, KMSG_CRED, KMSG_CRED_DIALOG_START, 0, m->vparam); /* at this point, the dialog window takes over. We let it run the show until KMSG_CRED_DIALOG_END is posted by the dialog procedure. */ break; case KMSG_CRED_PROCESS: /* a wave of these messages have completed. We should check if there's more */ nc = (khui_new_creds *) m->vparam; /* if we are done processing all the plug-ins, then check if there were any errors reported. Otherwise we dispatch another set of messages. */ if(!khm_cred_dispatch_process_level(nc)) { if(kherr_is_error()) { khui_alert * alert; kherr_event * evt; kherr_context * ctx; wchar_t ws_tfmt[512]; wchar_t w_idname[KCDB_IDENT_MAXCCH_NAME]; wchar_t ws_title[ARRAYLENGTH(ws_tfmt) + KCDB_IDENT_MAXCCH_NAME]; khm_size cb; /* For renewals, we suppress the error message for the following case: - The renewal was for an identity - There are no identity credentials for the identity (no credentials that have the same type as the identity provider). */ if (nc->subtype == KMSG_CRED_RENEW_CREDS && nc->ctx.scope == KHUI_SCOPE_IDENT && nc->ctx.identity != NULL) { khm_handle tcs = NULL; /* credential set */ khm_size count = 0; khm_int32 id_ctype = KCDB_CREDTYPE_INVALID; khm_int32 delta = 0; kcdb_identity_get_type(&id_ctype); kcdb_credset_create(&tcs); kcdb_credset_collect(tcs, NULL, nc->ctx.identity, id_ctype, &delta); kcdb_credset_get_size(tcs, &count); kcdb_credset_delete(tcs); if (count == 0) { goto done_with_op; } } ctx = kherr_peek_context(); evt = kherr_get_err_event(ctx); kherr_evaluate_event(evt); khui_alert_create_empty(&alert); if (nc->subtype == KMSG_CRED_NEW_CREDS) { khui_alert_set_type(alert, KHUI_ALERTTYPE_ACQUIREFAIL); cb = sizeof(w_idname); if (nc->n_identities == 0 || KHM_FAILED(kcdb_identity_get_name(nc->identities[0], w_idname, &cb))) { /* an identity could not be determined */ LoadString(khm_hInstance, IDS_NC_FAILED_TITLE, ws_title, ARRAYLENGTH(ws_title)); } else { LoadString(khm_hInstance, IDS_NC_FAILED_TITLE_I, ws_tfmt, ARRAYLENGTH(ws_tfmt)); StringCbPrintf(ws_title, sizeof(ws_title), ws_tfmt, w_idname); khui_alert_set_ctx(alert, KHUI_SCOPE_IDENT, nc->identities[0], KCDB_CREDTYPE_INVALID, NULL); } } else if (nc->subtype == KMSG_CRED_PASSWORD) { khui_alert_set_type(alert, KHUI_ALERTTYPE_CHPW); cb = sizeof(w_idname); if (nc->n_identities == 0 || KHM_FAILED(kcdb_identity_get_name(nc->identities[0], w_idname, &cb))) { LoadString(khm_hInstance, IDS_NC_PWD_FAILED_TITLE, ws_title, ARRAYLENGTH(ws_title)); } else { LoadString(khm_hInstance, IDS_NC_PWD_FAILED_TITLE_I, ws_tfmt, ARRAYLENGTH(ws_tfmt)); StringCbPrintf(ws_title, sizeof(ws_title), ws_tfmt, w_idname); khui_alert_set_ctx(alert, KHUI_SCOPE_IDENT, nc->identities[0], KCDB_CREDTYPE_INVALID, NULL); } } else if (nc->subtype == KMSG_CRED_RENEW_CREDS) { khui_alert_set_type(alert, KHUI_ALERTTYPE_RENEWFAIL); cb = sizeof(w_idname); if (nc->ctx.identity == NULL || KHM_FAILED(kcdb_identity_get_name(nc->ctx.identity, w_idname, &cb))) { LoadString(khm_hInstance, IDS_NC_REN_FAILED_TITLE, ws_title, ARRAYLENGTH(ws_title)); } else { LoadString(khm_hInstance, IDS_NC_REN_FAILED_TITLE_I, ws_tfmt, ARRAYLENGTH(ws_tfmt)); StringCbPrintf(ws_title, sizeof(ws_title), ws_tfmt, w_idname); khui_alert_set_ctx(alert, KHUI_SCOPE_IDENT, nc->ctx.identity, KCDB_CREDTYPE_INVALID, NULL); } } else { #ifdef DEBUG assert(FALSE); #endif } khui_alert_set_title(alert, ws_title); khui_alert_set_severity(alert, evt->severity); if(!evt->long_desc) khui_alert_set_message(alert, evt->short_desc); else khui_alert_set_message(alert, evt->long_desc); if(evt->suggestion) khui_alert_set_suggestion(alert, evt->suggestion); if (nc->subtype == KMSG_CRED_RENEW_CREDS && nc->ctx.identity != NULL) { khm_int32 n_cmd; n_cmd = khm_get_identity_new_creds_action(nc->ctx.identity); if (n_cmd != 0) { khui_alert_add_command(alert, n_cmd); khui_alert_add_command(alert, KHUI_PACTION_CLOSE); khui_alert_set_flags(alert, KHUI_ALERT_FLAG_DISPATCH_CMD, KHUI_ALERT_FLAG_DISPATCH_CMD); } } khui_alert_show(alert); khui_alert_release(alert); kherr_release_context(ctx); kherr_clear_error(); } done_with_op: if (nc->subtype == KMSG_CRED_RENEW_CREDS) { kmq_post_message(KMSG_CRED, KMSG_CRED_END, 0, m->vparam); } else { PostMessage(nc->hwnd, KHUI_WM_NC_NOTIFY, MAKEWPARAM(0, WMNC_DIALOG_PROCESS_COMPLETE), 0); } } break; case KMSG_CRED_END: /* all is done. */ { khui_new_creds * nc; khm_boolean continue_cmdline = TRUE; nc = (khui_new_creds *) m->vparam; if (nc->subtype == KMSG_CRED_NEW_CREDS || nc->subtype == KMSG_CRED_PASSWORD) { khm_cred_end_dialog(nc); } else if (nc->subtype == KMSG_CRED_RENEW_CREDS) { /* if this is a renewal that was triggered while we were processing the commandline, then we need to update the pending renewal count. */ if (khm_startup.processing) { LONG renewals; renewals = InterlockedDecrement(&khm_startup.pending_renewals); if (renewals != 0) { continue_cmdline = FALSE; } } } khui_cw_destroy_cred_blob(nc); kmq_post_message(KMSG_CRED, KMSG_CRED_REFRESH, 0, 0); if (continue_cmdline) kmq_post_message(KMSG_ACT, KMSG_ACT_CONTINUE_CMDLINE, 0, 0); } break; /* property sheet stuff */ case KMSG_CRED_PP_BEGIN: /* all the pages should have been added by now. Just send out the precreate message */ kmq_post_message(KMSG_CRED, KMSG_CRED_PP_PRECREATE, 0, m->vparam); break; case KMSG_CRED_PP_END: kmq_post_message(KMSG_CRED, KMSG_CRED_PP_DESTROY, 0, m->vparam); break; case KMSG_CRED_DESTROY_CREDS: #ifdef DEBUG assert(m->vparam != NULL); #endif khui_context_release((khui_action_context *) m->vparam); PFREE(m->vparam); kmq_post_message(KMSG_CRED, KMSG_CRED_REFRESH, 0, 0); kmq_post_message(KMSG_ACT, KMSG_ACT_CONTINUE_CMDLINE, 0, 0); break; case KMSG_CRED_IMPORT: { khm_boolean continue_cmdline = FALSE; LONG pending_renewals; /* once an import operation ends, we have to trigger a renewal so that other plug-ins that didn't participate in the import operation can have a chance at getting the necessary credentials. If we are in the middle of processing the commandline, we have to be a little bit careful. We can't issue a commandline conituation message right now because the import action is still ongoing (since the renewals are part of the action). Once the renewals have completed, the completion handler will automatically issue a commandline continuation message. However, if there were no identities to renew, then we have to issue the message ourselves. */ InterlockedIncrement(&khm_startup.pending_renewals); khm_cred_renew_all_identities(); pending_renewals = InterlockedDecrement(&khm_startup.pending_renewals); if (pending_renewals == 0 && khm_startup.processing) kmq_post_message(KMSG_ACT, KMSG_ACT_CONTINUE_CMDLINE, 0, 0); } break; case KMSG_CRED_REFRESH: kcdb_identity_refresh_all(); break; } }
/* Implements IUnknown::AddRef */ ULONG WINAPI QAxScriptSite::AddRef() { return InterlockedIncrement(&ref); }
static void BaseBackup(void) { PGresult *res; char *sysidentifier; uint32 latesttli; uint32 starttli; char current_path[MAXPGPATH]; char escaped_label[MAXPGPATH]; int i; char xlogstart[64]; char xlogend[64]; int minServerMajor, maxServerMajor; int serverMajor; /* * Connect in replication mode to the server */ conn = GetConnection(); if (!conn) /* Error message already written in GetConnection() */ exit(1); /* * Check server version. BASE_BACKUP command was introduced in 9.1, so we * can't work with servers older than 9.1. */ minServerMajor = 901; maxServerMajor = PG_VERSION_NUM / 100; serverMajor = PQserverVersion(conn) / 100; if (serverMajor < minServerMajor || serverMajor > maxServerMajor) { const char *serverver = PQparameterStatus(conn, "server_version"); fprintf(stderr, _("%s: incompatible server version %s\n"), progname, serverver ? serverver : "'unknown'"); disconnect_and_exit(1); } /* * If WAL streaming was requested, also check that the server is new * enough for that. */ if (streamwal && !CheckServerVersionForStreaming(conn)) { /* Error message already written in CheckServerVersionForStreaming() */ disconnect_and_exit(1); } /* * Build contents of recovery.conf if requested */ if (writerecoveryconf) GenerateRecoveryConf(conn); /* * Run IDENTIFY_SYSTEM so we can get the timeline */ res = PQexec(conn, "IDENTIFY_SYSTEM"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, _("%s: could not send replication command \"%s\": %s"), progname, "IDENTIFY_SYSTEM", PQerrorMessage(conn)); disconnect_and_exit(1); } if (PQntuples(res) != 1 || PQnfields(res) != 3) { fprintf(stderr, _("%s: could not identify system: got %d rows and %d fields, expected %d rows and %d fields\n"), progname, PQntuples(res), PQnfields(res), 1, 3); disconnect_and_exit(1); } sysidentifier = pg_strdup(PQgetvalue(res, 0, 0)); latesttli = atoi(PQgetvalue(res, 0, 1)); PQclear(res); /* * Start the actual backup */ PQescapeStringConn(conn, escaped_label, label, sizeof(escaped_label), &i); snprintf(current_path, sizeof(current_path), "BASE_BACKUP LABEL '%s' %s %s %s %s", escaped_label, showprogress ? "PROGRESS" : "", includewal && !streamwal ? "WAL" : "", fastcheckpoint ? "FAST" : "", includewal ? "NOWAIT" : ""); if (PQsendQuery(conn, current_path) == 0) { fprintf(stderr, _("%s: could not send replication command \"%s\": %s"), progname, "BASE_BACKUP", PQerrorMessage(conn)); disconnect_and_exit(1); } /* * Get the starting xlog position */ res = PQgetResult(conn); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, _("%s: could not initiate base backup: %s"), progname, PQerrorMessage(conn)); disconnect_and_exit(1); } if (PQntuples(res) != 1) { fprintf(stderr, _("%s: server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields\n"), progname, PQntuples(res), PQnfields(res), 1, 2); disconnect_and_exit(1); } strcpy(xlogstart, PQgetvalue(res, 0, 0)); /* * 9.3 and later sends the TLI of the starting point. With older servers, * assume it's the same as the latest timeline reported by * IDENTIFY_SYSTEM. */ if (PQnfields(res) >= 2) starttli = atoi(PQgetvalue(res, 0, 1)); else starttli = latesttli; PQclear(res); MemSet(xlogend, 0, sizeof(xlogend)); if (verbose && includewal) fprintf(stderr, _("transaction log start point: %s on timeline %u\n"), xlogstart, starttli); /* * Get the header */ res = PQgetResult(conn); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, _("%s: could not get backup header: %s"), progname, PQerrorMessage(conn)); disconnect_and_exit(1); } if (PQntuples(res) < 1) { fprintf(stderr, _("%s: no data returned from server\n"), progname); disconnect_and_exit(1); } /* * Sum up the total size, for progress reporting */ totalsize = totaldone = 0; tablespacecount = PQntuples(res); for (i = 0; i < PQntuples(res); i++) { if (showprogress) totalsize += atol(PQgetvalue(res, i, 2)); /* * Verify tablespace directories are empty. Don't bother with the * first once since it can be relocated, and it will be checked before * we do anything anyway. */ if (format == 'p' && !PQgetisnull(res, i, 1)) verify_dir_is_empty_or_create(PQgetvalue(res, i, 1)); } /* * When writing to stdout, require a single tablespace */ if (format == 't' && strcmp(basedir, "-") == 0 && PQntuples(res) > 1) { fprintf(stderr, _("%s: can only write single tablespace to stdout, database has %d\n"), progname, PQntuples(res)); disconnect_and_exit(1); } /* * If we're streaming WAL, start the streaming session before we start * receiving the actual data chunks. */ if (streamwal) { if (verbose) fprintf(stderr, _("%s: starting background WAL receiver\n"), progname); StartLogStreamer(xlogstart, starttli, sysidentifier); } /* * Start receiving chunks */ for (i = 0; i < PQntuples(res); i++) { if (format == 't') ReceiveTarFile(conn, res, i); else ReceiveAndUnpackTarFile(conn, res, i); } /* Loop over all tablespaces */ if (showprogress) { progress_report(PQntuples(res), NULL); fprintf(stderr, "\n"); /* Need to move to next line */ } PQclear(res); /* * Get the stop position */ res = PQgetResult(conn); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, _("%s: could not get transaction log end position from server: %s"), progname, PQerrorMessage(conn)); disconnect_and_exit(1); } if (PQntuples(res) != 1) { fprintf(stderr, _("%s: no transaction log end position returned from server\n"), progname); disconnect_and_exit(1); } strcpy(xlogend, PQgetvalue(res, 0, 0)); if (verbose && includewal) fprintf(stderr, "transaction log end point: %s\n", xlogend); PQclear(res); res = PQgetResult(conn); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, _("%s: final receive failed: %s"), progname, PQerrorMessage(conn)); disconnect_and_exit(1); } if (bgchild > 0) { #ifndef WIN32 int status; int r; #else DWORD status; uint32 hi, lo; #endif if (verbose) fprintf(stderr, _("%s: waiting for background process to finish streaming ...\n"), progname); #ifndef WIN32 if (write(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend)) { fprintf(stderr, _("%s: could not send command to background pipe: %s\n"), progname, strerror(errno)); disconnect_and_exit(1); } /* Just wait for the background process to exit */ r = waitpid(bgchild, &status, 0); if (r == -1) { fprintf(stderr, _("%s: could not wait for child process: %s\n"), progname, strerror(errno)); disconnect_and_exit(1); } if (r != bgchild) { fprintf(stderr, _("%s: child %d died, expected %d\n"), progname, r, (int) bgchild); disconnect_and_exit(1); } if (!WIFEXITED(status)) { fprintf(stderr, _("%s: child process did not exit normally\n"), progname); disconnect_and_exit(1); } if (WEXITSTATUS(status) != 0) { fprintf(stderr, _("%s: child process exited with error %d\n"), progname, WEXITSTATUS(status)); disconnect_and_exit(1); } /* Exited normally, we're happy! */ #else /* WIN32 */ /* * On Windows, since we are in the same process, we can just store the * value directly in the variable, and then set the flag that says * it's there. */ if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2) { fprintf(stderr, _("%s: could not parse transaction log location \"%s\"\n"), progname, xlogend); disconnect_and_exit(1); } xlogendptr = ((uint64) hi) << 32 | lo; InterlockedIncrement(&has_xlogendptr); /* First wait for the thread to exit */ if (WaitForSingleObjectEx((HANDLE) bgchild, INFINITE, FALSE) != WAIT_OBJECT_0) { _dosmaperr(GetLastError()); fprintf(stderr, _("%s: could not wait for child thread: %s\n"), progname, strerror(errno)); disconnect_and_exit(1); } if (GetExitCodeThread((HANDLE) bgchild, &status) == 0) { _dosmaperr(GetLastError()); fprintf(stderr, _("%s: could not get child thread exit status: %s\n"), progname, strerror(errno)); disconnect_and_exit(1); } if (status != 0) { fprintf(stderr, _("%s: child thread exited with error %u\n"), progname, (unsigned int) status); disconnect_and_exit(1); } /* Exited normally, we're happy */ #endif } /* Free the recovery.conf contents */ destroyPQExpBuffer(recoveryconfcontents); /* * End of copy data. Final result is already checked inside the loop. */ PQclear(res); PQfinish(conn); if (verbose) fprintf(stderr, "%s: base backup completed\n", progname); }