aboutsummaryrefslogtreecommitdiffstats
path: root/rc.d/rc.sysinit
blob: 6b134798d49dbd1675d392a210f60d3b1139b055 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
#!/bin/bash
#
# /etc/rc.sysinit - run once at boot time
#
# Taken in part from Miquel van Smoorenburg's bcheckrc.
#

# Rerun ourselves through initlog
if [ -z "$IN_INITLOG" ]; then
 [ -f /sbin/initlog ] && exec /sbin/initlog $INITLOG_ARGS -r /etc/rc.sysinit
fi

# If we're using devfs, start devfsd now - we need the old device names
[ -e /dev/.devfsd -a -x /sbin/devfsd ] && /sbin/devfsd /dev

# Set the path
PATH=/bin:/sbin:/usr/bin:/usr/sbin
export PATH

HOSTNAME=`/bin/hostname`

# Read in config data.
if [ -f /etc/sysconfig/network ]; then
    . /etc/sysconfig/network
else
    NETWORKING=no
fi

if [ -z "$HOSTNAME" -o "$HOSTNAME" = "(none)" ]; then
    HOSTNAME=localhost
fi

# Source functions
. /etc/init.d/functions

# Print a banner. ;)
echo -en $"\t\t\tWelcome to "
[ "$BOOTUP" != "serial" ] && echo -en $"\\033[1;31m"
echo -en $"Red Hat"
[ "$BOOTUP" != "serial" ] && echo -en $"\\033[0;39m"
echo $" Linux"
if [ "$PROMPT" != "no" ]; then
 echo -en $"\t\tPress 'I' to enter interactive startup."
 echo
 sleep 1
fi

# Fix console loglevel
/bin/dmesg -n $LOGLEVEL

# Mount /proc (done here so volume labels can work with fsck)

action $"Mounting proc filesystem: " mount -n -t proc /proc /proc

# Unmount the initrd, if necessary
if grep -q /initrd /proc/mounts ; then
   action $"Unmounting initrd: " umount /initrd
   /sbin/blockdev --flushbufs /dev/ram0 >/dev/null 2>&1
fi

# Configure kernel parameters

action $"Configuring kernel parameters: " sysctl -e -p /etc/sysctl.conf

# Set the system clock.
ARC=0
SRM=0
UTC=0

if [ -f /etc/sysconfig/clock ]; then
   . /etc/sysconfig/clock

   # convert old style clock config to new values
   if [ "${CLOCKMODE}" = "GMT" ]; then
      UTC=true
   elif [ "${CLOCKMODE}" = "ARC" ]; then
      ARC=true
   fi
fi

CLOCKDEF=""
CLOCKFLAGS="$CLOCKFLAGS --hctosys"

case "$UTC" in
   yes|true)
    CLOCKFLAGS="$CLOCKFLAGS -u";
    CLOCKDEF="$CLOCKDEF (utc)";
   ;;
   no|false)
    CLOCKFLAGS="$CLOCKFLAGS --localtime";
    CLOCKDEF="$CLOCKDEF (localtime)";
   ;;
esac

case "$ARC" in
     yes|true)
     	CLOCKFLAGS="$CLOCKFLAGS -A";
     	CLOCKDEF="$CLOCKDEF (arc)";
     ;;
esac
case "$SRM" in
     yes|true)
	CLOCKFLAGS="$CLOCKFLAGS -S";
	CLOCKDEF="$CLOCKDEF (srm)";
     ;;
esac

/sbin/hwclock $CLOCKFLAGS

action $"Setting clock $CLOCKDEF: `date`" date

if [ "`/sbin/consoletype`" = "vt" ]; then
 # Load keymap
 if [ -x /bin/loadkeys ]; then
 KEYTABLE=
 KEYMAP=
 if [ -f /etc/sysconfig/console/default.kmap ]; then
  KEYMAP=/etc/sysconfig/console/default.kmap
 else
  if [ -f /etc/sysconfig/keyboard ]; then
    . /etc/sysconfig/keyboard
  fi
  if [ -n "$KEYTABLE" -a -d "/usr/lib/kbd/keymaps" -o -d "/lib/kbd/keymaps" ]; then
     KEYMAP=$KEYTABLE
  fi
 fi
 if [ -n "$KEYMAP" ]; then 
  # Since this takes in/output from stdin/out, we can't use initlog
  if [ -n "$KEYTABLE" ]; then
    echo -n $"Loading default keymap ($KEYTABLE): "
  else
    echo -n $"Loading default keymap: "
  fi
  loadkeys $KEYMAP < /dev/tty0 > /dev/tty0 2>/dev/null && \
     success $"Loading default keymap" || failure $"Loading default keymap"
  echo
 fi   
 fi

 # Load system font
 if [ -x /sbin/setsysfont ]; then
    [ -f /etc/sysconfig/i18n ] && . /etc/sysconfig/i18n
    if [ -f /etc/sysconfig/console/$SYSFONT.psf.gz -o \
         -f /usr/lib/kbd/consolefonts/$SYSFONT.psf.gz -o \
         -f /etc/sysconfig/console/$SYSFONT.gz -o \
         -f /usr/lib/kbd/consolefonts/$SYSFONT.gz -o \
	 -f /lib/kbd/consolefonts/$SYSFONT.gz -o \
	 -f /lib/kbd/consolefonts/$SYSFONT.psf.gz ]; then
       action $"Setting default font ($SYSFONT): " /sbin/setsysfont
    fi
 fi
fi

# Start up swapping.
action $"Activating swap partitions: " swapon -a -e

# Set the hostname.
action $"Setting hostname ${HOSTNAME}: " hostname ${HOSTNAME}

# Initialize USB controller and HID devices
usb=0
if ! grep -iq "nousb" /proc/cmdline 2>/dev/null && ! grep -q "usb" /proc/devices 2>/dev/null ; then
    aliases=`/sbin/modprobe -c | egrep -s "^alias[[:space:]]+usb-controller" | awk '{ print $3 }'`
    if [ -n "$aliases" -a "$aliases" != "off" ] ; then
      modprobe usbcore
      action $"Mounting USB filesystem: "  mount -t usbdevfs usbdevfs /proc/bus/usb
      for alias in $aliases ; do 
      	action $"Initializing USB controller ($alias): " modprobe $alias
      done
      [ $? -eq 0 -a -n "$aliases" ] && usb=1
    fi
fi

if ! grep -iq "nousb" /proc/cmdline 2>/dev/null && grep -q "usb" /proc/devices 2>/dev/null ; then
  usb=1
fi

needusbstorage=
if [ $usb = "1" ]; then
    sleep 5
    mouseoutput=`cat /proc/bus/usb/devices 2>/dev/null|grep -E "^I.*Cls=03.*Prot=02"`
    kbdoutput=`cat /proc/bus/usb/devices 2>/dev/null|grep -E "^I.*Cls=03.*Prot=01"`
    needusbstorage=`cat /proc/bus/usb/devices 2>/dev/null|grep -e "^I.*Cls=08"`
    if [ -n "$kbdoutput" ] || [ -n "$mouseoutput" ]; then
	action $"Initializing USB HID interface: " modprobe hid 2> /dev/null
    fi
    if [ -n "$kbdoutput" ]; then
	action $"Initializing USB keyboard: " modprobe keybdev
    fi
    if [ -n "$mouseoutput" ]; then
	action $"Initializing USB mouse: " modprobe mousedev
    fi
fi

if [ -f /fastboot ] || grep -iq "fastboot" /proc/cmdline 2>/dev/null ; then
	fastboot=yes
    else
        fastboot=
fi

if [ -f /fsckoptions ]; then
	fsckoptions=`cat /fsckoptions`
    else
	fsckoptions=
fi

if [ -f /forcefsck ]; then
	fsckoptions="-f $fsckoptions"
fi

if [ "$BOOTUP" != "serial" ]; then
	fsckoptions="-C $fsckoptions"
else
	fsckoptions="-V $fsckoptions"
fi
 

_RUN_QUOTACHECK=0
ROOTFSTYPE=`grep " / " /proc/mounts | awk '{ print $3 }'`
if [ -z "$fastboot" -a "$ROOTFSTYPE" != "nfs" ]; then 

        STRING=$"Checking root filesystem"
	echo $STRING
	initlog -c "fsck -T -a $fsckoptions /"
	rc=$?
	
	if [ "$rc" = "0" ]; then
		success "$STRING"
		echo
	elif [ "$rc" = "1" ]; then
	        passed $"$STRING"
		echo
        fi
	
        # A return of 2 or higher means there were serious problems.
	if [ $rc -gt 1 ]; then
		failure "$STRING"
		echo
		echo
		echo $"*** An error occurred during the file system check."
		echo $"*** Dropping you to a shell; the system will reboot"
		echo $"*** when you leave the shell."

		PS1=$"(Repair filesystem) \# # "; export PS1
		sulogin

		echo $"Unmounting file systems"
		umount -a
		mount -n -o remount,ro /
		echo $"Automatic reboot in progress."
		reboot -f
	elif [ "$rc" = "1" ]; then
		_RUN_QUOTACHECK=1
	fi
fi

# Possibly update quotas if fsck was run on /.
grep -E '[[:space:]]+/[[:space:]]+' /etc/fstab | \
    awk '{ print $4 }' | \
    grep -q quota
_ROOT_HAS_QUOTA=$?
if [ X"$_RUN_QUOTACHECK" = X1 -a \
    "$_ROOT_HAS_QUOTA" -a \
    -x /sbin/quotacheck ]; then
	if [ -x /sbin/convertquota ]; then
	    if [ -f /quota.user ]; then
		action $"Converting old user quota files: " \
		    /sbin/convertquota -u / && rm -f /quota.user
	    fi
	    if [ -f /quota.group ]; then
		action $"Converting old group quota files: " \
		    /sbin/convertquota -g / && rm -f /quota.group
	    fi
	fi
	action $"Checking root filesystem quotas: " /sbin/quotacheck -n /
fi

# check for arguments passed from kernel

if grep -iq nopnp /proc/cmdline >/dev/null 2>&1 ; then
    PNP=
else
    PNP=yes
fi

# set up pnp 
if [ -x /sbin/isapnp -a -f /etc/isapnp.conf -a ! -f /proc/isapnp ]; then
    if [ -n "$PNP" ]; then
	action $"Setting up ISA PNP devices: " /sbin/isapnp /etc/isapnp.conf
    else
	action $"Skipping ISA PNP configuration at users request: " /bin/true
    fi
fi

# Remount the root filesystem read-write.
state=`awk '/(^\/dev\/root| \/ )/ { print $4 }' /proc/mounts`
[ "$state" != "rw" ] && \
  action $"Remounting root filesystem in read-write mode: " mount -n -o remount,rw /

# LVM initialization
if [ -e /proc/lvm -a -x /sbin/vgchange -a -f /etc/lvmtab ]; then
        action $"Setting up Logical Volume Management:" /sbin/vgscan && /sbin/vgchange -a y
fi

# Clear mtab
>/etc/mtab

# Remove stale backups
rm -f /etc/mtab~ /etc/mtab~~

# Enter root, /proc and (potentially) /proc/bus/usb and devfs into mtab.
mount -f /
mount -f /proc
[ -f /proc/bus/usb/devices ] && mount -f -t usbdevfs usbdevfs /proc/bus/usb
[ -e /dev/.devfsd ] && mount -f -t devfs devfs /dev 

# Turn on harddisk optimization
# There is only one file /etc/sysconfig/harddisks for all disks
# after installing the hdparm-RPM. If you need different hdparm parameters
# for each of your disks, copy /etc/sysconfig/harddisks to
# /etc/sysconfig/harddiskhda (hdb, hdc...) and modify it.
# each disk which has no special parameters will use the defaults.
 
disk[0]=s; disk[1]=hda; disk[2]=hdb; disk[3]=hdc;
disk[4]=hdd; disk[5]=hde; disk[6]=hdf; disk[7]=hdg; disk[8]=hdh;
 
 
if [ -x /sbin/hdparm ]; then
   for device in 0 1 2 3 4 5 6 7 8; do
   unset MULTIPLE_IO USE_DMA EIDE_32BIT LOOKAHEAD EXTRA_PARAMS
        if [ -f /etc/sysconfig/harddisk${disk[$device]} ]; then
                . /etc/sysconfig/harddisk${disk[$device]}
                HDFLAGS[$device]=
                if [ -n "$MULTIPLE_IO" ]; then
                    HDFLAGS[$device]="-q -m$MULTIPLE_IO"
                fi
                if [ -n "$USE_DMA" ]; then
                    HDFLAGS[$device]="${HDFLAGS[$device]} -q -d$USE_DMA"
                fi
                if [ -n "$EIDE_32BIT" ]; then
                    HDFLAGS[$device]="${HDFLAGS[$device]} -q -c$EIDE_32BIT"
                fi
                if [ -n "$LOOKAHEAD" ]; then
                    HDFLAGS[$device]="${HDFLAGS[$device]} -q -A$LOOKAHEAD"
                fi
                if [ -n "$EXTRA_PARAMS" ]; then
                    HDFLAGS[$device]="${HDFLAGS[$device]} $EXTRA_PARAMS"
                fi
        else
                HDFLAGS[$device]="${HDFLAGS[0]}"
        fi
        if [ -e "/proc/ide/${disk[$device]}/media" ] ; then
             hdmedia=`cat /proc/ide/${disk[$device]}/media`
             if [ "$hdmedia" = "disk" ]; then
                  if [ -n "${HDFLAGS[$device]}" ]; then
                      action $"Setting hard drive parameters for ${disk[$device]}: "  /sbin/hdparm ${HDFLAGS[$device]} /dev/${disk[$device]}
                  fi
             fi
        fi
   done
fi


# The root filesystem is now read-write, so we can now log via syslog() directly..
if [ -n "$IN_INITLOG" ]; then
    IN_INITLOG=
fi

if ! grep -iq nomodules /proc/cmdline >/dev/null 2>&1 && [ -f /proc/ksyms ]; then
    USEMODULES=y
else
    USEMODULES=
fi

# Our modutils don't support it anymore, so we might as well remove
# the preferred link.
rm -f /lib/modules/preferred
rm -f /lib/modules/default
if [ -x /sbin/depmod -a -n "$USEMODULES" ]; then
    # If they aren't using a recent sane kernel, make a link for them
    if [ ! -n "`uname -r | grep -- "-"`" ]; then
       ktag="`cat /proc/version`"
       mtag=`grep -l "$ktag" /lib/modules/*/.rhkmvtag 2> /dev/null`
       if [ -n "$mtag" ]; then
          mver=`echo $mtag | sed -e 's,/lib/modules/,,' -e 's,/.rhkmvtag,,' -e 's,[       ].*$,,'`
       fi
       if [ -n "$mver" ]; then
         ln -sf /lib/modules/$mver /lib/modules/default
       fi
    fi
    if [ -L /lib/modules/default ]; then
    	INITLOG_ARGS= action $"Finding module dependencies: " depmod -A default
    else
	INITLOG_ARGS= action $"Finding module dependencies: " depmod -A
    fi
fi

# tweak isapnp settings if needed.
if [ -n "$PNP" -a  -f /proc/isapnp -a -x /sbin/sndconfig ]; then
    /sbin/sndconfig --mungepnp >/dev/null 2>&1
fi

# Load sound modules iff they need persistent DMA buffers
if grep -q "options sound dmabuf=1" /etc/modules.conf 2>/dev/null ; then
  RETURN=0
  alias=`/sbin/modprobe -c | egrep -s "^alias[[:space:]]+sound[[:space:]]+" | awk '{ print $3 }'`
  if [ -n "$alias" -a "$alias" != "off" ] ; then
      action $"Loading sound module ($alias): " modprobe $alias
      RETURN=$?
  fi
  alias=`/sbin/modprobe -c | egrep -s "^alias[[:space:]]+sound-slot-0[[:space:]]+" | awk '{ print $3 }'`
  if [ -n "$alias" -a "$alias" != "off" ] ; then
      action $"Loading sound module ($alias): " modprobe $alias
      RETURN=$?
  fi
fi

if [ -f /proc/sys/kernel/modprobe ]; then
   if [ -n "$USEMODULES" ]; then
       sysctl -w kernel.modprobe="/sbin/modprobe" >/dev/null 2>&1
       sysctl -w kernel.hotplug="/sbin/hotplug" >/dev/null 2>&1
   else
       # We used to set this to NULL, but that causes 'failed to exec' messages"
       sysctl -w kernel.modprobe="/bin/true" >/dev/null 2>&1
       sysctl -w kernel.hotplug="/bin/true" >/dev/null 2>&1
   fi
fi

# Load modules (for backward compatibility with VARs)
if [ -f /etc/rc.modules ]; then
	/etc/rc.modules
fi

# Add raid devices
if [ ! -f /proc/mdstat ]; then
	modprobe md >/dev/null 2>&1
fi	

if [ -f /proc/mdstat -a -f /etc/raidtab ]; then
	echo -n $"Starting up RAID devices: " 

	rc=0
	
	for i in `grep "^raiddev" /etc/raidtab | awk '{print $2}'`
	do
		RAIDDEV=`basename $i`
                RAIDSTAT=`grep "^$RAIDDEV : active" /proc/mdstat`
		if [ -z "$RAIDSTAT" ]; then
			# First scan the /etc/fstab for the "noauto"-flag
			# for this device. If found, skip the initialization
			# for it to avoid dropping to a shell on errors.
			# If not, try raidstart...if that fails then
			# fall back to raidadd, raidrun.  If that
			# also fails, then we drop to a shell
			RESULT=1
			NOAUTO=`grep "^$i" /etc/fstab | grep -c "noauto"`
			if [ $NOAUTO -gt 0 ]; then
			    RESULT=0
			    RAIDDEV="$RAIDDEV(skipped)"
			fi
			if [ $RESULT -gt 0 -a -x /sbin/raidstart ]; then
				/sbin/raidstart $i
				RESULT=$?
			fi
			if [ $RESULT -gt 0 -a -x /sbin/raid0run ]; then
				/sbin/raid0run $i
				RESULT=$?
			fi
			if [ $RESULT -gt 0 -a -x /sbin/raidadd -a -x /sbin/raidrun ]; then
				/sbin/raidadd $i
				/sbin/raidrun $i
				RESULT=$?
			fi
			if [ $RESULT -gt 0 ]; then
				rc=1
			fi
			echo -n "$RAIDDEV "
		else
			echo -n "$RAIDDEV "
		fi
	done
	echo

	# A non-zero return means there were problems.
	if [ $rc -gt 0 ]; then
		echo
		echo
		echo $"*** An error occurred during the RAID startup"
		echo $"*** Dropping you to a shell; the system will reboot"
		echo $"*** when you leave the shell."

		PS1=$"(RAID Repair) \# # "; export PS1
		sulogin

		echo $"Unmounting file systems"
		umount -a
		mount -n -o remount,ro /
		echo $"Automatic reboot in progress."
		reboot -f
	fi
fi

_RUN_QUOTACHECK=0
# Check filesystems
if [ -z "$fastboot" ]; then
        STRING=$"Checking filesystems"
	echo $STRING
	initlog -c "fsck -T -R -A -a $fsckoptions"
	rc=$?
        if [ "$rc" = "0" ]; then
		success "$STRING"
		echo
	elif [ "$rc" = "1" ]; then
	        passed "$STRING"
		echo
	fi

	# A return of 2 or higher means there were serious problems.
	if [ $rc -gt 1 ]; then
	        failure "$STRING"
		echo
		echo
		echo $"*** An error occurred during the file system check."
		echo $"*** Dropping you to a shell; the system will reboot"
		echo $"*** when you leave the shell."

		PS1=$"(Repair filesystem) \# # "; export PS1
		sulogin

		echo $"Unmounting file systems"
		umount -a
		mount -n -o remount,ro /
		echo $"Automatic reboot in progress."
		reboot -f
	elif [ "$rc" = "1" -a -x /sbin/quotacheck ]; then
		_RUN_QUOTACHECK=1
	fi
fi

# Mount all other filesystems (except for NFS and /proc, which is already
# mounted). Contrary to standard usage,
# filesystems are NOT unmounted in single user mode.
action $"Mounting local filesystems: " mount -a -t nonfs,smbfs,ncpfs -O no_netdev

# check remaining quotas other than root
if [ X"$_RUN_QUOTACHECK" = X1 -a -x /sbin/quotacheck ]; then
	if [ -x /sbin/convertquota ]; then
	    # try to convert old quotas
	    for mountpt in `cat /etc/mtab | awk '$4 ~ /quota/{print $2}'`; do
		if [ -f "$mountpt/quota.user" ]; then
		    action $"Converting old user quota files: " \
		    /sbin/convertquota -u $mountpt && \
			rm -f $mountpt/quota.user
		fi
		if [ -f "$mountpt/quota.group" ]; then
		    action $"Converting old group quota files: " \
		    /sbin/convertquota -g $mountpt && \
			rm -f $mountpt/quota.group
		fi
	    done
	fi
	action $"Checking local filesystem quotas: " /sbin/quotacheck -aR
fi

if [ -x /sbin/quotaon ]; then
    action $"Enabling local filesystem quotas: " /sbin/quotaon -a
fi

# Turn on process accounting
if [ -x /sbin/accton ] ; then
	action $"Turning on process accounting" /sbin/accton /var/log/pacct
fi

# Configure machine if necessary.
if [ -f /.unconfigured ]; then
    if [ -x /usr/bin/passwd ]; then 
        /usr/bin/passwd root
    fi
    if [ -x /usr/sbin/netconfig ]; then
	/usr/sbin/netconfig
    fi
    if [ -x /usr/sbin/timeconfig ]; then
	/usr/sbin/timeconfig
    fi
    if [ -x /usr/sbin/authconfig ]; then
	/usr/sbin/authconfig --nostart
    fi
    if [ -x /usr/sbin/ntsysv ]; then
	/usr/sbin/ntsysv --level 35
    fi

    # Reread in network configuration data.
    if [ -f /etc/sysconfig/network ]; then
	. /etc/sysconfig/network

	# Reset the hostname.
	action $"Resetting hostname ${HOSTNAME}: " hostname ${HOSTNAME}
    fi

    rm -f /.unconfigured
fi

# Clean out /etc.
rm -f /fastboot /fsckoptions /forcefsck /halt /poweroff

# Do we need (w|u)tmpx files? We don't set them up, but the sysadmin might...
_NEED_XFILES=
[ -f /var/run/utmpx -o -f /var/log/wtmpx ] && _NEED_XFILES=1

# Clean up /var
# I'd use find, but /usr may not be mounted.
for afile in /var/lock/* /var/run/*; do
   if [ -d "$afile" ]; then
      [ "`basename $afile`" != "news" -a "`basename $afile`" != "sudo" -a "`basename $afile`" != "mon" ] && rm -f $afile/*
   else
      rm -f $afile
   fi
done

# Reset pam_console permissions
[ -x /sbin/pam_console_apply ] && /sbin/pam_console_apply -r

{
# Clean up utmp/wtmp
>/var/run/utmp
touch /var/log/wtmp
chgrp utmp /var/run/utmp /var/log/wtmp
chmod 0664 /var/run/utmp /var/log/wtmp
if [ -n "$_NEED_XFILES" ]; then
  >/var/run/utmpx
  touch /var/log/wtmpx
  chgrp utmp /var/run/utmpx /var/log/wtmpx
  chmod 0664 /var/run/utmpx /var/log/wtmpx
fi

# Delete X locks
rm -f /tmp/.X*-lock

# Delete Postgres sockets
rm -f /tmp/.s.PGSQL.*

# Now turn on swap in case we swap to files.
swapon -a
action $"Enabling swap space: " /bin/true

# Initialize the serial ports.
if [ -f /etc/rc.serial ]; then
	. /etc/rc.serial
fi

# If a SCSI tape has been detected, load the st module unconditionally
# since many SCSI tapes don't deal well with st being loaded and unloaded
if [ -f /proc/scsi/scsi ] && grep -q 'Type:   Sequential-Access' /proc/scsi/scsi 2>/dev/null ; then
	if grep -qv ' 9 st' /proc/devices ; then
		if [ -n "$USEMODULES" ] ; then
			# Try to load the module.  If it fails, ignore it...
			insmod -p st >/dev/null 2>&1 && modprobe st >/dev/null 2>&1
		fi
	fi
fi

# Load usb storage here, to match most other things
if [ -n "$needusbstorage" ]; then
	modprobe usb-storage >/dev/null 2>&1
fi

# If they asked for ide-scsi, load it
if grep -q "ide-scsi" /proc/cmdline ; then
	modprobe ide-cd >/dev/null 2>&1
	modprobe ide-scsi >/dev/null 2>&1
fi

# Generate a header that defines the boot kernel.
/sbin/mkkerneldoth

# Adjust symlinks as necessary in /boot to keep system services from
# spewing messages about mismatched System maps and so on.
if [ -L /boot/System.map -a -r /boot/System.map-`uname -r` -a \
	! /boot/System.map -ef /boot/System.map-`uname -r` ] ; then
	ln -s -f System.map-`uname -r` /boot/System.map
fi
if [ ! -e /boot/System.map -a -r /boot/System.map-`uname -r` ] ; then
	ln -s -f System.map-`uname -r` /boot/System.map
fi

# Now that we have all of our basic modules loaded and the kernel going,
# let's dump the syslog ring somewhere so we can find it later
dmesg > /var/log/dmesg
sleep 1
kill -TERM `/sbin/pidof getkey` >/dev/null 2>&1
} &
if [ "$PROMPT" != "no" ]; then
   /sbin/getkey i && touch /var/run/confirm
fi
wait
69' href='#n1269'>1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
/* SLang Screen management routines */
/* Copyright (c) 1992, 1999, 2001 John E. Davis
 * This file is part of the S-Lang library.
 *
 * You may distribute under the terms of either the GNU General Public
 * License or the Perl Artistic License.
 */

#include "slinclud.h"

#include "slang.h"
#include "_slang.h"

typedef struct Screen_Type
  {
     int n;                    /* number of chars written last time */
     int flags;                /* line untouched, etc... */
     SLsmg_Char_Type *old, *neew;
#ifndef IBMPC_SYSTEM
     unsigned long old_hash, new_hash;
#endif
  }
Screen_Type;

#define TOUCHED 0x1
#define TRASHED 0x2
static int Screen_Trashed;

#if !defined(__MSDOS_16BIT__)
# define MAX_SCREEN_SIZE 256
#else
# define MAX_SCREEN_SIZE 75
#endif

Screen_Type SL_Screen[MAX_SCREEN_SIZE];
static int Start_Col, Start_Row;
static int Screen_Cols, Screen_Rows;
static int This_Row, This_Col;
static int This_Color;		       /* only the first 8 bits of this
					* are used.  The highest bit is used
					* to indicate an alternate character
					* set.  This leaves 127 userdefineable
					* color combination.
					*/

#ifndef IBMPC_SYSTEM
#define ALT_CHAR_FLAG 0x80
#else
#define ALT_CHAR_FLAG 0x00
#endif

#if SLTT_HAS_NON_BCE_SUPPORT && !defined(IBMPC_SYSTEM)
#define REQUIRES_NON_BCE_SUPPORT 1
static int Bce_Color_Offset;
#endif

int SLsmg_Newline_Behavior = 0;
int SLsmg_Backspace_Moves = 0;
/* Backward compatibility. Not used. */
/* int SLsmg_Newline_Moves; */

static void (*tt_normal_video)(void) = SLtt_normal_video;
static void (*tt_goto_rc)(int, int) = SLtt_goto_rc;
static void (*tt_cls) (void) = SLtt_cls;
static void (*tt_del_eol) (void) = SLtt_del_eol;
static void (*tt_smart_puts) (SLsmg_Char_Type *, SLsmg_Char_Type *, int, int) = SLtt_smart_puts;
static int (*tt_flush_output) (void) = SLtt_flush_output;
static int (*tt_reset_video) (void) = SLtt_reset_video;
static int (*tt_init_video) (void) = SLtt_init_video;
static int *tt_Screen_Rows = &SLtt_Screen_Rows;
static int *tt_Screen_Cols = &SLtt_Screen_Cols;

#ifndef IBMPC_SYSTEM
static void (*tt_set_scroll_region)(int, int) = SLtt_set_scroll_region;
static void (*tt_reverse_index)(int) = SLtt_reverse_index;
static void (*tt_reset_scroll_region)(void) = SLtt_reset_scroll_region;
static void (*tt_delete_nlines)(int) = SLtt_delete_nlines;
#endif

#ifndef IBMPC_SYSTEM
static int *tt_Term_Cannot_Scroll = &SLtt_Term_Cannot_Scroll;
static int *tt_Has_Alt_Charset = &SLtt_Has_Alt_Charset;
static char **tt_Graphics_Char_Pairs = &SLtt_Graphics_Char_Pairs;
static int *tt_Use_Blink_For_ACS = &SLtt_Use_Blink_For_ACS;
#endif

static int Smg_Inited;

static void blank_line (SLsmg_Char_Type *p, int n, unsigned char ch)
{
   register SLsmg_Char_Type *pmax = p + n;
   register SLsmg_Char_Type color_ch;

   color_ch = SLSMG_BUILD_CHAR(ch,This_Color);

   while (p < pmax)
     {
	*p++ = color_ch;
     }
}

static void clear_region (int row, int n)
{
   int i;
   int imax = row + n;

   if (imax > Screen_Rows) imax = Screen_Rows;
   for (i = row; i < imax; i++)
     {
	if (i >= 0)
	  {
	     blank_line (SL_Screen[i].neew, Screen_Cols, ' ');
	     SL_Screen[i].flags |= TOUCHED;
	  }
     }
}

void SLsmg_erase_eol (void)
{
   int r, c;

   if (Smg_Inited == 0) return;

   c = This_Col - Start_Col;
   r = This_Row - Start_Row;

   if ((r < 0) || (r >= Screen_Rows)) return;
   if (c < 0) c = 0; else if (c >= Screen_Cols) return;
   blank_line (SL_Screen[This_Row].neew + c , Screen_Cols - c, ' ');
   SL_Screen[This_Row].flags |= TOUCHED;
}

static void scroll_up (void)
{
   unsigned int i, imax;
   SLsmg_Char_Type *neew;

   neew = SL_Screen[0].neew;
   imax = Screen_Rows - 1;
   for (i = 0; i < imax; i++)
     {
	SL_Screen[i].neew = SL_Screen[i + 1].neew;
	SL_Screen[i].flags |= TOUCHED;
     }
   SL_Screen[i].neew = neew;
   SL_Screen[i].flags |= TOUCHED;
   blank_line (neew, Screen_Cols, ' ');
   This_Row--;
}

void SLsmg_gotorc (int r, int c)
{
   This_Row = r;
   This_Col = c;
}

int SLsmg_get_row (void)
{
   return This_Row;
}

int SLsmg_get_column (void)
{
   return This_Col;
}

void SLsmg_erase_eos (void)
{
   if (Smg_Inited == 0) return;

   SLsmg_erase_eol ();
   clear_region (This_Row + 1, Screen_Rows);
}

static int This_Alt_Char;

void SLsmg_set_char_set (int i)
{
#ifdef IBMPC_SYSTEM
   (void) i;
#else
   if ((tt_Use_Blink_For_ACS != NULL)
       && (*tt_Use_Blink_For_ACS != 0))
     return;/* alt chars not used and the alt bit
	     * is used to indicate a blink.
	     */

   if (i) This_Alt_Char = ALT_CHAR_FLAG;
   else This_Alt_Char = 0;

   This_Color &= 0x7F;
   This_Color |= This_Alt_Char;
#endif
}

void SLsmg_set_color (int color)
{
   if (color < 0) return;
#ifdef REQUIRES_NON_BCE_SUPPORT
   color += Bce_Color_Offset;
#endif
   This_Color = color | This_Alt_Char;
}

void SLsmg_reverse_video (void)
{
   SLsmg_set_color (1);
}

void SLsmg_normal_video (void)
{
   SLsmg_set_color (0);
}

static int point_visible (int col_too)
{
   return ((This_Row >= Start_Row) && (This_Row < Start_Row + Screen_Rows)
	   && ((col_too == 0)
	       || ((This_Col >= Start_Col)
		   && (This_Col < Start_Col + Screen_Cols))));
}

void SLsmg_write_string (char *str)
{
   SLsmg_write_nchars (str, strlen (str));
}

void SLsmg_write_nstring (char *str, unsigned int n)
{
   unsigned int width;
   char blank = ' ';

   /* Avoid a problem if a user accidently passes a negative value */
   if ((int) n < 0)
     return;

   if (str == NULL) width = 0;
   else
     {
	width = strlen (str);
	if (width > n) width = n;
	SLsmg_write_nchars (str, width);
     }
   while (width++ < n) SLsmg_write_nchars (&blank, 1);
}

void SLsmg_write_wrapped_string (char *s, int r, int c,
				 unsigned int dr, unsigned int dc,
				 int fill)
{
   register char ch, *p;
   int maxc = (int) dc;

   if ((dr == 0) || (dc == 0)) return;
   p = s;
   dc = 0;
   while (1)
     {
	ch = *p++;
	if ((ch == 0) || (ch == '\n'))
	  {
	     int diff;

	     diff = maxc - (int) dc;

	     SLsmg_gotorc (r, c);
	     SLsmg_write_nchars (s, dc);
	     if (fill && (diff > 0))
	       {
		  while (diff--) SLsmg_write_char (' ');
	       }
	     if ((ch == 0) || (dr == 1)) break;

	     r++;
	     dc = 0;
	     dr--;
	     s = p;
	  }
	else if ((int) dc == maxc)
	  {
	     SLsmg_gotorc (r, c);
	     SLsmg_write_nchars (s, dc + 1);
	     if (dr == 1) break;

	     r++;
	     dc = 0;
	     dr--;
	     s = p;
	  }
	else dc++;
     }
}

int SLsmg_Tab_Width = 8;

/* Minimum value for which eight bit char is displayed as is. */

#ifndef IBMPC_SYSTEM
int SLsmg_Display_Eight_Bit = 160;
static unsigned char Alt_Char_Set[129];/* 129th is used as a flag */
#else
int SLsmg_Display_Eight_Bit = 128;
#endif

void SLsmg_write_nchars (char *str, unsigned int n)
{
   register SLsmg_Char_Type *p, old, neew, color;
   unsigned char ch;
   unsigned int flags;
   int len, start_len, max_len;
   char *str_max;
   int newline_flag;
#ifndef IBMPC_SYSTEM
   int alt_char_set_flag;

   alt_char_set_flag = ((This_Color & ALT_CHAR_FLAG)
			&& ((tt_Use_Blink_For_ACS == NULL)
			    || (*tt_Use_Blink_For_ACS == 0)));
#endif

   if (Smg_Inited == 0) return;

   str_max = str + n;
   color = This_Color;

   top:				       /* get here only on newline */

   newline_flag = 0;
   start_len = Start_Col;

   if (point_visible (0) == 0) return;

   len = This_Col;
   max_len = start_len + Screen_Cols;

   p = SL_Screen[This_Row - Start_Row].neew;
   if (len > start_len) p += (len - start_len);

   flags = SL_Screen[This_Row - Start_Row].flags;
   while ((len < max_len) && (str < str_max))
     {
	ch = (unsigned char) *str++;

#ifndef IBMPC_SYSTEM
	if (alt_char_set_flag)
	  ch = Alt_Char_Set [ch & 0x7F];
#endif
	if (((ch >= ' ') && (ch < 127))
	    || (ch >= (unsigned char) SLsmg_Display_Eight_Bit)
#ifndef IBMPC_SYSTEM
	    || alt_char_set_flag
#endif
	    )
	  {
	     len += 1;
	     if (len > start_len)
	       {
		  old = *p;
		  neew = SLSMG_BUILD_CHAR(ch,color);
		  if (old != neew)
		    {
		       flags |= TOUCHED;
		       *p = neew;
		    }
		  p++;
	       }
	  }

	else if ((ch == '\t') && (SLsmg_Tab_Width > 0))
	  {
	     n = len;
	     n += SLsmg_Tab_Width;
	     n = SLsmg_Tab_Width - (n % SLsmg_Tab_Width);
	     if ((unsigned int) len + n > (unsigned int) max_len)
	       n = (unsigned int) (max_len - len);
	     neew = SLSMG_BUILD_CHAR(' ',color);
	     while (n--)
	       {
		  len += 1;
		  if (len > start_len)
		    {
		       if (*p != neew)
			 {
			    flags |= TOUCHED;
			    *p = neew;
			 }
		       p++;
		    }
	       }
	  }
	else if ((ch == '\n')
		 && (SLsmg_Newline_Behavior != SLSMG_NEWLINE_PRINTABLE))
	  {
	     newline_flag = 1;
	     break;
	  }
	else if ((ch == 0x8) && SLsmg_Backspace_Moves)
	  {
	     if (len != 0) len--;
	  }
	else
	  {
	     if (ch & 0x80)
	       {
		  neew = SLSMG_BUILD_CHAR('~',color);
		  len += 1;
		  if (len > start_len)
		    {
		       if (*p != neew)
			 {
			    *p = neew;
			    flags |= TOUCHED;
			 }
		       p++;
		       if (len == max_len) break;
		       ch &= 0x7F;
		    }
	       }

	     len += 1;
	     if (len > start_len)
	       {
		  neew = SLSMG_BUILD_CHAR('^',color);
		  if (*p != neew)
		    {
		       *p = neew;
		       flags |= TOUCHED;
		    }
		  p++;
		  if (len == max_len) break;
	       }

	     if (ch == 127) ch = '?'; else ch = ch + '@';
	     len++;
	     if (len > start_len)
	       {
		  neew = SLSMG_BUILD_CHAR(ch,color);
		  if (*p != neew)
		    {
		       *p = neew;
		       flags |= TOUCHED;
		    }
		  p++;
	       }
	  }
     }

   SL_Screen[This_Row - Start_Row].flags = flags;
   This_Col = len;

   if (SLsmg_Newline_Behavior == 0)
     return;

   if (newline_flag == 0)
     {
	while (str < str_max)
	  {
	     if (*str == '\n') break;
	     str++;
	  }
	if (str == str_max) return;
	str++;
     }

   This_Row++;
   This_Col = 0;
   if (This_Row == Start_Row + Screen_Rows)
     {
	if (SLsmg_Newline_Behavior == SLSMG_NEWLINE_SCROLLS) scroll_up ();
     }
   goto top;
}

void SLsmg_write_char (char ch)
{
   SLsmg_write_nchars (&ch, 1);
}

static int Cls_Flag;

void SLsmg_cls (void)
{
   int tac;
   if (Smg_Inited == 0) return;

   tac = This_Alt_Char; This_Alt_Char = 0;
   SLsmg_set_color (0);
   clear_region (0, Screen_Rows);
   This_Alt_Char = tac;
   SLsmg_set_color (0);
   Cls_Flag = 1;
}
#if 0
static void do_copy (SLsmg_Char_Type *a, SLsmg_Char_Type *b)
{
   SLsmg_Char_Type *amax = a + Screen_Cols;

   while (a < amax) *a++ = *b++;
}
#endif

#ifndef IBMPC_SYSTEM
int SLsmg_Scroll_Hash_Border = 0;
static unsigned long compute_hash (SLsmg_Char_Type *s, int n)
{
   register unsigned long h = 0, g;
   register unsigned long sum = 0;
   register SLsmg_Char_Type *smax, ch;
   int is_blank = 2;

   s += SLsmg_Scroll_Hash_Border;
   smax = s + (n - SLsmg_Scroll_Hash_Border);
   while (s < smax)
     {
	ch = *s++;
	if (is_blank && (SLSMG_EXTRACT_CHAR(ch) != 32)) is_blank--;

	sum += ch;

	h = sum + (h << 3);
	if ((g = h & 0xE0000000UL) != 0)
	  {
	     h = h ^ (g >> 24);
	     h = h ^ g;
	  }
     }
   if (is_blank) return 0;
   return h;
}

static unsigned long Blank_Hash;

static int try_scroll_down (int rmin, int rmax)
{
   int i, r1, r2, di, j;
   unsigned long hash;
   int did_scroll;
   int color;
   SLsmg_Char_Type *tmp;
   int ignore;

   did_scroll = 0;
   for (i = rmax; i > rmin; i--)
     {
	hash = SL_Screen[i].new_hash;
	if (hash == Blank_Hash) continue;

	if ((hash == SL_Screen[i].old_hash)
#if 0
	    || ((i + 1 < Screen_Rows) && (hash == SL_Screen[i + 1].old_hash))
	    || ((i - 1 > rmin) && (SL_Screen[i].old_hash == SL_Screen[i - 1].new_hash))
#endif
	    )
	  continue;

	for (j = i - 1; j >= rmin; j--)
	  {
	     if (hash == SL_Screen[j].old_hash) break;
	  }
	if (j < rmin) continue;

	r2 = i;			       /* end scroll region */

	di = i - j;
	j--;
	ignore = 0;
	while ((j >= rmin) && (SL_Screen[j].old_hash == SL_Screen[j + di].new_hash))
	  {
	     if (SL_Screen[j].old_hash == Blank_Hash) ignore++;
	     j--;
	  }
	r1 = j + 1;

	/* If this scroll only scrolls this line into place, don't do it.
	 */
	if ((di > 1) && (r1 + di + ignore == r2)) continue;

	/* If there is anything in the scrolling region that is ok, abort the
	 * scroll.
	 */

	for (j = r1; j <= r2; j++)
	  {
	     if ((SL_Screen[j].old_hash != Blank_Hash)
		 && (SL_Screen[j].old_hash == SL_Screen[j].new_hash))
	       {
		  /* See if the scroll is happens to scroll this one into place. */
		  if ((j + di > r2) || (SL_Screen[j].old_hash != SL_Screen[j + di].new_hash))
		    break;
	       }
	  }
	if (j <= r2) continue;

	color = This_Color;  This_Color = 0;
	did_scroll = 1;
	(*tt_normal_video) ();
	(*tt_set_scroll_region) (r1, r2);
	(*tt_goto_rc) (0, 0);
	(*tt_reverse_index) (di);
	(*tt_reset_scroll_region) ();
	/* Now we have a hole in the screen.
	 * Make the virtual screen look like it.
	 * 
	 * Note that if the terminal does not support BCE, then we have
	 * no idea what color the hole is.  So, for this case, we do not
	 * want to add Bce_Color_Offset to This_Color since if Bce_Color_Offset
	 * is non-zero, then This_Color = 0 does not match any valid color
	 * obtained by adding Bce_Color_Offset.
	 */
	for (j = r1; j <= r2; j++) SL_Screen[j].flags = TOUCHED;

	while (di--)
	  {
	     tmp = SL_Screen[r2].old;
	     for (j = r2; j > r1; j--)
	       {
		  SL_Screen[j].old = SL_Screen[j - 1].old;
		  SL_Screen[j].old_hash = SL_Screen[j - 1].old_hash;
	       }
	     SL_Screen[r1].old = tmp;
	     blank_line (SL_Screen[r1].old, Screen_Cols, ' ');
	     SL_Screen[r1].old_hash = Blank_Hash;
	     r1++;
	  }
	This_Color = color;
     }

   return did_scroll;
}

static int try_scroll_up (int rmin, int rmax)
{
   int i, r1, r2, di, j;
   unsigned long hash;
   int did_scroll;
   int color;
   SLsmg_Char_Type *tmp;
   int ignore;

   did_scroll = 0;
   for (i = rmin; i < rmax; i++)
     {
	hash = SL_Screen[i].new_hash;
	if (hash == Blank_Hash) continue;
	if (hash == SL_Screen[i].old_hash)
	  continue;
	/* find a match further down screen */
	for (j = i + 1; j <= rmax; j++)
	  {
	     if (hash == SL_Screen[j].old_hash) break;
	  }
	if (j > rmax) continue;

	r1 = i;			       /* beg scroll region */
	di = j - i;		       /* number of lines to scroll */
	j++;			       /* since we know this is a match */

	/* find end of scroll region */
	ignore = 0;
	while ((j <= rmax) && (SL_Screen[j].old_hash == SL_Screen[j - di].new_hash))
	  {
	     if (SL_Screen[j].old_hash == Blank_Hash) ignore++;
	     j++;
	  }
	r2 = j - 1;		       /* end of scroll region */

	/* If this scroll only scrolls this line into place, don't do it.
	 */
	if ((di > 1) && (r1 + di + ignore == r2)) continue;

	/* If there is anything in the scrolling region that is ok, abort the
	 * scroll.
	 */

	for (j = r1; j <= r2; j++)
	  {
	     if ((SL_Screen[j].old_hash != Blank_Hash)
		 && (SL_Screen[j].old_hash == SL_Screen[j].new_hash))
	       {
		  if ((j - di < r1) || (SL_Screen[j].old_hash != SL_Screen[j - di].new_hash))
		    break;
	       }

	  }
	if (j <= r2) continue;

	did_scroll = 1;

	/* See the above comments about BCE */
	color = This_Color;  This_Color = 0;
	(*tt_normal_video) ();
	(*tt_set_scroll_region) (r1, r2);
	(*tt_goto_rc) (0, 0);	       /* relative to scroll region */
	(*tt_delete_nlines) (di);
	(*tt_reset_scroll_region) ();
	/* Now we have a hole in the screen.  Make the virtual screen look
	 * like it.
	 */
	for (j = r1; j <= r2; j++) SL_Screen[j].flags = TOUCHED;

	while (di--)
	  {
	     tmp = SL_Screen[r1].old;
	     for (j = r1; j < r2; j++)
	       {
		  SL_Screen[j].old = SL_Screen[j + 1].old;
		  SL_Screen[j].old_hash = SL_Screen[j + 1].old_hash;
	       }
	     SL_Screen[r2].old = tmp;
	     blank_line (SL_Screen[r2].old, Screen_Cols, ' ');
	     SL_Screen[r2].old_hash = Blank_Hash;
	     r2--;
	  }
	This_Color = color;
     }
   return did_scroll;
}

static void try_scroll (void)
{
   int r1, rmin, rmax;
   int num_up, num_down;
   /* find region limits. */

   for (rmax = Screen_Rows - 1; rmax > 0; rmax--)
     {
	if (SL_Screen[rmax].new_hash != SL_Screen[rmax].old_hash)
	  {
	     r1 = rmax - 1;
	     if ((r1 == 0)
		 || (SL_Screen[r1].new_hash != SL_Screen[r1].old_hash))
	       break;

	     rmax = r1;
	  }
     }

   for (rmin = 0; rmin < rmax; rmin++)
     {
	if (SL_Screen[rmin].new_hash != SL_Screen[rmin].old_hash)
	  {
	     r1 = rmin + 1;
	     if ((r1 == rmax)
		 || (SL_Screen[r1].new_hash != SL_Screen[r1].old_hash))
	       break;

	     rmin = r1;
	  }
     }

   /* Below, we have two scrolling algorithms.  The first has the effect of
    * scrolling lines down.  This is usually appropriate when one moves
    * up the display, e.g., with the UP arrow.  The second algorithm is
    * appropriate for going the other way.  It is important to choose the
    * correct one.
    */

   num_up = 0;
   for (r1 = rmin; r1 < rmax; r1++)
     {
	if (SL_Screen[r1].new_hash == SL_Screen[r1 + 1].old_hash)
	  num_up++;
     }

   num_down = 0;
   for (r1 = rmax; r1 > rmin; r1--)
     {
	if (SL_Screen[r1 - 1].old_hash == SL_Screen[r1].new_hash)
	  num_down++;
     }

   if (num_up > num_down)
     {
	if (try_scroll_up (rmin, rmax))
	  return;

	(void) try_scroll_down (rmin, rmax);
     }
   else
     {
	if (try_scroll_down (rmin, rmax))
	  return;

	(void) try_scroll_up (rmin, rmax);
     }
}
#endif   /* NOT IBMPC_SYSTEM */


#ifdef REQUIRES_NON_BCE_SUPPORT
static void adjust_colors (void)
{
   int bce;
   int i;

   bce = Bce_Color_Offset;
   Bce_Color_Offset = _SLtt_get_bce_color_offset ();
   if (bce == Bce_Color_Offset)
     return;
   
  if ((tt_Use_Blink_For_ACS != NULL)
       && (*tt_Use_Blink_For_ACS != 0))
     return;			       /* this mode does not support non-BCE
					* terminals.
					*/

   for (i = 0; i < Screen_Rows; i++)
     {
	SLsmg_Char_Type *s, *smax;

	SL_Screen[i].flags |= TRASHED;
	s = SL_Screen[i].neew;
	smax = s + Screen_Cols;
	
	while (s < smax)
	  {
	     int color = (int) SLSMG_EXTRACT_COLOR(*s);
	     int acs;

	     if (color < 0)
	       {
		  s++;
		  continue;
	       }
	     
	     acs = color & 0x80;
	     color = (color & 0x7F) - bce;
	     color += Bce_Color_Offset;
	     if (color >= 0)
	       {
		  unsigned char ch = SLSMG_EXTRACT_CHAR(*s);
		  *s = SLSMG_BUILD_CHAR(ch, ((color&0x7F)|acs));
	       }
	     s++;
	  }
     }
}
#endif

void SLsmg_refresh (void)
{
   int i;
#ifndef IBMPC_SYSTEM
   int trashed = 0;
#endif

   if (Smg_Inited == 0) return;
   
   if (Screen_Trashed)
     {
	Cls_Flag = 1;
	for (i = 0; i < Screen_Rows; i++)
	  SL_Screen[i].flags |= TRASHED;
#ifdef REQUIRES_NON_BCE_SUPPORT
	adjust_colors ();
#endif
     }

#ifndef IBMPC_SYSTEM
   for (i = 0; i < Screen_Rows; i++)
     {
	if (SL_Screen[i].flags == 0) continue;
	SL_Screen[i].new_hash = compute_hash (SL_Screen[i].neew, Screen_Cols);
	trashed = 1;
     }
#endif

   if (Cls_Flag)
     {
	(*tt_normal_video) ();  (*tt_cls) ();
     }
#ifndef IBMPC_SYSTEM
   else if (trashed && (*tt_Term_Cannot_Scroll == 0)) try_scroll ();
#endif

   for (i = 0; i < Screen_Rows; i++)
     {
	if (SL_Screen[i].flags == 0) continue;

	if (Cls_Flag || SL_Screen[i].flags & TRASHED)
	  {
	     int color = This_Color;

	     if (Cls_Flag == 0) 
	       {
		  (*tt_goto_rc) (i, 0);
		  (*tt_del_eol) ();
	       }
	     This_Color = 0;
	     blank_line (SL_Screen[i].old, Screen_Cols, ' ');
	     This_Color = color;
	  }

	SL_Screen[i].old[Screen_Cols] = 0;
	SL_Screen[i].neew[Screen_Cols] = 0;

	(*tt_smart_puts) (SL_Screen[i].neew, SL_Screen[i].old, Screen_Cols, i);

	SLMEMCPY ((char *) SL_Screen[i].old, (char *) SL_Screen[i].neew,
		  Screen_Cols * sizeof (SLsmg_Char_Type));

	SL_Screen[i].flags = 0;
#ifndef IBMPC_SYSTEM
	SL_Screen[i].old_hash = SL_Screen[i].new_hash;
#endif
     }

   if (point_visible (1)) (*tt_goto_rc) (This_Row - Start_Row, This_Col - Start_Col);
   (*tt_flush_output) ();
   Cls_Flag = 0;
   Screen_Trashed = 0;
}

static int compute_clip (int row, int n, int box_start, int box_end,
			 int *rmin, int *rmax)
{
   int row_max;

   if (n < 0) return 0;
   if (row >= box_end) return 0;
   row_max = row + n;
   if (row_max <= box_start) return 0;

   if (row < box_start) row = box_start;
   if (row_max >= box_end) row_max = box_end;
   *rmin = row;
   *rmax = row_max;
   return 1;
}

void SLsmg_touch_lines (int row, unsigned int n)
{
   int i;
   int r1, r2;

   /* Allow this function to be called even when we are not initialied.
    * Calling this function is useful after calling SLtt_set_color
    * to force the display to be redrawn
    */

   if (Smg_Inited == 0)
     return;

   if (0 == compute_clip (row, (int) n, Start_Row, Start_Row + Screen_Rows, &r1, &r2))
     return;

   r1 -= Start_Row;
   r2 -= Start_Row;
   for (i = r1; i < r2; i++)
     {
	SL_Screen[i].flags |= TRASHED;
     }
}

void SLsmg_touch_screen (void)
{
   Screen_Trashed = 1;
}

			  
#ifndef IBMPC_SYSTEM
static char Fake_Alt_Char_Pairs [] = "a:j+k+l+m+q-t+u+v+w+x|n+`+f\\g#~o,<+>.v-^h#0#";

static void init_alt_char_set (void)
{
   int i;
   unsigned char *p, *pmax, ch;

   if (Alt_Char_Set[128] == 128) return;

   i = 32;
   memset ((char *)Alt_Char_Set, ' ', i);
   while (i <= 128)
     {
	Alt_Char_Set [i] = i;
	i++;
     }

   /* Map to VT100 */
   if (*tt_Has_Alt_Charset)
     {
	if (tt_Graphics_Char_Pairs == NULL) p = NULL;
	else p = (unsigned char *) *tt_Graphics_Char_Pairs;
	if (p == NULL) return;
     }
   else	p = (unsigned char *) Fake_Alt_Char_Pairs;
   pmax = p + strlen ((char *) p);

   /* Some systems have messed up entries for this */
   while (p < pmax)
     {
	ch = *p++;
	ch &= 0x7F;		       /* should be unnecessary */
	Alt_Char_Set [ch] = *p;
	p++;
     }
}
#endif

#ifndef IBMPC_SYSTEM
# define BLOCK_SIGNALS SLsig_block_signals ()
# define UNBLOCK_SIGNALS SLsig_unblock_signals ()
#else
# define BLOCK_SIGNALS (void)0
# define UNBLOCK_SIGNALS (void)0
#endif

static int Smg_Suspended;
int SLsmg_suspend_smg (void)
{
   BLOCK_SIGNALS;

   if (Smg_Suspended == 0)
     {
	(*tt_reset_video) ();
	Smg_Suspended = 1;
     }

   UNBLOCK_SIGNALS;
   return 0;
}

int SLsmg_resume_smg (void)
{
   BLOCK_SIGNALS;

   if (Smg_Suspended == 0)
     {
	UNBLOCK_SIGNALS;
	return 0;
     }

   Smg_Suspended = 0;

   if (-1 == (*tt_init_video) ())
     {
	UNBLOCK_SIGNALS;
	return -1;
     }

   Cls_Flag = 1;
   SLsmg_touch_screen ();
   SLsmg_refresh ();

   UNBLOCK_SIGNALS;
   return 0;
}

   
static void reset_smg (void)
{
   int i;
   if (Smg_Inited == 0)
     return;

   for (i = 0; i < Screen_Rows; i++)
     {
	SLfree ((char *)SL_Screen[i].old);
	SLfree ((char *)SL_Screen[i].neew);
	SL_Screen[i].old = SL_Screen[i].neew = NULL;
     }
   This_Alt_Char = This_Color = 0;
   Smg_Inited = 0;
}


static int init_smg (void)
{
   int i, len;
   SLsmg_Char_Type *old, *neew;

   Smg_Inited = 0;

#ifdef REQUIRES_NON_BCE_SUPPORT
   Bce_Color_Offset = _SLtt_get_bce_color_offset ();
#endif

   Screen_Rows = *tt_Screen_Rows;
   if (Screen_Rows > MAX_SCREEN_SIZE)
     Screen_Rows = MAX_SCREEN_SIZE;

   Screen_Cols = *tt_Screen_Cols;

   This_Col = This_Row = Start_Col = Start_Row = 0;

   This_Alt_Char = 0;
   SLsmg_set_color (0);
   Cls_Flag = 1;
#ifndef IBMPC_SYSTEM
   init_alt_char_set ();
#endif
   len = Screen_Cols + 3;
   for (i = 0; i < Screen_Rows; i++)
     {
	if ((NULL == (old = (SLsmg_Char_Type *) SLmalloc (sizeof(SLsmg_Char_Type) * len)))
	    || ((NULL == (neew = (SLsmg_Char_Type *) SLmalloc (sizeof(SLsmg_Char_Type) * len)))))
	  {
	     SLfree ((char *) old);
	     return -1;
	  }
	blank_line (old, len, ' ');
	blank_line (neew, len, ' ');
	SL_Screen[i].old = old;
	SL_Screen[i].neew = neew;
	SL_Screen[i].flags = 0;
#ifndef IBMPC_SYSTEM
	Blank_Hash = compute_hash (old, Screen_Cols);
	SL_Screen[i].new_hash = SL_Screen[i].old_hash =  Blank_Hash;
#endif
     }
   
   _SLtt_color_changed_hook = SLsmg_touch_screen;
   Screen_Trashed = 1;
   Smg_Inited = 1;
   return 0;
}


int SLsmg_init_smg (void)
{
   int ret;

   BLOCK_SIGNALS;

   if (Smg_Inited)
     SLsmg_reset_smg ();

   if (-1 == (*tt_init_video) ())
     {
	UNBLOCK_SIGNALS;
	return -1;
     }
   
   if (-1 == (ret = init_smg ()))
     (void) (*tt_reset_video)();

   UNBLOCK_SIGNALS;
   return ret;
}

int SLsmg_reinit_smg (void)
{
   int ret;

   if (Smg_Inited == 0)
     return SLsmg_init_smg ();

   BLOCK_SIGNALS;
   reset_smg ();
   ret = init_smg ();
   UNBLOCK_SIGNALS;
   return ret;
}

void SLsmg_reset_smg (void)
{   
   if (Smg_Inited == 0)
     return;
   
   BLOCK_SIGNALS;

   reset_smg ();
   (*tt_reset_video)();

   UNBLOCK_SIGNALS;
}

SLsmg_Char_Type SLsmg_char_at (void)
{
   if (Smg_Inited == 0) return 0;

   if (point_visible (1))
     {
	return SL_Screen[This_Row - Start_Row].neew[This_Col - Start_Col];
     }
   return 0;
}

void SLsmg_vprintf (char *fmt, va_list ap)
{
   char buf[1024];

   if (Smg_Inited == 0) return;

   (void) _SLvsnprintf (buf, sizeof (buf), fmt, ap);
   SLsmg_write_string (buf);
}

void SLsmg_printf (char *fmt, ...)
{
   va_list ap;
   unsigned int len;
   char *f;

   if (Smg_Inited == 0) return;

   va_start(ap, fmt);

   f = fmt;
   while (*f && (*f != '%'))
     f++;
   len = (unsigned int) (f - fmt);
   if (len) SLsmg_write_nchars (fmt, len);

   if (*f != 0)
     SLsmg_vprintf (f, ap);

   va_end (ap);
}

void SLsmg_set_screen_start (int *r, int *c)
{
   int orow = Start_Row, oc = Start_Col;

   if (Smg_Inited == 0) return;

   if (c == NULL) Start_Col = 0;
   else
     {
	Start_Col = *c;
	*c = oc;
     }
   if (r == NULL) Start_Row = 0;
   else
     {
	Start_Row = *r;
	*r = orow;
     }
}

void SLsmg_draw_object (int r, int c, unsigned char object)
{
   This_Row = r;  This_Col = c;

   if (Smg_Inited == 0) return;

   if (point_visible (1))
     {
	int color = This_Color;
	This_Color |= ALT_CHAR_FLAG;
	SLsmg_write_char (object);
	This_Color = color;
     }

   This_Col = c + 1;
}

void SLsmg_draw_hline (unsigned int n)
{
   static unsigned char hbuf[16];
   int count;
   int cmin, cmax;
   int final_col = This_Col + (int) n;
   int save_color;

   if (Smg_Inited == 0) return;

   if ((This_Row < Start_Row) || (This_Row >= Start_Row + Screen_Rows)
       || (0 == compute_clip (This_Col, n, Start_Col, Start_Col + Screen_Cols,
			      &cmin, &cmax)))
     {
	This_Col = final_col;
	return;
     }

   if (hbuf[0] == 0)
     {
	SLMEMSET ((char *) hbuf, SLSMG_HLINE_CHAR, 16);
     }

   n = (unsigned int)(cmax - cmin);
   count = n / 16;

   save_color = This_Color;
   This_Color |= ALT_CHAR_FLAG;
   This_Col = cmin;

   SLsmg_write_nchars ((char *) hbuf, n % 16);
   while (count-- > 0)
     {
	SLsmg_write_nchars ((char *) hbuf, 16);
     }

   This_Color = save_color;
   This_Col = final_col;
}

void SLsmg_draw_vline (int n)
{
   unsigned char ch = SLSMG_VLINE_CHAR;
   int c = This_Col, rmin, rmax;
   int final_row = This_Row + n;
   int save_color;