Beispiel #1
0
/*
 * NV-CONTROL versions 1.8 and 1.9 pack the target_type and target_id
 * fields in reversed order.  In order to talk to one of these servers,
 * we need to swap these fields.
 */
static void XNVCTRLCheckTargetData(Display *dpy, XExtDisplayInfo *info,
                                   int *target_type, int *target_id)
{
    /* Find out what the server's NV-CONTROL version is and
     * setup for swapping if we need to.
     */
    if (info->data == NVCTRL_EXT_NEED_CHECK) {
        int major, minor;

        if (XNVCTRLQueryVersion(dpy, &major, &minor)) {
            if (major == 1 &&
                    (minor == 8 || minor == 9)) {
                info->data = NVCTRL_EXT_NEED_TARGET_SWAP;
            } else {
                info->data = NVCTRL_EXT_NEED_NOTHING;
            }
        } else {
            info->data = NVCTRL_EXT_NEED_NOTHING;
        }
    }

    /* We need to swap the target_type and target_id */
    if (info->data == NVCTRL_EXT_NEED_TARGET_SWAP) {
        int tmp;
        tmp = *target_type;
        *target_type = *target_id;
        *target_id = tmp;
    }
}
Beispiel #2
0
int CheckNVOpenGLSyncToVBlank(void)
{
    MythXDisplay *d = OpenMythXDisplay();
    if (!d)
        return -1;

    Display *dpy = d->GetDisplay();
    int screen   = d->GetScreen();

    if (!XNVCTRLIsNvScreen(dpy, screen))
    {
        delete d;
        return -1;
    }

    int major, minor;
    if (!XNVCTRLQueryVersion(dpy, &major, &minor))
        return -1;

    int sync = NV_CTRL_SYNC_TO_VBLANK_OFF;
    if (!XNVCTRLQueryAttribute(dpy, screen, 0, NV_CTRL_SYNC_TO_VBLANK, &sync))
    {
        delete d;
        return -1;
    }

    if (!sync)
    {
        LOG(VB_GENERAL, LOG_WARNING, LOC + "OpenGL Sync to VBlank is disabled.");
        LOG(VB_GENERAL, LOG_WARNING, LOC + "For best results enable this in NVidia settings or try running:");
        LOG(VB_GENERAL, LOG_WARNING, LOC + "nvidia-settings -a \"SyncToVBlank=1\"");
    }

    if (!sync && getenv("__GL_SYNC_TO_VBLANK"))
    {
        LOG(VB_GENERAL, LOG_INFO, LOC +
            "OpenGL Sync to VBlank enabled via __GL_SYNC_TO_VBLANK.");
        sync = 1;
    }
    else if (!sync)
    {
        LOG(VB_GENERAL, LOG_WARNING, LOC +
            "Alternatively try setting the '__GL_SYNC_TO_VBLANK' environment variable.");
    }

    return sync;
}
Beispiel #3
0
bool UINVControl::NVControlAvailable(Display *XDisplay)
{
    QMutexLocker locker(gNVCtrlLock);

    static bool available = false;
    static bool checked   = false;

    if (checked || !XDisplay)
        return available;

    checked = true;

    int event = 0;
    int error = 0;
    Bool ok = XNVCTRLQueryExtension(XDisplay, &event, &error);

    if (ok != True)
    {
        LOG(VB_GENERAL, LOG_INFO, QString("NV-CONTROL X extension not available on display '%1'").arg(XDisplayName(NULL)));
        return available;
    }

    int major = 0;
    int minor = 0;
    ok = XNVCTRLQueryVersion(XDisplay, &major, &minor);

    if (ok != True)
    {
        LOG(VB_GENERAL, LOG_INFO, QString("NV-CONTROL X extension not available on display '%1'").arg(XDisplayName(NULL)));
        return available;
    }

    available = true;

    LOG(VB_GENERAL, LOG_INFO, QString("NV-CONTROL X extension version %1.%2 available on display '%3'")
        .arg(major).arg(minor).arg(XDisplayName(NULL)));

    return available;
}
Beispiel #4
0
static uintptr_t version_flags(Display *dpy, XExtDisplayInfo *info)
{
    uintptr_t data = (uintptr_t)info->data;

    /* If necessary, determine the NV-CONTROL version */
    if (data & NVCTRL_EXT_NEED_CHECK) {
        int major, minor;
        data = 0;
        if (XNVCTRLQueryVersion(dpy, &major, &minor)) {
            data |= NVCTRL_EXT_EXISTS;
            if (major == 1 && (minor == 8 || minor == 9)) {
                data |= NVCTRL_EXT_NEED_TARGET_SWAP;
            }
            if ((major > 1) || ((major == 1) && (minor > 20))) {
                data |= NVCTRL_EXT_64_BIT_ATTRIBUTES;
            }
        }

        info->data = (XPointer)data;
    }

    return data;
}
Beispiel #5
0
/*
 * Open a display connection, and make sure the NV-CONTROL X
 * extension is present on the screen we want to use.
 */  
static Bool setup(Display** dpy, int* screen) {
  int major, minor;
  Bool ret;

  *dpy = XOpenDisplay(NULL);
  if (!(*dpy)) {
    fprintf(stderr, "Cannot open display '%s'.\n\n", XDisplayName(NULL));
    return False;
  }

  *screen = GetNvXScreen(*dpy);
  if (*screen == -1) {
    return False;
  }

  ret = XNVCTRLQueryVersion(*dpy, &major, &minor);
  if (ret != True) {
    fprintf(stderr, "The NV-CONTROL X extension does not exist "
	    "on '%s'.\n\n", XDisplayName(NULL));
    return False;
  }

  return True;
}
Beispiel #6
0
int GetNvidiaRates(t_screenrate& screenmap)
{
#ifdef USING_XRANDR

    MythXDisplay *d = OpenMythXDisplay();
    if (!d)
    {
        return -1;
    }
    Display *dpy;
    bool ret;
    int screen, display_devices, mask, major, minor, len, j;
    char *str, *start;
    int nDisplayDevice;
    
    char *pMetaModes, *pModeLines[8], *tmp, *modeString;
    char *modeLine, *modeName;
    int MetaModeLen, ModeLineLen[8];
    int thisMask;
    int id;
    int twinview =  0;
    map<int, map<int,bool> > maprate;

    memset(pModeLines, 0, sizeof(pModeLines));
    memset(ModeLineLen, 0, sizeof(ModeLineLen));

    /*
     * Open a display connection, and make sure the NV-CONTROL X
     * extension is present on the screen we want to use.
     */

    dpy = d->GetDisplay();    
    screen = d->GetScreen();

    if (!XNVCTRLIsNvScreen(dpy, screen))
    {
        LOG(VB_PLAYBACK, LOG_INFO,
            QString("The NV-CONTROL X extension is not available on screen %1 "
                    "of '%2'.")
                .arg(screen) .arg(XDisplayName(NULL)));
        delete d;
        return -1;
    }

    ret = XNVCTRLQueryVersion(dpy, &major, &minor);
    if (ret != True)
    {
        LOG(VB_PLAYBACK, LOG_INFO,
            QString("The NV-CONTROL X extension does not exist on '%1'.")
                .arg(XDisplayName(NULL)));
        delete d;
        return -1;
    }

    ret = XNVCTRLQueryAttribute(dpy, screen, 0, NV_CTRL_DYNAMIC_TWINVIEW, &twinview);

    if (!ret)
    {
        LOG(VB_PLAYBACK, LOG_ERR,
             "Failed to query if Dynamic Twinview is enabled");
        XCloseDisplay(dpy);
        return -1;
    }
    if (!twinview)
    {
        LOG(VB_PLAYBACK, LOG_ERR, "Dynamic Twinview not enabled, ignoring");
        delete d;
        return 0;
    }

    /*
     * query the connected display devices on this X screen and print
     * basic information about each X screen
     */

    ret = XNVCTRLQueryAttribute(dpy, screen, 0,
                                NV_CTRL_CONNECTED_DISPLAYS, &display_devices);

    if (!ret)
    {
        LOG(VB_PLAYBACK, LOG_ERR,
            "Failed to query the enabled Display Devices.");
        delete d;
        return -1;
    }

    /* first, we query the MetaModes on this X screen */

    ret = XNVCTRLQueryBinaryData(dpy, screen, 0, // n/a
                           NV_CTRL_BINARY_DATA_METAMODES,
                           (unsigned char **)&pMetaModes, &MetaModeLen);
    if (!ret)
    {
        LOG(VB_PLAYBACK, LOG_ERR,
            "Failed to query the metamode on selected display device.");
        delete d;
        return -1;
    }

    /*
     * then, we query the ModeLines for each display device on
     * this X screen; we'll need these later
     */

    nDisplayDevice = 0;

    for (mask = 1; mask < (1 << 24); mask <<= 1)
    {
        if (!(display_devices & mask)) continue;

        ret = XNVCTRLQueryBinaryData(dpy, screen, mask,
                               NV_CTRL_BINARY_DATA_MODELINES,
                               (unsigned char **)&str, &len);
        if (!ret)
        {
            LOG(VB_PLAYBACK, LOG_ERR,
               "Unknown error. Failed to query the enabled Display Devices.");
            // Free Memory currently allocated
            for (j=0; j < nDisplayDevice; ++j)
            {
                free(pModeLines[j]);
            }
            delete d;
            return -1;
        }

        pModeLines[nDisplayDevice] = str;
        ModeLineLen[nDisplayDevice] = len;

        nDisplayDevice++;
    }

    /* now, parse each MetaMode */
    str = start = pMetaModes;

    for (j = 0; j < MetaModeLen - 1; ++j)
    {
        /*
         * if we found the end of a line, treat the string from
         * start to str[j] as a MetaMode
         */

        if ((str[j] == '\0') && (str[j+1] != '\0'))
        {
            id = extract_id_string(start);
            /*
             * the MetaMode may be preceded with "token=value"
             * pairs, separated by the main MetaMode with "::"; if
             * "::" exists in the string, skip past it
             */

            tmp = strstr(start, "::");
            if (tmp)
            {
                tmp += 2;
            }
            else
            {
                tmp = start;
            }

            /* split the MetaMode string by comma */

            char *strtok_state = NULL;
            for (modeString = strtok_r(tmp, ",", &strtok_state);
                 modeString;
                 modeString = strtok_r(NULL, ",", &strtok_state))
            {
                /*
                 * retrieve the modeName and display device mask
                 * for this segment of the Metamode
                 */

                parse_mode_string(modeString, &modeName, &thisMask);

                /* lookup the modeline that matches */
                nDisplayDevice = 0;
                if (thisMask)
                {
                    for (mask = 1; mask < (1 << 24); mask <<= 1)
                    {
                        if (!(display_devices & mask)) continue;
                        if (thisMask & mask) break;
                        nDisplayDevice++;
                    }
                }

                modeLine = find_modeline(modeName,
                                         pModeLines[nDisplayDevice],
                                         ModeLineLen[nDisplayDevice]);

                if (modeLine && !modeline_is_interlaced(modeLine))
                {
                    int w, h, vfl, hfl, i, irate;
                    double dcl, r;
                    char *buf[256];
                    uint64_t key, key2;

                    // skip name
                    tmp = strchr(modeLine, '"');
                    tmp = strchr(tmp+1, '"') +1 ;
                    while (*tmp == ' ')
                        tmp++;
                    i = 0;
                    for (modeString = strtok_r(tmp, " ", &strtok_state);
                         modeString;
                         modeString = strtok_r(NULL, " ", &strtok_state))
                    {
                        buf[i++] = modeString;
                    }
                    w = strtol(buf[1], NULL, 10);
                    h = strtol(buf[5], NULL, 10);
                    vfl = strtol(buf[8], NULL, 10);
                    hfl = strtol(buf[4], NULL, 10);
                    h = strtol(buf[5], NULL, 10);
                    istringstream istr(buf[0]);
                    istr.imbue(locale("C"));
                    istr >> dcl;
                    r = (dcl * 1000000.0) / (vfl * hfl);
                    irate = (int) round(r * 1000.0);
                    key = DisplayResScreen::CalcKey(w, h, (double) id);
                    key2 = DisplayResScreen::CalcKey(w, h, 0.0);
                    // We need to eliminate duplicates, giving priority to the first entries found
                    if (maprate.find(key2) == maprate.end())
                    {
                        // First time we see this resolution, create a map for it
                        maprate[key2] = map<int, bool>();
                    }
                    if ((maprate[key2].find(irate) == maprate[key2].end()) &&
                        (screenmap.find(key) == screenmap.end()))
                    {
                        screenmap[key] = r;
                        maprate[key2][irate] = true;
                    }
                }
                free(modeName);
            }

            /* move to the next MetaMode */
            start = &str[j+1];
        }
int main(int argc, char *argv[])
{
    Display *dpy;
    Bool ret;
    int major, minor;
    int use_gvi = -1;
    int i;
    char *topology_str = NULL;

    /*
     * Open a display connection, and make sure the NV-CONTROL X
     * extension is present on the screen we want to use.
     */
    
    dpy = XOpenDisplay(NULL);
    if (!dpy) {
        printf("Cannot open display '%s'.\n", XDisplayName(NULL));
        return 1;
    }
    
    /* Query the NV-CONTROL version */

    ret = XNVCTRLQueryVersion(dpy, &major, &minor);
    if (ret != True) {
        printf("The NV-CONTROL X extension does not exist on '%s'.\n",
                XDisplayName(NULL));
        return 1;
    }
    
    /* Print some information */

    printf("Using NV-CONTROL extension %d.%d on %s\n\n",
           major, minor, XDisplayName(NULL));

    /* See if user wants a specific GVI device */

    for (i = 0; i < argc; i++) {
        if ((strcmp(argv[i], "-g") == 0) && ((i+1) < argc)) {
            use_gvi = strtol(argv[i+1], NULL, 10);
        }
        if ((strcmp(argv[i], "-c") == 0) && ((i+1) < argc)) {
            topology_str = argv[i+1];
        }
    }
    
    /* Do what the user wants */

    ret = 0;
    for (i = 0; i < argc; i++) {
        if (strcmp(argv[i], "-q") == 0) {
            do_query(dpy, use_gvi);
            ret = 1;
            break;
        } else if (strcmp(argv[i], "-c") == 0) {
            do_configure(dpy, use_gvi, topology_str);
            ret = 1;
            break;
        } else if (strcmp(argv[i], "-l") == 0) {
            do_listconfig(dpy, use_gvi);
            ret = 1;
        }
    }
    if (!ret) {
        do_help();
    }

    return 0;
}
/**
 * load initial data
 *
 * TODO:350:M: Implement nvCtrlTable data load
 * This function will also be called by the cache helper to load
 * the container again (after the container free function has been
 * called to free the previous contents).
 *
 * @param container container to which items should be inserted
 *
 * @retval MFD_SUCCESS              : success.
 * @retval MFD_RESOURCE_UNAVAILABLE : Can't access data source
 * @retval MFD_ERROR                : other error.
 *
 *  This function is called to load the index(es) (and data, optionally)
 *  for the every row in the data set.
 *
 * @remark
 *  While loading the data, the only important thing is the indexes.
 *  If access to your data is cheap/fast (e.g. you have a pointer to a
 *  structure in memory), it would make sense to update the data here.
 *  If, however, the accessing the data invovles more work (e.g. parsing
 *  some other existing data, or peforming calculations to derive the data),
 *  then you can limit yourself to setting the indexes and saving any
 *  information you will need later. Then use the saved information in
 *  nvCtrlTable_row_prep() for populating data.
 *
 * @note
 *  If you need consistency between rows (like you want statistics
 *  for each row to be from the same time frame), you should set all
 *  data here.
 *
 */
int
nvCtrlTable_container_load(netsnmp_container *container)
{
    nvCtrlTable_rowreq_ctx *rowreq_ctx;
    size_t                 count = 0;
    Display *dpy;
    Bool ret;
    int event_base, error_base, major, minor, gpus;
    int gpu, retval, len;
    char *str;

    DEBUGMSGTL(("verbose:nvCtrlTable:nvCtrlTable_container_load", "called\n"));

    /*
     * open a connection to the X server indicated by the DISPLAY
     * environment variable
     */

    dpy = XOpenDisplay(NULL);
    if (!dpy) {
	DEBUGMSGTL(("nvCtrlTable:nvCtrlTable_container_load",
		    "Cannot open display '%s'.\n", XDisplayName(NULL)));
        return MFD_RESOURCE_UNAVAILABLE;
    }

    /*
     * check if the NV-CONTROL X extension is present on this X server
     */

    ret = XNVCTRLQueryExtension(dpy, &event_base, &error_base);
    if (ret != True) {
	DEBUGMSGTL(("nvCtrlTable:nvCtrlTable_container_load",
		    "The NV-CONTROL X extension does not exist on '%s'.\n",
		    XDisplayName(NULL)));
        return MFD_RESOURCE_UNAVAILABLE;
    }

    /*
     * query the major and minor extension version
     */

    ret = XNVCTRLQueryVersion(dpy, &major, &minor);
    if (ret != True) {
	DEBUGMSGTL(("nvCtrlTable:nvCtrlTable_container_load",
		    "The NV-CONTROL X extension does not exist on '%s'.\n",
		    XDisplayName(NULL)));
        return MFD_RESOURCE_UNAVAILABLE;
    }

    /*
     * query number of GPUs via the NV-CONTROL X extension; then, allocate
     * a rowreq context, set the index(es) and data, and insert into the
     * container.
     */

    if (!XNVCTRLQueryTargetCount(dpy, NV_CTRL_TARGET_TYPE_GPU, &gpus)) {
	snmp_log(LOG_ERR, "failed to query number of GPUs\n");
	return MFD_ERROR;
    }

    for (gpu = 0; gpu < gpus; gpu++) {
        rowreq_ctx = nvCtrlTable_allocate_rowreq_ctx();
        if (NULL == rowreq_ctx) {
            snmp_log(LOG_ERR, "memory allocation failed\n");
            return MFD_RESOURCE_UNAVAILABLE;
        }
	if (MFD_SUCCESS != nvCtrlTable_indexes_set(rowreq_ctx, gpu)) {
            snmp_log(LOG_ERR, "error setting index while loading"
		     "nvCtrlTable data.\n");
            nvCtrlTable_release_rowreq_ctx(rowreq_ctx);
            continue;
        }

	/*
	 * setup/save data for nvCtrlProductName
	 * nvCtrlProductName(2)/DisplayString/ASN_OCTET_STR/char(char)//L/A/w/e/R/d/H
	 */
	ret = XNVCTRLQueryTargetStringAttribute(dpy,
						NV_CTRL_TARGET_TYPE_GPU,
						gpu,
						0,
						NV_CTRL_STRING_PRODUCT_NAME,
						&str);
	if (ret) {
	    len = strlen(str);
	    if (sizeof(rowreq_ctx->data.nvCtrlProductName) < len) {
		snmp_log(LOG_ERR,"not enough space for value\n");
		return MFD_ERROR;
	    }
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_PRODUCT_NAME_FLAG;
	    rowreq_ctx->data.nvCtrlProductName_len = len;
	    memcpy(rowreq_ctx->data.nvCtrlProductName, str, len);
	    XFree(str);
	}

	/*
	 * setup/save data for nvCtrlVBiosVersion
	 * nvCtrlVBiosVersion(3)/DisplayString/ASN_OCTET_STR/char(char)//L/A/w/e/R/d/H
	 */
	ret = XNVCTRLQueryTargetStringAttribute(dpy,
						NV_CTRL_TARGET_TYPE_GPU,
						gpu,
						0,
						NV_CTRL_STRING_VBIOS_VERSION,
						&str);
	if (ret) {
	    len = strlen(str);
	    if (sizeof(rowreq_ctx->data.nvCtrlVBiosVersion) < len) {
		snmp_log(LOG_ERR,"not enough space for value\n");
		return MFD_ERROR;
	    }
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_VBIOS_VERSION_FLAG;
	    rowreq_ctx->data.nvCtrlVBiosVersion_len = len;
	    memcpy(rowreq_ctx->data.nvCtrlVBiosVersion, str, len);
	    XFree(str);
	}

	/*
	 * setup/save data for nvCtrlNvidiaDriverVersion
	 * nvCtrlNvidiaDriverVersion(4)/DisplayString/ASN_OCTET_STR/char(char)//L/A/w/e/R/d/H
	 */
	ret = XNVCTRLQueryTargetStringAttribute(dpy,
						NV_CTRL_TARGET_TYPE_GPU,
						gpu,
						0,
						NV_CTRL_STRING_NVIDIA_DRIVER_VERSION,
						&str);
	if (ret) {
	    len = strlen(str);
	    if (sizeof(rowreq_ctx->data.nvCtrlNvidiaDriverVersion) < len) {
		snmp_log(LOG_ERR,"not enough space for value\n");
		return MFD_ERROR;
	    }
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_NVIDIA_DRIVER_VERSION_FLAG;
	    rowreq_ctx->data.nvCtrlNvidiaDriverVersion_len = len;
	    memcpy(rowreq_ctx->data.nvCtrlNvidiaDriverVersion, str, len);
	    XFree(str);
	}

	/*
	 * setup/save data for nvCtrlVersion
	 * nvCtrlVersion(5)/DisplayString/ASN_OCTET_STR/char(char)//L/A/w/e/R/d/H
	 */
	rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_VERSION_FLAG;
	snprintf(rowreq_ctx->data.nvCtrlVersion, sizeof(rowreq_ctx->data.nvCtrlVersion), "%d.%d", major, minor);
	rowreq_ctx->data.nvCtrlVersion_len = strlen(rowreq_ctx->data.nvCtrlVersion);

	/*
	 * setup/save data for nvCtrlBusType
	 * nvCtrlBusType(6)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_BUS_TYPE,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_BUS_TYPE_FLAG;
	    rowreq_ctx->data.nvCtrlBusType = retval;
	}

	/*
	 * setup/save data for nvCtrlBusRate
	 * nvCtrlBusRate(7)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_BUS_RATE,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_BUS_RATE_FLAG;
	    rowreq_ctx->data.nvCtrlBusRate = retval;
	}

	/*
	 * setup/save data for nvCtrlVideoRam
	 * nvCtrlVideoRam(8)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_VIDEO_RAM,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_VIDEO_RAM_FLAG;
	    rowreq_ctx->data.nvCtrlVideoRam = retval;
	}

	/*
	 * setup/save data for nvCtrlIrq
	 * nvCtrlIrq(9)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_IRQ,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_IRQ_FLAG;
	    rowreq_ctx->data.nvCtrlIrq = retval;
	}

	/*
	 * setup/save data for nvCtrlGPUCoreTemp
	 * nvCtrlGPUCoreTemp(10)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_GPU_CORE_TEMPERATURE,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_CORE_TEMP_FLAG;
	    rowreq_ctx->data.nvCtrlGPUCoreTemp = retval;
	}

	/*
	 * setup/save data for nvCtrlGPUCoreThreshold
	 * nvCtrlGPUCoreThreshold(11)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_GPU_CORE_THRESHOLD,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_CORE_THRESHOLD_FLAG;
	    rowreq_ctx->data.nvCtrlGPUCoreThreshold = retval;
	}

	/*
	 * setup/save data for nvCtrlGPUDefaultCoreThreshold
	 * nvCtrlGPUDefaultCoreThreshold(12)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_GPU_DEFAULT_CORE_THRESHOLD,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_DEFAULT_CORE_THRESHOLD_FLAG;
	    rowreq_ctx->data.nvCtrlGPUDefaultCoreThreshold = retval;
	}

	/*
	 * setup/save data for nvCtrlGPUMaxCoreThreshold
	 * nvCtrlGPUMaxCoreThreshold(13)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_GPU_MAX_CORE_THRESHOLD,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_MAX_CORE_THRESHOLD_FLAG;
	    rowreq_ctx->data.nvCtrlGPUMaxCoreThreshold = retval;
	}

	/*
	 * setup/save data for nvCtrlGPUAmbientTemp
	 * nvCtrlGPUAmbientTemp(14)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_AMBIENT_TEMPERATURE,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_AMBIENT_TEMP_FLAG;
	    rowreq_ctx->data.nvCtrlGPUAmbientTemp = retval;
	}

	/*
	 * setup/save data for nvCtrlGPUOverclockingState
	 * nvCtrlGPUOverclockingState(15)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_GPU_OVERCLOCKING_STATE,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_OVERCLOCKING_STATE_FLAG;
	    rowreq_ctx->data.nvCtrlGPUOverclockingState = retval;
	}

	/*
	 * setup/save data for nvCtrlGPU2DGPUClockFreq
	 * nvCtrlGPU2DGPUClockFreq(16)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_GPU_2D_CLOCK_FREQS,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_2D_GPU_CLOCK_FREQ_FLAG;
	    rowreq_ctx->data.nvCtrlGPU2DGPUClockFreq = (retval >> 16) & 0xFFFF;
	}

	/*
	 * setup/save data for nvCtrlGPU2DMemClockFreq
	 * nvCtrlGPU2DMemClockFreq(17)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_2D_MEM_CLOCK_FREQ_FLAG;
	    rowreq_ctx->data.nvCtrlGPU2DMemClockFreq = retval & 0xFFFF;
	}

	/*
	 * setup/save data for nvCtrlGPU3DGPUClockFreq
	 * nvCtrlGPU3DGPUClockFreq(18)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_GPU_3D_CLOCK_FREQS,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_3D_GPU_CLOCK_FREQ_FLAG;
	    rowreq_ctx->data.nvCtrlGPU3DGPUClockFreq = (retval >> 16) & 0xFFFF;
	}

	/*
	 * setup/save data for nvCtrlGPU3DMemClockFreq
	 * nvCtrlGPU3DMemClockFreq(19)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_3D_MEM_CLOCK_FREQ_FLAG;
	    rowreq_ctx->data.nvCtrlGPU3DMemClockFreq = retval & 0xFFFF;
	}

	/*
	 * setup/save data for nvCtrlGPUDefault2DGPUClockFreq
	 * nvCtrlGPUDefault2DGPUClockFreq(20)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_GPU_DEFAULT_2D_CLOCK_FREQS,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_DEFAULT_2D_GPU_CLOCK_FREQ_FLAG;
	    rowreq_ctx->data.nvCtrlGPUDefault2DGPUClockFreq = (retval >> 16) & 0xFFFF;
	}

	/*
	 * setup/save data for nvCtrlGPUDefault2DMemClockFreq
	 * nvCtrlGPUDefault2DMemClockFreq(21)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_DEFAULT_2D_MEM_CLOCK_FREQ_FLAG;
	    rowreq_ctx->data.nvCtrlGPUDefault2DMemClockFreq = retval & 0xFFFF;
	}

	/*
	 * setup/save data for nvCtrlGPUDefault3DGPUClockFreq
	 * nvCtrlGPUDefault3DGPUClockFreq(22)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_GPU_DEFAULT_3D_CLOCK_FREQS,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_DEFAULT_3D_GPU_CLOCK_FREQ_FLAG;
	    rowreq_ctx->data.nvCtrlGPUDefault3DGPUClockFreq = (retval >> 16) & 0xFFFF;
	}

	/*
	 * setup/save data for nvCtrlGPUDefault3DMemClockFreq
	 * nvCtrlGPUDefault3DMemClockFreq(23)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_DEFAULT_3D_MEM_CLOCK_FREQ_FLAG;
	    rowreq_ctx->data.nvCtrlGPUDefault3DMemClockFreq = retval & 0xFFFF;
	}

	/*
	 * setup/save data for nvCtrlGPUCurrentGPUClockFreq
	 * nvCtrlGPUCurrentGPUClockFreq(24)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	ret = XNVCTRLQueryTargetAttribute(dpy,
					  NV_CTRL_TARGET_TYPE_GPU,
					  gpu,
					  0,
					  NV_CTRL_GPU_CURRENT_CLOCK_FREQS,
					  &retval);
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_CURRENT_GPU_CLOCK_FREQ_FLAG;
	    rowreq_ctx->data.nvCtrlGPUCurrentGPUClockFreq = (retval >> 16) & 0xFFFF;
	}

	/*
	 * setup/save data for nvCtrlGPUCurrentMemClockFreq
	 * nvCtrlGPUCurrentMemClockFreq(25)/INTEGER32/ASN_INTEGER/long(long)//l/A/w/e/r/d/h
	 */
	if (ret) {
	    rowreq_ctx->column_exists_flags |= COLUMN_NV_CTRL_GPU_CURRENT_MEM_CLOCK_FREQ_FLAG;
	    rowreq_ctx->data.nvCtrlGPUCurrentMemClockFreq = retval & 0xFFFF;
	}

	/*
	 * insert into table container
	 */
	CONTAINER_INSERT(container, rowreq_ctx);
	++count;
    }

    /*
     * close the display connection
     */

    XCloseDisplay(dpy);


    DEBUGMSGT(("verbose:nvCtrlTable:nvCtrlTable_container_load",
               "inserted %d records\n", count));

    return MFD_SUCCESS;
} /* nvCtrlTable_container_load */
int main(int argc, char *argv[])
{
    Display *dpy;
    Bool ret;
    int screen, major, minor, len, i, j;
    char *str, *start, *str0, *str1;
    int *enabledDpyIds;


    /*
     * Open a display connection, and make sure the NV-CONTROL X
     * extension is present on the screen we want to use.
     */
    
    dpy = XOpenDisplay(NULL);
    if (!dpy) {
        fprintf(stderr, "Cannot open display '%s'.\n\n", XDisplayName(NULL));
        return 1;
    }
    
    screen = GetNvXScreen(dpy);

    ret = XNVCTRLQueryVersion(dpy, &major, &minor);
    if (ret != True) {
        fprintf(stderr, "The NV-CONTROL X extension does not exist "
                "on '%s'.\n\n", XDisplayName(NULL));
        return 1;
    }

    printf("\nUsing NV-CONTROL extension %d.%d on %s\n\n",
           major, minor, XDisplayName(NULL));


    /*
     * query the enabled display devices on this X screen and print basic
     * information about each X screen.
     */

    ret = XNVCTRLQueryTargetBinaryData(dpy,
                                       NV_CTRL_TARGET_TYPE_X_SCREEN,
                                       screen,
                                       0,
                                       NV_CTRL_BINARY_DATA_DISPLAYS_ENABLED_ON_XSCREEN,
                                       (unsigned char **) &enabledDpyIds,
                                       &len);
    if (!ret || (len < sizeof(enabledDpyIds[0]))) {
        fprintf(stderr, "Failed to query the enabled Display Devices.\n\n");
        return 1;
    }

    printf("Enabled Display Devices:\n");

    for (i = 0; i < enabledDpyIds[0]; i++) {
        int dpyId = enabledDpyIds[i+1];

        print_display_id_and_name(dpy, dpyId, "  ");
    }

    printf("\n");
    
    
    /*
     * perform the requested action, based on the specified
     * commandline option
     */
    
    if (argc <= 1) goto printHelp;


    /*
     * for each enabled display device on this X screen, query the list of
     * modelines in the mode pool using NV_CTRL_BINARY_DATA_MODELINES, then
     * print the results.
     */

    if (strcmp(argv[1], "--print-modelines") == 0) {

        for (i = 0; i < enabledDpyIds[0]; i++) {
            int dpyId = enabledDpyIds[i+1];

            ret = XNVCTRLQueryTargetBinaryData(dpy,
                                               NV_CTRL_TARGET_TYPE_DISPLAY,
                                               dpyId,
                                               0,
                                               NV_CTRL_BINARY_DATA_MODELINES,
                                               (void *) &str, &len);
            if (!ret) {
                fprintf(stderr, "Failed to query ModeLines.\n\n");
                return 1;
            }

            /*
             * the returned data is in the form:
             *
             *  "ModeLine 1\0ModeLine 2\0ModeLine 3\0Last ModeLine\0\0"
             *
             * so walk from one "\0" to the next to print each ModeLine.
             */

            printf("Modelines for DPY-%d:\n", dpyId);

            start = str;
            for (j = 0; j < len; j++) {
                if (str[j] == '\0') {
                    printf("  %s\n", start);
                    start = &str[j+1];
                }
            }

            XFree(str);
        }
    }


    /*
     * for each enabled display device on this X screen, query the current
     * modeline using NV_CTRL_STRING_CURRENT_MODELINE.
     */

    else if (strcmp(argv[1], "--print-current-modeline") == 0) {

       for (i = 0; i < enabledDpyIds[0]; i++) {
            int dpyId = enabledDpyIds[i+1];

            ret = XNVCTRLQueryTargetStringAttribute(dpy,
                                                    NV_CTRL_TARGET_TYPE_DISPLAY,
                                                    dpyId,
                                                    0,
                                                    NV_CTRL_STRING_CURRENT_MODELINE,
                                                    &str);
            if (!ret) {
                fprintf(stderr, "Failed to query current ModeLine.\n\n");
                return 1;
            }

            printf("Current Modeline for DPY-%d:\n", dpyId);
            printf("  %s\n\n", str);

            XFree(str);
        }
    }
    

    /*
     * add the specified modeline to the mode pool for the specified
     * display device, using NV_CTRL_STRING_ADD_MODELINE
     */
    
    else if ((strcmp(argv[1], "--add-modeline") == 0) &&
             argv[2] && argv[3]) {
        
        int dpyId = strtol(argv[2], NULL, 0);

        ret = XNVCTRLSetTargetStringAttribute(dpy,
                                              NV_CTRL_TARGET_TYPE_DISPLAY,
                                              dpyId,
                                              0,
                                              NV_CTRL_STRING_ADD_MODELINE,
                                              argv[3]);
        
        if (!ret) {
            fprintf(stderr, "Failed to add the modeline \"%s\" to DPY-%d's "
                    "mode pool.\n\n", argv[3], dpyId);
            return 1;
        }
        
        printf("Added modeline \"%s\" to DPY-%d's mode pool.\n\n",
               argv[3], dpyId);
    }

    
    /*
     * delete the specified modeline from the mode pool for the
     * specified display device, using NV_CTRL_STRING_DELETE_MODELINE
     */
    
    else if ((strcmp(argv[1], "--delete-modeline") == 0) &&
             argv[2] && argv[3]) {
        
        int dpyId = strtol(argv[2], NULL, 0);
    
        ret = XNVCTRLSetTargetStringAttribute(dpy,
                                              NV_CTRL_TARGET_TYPE_DISPLAY,
                                              dpyId,
                                              0,
                                              NV_CTRL_STRING_DELETE_MODELINE,
                                              argv[3]);
        
        if (!ret) {
            fprintf(stderr, "Failed to delete the mode \"%s\" from DPY-%d's "
                    "mode pool.\n\n", argv[3], dpyId);
            return 1;
        }
        
        printf("Deleted modeline \"%s\" from DPY-%d's mode pool.\n\n",
               argv[3], dpyId);
    }
    
    
    /*
     * generate a GTF modeline using NV_CTRL_STRING_OPERATION_GTF_MODELINE
     */
    
    else if ((strcmp(argv[1], "--generate-gtf-modeline") == 0) &&
             argv[2] && argv[3] && argv[4]) {
        
        char pGtfString[128];
        char *pOut;
        
        snprintf(pGtfString, 128, "width=%s, height=%s, refreshrate=%s",
                 argv[2], argv[3], argv[4]);

        ret = XNVCTRLStringOperation(dpy,
                                     NV_CTRL_TARGET_TYPE_X_SCREEN,
                                     screen,
                                     0,
                                     NV_CTRL_STRING_OPERATION_GTF_MODELINE,
                                     pGtfString,
                                     &pOut);

        if (!ret) {
            fprintf(stderr, "Failed to generate GTF ModeLine from "
                    "\"%s\".\n\n", pGtfString);
            return 1;
        }
        
        printf("GTF ModeLine from \"%s\": %s\n\n", pGtfString, pOut);
    }
    
    
    /*
     * generate a CVT modeline using NV_CTRL_STRING_OPERATION_CVT_MODELINE
     */

    else if ((strcmp(argv[1], "--generate-cvt-modeline") == 0) &&
             argv[2] && argv[3] && argv[4] && argv[5]) {

        char pCvtString[128];
        char *pOut;
        
        snprintf(pCvtString, 128, "width=%s, height=%s, refreshrate=%s, "
                 "reduced-blanking=%s",
                 argv[2], argv[3], argv[4], argv[5]);
        
        ret = XNVCTRLStringOperation(dpy,
                                     NV_CTRL_TARGET_TYPE_X_SCREEN,
                                     screen,
                                     0,
                                     NV_CTRL_STRING_OPERATION_CVT_MODELINE,
                                     pCvtString,
                                     &pOut);

        if (!ret) {
            fprintf(stderr, "Failed to generate CVT ModeLine from "
                    "\"%s\".\n\n", pCvtString);
            return 1;
        }

        printf("CVT ModeLine from \"%s\": %s\n\n", pCvtString, pOut);
    }

    
    /*
     * query the MetaModes for the X screen, using
     * NV_CTRL_BINARY_DATA_METAMODES.
     */
    
    else if (strcmp(argv[1], "--print-metamodes") == 0) {

        /* get list of metamodes */
        
        ret = XNVCTRLQueryBinaryData(dpy, screen, 0, // n/a
                                     NV_CTRL_BINARY_DATA_METAMODES,
                                     (void *) &str, &len);
        
        if (!ret) {
            fprintf(stderr, "Failed to query MetaModes.\n\n");
            return 1;
        }
        
        /*
         * the returned data is in the form:
         *
         *   "MetaMode 1\0MetaMode 2\0MetaMode 3\0Last MetaMode\0\0"
         *
         * so walk from one "\0" to the next to print each MetaMode.
         */
        
        printf("MetaModes:\n");
        
        start = str;
        for (j = 0; j < len; j++) {
            if (str[j] == '\0') {
                printf("  %s\n", start);
                start = &str[j+1];
            }
        }
        
        XFree(str);
    }


    /*
     * query the MetaModes for the X screen, using
     * NV_CTRL_BINARY_DATA_METAMODES_VERSION_2.
     */

    else if (strcmp(argv[1], "--print-metamodes-version2") == 0) {

        /* get list of metamodes */

        ret = XNVCTRLQueryBinaryData(dpy, screen, 0, // n/a
                                     NV_CTRL_BINARY_DATA_METAMODES_VERSION_2,
                                     (void *) &str, &len);

        if (!ret) {
            fprintf(stderr, "Failed to query MetaModes.\n\n");
            return 1;
        }

        /*
         * the returned data is in the form:
         *
         *   "MetaMode 1\0MetaMode 2\0MetaMode 3\0Last MetaMode\0\0"
         *
         * so walk from one "\0" to the next to print each MetaMode.
         */

        printf("MetaModes:\n");

        start = str;
        for (j = 0; j < len; j++) {
            if (str[j] == '\0') {
                printf("  %s\n", start);
                start = &str[j+1];
            }
        }

        XFree(str);
    }


    /*
     * query the currently in use MetaMode.  Note that an alternative
     * way to accomplish this is to use XRandR to query the current
     * mode's refresh rate, and then match the refresh rate to the id
     * reported in the returned NV_CTRL_BINARY_DATA_METAMODES data.
     */
    
    else if (strcmp(argv[1], "--print-current-metamode") == 0) {
        
        ret = XNVCTRLQueryStringAttribute(dpy, screen, 0,
                                          NV_CTRL_STRING_CURRENT_METAMODE,
                                          &str);
        
        if (!ret) {
            fprintf(stderr, "Failed to query the current MetaMode.\n\n");
            return 1;
        }
        
        printf("current metamode: \"%s\"\n\n", str);

        XFree(str);
    }


    /*
     * query the currently in use MetaMode.  Note that an alternative
     * way to accomplish this is to use XRandR to query the current
     * mode's refresh rate, and then match the refresh rate to the id
     * reported in the returned NV_CTRL_BINARY_DATA_METAMODES_VERSION_2 data.
     */

    else if (strcmp(argv[1], "--print-current-metamode-version2") == 0) {

        ret = XNVCTRLQueryStringAttribute(dpy, screen, 0,
                                          NV_CTRL_STRING_CURRENT_METAMODE_VERSION_2,
                                          &str);

        if (!ret) {
            fprintf(stderr, "Failed to query the current MetaMode.\n\n");
            return 1;
        }

        printf("current metamode: \"%s\"\n\n", str);

        XFree(str);
    }


    /*
     * add the given MetaMode to X screen's list of MetaModes, using
     * NV_CTRL_STRING_OPERATION_ADD_METAMODE; example MetaMode string:
     *
     * "nvidia-auto-select, nvidia-auto-select"
     *
     * The output string will contain "id=#" which indicates the
     * unique identifier for this MetaMode.  You can then use XRandR
     * to switch to this mode by matching the identifier with the
     * refresh rate reported via XRandR.
     *
     * For example:
     *
     * $ ./nv-control-dpy --add-metamode \
     *                         "nvidia-auto-select, nvidia-auto-select"
     *
     * Using NV-CONTROL extension 1.12 on :0
     * Enabled Display Devices:
     *   DPY-0 : EIZO F931
     *   DPY-1 : ViewSonic P815-4
     *
     * Added MetaMode "nvidia-auto-select, nvidia-auto-select"; 
     * pOut: "id=52"
     *
     * $ xrandr -q
     * SZ:    Pixels          Physical       Refresh
     *  0   3200 x 1200   ( 821mm x 302mm )   51   52  
     * *1   1600 x 600    ( 821mm x 302mm )  *50  
     * Current rotation - normal
     * Current reflection - none
     * Rotations possible - normal 
     * Reflections possible - none
     *
     * $ xrandr -s 0 -r 52
     */
    
    else if ((strcmp(argv[1], "--add-metamode") == 0) && (argv[2])) {
        
        char *pOut;
        
        ret = XNVCTRLStringOperation(dpy,
                                     NV_CTRL_TARGET_TYPE_X_SCREEN,
                                     screen,
                                     0,
                                     NV_CTRL_STRING_OPERATION_ADD_METAMODE,
                                     argv[2],
                                     &pOut);

        if (!ret) {
            fprintf(stderr, "Failed to add the MetaMode \"%s\".\n\n",
                    argv[2]);
            return 1;
        }

        printf("Added MetaMode \"%s\"; pOut: \"%s\"\n\n", argv[2], pOut);
        
        XFree(pOut);
    }
    
    
    /*
     * delete the given MetaMode from the X screen's list of
     * MetaModes, using NV_CTRL_STRING_DELETE_METAMODE
     */

    else if ((strcmp(argv[1], "--delete-metamode") == 0) && (argv[1])) {
        
        ret = XNVCTRLSetStringAttribute(dpy,
                                        screen,
                                        0,
                                        NV_CTRL_STRING_DELETE_METAMODE,
                                        argv[2]);

        if (!ret) {
            fprintf(stderr, "Failed to delete the MetaMode.\n\n");
            return 1;
        }
        
        printf("Deleted MetaMode \"%s\".\n\n", argv[2]);
    }
    
    
    /*
     * query the valid frequency ranges for each display device, using
     * NV_CTRL_STRING_VALID_HORIZ_SYNC_RANGES and
     * NV_CTRL_STRING_VALID_VERT_REFRESH_RANGES
     */
    
    else if (strcmp(argv[1], "--get-valid-freq-ranges") == 0) {

        for (i = 0; i < enabledDpyIds[0]; i++) {
            int dpyId = enabledDpyIds[i+1];

            ret = XNVCTRLQueryTargetStringAttribute
                (dpy, NV_CTRL_TARGET_TYPE_DISPLAY, dpyId, 0,
                 NV_CTRL_STRING_VALID_HORIZ_SYNC_RANGES,
                 &str0);

            if (!ret) {
                fprintf(stderr, "Failed to query HorizSync for DPY-%d.\n\n",
                        dpyId);
                return 1;
            }

            ret = XNVCTRLQueryTargetStringAttribute
                (dpy, NV_CTRL_TARGET_TYPE_DISPLAY, dpyId, 0,
                 NV_CTRL_STRING_VALID_VERT_REFRESH_RANGES,
                 &str1);

            if (!ret) {
                fprintf(stderr, "Failed to query VertRefresh for DPY-%d.\n\n",
                        dpyId);
                XFree(str0);
                return 1;
            }

            printf("frequency information for DPY-%d:\n", dpyId);
            printf("  HorizSync   : \"%s\"\n", str0);
            printf("  VertRefresh : \"%s\"\n\n", str1);

            XFree(str0);
            XFree(str1);
        }
    }
    
    
    /*
     * attempt to build the modepool for each display device; this
     * will fail for any display device that already has a modepool
     */
    
    else if (strcmp(argv[1], "--build-modepool") == 0) {

        for (i = 0; i < enabledDpyIds[0]; i++) {
            int dpyId = enabledDpyIds[i+1];

            ret = XNVCTRLStringOperation
                (dpy,
                 NV_CTRL_TARGET_TYPE_DISPLAY,
                 dpyId,
                 0,
                 NV_CTRL_STRING_OPERATION_BUILD_MODEPOOL,
                 argv[2],
                 &str0);

            if (!ret) {
                fprintf(stderr, "Failed to build modepool for DPY-%d (it most "
                        "likely already has a modepool).\n\n", dpyId);
            } else {
                printf("Built modepool for DPY-%d.\n\n", dpyId);
            }
        }
    }

    
    /*
     * query the assigned display devices on this X screen; these are the
     * display devices that are available to the X screen for use by MetaModes.
     */

    else if (strcmp(argv[1], "--get-assigned-dpys") == 0) {

        int *pData = NULL;
        int len;

        ret = XNVCTRLQueryTargetBinaryData(dpy,
                                           NV_CTRL_TARGET_TYPE_X_SCREEN,
                                           screen,
                                           0,
                                           NV_CTRL_BINARY_DATA_DISPLAYS_ASSIGNED_TO_XSCREEN,
                                           (unsigned char **) &pData,
                                           &len);
        if (!ret || (len < sizeof(pData[0]))) {
            fprintf(stderr, "failed to query the assigned display "
                    "devices.\n\n");
            return 1;
        }

        printf("Assigned display devices:\n");

        for (i = 0; i < pData[0]; i++) {
            int dpyId = pData[i+1];

            printf("  DPY-%d\n", dpyId);
        }

        printf("\n");
        XFree(pData);
    }

    /*
     * query information about the GPUs in the system
     */
    
    else if (strcmp(argv[1], "--query-gpus") == 0) {

        int num_gpus, num_screens, i;
        int *pData;

        printf("GPU Information:\n");

        /* Get the number of gpus in the system */
        
        ret = XNVCTRLQueryTargetCount(dpy, NV_CTRL_TARGET_TYPE_GPU,
                                      &num_gpus);
        if (!ret) {
            fprintf(stderr, "Failed to query number of gpus.\n\n");
            return 1;
        }

        printf("  number of GPUs: %d\n", num_gpus);

        /* List the X screen number of all X screens driven by each gpu */
        
        for (i = 0; i < num_gpus; i++) {
            
            ret = XNVCTRLQueryTargetBinaryData
                (dpy,
                 NV_CTRL_TARGET_TYPE_GPU,
                 i, // target_id
                 0,
                 NV_CTRL_BINARY_DATA_XSCREENS_USING_GPU,
                 (unsigned char **) &pData,
                 &len);
            
            if (!ret || (len < sizeof(pData[0]))) {
                fprintf(stderr, "Failed to query list of X Screens\n");
                return 1;
            }
            
            printf("  number of X screens using GPU %d: %d\n", i, pData[0]);
            
            /* List X Screen number of all X Screens driven by this GPU. */
            
            printf("    Indices of X screens using GPU %d: ", i);
            
            for (j = 1; j <= pData[0]; j++) {
                printf(" %d", pData[j]);
            }
            printf("\n");
            XFree(pData);
        }
        

        /* Get the number of X Screens in the system 
         *
         * NOTE: If Xinerama is enabled, ScreenCount(dpy) will return 1,
         *       where as querying the screen count information from
         *       NV-CONTROL will return the number of underlying X Screens.
         */
        
        ret = XNVCTRLQueryTargetCount(dpy, NV_CTRL_TARGET_TYPE_X_SCREEN,
                                      &num_screens);
        if (!ret) {
            fprintf(stderr, "Failed to query number of X Screens\n\n");
            return 1;
        }

        printf("\n");
        printf("  number of X screens (ScreenCount): %d\n",
               ScreenCount(dpy));
        printf("  number of X screens (NV-CONTROL): %d\n\n",
               num_screens);

        for (i = 0; i < num_screens; i++) {
            
            ret = XNVCTRLQueryTargetBinaryData
                (dpy,
                 NV_CTRL_TARGET_TYPE_X_SCREEN,
                 i, // target_id
                 0,
                 NV_CTRL_BINARY_DATA_GPUS_USED_BY_XSCREEN,
                 (unsigned char **) &pData,
                 &len);
            
            if (!ret || (len < sizeof(pData[0]))) {
                fprintf(stderr, "Failed to query list of gpus\n\n");
                return 1;
            }
            
            printf("  number of GPUs used by X screen %d: %d\n", i,
                   pData[0]);

            /* List gpu number of all gpus driven by this X screen */

            printf("    Indices of GPUs used by X screen %d: ", i);
            for (j = 1; j <= pData[0]; j++) {
                printf(" %d", pData[j]);
            }
            printf("\n");
            XFree(pData);
        }
        
        printf("\n");

    }
    
    
    /*
     * probe for any newly connected display devices
     */
    
    else if (strcmp(argv[1], "--probe-dpys") == 0) {

        int num_gpus, i;

        printf("Display Device Probed Information:\n\n");

        /* Get the number of gpus in the system */
        
        ret = XNVCTRLQueryTargetCount(dpy, NV_CTRL_TARGET_TYPE_GPU,
                                      &num_gpus);
        
        if (!ret) {
            fprintf(stderr, "Failed to query number of gpus\n\n");
            return 1;
        }
        
        printf("  number of GPUs: %d\n", num_gpus);

        /* Probe and list the Display devices */
        
        for (i = 0; i < num_gpus; i++) {
            int deprecated;
            int *pData;
            
            /* Get the gpu name */
            
            ret = XNVCTRLQueryTargetStringAttribute
                (dpy, NV_CTRL_TARGET_TYPE_GPU, i, 0,
                 NV_CTRL_STRING_PRODUCT_NAME, &str);
            
            if (!ret) {
                fprintf(stderr, "Failed to query gpu name\n\n");
                return 1;
            }

            /* Probe the GPU for new/old display devices */
            
            ret = XNVCTRLQueryTargetAttribute(dpy,
                                              NV_CTRL_TARGET_TYPE_GPU, i,
                                              0,
                                              NV_CTRL_PROBE_DISPLAYS,
                                              &deprecated);
            
            if (!ret) {
                fprintf(stderr, "Failed to probe the enabled Display "
                        "Devices on GPU-%d (%s).\n\n", i, str);
                return 1;
            }
            
            printf("  display devices on GPU-%d (%s):\n", i, str);
            XFree(str);
        
            /* Report results */

            ret = XNVCTRLQueryTargetBinaryData(dpy,
                                               NV_CTRL_TARGET_TYPE_GPU, i,
                                               0,
                                               NV_CTRL_BINARY_DATA_DISPLAYS_CONNECTED_TO_GPU,
                                               (unsigned char **) &pData,
                                               &len);
            if (!ret || (len < sizeof(pData[0]))) {
                fprintf(stderr, "Failed to query the connected Display Devices.\n\n");
                return 1;
            }

            for (j = 0; j < pData[0]; j++) {
                int dpyId = pData[j+1];

                print_display_id_and_name(dpy, dpyId, "    ");
            }

            printf("\n");
        }
        
        printf("\n");
    }
    
    
    /*
     * query the nvidiaXineramaInfoOrder
     */
    
    else if (strcmp(argv[1], "--query-nvidia-xinerama-info-order") == 0) {
        
        ret = XNVCTRLQueryTargetStringAttribute
            (dpy, NV_CTRL_TARGET_TYPE_X_SCREEN, screen, 0,
             NV_CTRL_STRING_NVIDIA_XINERAMA_INFO_ORDER, &str);
        
        if (!ret) {
            fprintf(stderr, "Failed to query nvidiaXineramaInfoOrder.\n\n");
            return 1;
        }
        
        printf("nvidiaXineramaInfoOrder: %s\n\n", str);
    }
    
    
    /*
     * assign the nvidiaXineramaInfoOrder
     */
    
    else if ((strcmp(argv[1], "--assign-nvidia-xinerama-info-order")== 0)
             && argv[2]) {
        
        ret = XNVCTRLSetStringAttribute
            (dpy,
             screen,
             0,
             NV_CTRL_STRING_NVIDIA_XINERAMA_INFO_ORDER,
             argv[2]);
        
        if (!ret) {
            fprintf(stderr, "Failed to assign "
                    "nvidiaXineramaInfoOrder = \"%s\".\n\n", argv[2]);
            return 1;
        }
        
        printf("assigned nvidiaXineramaInfoOrder: \"%s\"\n\n",
               argv[2]);
    }


    /*
     * use NV_CTRL_MAX_SCREEN_WIDTH and NV_CTRL_MAX_SCREEN_HEIGHT to
     * query the maximum screen dimensions on each GPU in the system
     */
    
    else if (strcmp(argv[1], "--max-screen-size") == 0) {

        int num_gpus, i, width, height;
        
        /* Get the number of gpus in the system */
        
        ret = XNVCTRLQueryTargetCount(dpy, NV_CTRL_TARGET_TYPE_GPU,
                                      &num_gpus);
        if (!ret) {
            fprintf(stderr, "Failed to query number of gpus.\n\n");
            return 1;
        }
        
        for (i = 0; i < num_gpus; i++) {
            
            ret = XNVCTRLQueryTargetAttribute(dpy,
                                              NV_CTRL_TARGET_TYPE_GPU,
                                              i,
                                              0,
                                              NV_CTRL_MAX_SCREEN_WIDTH,
                                              &width);

            if (!ret) {
                fprintf(stderr, "Failed to query the maximum screen "
                        "width on GPU-%d\n\n", i);
                return 1;
            }
            
            ret = XNVCTRLQueryTargetAttribute(dpy,
                                              NV_CTRL_TARGET_TYPE_GPU,
                                              i,
                                              0,
                                              NV_CTRL_MAX_SCREEN_HEIGHT,
                                              &height);

            if (!ret) {
                fprintf(stderr, "Failed to query the maximum screen "
                        "height on GPU-%d.\n\n", i);
                return 1;
            }
            
            printf("GPU-%d: maximum X screen size: %d x %d.\n\n",
                   i, width, height);
        }
    }


    /*
     * demonstrate how to use NV-CONTROL to query what modelines are
     * used by the MetaModes of the X screen: we first query all the
     * MetaModes, parse out the display device names and mode names,
     * and then lookup the modelines associated with those mode names
     * on those display devices
     *
     * this could be implemented much more efficiently, but
     * demonstrates the general idea
     */
    
    else if (strcmp(argv[1], "--print-used-modelines") == 0) {

        char *pMetaModes, *pModeLines[8], *tmp, *modeString;
        char *modeLine, *modeName, *noWhiteSpace;
        int MetaModeLen, ModeLineLen[8], ModeLineDpyId[8];
        int dpyId;

        /* first, we query the MetaModes on this X screen */
        
        XNVCTRLQueryBinaryData(dpy, screen, 0,
                               NV_CTRL_BINARY_DATA_METAMODES_VERSION_2,
                               (void *) &pMetaModes, &MetaModeLen);
        
        /*
         * then, we query the ModeLines for each display device on
         * this X screen; we'll need these later
         */

        for (i = 0; i < enabledDpyIds[0]; i++) {
            dpyId = enabledDpyIds[i+1];

            XNVCTRLQueryTargetBinaryData(dpy, NV_CTRL_TARGET_TYPE_DISPLAY,
                                         dpyId,
                                         0,
                                         NV_CTRL_BINARY_DATA_MODELINES,
                                         (void *) &str, &len);

            pModeLines[i] = str;
            ModeLineLen[i] = len;
            ModeLineDpyId[i] = dpyId;
        }
        
        /* now, parse each MetaMode */
        
        str = start = pMetaModes;
        
        for (j = 0; j < MetaModeLen - 1; j++) {

            /*
             * if we found the end of a line, treat the string from
             * start to str[j] as a MetaMode
             */

            if ((str[j] == '\0') && (str[j+1] != '\0')) {

                printf("MetaMode: %s\n", start);
                
                /*
                 * remove any white space from the string to make
                 * parsing easier
                 */
                
                noWhiteSpace = remove_whitespace(start);

                /*
                 * the MetaMode may be preceded with "token=value"
                 * pairs, separated by the main MetaMode with "::"; if
                 * "::" exists in the string, skip past it
                 */
                
                tmp = strstr(noWhiteSpace, "::");
                if (tmp) {
                    tmp += 2;
                } else {
                    tmp = noWhiteSpace;
                }

                /* Parse each mode from the metamode */

                for (modeString = mode_strtok(tmp);
                     modeString;
                     modeString = mode_strtok(NULL)) {

                    /*
                     * retrieve the modeName and display device id
                     * for this segment of the Metamode
                     */

                    if (!parse_mode_string(modeString, &modeName, &dpyId)) {
                        fprintf(stderr, "  Failed to parse mode string '%s'."
                                "\n\n",
                                modeString);
                        continue;
                    }

                    /* lookup the modeline that matches */

                    for (i = 0; i < enabledDpyIds[0]; i++) {
                        if (ModeLineDpyId[i] == dpyId) {
                            break;
                        }
                    }
                    if ( i >= enabledDpyIds[0] ) {
                        fprintf(stderr, "  Failed to find modelines for "
                                "DPY-%d.\n\n",
                                dpyId);
                        continue;
                    }

                    modeLine = find_modeline(modeName,
                                             pModeLines[i],
                                             ModeLineLen[i]);

                    printf("  DPY-%d: %s\n", dpyId, modeLine);
                }

                printf("\n");

                free(noWhiteSpace);
                
                /* move to the next MetaMode */
                
                start = &str[j+1];
            }
        }
    }


    /* Display all names each display device goes by
     */
    else if (strcmp(argv[1], "--print-display-names") == 0) {
        int *pData;
        int len, i;

        printf("Display Device Information:\n");

        ret = XNVCTRLQueryTargetBinaryData(dpy,
                                           NV_CTRL_TARGET_TYPE_GPU,
                                           0,
                                           0,
                                           NV_CTRL_BINARY_DATA_DISPLAY_TARGETS,
                                           (unsigned char **) &pData,
                                           &len);
        if (!ret || (len < sizeof(pData[0]))) {
            fprintf(stderr, "Failed to query number of display devices.\n\n");
            return 1;
        }

        printf("  number of display devices: %d\n", pData[0]);

        for (i = 1; i <= pData[0]; i++) {

            printf("\n  Display Device: %d\n", pData[i]);

            print_display_name(dpy, pData[i],
                               NV_CTRL_STRING_DISPLAY_NAME_TYPE_BASENAME,
                               "Type Basename");
            print_display_name(dpy, pData[i],
                               NV_CTRL_STRING_DISPLAY_NAME_TYPE_ID,
                               "Type ID");
            print_display_name(dpy, pData[i],
                               NV_CTRL_STRING_DISPLAY_NAME_DP_GUID,
                               "DP GUID");
            print_display_name(dpy, pData[i],
                               NV_CTRL_STRING_DISPLAY_NAME_EDID_HASH,
                               "EDID HASH");
            print_display_name(dpy, pData[i],
                               NV_CTRL_STRING_DISPLAY_NAME_TARGET_INDEX,
                               "Target Index");
            print_display_name(dpy, pData[i],
                               NV_CTRL_STRING_DISPLAY_NAME_RANDR,
                               "RANDR");
        }
    }

    /*
     * print help information
     */

    else {
        
    printHelp:
        
        printf("\nnv-control-dpy [options]:\n\n");
        
        
        printf(" ModeLine options:\n\n");

        printf("  --print-modelines: print the modelines in the mode pool "
               "for each Display Device.\n\n");
        
        printf("  --print-current-modeline: print the current modeline "
               "for each Display Device.\n\n");

        printf("  --add-modeline [dpy id] [modeline]: "
               "add new modeline.\n\n");
        
        printf("  --delete-modeline [dpy id] [modename]: "
               "delete modeline with modename.\n\n");
        
        printf("  --generate-gtf-modeline [width] [height] [refreshrate]:"
               " use the GTF formula"
               " to generate a modeline for the specified parameters.\n\n");
        
        printf("  --generate-cvt-modeline [width] [height] [refreshrate]"
               " [reduced-blanking]: use the CVT formula"
               " to generate a modeline for the specified parameters.\n\n");
                

        printf(" MetaMode options:\n\n");

        printf("  --print-metamodes: print the current MetaModes for the "
               "X screen\n\n");

        printf("  --print-metamodes-version2: print the current MetaModes for "
               "the X screen with extended information\n\n");

        printf("  --add-metamode [metamode]: add the specified "
               "MetaMode to the X screen's list of MetaModes.\n\n");
        
        printf("  --delete-metamode [metamode]: delete the specified MetaMode "
               "from the X screen's list of MetaModes.\n\n");

        printf("  --print-current-metamode: print the current MetaMode.\n\n");

        printf("  --print-current-metamode-version2: print the current "
               "MetaMode with extended information.\n\n");


        printf(" Misc options:\n\n");
        
        printf("  --get-valid-freq-ranges: query the valid frequency "
               "information for each display device.\n\n");
        
        printf("  --build-modepool: build a modepool for any display device "
               "that does not already have one.\n\n");
                
        printf("  --get-assigned-dpys: query the assigned display device for "
               "this X screen\n\n");
        
        printf("  --query-gpus: print GPU information and relationship to "
               "X screens.\n\n");
        
        printf("  --probe-dpys: probe GPUs for new display devices\n\n");
        
        printf("  --query-nvidia-xinerama-info-order: query the "
               "nvidiaXineramaInfoOrder.\n\n");
        
        printf("  --assign-nvidia-xinerama-info-order [order]: assign the "
               "nvidiaXineramaInfoOrder.\n\n");

        printf("  --max-screen-size: query the maximum screen size "
               "on all GPUs in the system\n\n");

        printf("  --print-used-modelines: print the modeline for each display "
               "device for each MetaMode on the X screen.\n\n");

        printf("  --print-display-names: print all the names associated with "
               "each display device on the server\n\n");
    }

    return 0;

}
int main(void)
{
    Display *dpy;
    Bool ret;
    int event_base, error_base, major, minor, screens, i;
    char *str;
        
    /*
     * open a connection to the X server indicated by the DISPLAY
     * environment variable
     */
    
    dpy = XOpenDisplay(NULL);
    if (!dpy) {
        fprintf(stderr, "Cannot open display '%s'.\n", XDisplayName(NULL));
        return 1;
    }
    
    /*
     * check if the NV-CONTROL X extension is present on this X server
     */

    ret = XNVCTRLQueryExtension(dpy, &event_base, &error_base);
    if (ret != True) {
        fprintf(stderr, "The NV-CONTROL X extension does not exist on '%s'.\n",
                XDisplayName(NULL));
        return 1;
    }

    /*
     * query the major and minor extension version
     */

    ret = XNVCTRLQueryVersion(dpy, &major, &minor);
    if (ret != True) {
        fprintf(stderr, "The NV-CONTROL X extension does not exist on '%s'.\n",
                XDisplayName(NULL));
        return 1;
    }

    /*
     * print statistics thus far
     */

    printf("NV-CONTROL X extension present\n");
    printf("  version        : %d.%d\n", major, minor);
    printf("  event base     : %d\n", event_base);
    printf("  error base     : %d\n", error_base);
    
    /*
     * loop over each screen, and determine if each screen is
     * controlled by the NVIDIA X driver (and thus supports the
     * NV-CONTROL X extension); then, query the string attributes on
     * the screen.
     */

    screens = ScreenCount(dpy);
    for (i = 0; i < screens; i++) {
        if (XNVCTRLIsNvScreen(dpy, i)) {
            printf("Screen %d supports the NV-CONTROL X extension\n", i);

            ret = XNVCTRLQueryStringAttribute(dpy, i,
                                              0, /* XXX not curently used */
                                              NV_CTRL_STRING_PRODUCT_NAME,
                                              &str);
            if (ret) {
                printf("  GPU            : %s\n", str);
                XFree(str);
            }
            
            ret = XNVCTRLQueryStringAttribute(dpy, i,
                                              0, /* XXX not curently used */
                                              NV_CTRL_STRING_VBIOS_VERSION,
                                              &str);
            
            if (ret) {
                printf("  VideoBIOS      : %s\n", str);
                XFree(str);
            }

            ret = XNVCTRLQueryStringAttribute(dpy, i,
                                              0, /* XXX not curently used */
                                              NV_CTRL_STRING_NVIDIA_DRIVER_VERSION,
                                              &str);

            if (ret) {
                printf("  Driver version : %s\n", str);
                XFree(str);
            }
        }
    }

    /*
     * print attribute permission and type information.
     */

    printf("Attributes (Integers):\n");
    for (i = 0; i < NV_CTRL_LAST_ATTRIBUTE; i++) {
        const char *name = attr2str(i, attr_int_table);
        if (name) {
            NVCTRLAttributePermissionsRec perms;

            printf("  (%3d) [Perms: ", i);

            memset(&perms, 0, sizeof(NVCTRLAttributePermissionsRec));

            XNVCTRLQueryAttributePermissions(dpy, i, &perms);
            print_perms(&perms);
            printf("] [ ");
            printf("%-32s", GetAttrTypeName(perms.type));
            printf("] - %s\n", name);
        }
    }

    printf("Attributes (Strings):\n");
    for (i = 0; i < NV_CTRL_STRING_LAST_ATTRIBUTE; i++) {
        const char *name = attr2str(i, attr_str_table);
        if (name) {
            NVCTRLAttributePermissionsRec perms;

            printf("  (%3d) [Perms: ", i);

            memset(&perms, 0, sizeof(NVCTRLAttributePermissionsRec));

            XNVCTRLQueryStringAttributePermissions(dpy, i, &perms);
            print_perms(&perms);
            printf("] [ ");
            printf("%-32s", GetAttrTypeName(perms.type));
            printf("] - %s\n", name);
        }
    }

    printf("Attributes (Binary Data):\n");
    for (i = 0; i < NV_CTRL_BINARY_DATA_LAST_ATTRIBUTE; i++) {
        const char *name = attr2str(i, attr_bin_table);
        if (name) {
            NVCTRLAttributePermissionsRec perms;

            printf("  (%3d) [Perms: ", i);

            memset(&perms, 0, sizeof(NVCTRLAttributePermissionsRec));

            XNVCTRLQueryBinaryDataAttributePermissions(dpy, i, &perms);
            print_perms(&perms);
            printf("] [ ");
            printf("%-32s", GetAttrTypeName(perms.type));
            printf("] - %s\n", name);
        }
    }

    printf("Attributes (String Operations):\n");
    for (i = 0; i < NV_CTRL_STRING_OPERATION_LAST_ATTRIBUTE; i++) {
        const char *name = attr2str(i, attr_strop_table);
        if (name) {
            NVCTRLAttributePermissionsRec perms;

            printf("  (%3d) [Perms: ", i);

            memset(&perms, 0, sizeof(NVCTRLAttributePermissionsRec));

            XNVCTRLQueryStringOperationAttributePermissions(dpy, i, &perms);
            print_perms(&perms);
            printf("] [ ");
            printf("%-32s", GetAttrTypeName(perms.type));
            printf("] - %s\n", name);
        }
    }

    /*
     * close the display connection
     */

    XCloseDisplay(dpy);

    return 0;
}
Beispiel #11
0
int main(int argc, char *argv[])
{
    Display *dpy;
    Bool ret;
    int screen, display_devices, mask, major, minor;
    char *str;
    int nDisplayDevice;


    /*
* Open a display connection, and make sure the NV-CONTROL X
* extension is present on the screen we want to use.
*/

    dpy = XOpenDisplay(NULL);
    if (!dpy) {
        fprintf(stderr, "Cannot open display '%s'.\n\n", XDisplayName(NULL));
        return 1;
    }

    screen = GetNvXScreen(dpy);

    ret = XNVCTRLQueryVersion(dpy, &major, &minor);
    if (ret != True) {
        fprintf(stderr, "The NV-CONTROL X extension does not exist on '%s'.\n\n", XDisplayName(NULL));
        return 1;
    }

    /*
	* query the connected display devices on this X screen and print
	* basic information about each X screen
	*/

    ret = XNVCTRLQueryAttribute(dpy, screen, 0,
                                NV_CTRL_CONNECTED_DISPLAYS, &display_devices);

    if (!ret) {
        fprintf(stderr, "Failed to query the enabled Display Devices.\n\n");
        return 1;
    }

    int pci_bus;
    int pci_device;
    int pci_func;
    ret = XNVCTRLQueryTargetAttribute(dpy,
										NV_CTRL_TARGET_TYPE_GPU, 0 /* Just query first GPU */,
										0,
										NV_CTRL_PCI_BUS,
										&pci_bus);
	ret = XNVCTRLQueryTargetAttribute(dpy,
										NV_CTRL_TARGET_TYPE_GPU, 0 /* Just query first GPU */,
										0,
										NV_CTRL_PCI_DEVICE,
										&pci_device);
	ret = XNVCTRLQueryTargetAttribute(dpy,
										NV_CTRL_TARGET_TYPE_GPU, 0 /* Just query first GPU */,
										0,
										NV_CTRL_PCI_FUNCTION,
										&pci_func);
	dbset("system.hardware.nvidia.busid=%i:%i:%i", pci_bus, pci_device, pci_func);

    nDisplayDevice = 0;
    for (mask = 1; mask < (1 << 24); mask <<= 1) {
        if (display_devices & mask) {
            XNVCTRLQueryStringAttribute(dpy, screen, mask,
                                        NV_CTRL_STRING_DISPLAY_DEVICE_NAME,
                                        &str);

            dbset("system.x11.display.%i.device=%s" , nDisplayDevice, display_device_name(mask));
            dbset("system.x11.display.%i.mode.0=nvidia-auto-select", nDisplayDevice);
            dbset("system.x11.display.%i.default=nvidia-auto-select", nDisplayDevice);

            printf("%i:%s:0x%08x:%s\n", nDisplayDevice, display_device_name(mask), mask, str);

            nDisplayDevice++;
        }
    }

    if (nDisplayDevice > 1) { // more than one screen found
    	dbset("system.x11.dualhead.enabled=1");
    } else {
    	dbset("system.x11.dualhead.enabled=0");
    }

    char *dummy;
    for (; nDisplayDevice <= 3; nDisplayDevice++) {
    	if (asprintf(&dummy, "system.x11.display.%i", nDisplayDevice) >= 0) {
    		dbremove(dummy);
    		free(dummy);
    	}
    }

    return 0;
}
Beispiel #12
0
/*
================
Sys_GetVideoRam
returns in megabytes
open your own display connection for the query and close it
using the one shared with GLimp_Init is not stable
================
*/
int Sys_GetVideoRam( void ) {
#ifdef USE_SDL
	return 128;
#else
	static int run_once = 0;
	int major, minor, value;
	Display *l_dpy;
	int l_scrnum;

	if ( run_once ) {
		return run_once;
	}

	if ( sys_videoRam.GetInteger() ) {
		run_once = sys_videoRam.GetInteger();
		return sys_videoRam.GetInteger();
	}

	// try a few strategies to guess the amount of video ram
	common->Printf( "guessing video ram ( use +set sys_videoRam to force ) ..\n" );
	if ( !GLimp_OpenDisplay( ) ) {
		run_once = 64;
		return run_once;
	}

	l_dpy = dpy;
	l_scrnum = scrnum;
	// go for nvidia ext first
	if ( XNVCTRLQueryVersion( l_dpy, &major, &minor ) ) {
		common->Printf( "found XNVCtrl extension %d.%d\n", major, minor );
		if ( XNVCTRLIsNvScreen( l_dpy, l_scrnum ) ) {
			if ( XNVCTRLQueryAttribute( l_dpy, l_scrnum, 0, NV_CTRL_VIDEO_RAM, &value ) ) {
				run_once = value / 1024;
				return run_once;
			} else {
				common->Printf( "XNVCtrlQueryAttribute NV_CTRL_VIDEO_RAM failed\n" );
			}
		} else {
			common->Printf( "default screen %d is not controlled by NVIDIA driver\n", l_scrnum );
		}
	}
	// try ATI /proc read ( for the lack of a better option )
	int fd;
	if ( ( fd = open( "/proc/dri/0/umm", O_RDONLY ) ) != -1 ) {
		int len;
		char umm_buf[ 1024 ];
		char *line;
		if ( ( len = read( fd, umm_buf, 1024 ) ) != -1 ) {
			// should be way enough to get the full file
			// grab "free  LFB = " line and "free  Inv = " lines
			umm_buf[ len-1 ] = '\0';
			line = umm_buf;
			line = strtok( umm_buf, "\n" );
			int total = 0;
			while ( line ) {
				if ( strlen( line ) >= 13 && strstr( line, "max   LFB =" ) == line ) {
					total += atoi( line + 12 );
				} else if ( strlen( line ) >= 13 && strstr( line, "max   Inv =" ) == line ) {
					total += atoi( line + 12 );
				}
				line = strtok( NULL, "\n" );
			}
			if ( total ) {
				run_once = total / 1048576;
				// round to the lower 16Mb
				run_once &= ~15;
				return run_once;
			}
		} else {
			common->Printf( "read /proc/dri/0/umm failed: %s\n", strerror( errno ) );
		}
	}
	common->Printf( "guess failed, return default low-end VRAM setting ( 64MB VRAM )\n" );
	run_once = 64;
	return run_once;
#endif
}