xref: /openbsd/sys/dev/pci/drm/drm_modes.c (revision 91f110e0)
1 /*	$OpenBSD: drm_modes.c,v 1.3 2013/09/02 06:25:28 jsg Exp $	*/
2 /*
3  * Copyright © 1997-2003 by The XFree86 Project, Inc.
4  * Copyright © 2007 Dave Airlie
5  * Copyright © 2007-2008 Intel Corporation
6  *   Jesse Barnes <jesse.barnes@intel.com>
7  * Copyright 2005-2006 Luc Verhaegen
8  * Copyright (c) 2001, Andy Ritger  aritger@nvidia.com
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a
11  * copy of this software and associated documentation files (the "Software"),
12  * to deal in the Software without restriction, including without limitation
13  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
14  * and/or sell copies of the Software, and to permit persons to whom the
15  * Software is furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included in
18  * all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
23  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
24  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
25  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
26  * OTHER DEALINGS IN THE SOFTWARE.
27  *
28  * Except as contained in this notice, the name of the copyright holder(s)
29  * and author(s) shall not be used in advertising or otherwise to promote
30  * the sale, use or other dealings in this Software without prior written
31  * authorization from the copyright holder(s) and author(s).
32  */
33 
34 #include "drmP.h"
35 #include "drm_crtc.h"
36 
37 #define KHZ2PICOS(a) (1000000000UL/(a))
38 
39 void	 drm_mode_validate_clocks(struct drm_device *, struct list_head *,
40 	     int *, int *, int);
41 long	 simple_strtol(const char *, char **, int);
42 
43 /**
44  * drm_mode_debug_printmodeline - debug print a mode
45  * @dev: DRM device
46  * @mode: mode to print
47  *
48  * LOCKING:
49  * None.
50  *
51  * Describe @mode using DRM_DEBUG.
52  */
53 void drm_mode_debug_printmodeline(const struct drm_display_mode *mode)
54 {
55 	DRM_DEBUG_KMS("Modeline %d:\"%s\" %d %d %d %d %d %d %d %d %d %d "
56 			"0x%x 0x%x\n",
57 		mode->base.id, mode->name, mode->vrefresh, mode->clock,
58 		mode->hdisplay, mode->hsync_start,
59 		mode->hsync_end, mode->htotal,
60 		mode->vdisplay, mode->vsync_start,
61 		mode->vsync_end, mode->vtotal, mode->type, mode->flags);
62 }
63 EXPORT_SYMBOL(drm_mode_debug_printmodeline);
64 
65 /**
66  * drm_cvt_mode -create a modeline based on CVT algorithm
67  * @dev: DRM device
68  * @hdisplay: hdisplay size
69  * @vdisplay: vdisplay size
70  * @vrefresh  : vrefresh rate
71  * @reduced : Whether the GTF calculation is simplified
72  * @interlaced:Whether the interlace is supported
73  *
74  * LOCKING:
75  * none.
76  *
77  * return the modeline based on CVT algorithm
78  *
79  * This function is called to generate the modeline based on CVT algorithm
80  * according to the hdisplay, vdisplay, vrefresh.
81  * It is based from the VESA(TM) Coordinated Video Timing Generator by
82  * Graham Loveridge April 9, 2003 available at
83  * http://www.elo.utfsm.cl/~elo212/docs/CVTd6r1.xls
84  *
85  * And it is copied from xf86CVTmode in xserver/hw/xfree86/modes/xf86cvt.c.
86  * What I have done is to translate it by using integer calculation.
87  */
88 #define HV_FACTOR			1000
89 struct drm_display_mode *drm_cvt_mode(struct drm_device *dev, int hdisplay,
90 				      int vdisplay, int vrefresh,
91 				      bool reduced, bool interlaced, bool margins)
92 {
93 	/* 1) top/bottom margin size (% of height) - default: 1.8, */
94 #define	CVT_MARGIN_PERCENTAGE		18
95 	/* 2) character cell horizontal granularity (pixels) - default 8 */
96 #define	CVT_H_GRANULARITY		8
97 	/* 3) Minimum vertical porch (lines) - default 3 */
98 #define	CVT_MIN_V_PORCH			3
99 	/* 4) Minimum number of vertical back porch lines - default 6 */
100 #define	CVT_MIN_V_BPORCH		6
101 	/* Pixel Clock step (kHz) */
102 #define CVT_CLOCK_STEP			250
103 	struct drm_display_mode *drm_mode;
104 	unsigned int vfieldrate, hperiod;
105 	int hdisplay_rnd, hmargin, vdisplay_rnd, vmargin, vsync;
106 	int interlace;
107 
108 	/* allocate the drm_display_mode structure. If failure, we will
109 	 * return directly
110 	 */
111 	drm_mode = drm_mode_create(dev);
112 	if (!drm_mode)
113 		return NULL;
114 
115 	/* the CVT default refresh rate is 60Hz */
116 	if (!vrefresh)
117 		vrefresh = 60;
118 
119 	/* the required field fresh rate */
120 	if (interlaced)
121 		vfieldrate = vrefresh * 2;
122 	else
123 		vfieldrate = vrefresh;
124 
125 	/* horizontal pixels */
126 	hdisplay_rnd = hdisplay - (hdisplay % CVT_H_GRANULARITY);
127 
128 	/* determine the left&right borders */
129 	hmargin = 0;
130 	if (margins) {
131 		hmargin = hdisplay_rnd * CVT_MARGIN_PERCENTAGE / 1000;
132 		hmargin -= hmargin % CVT_H_GRANULARITY;
133 	}
134 	/* find the total active pixels */
135 	drm_mode->hdisplay = hdisplay_rnd + 2 * hmargin;
136 
137 	/* find the number of lines per field */
138 	if (interlaced)
139 		vdisplay_rnd = vdisplay / 2;
140 	else
141 		vdisplay_rnd = vdisplay;
142 
143 	/* find the top & bottom borders */
144 	vmargin = 0;
145 	if (margins)
146 		vmargin = vdisplay_rnd * CVT_MARGIN_PERCENTAGE / 1000;
147 
148 	drm_mode->vdisplay = vdisplay + 2 * vmargin;
149 
150 	/* Interlaced */
151 	if (interlaced)
152 		interlace = 1;
153 	else
154 		interlace = 0;
155 
156 	/* Determine VSync Width from aspect ratio */
157 	if (!(vdisplay % 3) && ((vdisplay * 4 / 3) == hdisplay))
158 		vsync = 4;
159 	else if (!(vdisplay % 9) && ((vdisplay * 16 / 9) == hdisplay))
160 		vsync = 5;
161 	else if (!(vdisplay % 10) && ((vdisplay * 16 / 10) == hdisplay))
162 		vsync = 6;
163 	else if (!(vdisplay % 4) && ((vdisplay * 5 / 4) == hdisplay))
164 		vsync = 7;
165 	else if (!(vdisplay % 9) && ((vdisplay * 15 / 9) == hdisplay))
166 		vsync = 7;
167 	else /* custom */
168 		vsync = 10;
169 
170 	if (!reduced) {
171 		/* simplify the GTF calculation */
172 		/* 4) Minimum time of vertical sync + back porch interval (µs)
173 		 * default 550.0
174 		 */
175 		int tmp1, tmp2;
176 #define CVT_MIN_VSYNC_BP	550
177 		/* 3) Nominal HSync width (% of line period) - default 8 */
178 #define CVT_HSYNC_PERCENTAGE	8
179 		unsigned int hblank_percentage;
180 		int vsyncandback_porch, vback_porch, hblank;
181 
182 		/* estimated the horizontal period */
183 		tmp1 = HV_FACTOR * 1000000  -
184 				CVT_MIN_VSYNC_BP * HV_FACTOR * vfieldrate;
185 		tmp2 = (vdisplay_rnd + 2 * vmargin + CVT_MIN_V_PORCH) * 2 +
186 				interlace;
187 		hperiod = tmp1 * 2 / (tmp2 * vfieldrate);
188 
189 		tmp1 = CVT_MIN_VSYNC_BP * HV_FACTOR / hperiod + 1;
190 		/* 9. Find number of lines in sync + backporch */
191 		if (tmp1 < (vsync + CVT_MIN_V_PORCH))
192 			vsyncandback_porch = vsync + CVT_MIN_V_PORCH;
193 		else
194 			vsyncandback_porch = tmp1;
195 		/* 10. Find number of lines in back porch */
196 		vback_porch = vsyncandback_porch - vsync;
197 		drm_mode->vtotal = vdisplay_rnd + 2 * vmargin +
198 				vsyncandback_porch + CVT_MIN_V_PORCH;
199 		/* 5) Definition of Horizontal blanking time limitation */
200 		/* Gradient (%/kHz) - default 600 */
201 #define CVT_M_FACTOR	600
202 		/* Offset (%) - default 40 */
203 #define CVT_C_FACTOR	40
204 		/* Blanking time scaling factor - default 128 */
205 #define CVT_K_FACTOR	128
206 		/* Scaling factor weighting - default 20 */
207 #define CVT_J_FACTOR	20
208 #define CVT_M_PRIME	(CVT_M_FACTOR * CVT_K_FACTOR / 256)
209 #define CVT_C_PRIME	((CVT_C_FACTOR - CVT_J_FACTOR) * CVT_K_FACTOR / 256 + \
210 			 CVT_J_FACTOR)
211 		/* 12. Find ideal blanking duty cycle from formula */
212 		hblank_percentage = CVT_C_PRIME * HV_FACTOR - CVT_M_PRIME *
213 					hperiod / 1000;
214 		/* 13. Blanking time */
215 		if (hblank_percentage < 20 * HV_FACTOR)
216 			hblank_percentage = 20 * HV_FACTOR;
217 		hblank = drm_mode->hdisplay * hblank_percentage /
218 			 (100 * HV_FACTOR - hblank_percentage);
219 		hblank -= hblank % (2 * CVT_H_GRANULARITY);
220 		/* 14. find the total pixes per line */
221 		drm_mode->htotal = drm_mode->hdisplay + hblank;
222 		drm_mode->hsync_end = drm_mode->hdisplay + hblank / 2;
223 		drm_mode->hsync_start = drm_mode->hsync_end -
224 			(drm_mode->htotal * CVT_HSYNC_PERCENTAGE) / 100;
225 		drm_mode->hsync_start += CVT_H_GRANULARITY -
226 			drm_mode->hsync_start % CVT_H_GRANULARITY;
227 		/* fill the Vsync values */
228 		drm_mode->vsync_start = drm_mode->vdisplay + CVT_MIN_V_PORCH;
229 		drm_mode->vsync_end = drm_mode->vsync_start + vsync;
230 	} else {
231 		/* Reduced blanking */
232 		/* Minimum vertical blanking interval time (µs)- default 460 */
233 #define CVT_RB_MIN_VBLANK	460
234 		/* Fixed number of clocks for horizontal sync */
235 #define CVT_RB_H_SYNC		32
236 		/* Fixed number of clocks for horizontal blanking */
237 #define CVT_RB_H_BLANK		160
238 		/* Fixed number of lines for vertical front porch - default 3*/
239 #define CVT_RB_VFPORCH		3
240 		int vbilines;
241 		int tmp1, tmp2;
242 		/* 8. Estimate Horizontal period. */
243 		tmp1 = HV_FACTOR * 1000000 -
244 			CVT_RB_MIN_VBLANK * HV_FACTOR * vfieldrate;
245 		tmp2 = vdisplay_rnd + 2 * vmargin;
246 		hperiod = tmp1 / (tmp2 * vfieldrate);
247 		/* 9. Find number of lines in vertical blanking */
248 		vbilines = CVT_RB_MIN_VBLANK * HV_FACTOR / hperiod + 1;
249 		/* 10. Check if vertical blanking is sufficient */
250 		if (vbilines < (CVT_RB_VFPORCH + vsync + CVT_MIN_V_BPORCH))
251 			vbilines = CVT_RB_VFPORCH + vsync + CVT_MIN_V_BPORCH;
252 		/* 11. Find total number of lines in vertical field */
253 		drm_mode->vtotal = vdisplay_rnd + 2 * vmargin + vbilines;
254 		/* 12. Find total number of pixels in a line */
255 		drm_mode->htotal = drm_mode->hdisplay + CVT_RB_H_BLANK;
256 		/* Fill in HSync values */
257 		drm_mode->hsync_end = drm_mode->hdisplay + CVT_RB_H_BLANK / 2;
258 		drm_mode->hsync_start = drm_mode->hsync_end - CVT_RB_H_SYNC;
259 		/* Fill in VSync values */
260 		drm_mode->vsync_start = drm_mode->vdisplay + CVT_RB_VFPORCH;
261 		drm_mode->vsync_end = drm_mode->vsync_start + vsync;
262 	}
263 	/* 15/13. Find pixel clock frequency (kHz for xf86) */
264 	drm_mode->clock = drm_mode->htotal * HV_FACTOR * 1000 / hperiod;
265 	drm_mode->clock -= drm_mode->clock % CVT_CLOCK_STEP;
266 	/* 18/16. Find actual vertical frame frequency */
267 	/* ignore - just set the mode flag for interlaced */
268 	if (interlaced) {
269 		drm_mode->vtotal *= 2;
270 		drm_mode->flags |= DRM_MODE_FLAG_INTERLACE;
271 	}
272 	/* Fill the mode line name */
273 	drm_mode_set_name(drm_mode);
274 	if (reduced)
275 		drm_mode->flags |= (DRM_MODE_FLAG_PHSYNC |
276 					DRM_MODE_FLAG_NVSYNC);
277 	else
278 		drm_mode->flags |= (DRM_MODE_FLAG_PVSYNC |
279 					DRM_MODE_FLAG_NHSYNC);
280 
281 	return drm_mode;
282 }
283 EXPORT_SYMBOL(drm_cvt_mode);
284 
285 /**
286  * drm_gtf_mode_complex - create the modeline based on full GTF algorithm
287  *
288  * @dev		:drm device
289  * @hdisplay	:hdisplay size
290  * @vdisplay	:vdisplay size
291  * @vrefresh	:vrefresh rate.
292  * @interlaced	:whether the interlace is supported
293  * @margins	:desired margin size
294  * @GTF_[MCKJ]  :extended GTF formula parameters
295  *
296  * LOCKING.
297  * none.
298  *
299  * return the modeline based on full GTF algorithm.
300  *
301  * GTF feature blocks specify C and J in multiples of 0.5, so we pass them
302  * in here multiplied by two.  For a C of 40, pass in 80.
303  */
304 struct drm_display_mode *
305 drm_gtf_mode_complex(struct drm_device *dev, int hdisplay, int vdisplay,
306 		     int vrefresh, bool interlaced, int margins,
307 		     int GTF_M, int GTF_2C, int GTF_K, int GTF_2J)
308 {	/* 1) top/bottom margin size (% of height) - default: 1.8, */
309 #define	GTF_MARGIN_PERCENTAGE		18
310 	/* 2) character cell horizontal granularity (pixels) - default 8 */
311 #define	GTF_CELL_GRAN			8
312 	/* 3) Minimum vertical porch (lines) - default 3 */
313 #define	GTF_MIN_V_PORCH			1
314 	/* width of vsync in lines */
315 #define V_SYNC_RQD			3
316 	/* width of hsync as % of total line */
317 #define H_SYNC_PERCENT			8
318 	/* min time of vsync + back porch (microsec) */
319 #define MIN_VSYNC_PLUS_BP		550
320 	/* C' and M' are part of the Blanking Duty Cycle computation */
321 #define GTF_C_PRIME	((((GTF_2C - GTF_2J) * GTF_K / 256) + GTF_2J) / 2)
322 #define GTF_M_PRIME	(GTF_K * GTF_M / 256)
323 	struct drm_display_mode *drm_mode;
324 	unsigned int hdisplay_rnd, vdisplay_rnd, vfieldrate_rqd;
325 	int top_margin, bottom_margin;
326 	int interlace;
327 	unsigned int hfreq_est;
328 	int vsync_plus_bp, vback_porch;
329 	unsigned int vtotal_lines, vfieldrate_est, hperiod;
330 	unsigned int vfield_rate, vframe_rate;
331 	int left_margin, right_margin;
332 	unsigned int total_active_pixels, ideal_duty_cycle;
333 	unsigned int hblank, total_pixels, pixel_freq;
334 	int hsync, hfront_porch, vodd_front_porch_lines;
335 	unsigned int tmp1, tmp2;
336 
337 	drm_mode = drm_mode_create(dev);
338 	if (!drm_mode)
339 		return NULL;
340 
341 	/* 1. In order to give correct results, the number of horizontal
342 	 * pixels requested is first processed to ensure that it is divisible
343 	 * by the character size, by rounding it to the nearest character
344 	 * cell boundary:
345 	 */
346 	hdisplay_rnd = (hdisplay + GTF_CELL_GRAN / 2) / GTF_CELL_GRAN;
347 	hdisplay_rnd = hdisplay_rnd * GTF_CELL_GRAN;
348 
349 	/* 2. If interlace is requested, the number of vertical lines assumed
350 	 * by the calculation must be halved, as the computation calculates
351 	 * the number of vertical lines per field.
352 	 */
353 	if (interlaced)
354 		vdisplay_rnd = vdisplay / 2;
355 	else
356 		vdisplay_rnd = vdisplay;
357 
358 	/* 3. Find the frame rate required: */
359 	if (interlaced)
360 		vfieldrate_rqd = vrefresh * 2;
361 	else
362 		vfieldrate_rqd = vrefresh;
363 
364 	/* 4. Find number of lines in Top margin: */
365 	top_margin = 0;
366 	if (margins)
367 		top_margin = (vdisplay_rnd * GTF_MARGIN_PERCENTAGE + 500) /
368 				1000;
369 	/* 5. Find number of lines in bottom margin: */
370 	bottom_margin = top_margin;
371 
372 	/* 6. If interlace is required, then set variable interlace: */
373 	if (interlaced)
374 		interlace = 1;
375 	else
376 		interlace = 0;
377 
378 	/* 7. Estimate the Horizontal frequency */
379 	{
380 		tmp1 = (1000000  - MIN_VSYNC_PLUS_BP * vfieldrate_rqd) / 500;
381 		tmp2 = (vdisplay_rnd + 2 * top_margin + GTF_MIN_V_PORCH) *
382 				2 + interlace;
383 		hfreq_est = (tmp2 * 1000 * vfieldrate_rqd) / tmp1;
384 	}
385 
386 	/* 8. Find the number of lines in V sync + back porch */
387 	/* [V SYNC+BP] = RINT(([MIN VSYNC+BP] * hfreq_est / 1000000)) */
388 	vsync_plus_bp = MIN_VSYNC_PLUS_BP * hfreq_est / 1000;
389 	vsync_plus_bp = (vsync_plus_bp + 500) / 1000;
390 	/*  9. Find the number of lines in V back porch alone: */
391 	vback_porch = vsync_plus_bp - V_SYNC_RQD;
392 	/*  10. Find the total number of lines in Vertical field period: */
393 	vtotal_lines = vdisplay_rnd + top_margin + bottom_margin +
394 			vsync_plus_bp + GTF_MIN_V_PORCH;
395 	/*  11. Estimate the Vertical field frequency: */
396 	vfieldrate_est = hfreq_est / vtotal_lines;
397 	/*  12. Find the actual horizontal period: */
398 	hperiod = 1000000 / (vfieldrate_rqd * vtotal_lines);
399 
400 	/*  13. Find the actual Vertical field frequency: */
401 	vfield_rate = hfreq_est / vtotal_lines;
402 	/*  14. Find the Vertical frame frequency: */
403 	if (interlaced)
404 		vframe_rate = vfield_rate / 2;
405 	else
406 		vframe_rate = vfield_rate;
407 	/*  15. Find number of pixels in left margin: */
408 	if (margins)
409 		left_margin = (hdisplay_rnd * GTF_MARGIN_PERCENTAGE + 500) /
410 				1000;
411 	else
412 		left_margin = 0;
413 
414 	/* 16.Find number of pixels in right margin: */
415 	right_margin = left_margin;
416 	/* 17.Find total number of active pixels in image and left and right */
417 	total_active_pixels = hdisplay_rnd + left_margin + right_margin;
418 	/* 18.Find the ideal blanking duty cycle from blanking duty cycle */
419 	ideal_duty_cycle = GTF_C_PRIME * 1000 -
420 				(GTF_M_PRIME * 1000000 / hfreq_est);
421 	/* 19.Find the number of pixels in the blanking time to the nearest
422 	 * double character cell: */
423 	hblank = total_active_pixels * ideal_duty_cycle /
424 			(100000 - ideal_duty_cycle);
425 	hblank = (hblank + GTF_CELL_GRAN) / (2 * GTF_CELL_GRAN);
426 	hblank = hblank * 2 * GTF_CELL_GRAN;
427 	/* 20.Find total number of pixels: */
428 	total_pixels = total_active_pixels + hblank;
429 	/* 21.Find pixel clock frequency: */
430 	pixel_freq = total_pixels * hfreq_est / 1000;
431 	/* Stage 1 computations are now complete; I should really pass
432 	 * the results to another function and do the Stage 2 computations,
433 	 * but I only need a few more values so I'll just append the
434 	 * computations here for now */
435 	/* 17. Find the number of pixels in the horizontal sync period: */
436 	hsync = H_SYNC_PERCENT * total_pixels / 100;
437 	hsync = (hsync + GTF_CELL_GRAN / 2) / GTF_CELL_GRAN;
438 	hsync = hsync * GTF_CELL_GRAN;
439 	/* 18. Find the number of pixels in horizontal front porch period */
440 	hfront_porch = hblank / 2 - hsync;
441 	/*  36. Find the number of lines in the odd front porch period: */
442 	vodd_front_porch_lines = GTF_MIN_V_PORCH ;
443 
444 	/* finally, pack the results in the mode struct */
445 	drm_mode->hdisplay = hdisplay_rnd;
446 	drm_mode->hsync_start = hdisplay_rnd + hfront_porch;
447 	drm_mode->hsync_end = drm_mode->hsync_start + hsync;
448 	drm_mode->htotal = total_pixels;
449 	drm_mode->vdisplay = vdisplay_rnd;
450 	drm_mode->vsync_start = vdisplay_rnd + vodd_front_porch_lines;
451 	drm_mode->vsync_end = drm_mode->vsync_start + V_SYNC_RQD;
452 	drm_mode->vtotal = vtotal_lines;
453 
454 	drm_mode->clock = pixel_freq;
455 
456 	if (interlaced) {
457 		drm_mode->vtotal *= 2;
458 		drm_mode->flags |= DRM_MODE_FLAG_INTERLACE;
459 	}
460 
461 	drm_mode_set_name(drm_mode);
462 	if (GTF_M == 600 && GTF_2C == 80 && GTF_K == 128 && GTF_2J == 40)
463 		drm_mode->flags = DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC;
464 	else
465 		drm_mode->flags = DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC;
466 
467 	return drm_mode;
468 }
469 EXPORT_SYMBOL(drm_gtf_mode_complex);
470 
471 /**
472  * drm_gtf_mode - create the modeline based on GTF algorithm
473  *
474  * @dev		:drm device
475  * @hdisplay	:hdisplay size
476  * @vdisplay	:vdisplay size
477  * @vrefresh	:vrefresh rate.
478  * @interlaced	:whether the interlace is supported
479  * @margins	:whether the margin is supported
480  *
481  * LOCKING.
482  * none.
483  *
484  * return the modeline based on GTF algorithm
485  *
486  * This function is to create the modeline based on the GTF algorithm.
487  * Generalized Timing Formula is derived from:
488  *	GTF Spreadsheet by Andy Morrish (1/5/97)
489  *	available at http://www.vesa.org
490  *
491  * And it is copied from the file of xserver/hw/xfree86/modes/xf86gtf.c.
492  * What I have done is to translate it by using integer calculation.
493  * I also refer to the function of fb_get_mode in the file of
494  * drivers/video/fbmon.c
495  *
496  * Standard GTF parameters:
497  * M = 600
498  * C = 40
499  * K = 128
500  * J = 20
501  */
502 struct drm_display_mode *
503 drm_gtf_mode(struct drm_device *dev, int hdisplay, int vdisplay, int vrefresh,
504 	     bool lace, int margins)
505 {
506 	return drm_gtf_mode_complex(dev, hdisplay, vdisplay, vrefresh, lace,
507 				    margins, 600, 40 * 2, 128, 20 * 2);
508 }
509 EXPORT_SYMBOL(drm_gtf_mode);
510 
511 /**
512  * drm_mode_set_name - set the name on a mode
513  * @mode: name will be set in this mode
514  *
515  * LOCKING:
516  * None.
517  *
518  * Set the name of @mode to a standard format.
519  */
520 void drm_mode_set_name(struct drm_display_mode *mode)
521 {
522 	bool interlaced = !!(mode->flags & DRM_MODE_FLAG_INTERLACE);
523 
524 	snprintf(mode->name, DRM_DISPLAY_MODE_LEN, "%dx%d%s",
525 		 mode->hdisplay, mode->vdisplay,
526 		 interlaced ? "i" : "");
527 }
528 EXPORT_SYMBOL(drm_mode_set_name);
529 
530 /**
531  * drm_mode_list_concat - move modes from one list to another
532  * @head: source list
533  * @new: dst list
534  *
535  * LOCKING:
536  * Caller must ensure both lists are locked.
537  *
538  * Move all the modes from @head to @new.
539  */
540 void drm_mode_list_concat(struct list_head *head, struct list_head *new)
541 {
542 
543 	struct list_head *entry, *tmp;
544 
545 	list_for_each_safe(entry, tmp, head) {
546 		list_move_tail(entry, new);
547 	}
548 }
549 EXPORT_SYMBOL(drm_mode_list_concat);
550 
551 /**
552  * drm_mode_width - get the width of a mode
553  * @mode: mode
554  *
555  * LOCKING:
556  * None.
557  *
558  * Return @mode's width (hdisplay) value.
559  *
560  * FIXME: is this needed?
561  *
562  * RETURNS:
563  * @mode->hdisplay
564  */
565 int drm_mode_width(const struct drm_display_mode *mode)
566 {
567 	return mode->hdisplay;
568 
569 }
570 EXPORT_SYMBOL(drm_mode_width);
571 
572 /**
573  * drm_mode_height - get the height of a mode
574  * @mode: mode
575  *
576  * LOCKING:
577  * None.
578  *
579  * Return @mode's height (vdisplay) value.
580  *
581  * FIXME: is this needed?
582  *
583  * RETURNS:
584  * @mode->vdisplay
585  */
586 int drm_mode_height(const struct drm_display_mode *mode)
587 {
588 	return mode->vdisplay;
589 }
590 EXPORT_SYMBOL(drm_mode_height);
591 
592 /** drm_mode_hsync - get the hsync of a mode
593  * @mode: mode
594  *
595  * LOCKING:
596  * None.
597  *
598  * Return @modes's hsync rate in kHz, rounded to the nearest int.
599  */
600 int drm_mode_hsync(const struct drm_display_mode *mode)
601 {
602 	unsigned int calc_val;
603 
604 	if (mode->hsync)
605 		return mode->hsync;
606 
607 	if (mode->htotal < 0)
608 		return 0;
609 
610 	calc_val = (mode->clock * 1000) / mode->htotal; /* hsync in Hz */
611 	calc_val += 500;				/* round to 1000Hz */
612 	calc_val /= 1000;				/* truncate to kHz */
613 
614 	return calc_val;
615 }
616 EXPORT_SYMBOL(drm_mode_hsync);
617 
618 /**
619  * drm_mode_vrefresh - get the vrefresh of a mode
620  * @mode: mode
621  *
622  * LOCKING:
623  * None.
624  *
625  * Return @mode's vrefresh rate in Hz or calculate it if necessary.
626  *
627  * FIXME: why is this needed?  shouldn't vrefresh be set already?
628  *
629  * RETURNS:
630  * Vertical refresh rate. It will be the result of actual value plus 0.5.
631  * If it is 70.288, it will return 70Hz.
632  * If it is 59.6, it will return 60Hz.
633  */
634 int drm_mode_vrefresh(const struct drm_display_mode *mode)
635 {
636 	int refresh = 0;
637 	unsigned int calc_val;
638 
639 	if (mode->vrefresh > 0)
640 		refresh = mode->vrefresh;
641 	else if (mode->htotal > 0 && mode->vtotal > 0) {
642 		int vtotal;
643 		vtotal = mode->vtotal;
644 		/* work out vrefresh the value will be x1000 */
645 		calc_val = (mode->clock * 1000);
646 		calc_val /= mode->htotal;
647 		refresh = (calc_val + vtotal / 2) / vtotal;
648 
649 		if (mode->flags & DRM_MODE_FLAG_INTERLACE)
650 			refresh *= 2;
651 		if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
652 			refresh /= 2;
653 		if (mode->vscan > 1)
654 			refresh /= mode->vscan;
655 	}
656 	return refresh;
657 }
658 EXPORT_SYMBOL(drm_mode_vrefresh);
659 
660 /**
661  * drm_mode_set_crtcinfo - set CRTC modesetting parameters
662  * @p: mode
663  * @adjust_flags: unused? (FIXME)
664  *
665  * LOCKING:
666  * None.
667  *
668  * Setup the CRTC modesetting parameters for @p, adjusting if necessary.
669  */
670 void drm_mode_set_crtcinfo(struct drm_display_mode *p, int adjust_flags)
671 {
672 	if ((p == NULL) || ((p->type & DRM_MODE_TYPE_CRTC_C) == DRM_MODE_TYPE_BUILTIN))
673 		return;
674 
675 	p->crtc_hdisplay = p->hdisplay;
676 	p->crtc_hsync_start = p->hsync_start;
677 	p->crtc_hsync_end = p->hsync_end;
678 	p->crtc_htotal = p->htotal;
679 	p->crtc_hskew = p->hskew;
680 	p->crtc_vdisplay = p->vdisplay;
681 	p->crtc_vsync_start = p->vsync_start;
682 	p->crtc_vsync_end = p->vsync_end;
683 	p->crtc_vtotal = p->vtotal;
684 
685 	if (p->flags & DRM_MODE_FLAG_INTERLACE) {
686 		if (adjust_flags & CRTC_INTERLACE_HALVE_V) {
687 			p->crtc_vdisplay /= 2;
688 			p->crtc_vsync_start /= 2;
689 			p->crtc_vsync_end /= 2;
690 			p->crtc_vtotal /= 2;
691 		}
692 	}
693 
694 	if (p->flags & DRM_MODE_FLAG_DBLSCAN) {
695 		p->crtc_vdisplay *= 2;
696 		p->crtc_vsync_start *= 2;
697 		p->crtc_vsync_end *= 2;
698 		p->crtc_vtotal *= 2;
699 	}
700 
701 	if (p->vscan > 1) {
702 		p->crtc_vdisplay *= p->vscan;
703 		p->crtc_vsync_start *= p->vscan;
704 		p->crtc_vsync_end *= p->vscan;
705 		p->crtc_vtotal *= p->vscan;
706 	}
707 
708 	p->crtc_vblank_start = min(p->crtc_vsync_start, p->crtc_vdisplay);
709 	p->crtc_vblank_end = max(p->crtc_vsync_end, p->crtc_vtotal);
710 	p->crtc_hblank_start = min(p->crtc_hsync_start, p->crtc_hdisplay);
711 	p->crtc_hblank_end = max(p->crtc_hsync_end, p->crtc_htotal);
712 }
713 EXPORT_SYMBOL(drm_mode_set_crtcinfo);
714 
715 
716 /**
717  * drm_mode_copy - copy the mode
718  * @dst: mode to overwrite
719  * @src: mode to copy
720  *
721  * LOCKING:
722  * None.
723  *
724  * Copy an existing mode into another mode, preserving the object id
725  * of the destination mode.
726  */
727 void drm_mode_copy(struct drm_display_mode *dst, const struct drm_display_mode *src)
728 {
729 	int id = dst->base.id;
730 
731 	*dst = *src;
732 	dst->base.id = id;
733 	INIT_LIST_HEAD(&dst->head);
734 }
735 EXPORT_SYMBOL(drm_mode_copy);
736 
737 /**
738  * drm_mode_duplicate - allocate and duplicate an existing mode
739  * @m: mode to duplicate
740  *
741  * LOCKING:
742  * None.
743  *
744  * Just allocate a new mode, copy the existing mode into it, and return
745  * a pointer to it.  Used to create new instances of established modes.
746  */
747 struct drm_display_mode *drm_mode_duplicate(struct drm_device *dev,
748 					    const struct drm_display_mode *mode)
749 {
750 	struct drm_display_mode *nmode;
751 
752 	nmode = drm_mode_create(dev);
753 	if (!nmode)
754 		return NULL;
755 
756 	drm_mode_copy(nmode, mode);
757 
758 	return nmode;
759 }
760 EXPORT_SYMBOL(drm_mode_duplicate);
761 
762 /**
763  * drm_mode_equal - test modes for equality
764  * @mode1: first mode
765  * @mode2: second mode
766  *
767  * LOCKING:
768  * None.
769  *
770  * Check to see if @mode1 and @mode2 are equivalent.
771  *
772  * RETURNS:
773  * True if the modes are equal, false otherwise.
774  */
775 bool drm_mode_equal(const struct drm_display_mode *mode1, const struct drm_display_mode *mode2)
776 {
777 	/* do clock check convert to PICOS so fb modes get matched
778 	 * the same */
779 	if (mode1->clock && mode2->clock) {
780 		if (KHZ2PICOS(mode1->clock) != KHZ2PICOS(mode2->clock))
781 			return false;
782 	} else if (mode1->clock != mode2->clock)
783 		return false;
784 
785 	if (mode1->hdisplay == mode2->hdisplay &&
786 	    mode1->hsync_start == mode2->hsync_start &&
787 	    mode1->hsync_end == mode2->hsync_end &&
788 	    mode1->htotal == mode2->htotal &&
789 	    mode1->hskew == mode2->hskew &&
790 	    mode1->vdisplay == mode2->vdisplay &&
791 	    mode1->vsync_start == mode2->vsync_start &&
792 	    mode1->vsync_end == mode2->vsync_end &&
793 	    mode1->vtotal == mode2->vtotal &&
794 	    mode1->vscan == mode2->vscan &&
795 	    mode1->flags == mode2->flags)
796 		return true;
797 
798 	return false;
799 }
800 EXPORT_SYMBOL(drm_mode_equal);
801 
802 /**
803  * drm_mode_validate_size - make sure modes adhere to size constraints
804  * @dev: DRM device
805  * @mode_list: list of modes to check
806  * @maxX: maximum width
807  * @maxY: maximum height
808  * @maxPitch: max pitch
809  *
810  * LOCKING:
811  * Caller must hold a lock protecting @mode_list.
812  *
813  * The DRM device (@dev) has size and pitch limits.  Here we validate the
814  * modes we probed for @dev against those limits and set their status as
815  * necessary.
816  */
817 void drm_mode_validate_size(struct drm_device *dev,
818 			    struct list_head *mode_list,
819 			    int maxX, int maxY, int maxPitch)
820 {
821 	struct drm_display_mode *mode;
822 
823 	list_for_each_entry(mode, mode_list, head) {
824 		if (maxPitch > 0 && mode->hdisplay > maxPitch)
825 			mode->status = MODE_BAD_WIDTH;
826 
827 		if (maxX > 0 && mode->hdisplay > maxX)
828 			mode->status = MODE_VIRTUAL_X;
829 
830 		if (maxY > 0 && mode->vdisplay > maxY)
831 			mode->status = MODE_VIRTUAL_Y;
832 	}
833 }
834 EXPORT_SYMBOL(drm_mode_validate_size);
835 
836 /**
837  * drm_mode_validate_clocks - validate modes against clock limits
838  * @dev: DRM device
839  * @mode_list: list of modes to check
840  * @min: minimum clock rate array
841  * @max: maximum clock rate array
842  * @n_ranges: number of clock ranges (size of arrays)
843  *
844  * LOCKING:
845  * Caller must hold a lock protecting @mode_list.
846  *
847  * Some code may need to check a mode list against the clock limits of the
848  * device in question.  This function walks the mode list, testing to make
849  * sure each mode falls within a given range (defined by @min and @max
850  * arrays) and sets @mode->status as needed.
851  */
852 void drm_mode_validate_clocks(struct drm_device *dev,
853 			      struct list_head *mode_list,
854 			      int *min, int *max, int n_ranges)
855 {
856 	struct drm_display_mode *mode;
857 	int i;
858 
859 	list_for_each_entry(mode, mode_list, head) {
860 		bool good = false;
861 		for (i = 0; i < n_ranges; i++) {
862 			if (mode->clock >= min[i] && mode->clock <= max[i]) {
863 				good = true;
864 				break;
865 			}
866 		}
867 		if (!good)
868 			mode->status = MODE_CLOCK_RANGE;
869 	}
870 }
871 EXPORT_SYMBOL(drm_mode_validate_clocks);
872 
873 /**
874  * drm_mode_prune_invalid - remove invalid modes from mode list
875  * @dev: DRM device
876  * @mode_list: list of modes to check
877  * @verbose: be verbose about it
878  *
879  * LOCKING:
880  * Caller must hold a lock protecting @mode_list.
881  *
882  * Once mode list generation is complete, a caller can use this routine to
883  * remove invalid modes from a mode list.  If any of the modes have a
884  * status other than %MODE_OK, they are removed from @mode_list and freed.
885  */
886 void drm_mode_prune_invalid(struct drm_device *dev,
887 			    struct list_head *mode_list, bool verbose)
888 {
889 	struct drm_display_mode *mode, *t;
890 
891 	list_for_each_entry_safe(mode, t, mode_list, head) {
892 		if (mode->status != MODE_OK) {
893 			list_del(&mode->head);
894 			if (verbose) {
895 				drm_mode_debug_printmodeline(mode);
896 				DRM_DEBUG_KMS("Not using %s mode %d\n",
897 					mode->name, mode->status);
898 			}
899 			drm_mode_destroy(dev, mode);
900 		}
901 	}
902 }
903 EXPORT_SYMBOL(drm_mode_prune_invalid);
904 
905 /**
906  * drm_mode_compare - compare modes for favorability
907  * @priv: unused
908  * @lh_a: list_head for first mode
909  * @lh_b: list_head for second mode
910  *
911  * LOCKING:
912  * None.
913  *
914  * Compare two modes, given by @lh_a and @lh_b, returning a value indicating
915  * which is better.
916  *
917  * RETURNS:
918  * Negative if @lh_a is better than @lh_b, zero if they're equivalent, or
919  * positive if @lh_b is better than @lh_a.
920  */
921 static int drm_mode_compare(struct drm_display_mode *a, struct drm_display_mode* b)
922 {
923 	int diff;
924 
925 	diff = ((b->type & DRM_MODE_TYPE_PREFERRED) != 0) -
926 		((a->type & DRM_MODE_TYPE_PREFERRED) != 0);
927 	if (diff)
928 		return diff;
929 	diff = b->hdisplay * b->vdisplay - a->hdisplay * a->vdisplay;
930 	if (diff)
931 		return diff;
932 	diff = b->clock - a->clock;
933 	return diff;
934 }
935 
936 /**
937  * drm_mode_sort - sort mode list
938  * @mode_list: list to sort
939  *
940  * LOCKING:
941  * Caller must hold a lock protecting @mode_list.
942  *
943  * Sort @mode_list by favorability, putting good modes first.
944  */
945 RB_HEAD(drm_mode_sort, drm_display_mode);
946 
947 RB_PROTOTYPE(drm_mode_sort, drm_display_mode, sort, drm_mode_compare);
948 
949 void drm_mode_sort(struct list_head *mode_list)
950 {
951 	struct drm_display_mode *mode, *t;
952 	struct drm_mode_sort drm_mode_tree;
953 
954 	RB_INIT(&drm_mode_tree);
955 	list_for_each_entry_safe(mode, t, mode_list, head) {
956 		RB_INSERT(drm_mode_sort, &drm_mode_tree, mode);
957 		list_del(&mode->head);
958 	}
959 	RB_FOREACH(mode, drm_mode_sort, &drm_mode_tree)
960 		list_add_tail(&mode->head, mode_list);
961 }
962 EXPORT_SYMBOL(drm_mode_sort);
963 
964 RB_GENERATE(drm_mode_sort, drm_display_mode, sort, drm_mode_compare);
965 
966 /**
967  * drm_mode_connector_list_update - update the mode list for the connector
968  * @connector: the connector to update
969  *
970  * LOCKING:
971  * Caller must hold a lock protecting @mode_list.
972  *
973  * This moves the modes from the @connector probed_modes list
974  * to the actual mode list. It compares the probed mode against the current
975  * list and only adds different modes. All modes unverified after this point
976  * will be removed by the prune invalid modes.
977  */
978 void drm_mode_connector_list_update(struct drm_connector *connector)
979 {
980 	struct drm_display_mode *mode;
981 	struct drm_display_mode *pmode, *pt;
982 	int found_it;
983 
984 	list_for_each_entry_safe(pmode, pt, &connector->probed_modes,
985 				 head) {
986 		found_it = 0;
987 		/* go through current modes checking for the new probed mode */
988 		list_for_each_entry(mode, &connector->modes, head) {
989 			if (drm_mode_equal(pmode, mode)) {
990 				found_it = 1;
991 				/* if equal delete the probed mode */
992 				mode->status = pmode->status;
993 				/* Merge type bits together */
994 				mode->type |= pmode->type;
995 				list_del(&pmode->head);
996 				drm_mode_destroy(connector->dev, pmode);
997 				break;
998 			}
999 		}
1000 
1001 		if (!found_it) {
1002 			list_move_tail(&pmode->head, &connector->modes);
1003 		}
1004 	}
1005 }
1006 EXPORT_SYMBOL(drm_mode_connector_list_update);
1007 
1008 /**
1009  * drm_mode_parse_command_line_for_connector - parse command line for connector
1010  * @mode_option - per connector mode option
1011  * @connector - connector to parse line for
1012  *
1013  * This parses the connector specific then generic command lines for
1014  * modes and options to configure the connector.
1015  *
1016  * This uses the same parameters as the fb modedb.c, except for extra
1017  *	<xres>x<yres>[M][R][-<bpp>][@<refresh>][i][m][eDd]
1018  *
1019  * enable/enable Digital/disable bit at the end
1020  */
1021 bool drm_mode_parse_command_line_for_connector(const char *mode_option,
1022 					       struct drm_connector *connector,
1023 					       struct drm_cmdline_mode *mode)
1024 {
1025 	const char *name;
1026 	unsigned int namelen;
1027 	bool res_specified = false, bpp_specified = false, refresh_specified = false;
1028 	unsigned int xres = 0, yres = 0, bpp = 32, refresh = 0;
1029 	bool yres_specified = false, cvt = false, rb = false;
1030 	bool interlace = false, margins = false, was_digit = false;
1031 	int i;
1032 	enum drm_connector_force force = DRM_FORCE_UNSPECIFIED;
1033 
1034 #ifdef CONFIG_FB
1035 	if (!mode_option)
1036 		mode_option = fb_mode_option;
1037 #endif
1038 
1039 	if (!mode_option) {
1040 		mode->specified = false;
1041 		return false;
1042 	}
1043 
1044 	name = mode_option;
1045 	namelen = strlen(name);
1046 	for (i = namelen-1; i >= 0; i--) {
1047 		switch (name[i]) {
1048 		case '@':
1049 			if (!refresh_specified && !bpp_specified &&
1050 			    !yres_specified && !cvt && !rb && was_digit) {
1051 				refresh = simple_strtol(&name[i+1], NULL, 10);
1052 				refresh_specified = true;
1053 				was_digit = false;
1054 			} else
1055 				goto done;
1056 			break;
1057 		case '-':
1058 			if (!bpp_specified && !yres_specified && !cvt &&
1059 			    !rb && was_digit) {
1060 				bpp = simple_strtol(&name[i+1], NULL, 10);
1061 				bpp_specified = true;
1062 				was_digit = false;
1063 			} else
1064 				goto done;
1065 			break;
1066 		case 'x':
1067 			if (!yres_specified && was_digit) {
1068 				yres = simple_strtol(&name[i+1], NULL, 10);
1069 				yres_specified = true;
1070 				was_digit = false;
1071 			} else
1072 				goto done;
1073 		case '0' ... '9':
1074 			was_digit = true;
1075 			break;
1076 		case 'M':
1077 			if (yres_specified || cvt || was_digit)
1078 				goto done;
1079 			cvt = true;
1080 			break;
1081 		case 'R':
1082 			if (yres_specified || cvt || rb || was_digit)
1083 				goto done;
1084 			rb = true;
1085 			break;
1086 		case 'm':
1087 			if (cvt || yres_specified || was_digit)
1088 				goto done;
1089 			margins = true;
1090 			break;
1091 		case 'i':
1092 			if (cvt || yres_specified || was_digit)
1093 				goto done;
1094 			interlace = true;
1095 			break;
1096 		case 'e':
1097 			if (yres_specified || bpp_specified || refresh_specified ||
1098 			    was_digit || (force != DRM_FORCE_UNSPECIFIED))
1099 				goto done;
1100 
1101 			force = DRM_FORCE_ON;
1102 			break;
1103 		case 'D':
1104 			if (yres_specified || bpp_specified || refresh_specified ||
1105 			    was_digit || (force != DRM_FORCE_UNSPECIFIED))
1106 				goto done;
1107 
1108 			if ((connector->connector_type != DRM_MODE_CONNECTOR_DVII) &&
1109 			    (connector->connector_type != DRM_MODE_CONNECTOR_HDMIB))
1110 				force = DRM_FORCE_ON;
1111 			else
1112 				force = DRM_FORCE_ON_DIGITAL;
1113 			break;
1114 		case 'd':
1115 			if (yres_specified || bpp_specified || refresh_specified ||
1116 			    was_digit || (force != DRM_FORCE_UNSPECIFIED))
1117 				goto done;
1118 
1119 			force = DRM_FORCE_OFF;
1120 			break;
1121 		default:
1122 			goto done;
1123 		}
1124 	}
1125 
1126 	if (i < 0 && yres_specified) {
1127 		char *ch;
1128 		xres = simple_strtol(name, &ch, 10);
1129 		if ((ch != NULL) && (*ch == 'x'))
1130 			res_specified = true;
1131 		else
1132 			i = ch - name;
1133 	} else if (!yres_specified && was_digit) {
1134 		/* catch mode that begins with digits but has no 'x' */
1135 		i = 0;
1136 	}
1137 done:
1138 	if (i >= 0) {
1139 		printf("parse error at position %i in video mode '%s'\n",
1140 			i, name);
1141 		mode->specified = false;
1142 		return false;
1143 	}
1144 
1145 	if (res_specified) {
1146 		mode->specified = true;
1147 		mode->xres = xres;
1148 		mode->yres = yres;
1149 	}
1150 
1151 	if (refresh_specified) {
1152 		mode->refresh_specified = true;
1153 		mode->refresh = refresh;
1154 	}
1155 
1156 	if (bpp_specified) {
1157 		mode->bpp_specified = true;
1158 		mode->bpp = bpp;
1159 	}
1160 	mode->rb = rb;
1161 	mode->cvt = cvt;
1162 	mode->interlace = interlace;
1163 	mode->margins = margins;
1164 	mode->force = force;
1165 
1166 	return true;
1167 }
1168 EXPORT_SYMBOL(drm_mode_parse_command_line_for_connector);
1169 
1170 struct drm_display_mode *
1171 drm_mode_create_from_cmdline_mode(struct drm_device *dev,
1172 				  struct drm_cmdline_mode *cmd)
1173 {
1174 	struct drm_display_mode *mode;
1175 
1176 	if (cmd->cvt)
1177 		mode = drm_cvt_mode(dev,
1178 				    cmd->xres, cmd->yres,
1179 				    cmd->refresh_specified ? cmd->refresh : 60,
1180 				    cmd->rb, cmd->interlace,
1181 				    cmd->margins);
1182 	else
1183 		mode = drm_gtf_mode(dev,
1184 				    cmd->xres, cmd->yres,
1185 				    cmd->refresh_specified ? cmd->refresh : 60,
1186 				    cmd->interlace,
1187 				    cmd->margins);
1188 	if (!mode)
1189 		return NULL;
1190 
1191 	drm_mode_set_crtcinfo(mode, CRTC_INTERLACE_HALVE_V);
1192 	return mode;
1193 }
1194 EXPORT_SYMBOL(drm_mode_create_from_cmdline_mode);
1195 
1196 /*-
1197  * Copyright (c) 1990 The Regents of the University of California.
1198  * All rights reserved.
1199  *
1200  * Redistribution and use in source and binary forms, with or without
1201  * modification, are permitted provided that the following conditions
1202  * are met:
1203  * 1. Redistributions of source code must retain the above copyright
1204  *    notice, this list of conditions and the following disclaimer.
1205  * 2. Redistributions in binary form must reproduce the above copyright
1206  *    notice, this list of conditions and the following disclaimer in the
1207  *    documentation and/or other materials provided with the distribution.
1208  * 3. Neither the name of the University nor the names of its contributors
1209  *    may be used to endorse or promote products derived from this software
1210  *    without specific prior written permission.
1211  *
1212  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1213  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1214  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1215  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
1216  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1217  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1218  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1219  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1220  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1221  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1222  * SUCH DAMAGE.
1223  */
1224 
1225 
1226 /*
1227  * Convert a string to a long integer.
1228  *
1229  * Ignores `locale' stuff.  Assumes that the upper and lower case
1230  * alphabets and digits are each contiguous.
1231  */
1232 #include <sys/limits.h>
1233 
1234 long
1235 simple_strtol(const char *nptr, char **endptr, int base)
1236 {
1237 	const char *s;
1238 	long acc, cutoff;
1239 	int c;
1240 	int neg, any, cutlim;
1241 	int errno;
1242 
1243 	/*
1244 	 * Skip white space and pick up leading +/- sign if any.
1245 	 * If base is 0, allow 0x for hex and 0 for octal, else
1246 	 * assume decimal; if base is already 16, allow 0x.
1247 	 */
1248 	s = nptr;
1249 	do {
1250 		c = (unsigned char) *s++;
1251 	} while (c == ' ' || c == '\t');
1252 	if (c == '-') {
1253 		neg = 1;
1254 		c = *s++;
1255 	} else {
1256 		neg = 0;
1257 		if (c == '+')
1258 			c = *s++;
1259 	}
1260 	if ((base == 0 || base == 16) &&
1261 	    c == '0' && (*s == 'x' || *s == 'X')) {
1262 		c = s[1];
1263 		s += 2;
1264 		base = 16;
1265 	}
1266 	if (base == 0)
1267 		base = c == '0' ? 8 : 10;
1268 
1269 	/*
1270 	 * Compute the cutoff value between legal numbers and illegal
1271 	 * numbers.  That is the largest legal value, divided by the
1272 	 * base.  An input number that is greater than this value, if
1273 	 * followed by a legal input character, is too big.  One that
1274 	 * is equal to this value may be valid or not; the limit
1275 	 * between valid and invalid numbers is then based on the last
1276 	 * digit.  For instance, if the range for longs is
1277 	 * [-2147483648..2147483647] and the input base is 10,
1278 	 * cutoff will be set to 214748364 and cutlim to either
1279 	 * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
1280 	 * a value > 214748364, or equal but the next digit is > 7 (or 8),
1281 	 * the number is too big, and we will return a range error.
1282 	 *
1283 	 * Set any if any `digits' consumed; make it negative to indicate
1284 	 * overflow.
1285 	 */
1286 	cutoff = neg ? LONG_MIN : LONG_MAX;
1287 	cutlim = cutoff % base;
1288 	cutoff /= base;
1289 	if (neg) {
1290 		if (cutlim > 0) {
1291 			cutlim -= base;
1292 			cutoff += 1;
1293 		}
1294 		cutlim = -cutlim;
1295 	}
1296 	for (acc = 0, any = 0;; c = (unsigned char) *s++) {
1297 		if (c >= '0' && c <= '9')
1298 			c -= '0';
1299 		else if (c >= 'A' && c <= 'Z')
1300 			c -= 'A' - 10;
1301 		else if( c >= 'a' && c <= 'z')
1302 			c -=  'a' - 10;
1303 		else
1304 			break;
1305 		if (c >= base)
1306 			break;
1307 		if (any < 0)
1308 			continue;
1309 		if (neg) {
1310 			if (acc < cutoff || (acc == cutoff && c > cutlim)) {
1311 				any = -1;
1312 				acc = LONG_MIN;
1313 				errno = ERANGE;
1314 			} else {
1315 				any = 1;
1316 				acc *= base;
1317 				acc -= c;
1318 			}
1319 		} else {
1320 			if (acc > cutoff || (acc == cutoff && c > cutlim)) {
1321 				any = -1;
1322 				acc = LONG_MAX;
1323 				errno = ERANGE;
1324 			} else {
1325 				any = 1;
1326 				acc *= base;
1327 				acc += c;
1328 			}
1329 		}
1330 	}
1331 	if (endptr != 0)
1332 		*endptr = (char *) (any ? s - 1 : nptr);
1333 	return (acc);
1334 }
1335