text:
package route

import (
	"fmt"

	"github.com/blang/semver"
	"github.com/cloudfoundry/cli/cf"
	"github.com/cloudfoundry/cli/cf/api"
	"github.com/cloudfoundry/cli/cf/commandregistry"
	"github.com/cloudfoundry/cli/cf/configuration/coreconfig"
	"github.com/cloudfoundry/cli/cf/errors"
	. "github.com/cloudfoundry/cli/cf/i18n"
	"github.com/cloudfoundry/cli/cf/models"
	"github.com/cloudfoundry/cli/cf/requirements"
	"github.com/cloudfoundry/cli/cf/terminal"
	"github.com/cloudfoundry/cli/flags"
)

type DeleteRoute struct {
	ui        terminal.UI
	config    coreconfig.Reader
	routeRepo api.RouteRepository
	domainReq requirements.DomainRequirement
}

func init() {
	commandregistry.Register(&DeleteRoute{})
}

func (cmd *DeleteRoute) MetaData() commandregistry.CommandMetadata {
	fs := make(map[string]flags.FlagSet)
	fs["f"] = &flags.BoolFlag{ShortName: "f", Usage: T("Force deletion without confirmation")}
	fs["hostname"] = &flags.StringFlag{Name: "hostname", ShortName: "n", Usage: T("Hostname used to identify the HTTP route")}
	fs["path"] = &flags.StringFlag{Name: "path", Usage: T("Path used to identify the HTTP route")}
	fs["port"] = &flags.IntFlag{Name: "port", Usage: T("Port used to identify the TCP route")}

	return commandregistry.CommandMetadata{
		Name:        "delete-route",
		Description: T("Delete a route"),
		Usage: []string{
			fmt.Sprintf("%s:\n", T("Delete an HTTP route")),
			"      CF_NAME delete-route ",
			fmt.Sprintf("%s ", T("DOMAIN")),
			fmt.Sprintf("[--hostname %s] ", T("HOSTNAME")),
			fmt.Sprintf("[--path %s] [-f]\n\n", T("PATH")),
			fmt.Sprintf("   %s:\n", T("Delete a TCP route")),
			"      CF_NAME delete-route ",
			fmt.Sprintf("%s ", T("DOMAIN")),
			fmt.Sprintf("--port %s [-f]", T("PORT")),
		},
		Examples: []string{
			"CF_NAME delete-route example.com                              # example.com",
			"CF_NAME delete-route example.com --hostname myhost            # myhost.example.com",
			"CF_NAME delete-route example.com --hostname myhost --path foo # myhost.example.com/foo",
			"CF_NAME delete-route example.com --port 50000                 # example.com:50000",
		},
		Flags: fs,
	}
}

func (cmd *DeleteRoute) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) []requirements.Requirement {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("delete-route"))
	}

	if fc.IsSet("port") && (fc.IsSet("hostname") || fc.IsSet("path")) {
		cmd.ui.Failed(T("Cannot specify port together with hostname and/or path."))
	}

	cmd.domainReq = requirementsFactory.NewDomainRequirement(fc.Args()[0])

	requiredVersion, err := semver.Make("2.36.0")
	if err != nil {
		panic(err.Error())
	}

	var reqs []requirements.Requirement

	if fc.String("path") != "" {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--path'", requiredVersion))
	}

	if fc.IsSet("port") {
		reqs = append(reqs, requirementsFactory.NewMinAPIVersionRequirement("Option '--port'", cf.TcpRoutingMinimumAPIVersion))
	}

	reqs = append(reqs, []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		cmd.domainReq,
	}...)

	return reqs
}

func (cmd *DeleteRoute) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command {
	cmd.ui = deps.UI
	cmd.config = deps.Config
	cmd.routeRepo = deps.RepoLocator.GetRouteRepository()
	return cmd
}

func (cmd *DeleteRoute) Execute(c flags.FlagContext) {
	host := c.String("n")
	path := c.String("path")
	domainName := c.Args()[0]
	port := c.Int("port")

	url := (&models.RoutePresenter{
		Host:   host,
		Domain: domainName,
		Path:   path,
		Port:   port,
	}).URL()

	if !c.Bool("f") {
		if !cmd.ui.ConfirmDelete("route", url) {
			return
		}
	}

	cmd.ui.Say(T("Deleting route {{.URL}}...", map[string]interface{}{"URL": terminal.EntityNameColor(url)}))

	domain := cmd.domainReq.GetDomain()
	route, err := cmd.routeRepo.Find(host, domain, path, port)
	if err != nil {
		if _, ok := err.(*errors.ModelNotFoundError); ok {
			cmd.ui.Warn(T("Unable to delete, route '{{.URL}}' does not exist.",
				map[string]interface{}{"URL": url}))
			return
		}
		cmd.ui.Failed(err.Error())
		return
	}

	err = cmd.routeRepo.Delete(route.GUID)
	if err != nil {
		cmd.ui.Failed(err.Error())
		return
	}

	cmd.ui.Ok()
}


text:
Redefining language constructs like die(), echo, require_once etc. (https://github.com/antecedent/patchwork/issues/59)

--SKIPIF--
<?php !defined('HHVM_VERSION')
      or die('skip because the redefinition of language constructs is not yet implemented for HHVM') ?>

--FILE--
<?php

namespace Patchwork;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 1);
error_reporting(E_ALL | E_STRICT);

$_SERVER['PHP_SELF'] = __FILE__;

require __DIR__ . "/../Patchwork.php";

$calls = [
    'die' => [],
    'exit' => [],
    'echo' => [],
    'print' => [],
];

function collect(array &$collection)
{
    return function() use (&$collection) {
        $collection[] = func_get_args();
    };
}

redefine('die', collect($calls['die']));
redefine('exit', collect($calls['exit']));
redefine('echo', collect($calls['echo']));
redefine('print', collect($calls['print']));

require __DIR__ . "/includes/LanguageConstructUsages.php";

assert($calls['die'] == [
    [],
    [],
    [],
]);

assert($calls['exit'] == [
    ['error'],
]);

assert($calls['echo'] == [
    ['This is a string'],
    ['This is a string', ' and this is another one'],
    ['Hello ', 'world'],
]);

assert($calls['print'] == [
    [404],
]);

?>
===DONE===

--EXPECT--
===DONE===

redpajama_set_name: RedPajamaGithub


text:
package jsettlers.main.android.core.controls;

import jsettlers.common.player.IInGamePlayer;
import jsettlers.graphics.map.MapContent;
import jsettlers.main.android.core.GameManager;

import android.app.Activity;

/**
 * Created by tompr on 13/01/2017.
 */
public class ControlsResolver {
	private final ControlsAdapter controlsAdapter;

	public ControlsResolver(Activity activity) {
		this.controlsAdapter = ((GameManager) activity.getApplication()).getControlsAdapter();
	}

	public ActionControls getActionControls() {
		return controlsAdapter;
	}

	public DrawControls getDrawControls() {
		return controlsAdapter;
	}

	public SelectionControls getSelectionControls() {
		return controlsAdapter;
	}

	public TaskControls getTaskControls() {
		return controlsAdapter;
	}

	public MapContent getMapContent() {
		return controlsAdapter.getMapContent();
	}

	public GameMenu getGameMenu() {
		return controlsAdapter.getGameMenu();
	}

    public PositionControls getPositionControls() {
        return controlsAdapter;
    }

    public IInGamePlayer getPlayer() {
		return controlsAdapter.getInGamePlayer();
	}
}


text:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta http-equiv="X-UA-Compatible" content="chrome=1">

    <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
    <link rel="stylesheet" type="text/css" href="stylesheets/github-dark.css" media="screen">
    <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">

    <title>Per Henrik Lausten by perlausten</title>

perlausten

Per Henrik Lausten

          View on GitHub

Per Henrik Lausten

Bio

Per Henrik Lausten is an independent web developer with his own one-man company in Denmark. He builds solutions for web, tablets and mobile primarily using Java and Javascript.

Current roles

Web developer at PHL Consult.
Web developer at Sherlock Web.
Web developer at fmcg solutions.

Blog

Per Henrik Lausten blogs at per.lausten.dk/blog.


text:
from __future__ import unicode_literals

from django.db import models, migrations
import datetime
from django.conf import settings
from django.utils.timezone import utc

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0002_userprofile'),
    ]

    operations = [
        migrations.CreateModel(
            name='Membership',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('date_end', models.DateTimeField(default=datetime.datetime(2015, 2, 3, 3, 28, 16, 186674, tzinfo=utc))),
                ('date_start', models.DateTimeField(default=datetime.datetime(2015, 2, 3, 3, 28, 16, 186899, tzinfo=utc))),
                ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
class Term < ActiveRecord::Base
  belongs_to :school
  has_many :courses, dependent: :restrict_with_error
  validates :name, presence: true
  validates :school_id, presence: true
  validates :starts_on, presence: true
  validates :ends_on, presence: true
  default_scope { order('ends_on DESC') }

  scope :for_school_id, ->(school_id) { where("school_id = ?", school_id) }

  def school_name
    school ? school.name : "None"
  end
end


text:
import numpy as np
import pytest

import pandas as pd
import pandas.util.testing as tm

@pytest.mark.filterwarnings("ignore:Sparse:FutureWarning")
@pytest.mark.filterwarnings("ignore:Series.to_sparse:FutureWarning")
@pytest.mark.filterwarnings("ignore:DataFrame.to_sparse:FutureWarning")
class TestPivotTable:

    def setup_method(self, method):
        self.dense = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
                                         'foo', 'bar', 'foo', 'foo'],
                                   'B': ['one', 'one', 'two', 'three',
                                         'two', 'two', 'one', 'three'],
                                   'C': np.random.randn(8),
                                   'D': np.random.randn(8),
                                   'E': [np.nan, np.nan, 1, 2,
                                         np.nan, 1, np.nan, np.nan]})
        self.sparse = self.dense.to_sparse()

    def test_pivot_table(self):
        res_sparse = pd.pivot_table(self.sparse, index='A', columns='B',
                                    values='C')
        res_dense = pd.pivot_table(self.dense, index='A', columns='B',
                                   values='C')
        tm.assert_frame_equal(res_sparse, res_dense)

        res_sparse = pd.pivot_table(self.sparse, index='A', columns='B',
                                    values='E')
        res_dense = pd.pivot_table(self.dense, index='A', columns='B',
                                   values='E')
        tm.assert_frame_equal(res_sparse, res_dense)

        res_sparse = pd.pivot_table(self.sparse, index='A', columns='B',
                                    values='E', aggfunc='mean')
        res_dense = pd.pivot_table(self.dense, index='A', columns='B',
                                   values='E', aggfunc='mean')
        tm.assert_frame_equal(res_sparse, res_dense)

        # ToDo: sum doesn't handle nan properly
        # res_sparse = pd.pivot_table(self.sparse, index='A', columns='B',
        #                             values='E', aggfunc='sum')
        # res_dense = pd.pivot_table(self.dense, index='A', columns='B',
        #                            values='E', aggfunc='sum')
        # tm.assert_frame_equal(res_sparse, res_dense)

    def test_pivot_table_multi(self):
        res_sparse = pd.pivot_table(self.sparse, index='A', columns='B',
                                    values=['D', 'E'])
        res_dense = pd.pivot_table(self.dense, index='A', columns='B',
                                   values=['D', 'E'])
        res_dense = res_dense.apply(lambda x: x.astype("Sparse[float64]"))
        tm.assert_frame_equal(res_sparse, res_dense)


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Cyananthus spathulifolius Nannf.

### Remarks
null


text:
Data structure and Algorithm is always important for any programming language. PHP, being one of the most popular language for web development, also requires the pure data structure and algorithm implementations.

In this project, i am trying to cover major data structure and algorithm implementations using PHP 7. For more details discussion about the topics, you can read my book , https://www.amazon.com/PHP-7-Data-Structures-Algorithms/dp/178646389X/

Any feedback, bugs or suggestion will be welcomed.

# Topics covered #

1. Linked List
   - Single Linked list
   - Circular Linked list
   - Doubly Linked List

2. Stacks
   - Stack using Array
   - Stack using Linked List

3. Queues
   - Queue using Array
   - Queue using Linked List
   - Priority Queue
   - Circular Queue
   - Double Ended Queue - DeQueue

4. Trees
   - Generic Tree
   - Binary Tree
   - Binary Search Tree
   - Tree Traversal (In-order, pre-order, post-order)
   - Trie (Simple insert and search operation)

5. Heaps
    - Min Heap
    - Max Heap

6. Graph
    - BFS
    - Bellman Ford Algorithm
    - DFS
    - Dijkstra
    - Floyd Warshall
    - Kruksal
    - Prim Minimum Spanning tree
    - Topological Sorting

7. Sorting
    - Bubble sort
    - Bubble Sort with improvements
    - Bucket sort
    - Heap Sort
    - Insertion Sort
    - Merge Sort
    - Quick Sort
    - Radix Sort
    - Selection Sort

8. Searching
    - BFS
    - Binary Search (Iterative)
    - Binary Search (Recursive)
    - DFS
    - DFS using Stack
    - Exponential Search
    - Interpolation Search
    - Repetitive Binary Search

9. Dynamic Programming and Others
    - Sudoku (Backtracking)
    - Collaborative Filtering
    - DNA Sequencing (NeedlemanWunsch Algorithm)
    - 0/1 KnapSack Dynamic Programming
    - Fibonacci (Recursive)
    - Fibonacci (Memoized)
    - Huffman Encoding (Greedy Algorithm)
    - Job Scheduler (Greedy Algorithm)
    - KMP String matching algorithm
    - Longest Common Subsequences (LCS)
    - Pattern Matching
    - Sparse Array

 10. Numbers and Maths
    - PHP Big Integer Implementation
    - Prime number generation - Sieve

I know lots of things are missing in the list? Would you mind to let me know what you wanna see implemented? I will priortize those and add here.

# Coming Soon #

- AVL tree implemenations
- Project Euler Solutions in PHP for Hackerrank.com
- More algorithms


text:
var Prism = require('Prism');
var React = require('React');
var Site = require('Site');

var index = React.createClass({
  render: function() {
    return (
      <Site>

React Native

              A framework for building native apps using React

            React Native enables you to build world-class application experiences on native platforms using a consistent developer experience based on JavaScript and
            {' '}React{'. '}
            The focus of React Native is on developer efficiency across all the platforms you care about — learn once, write anywhere.
            Facebook uses React Native in multiple production apps and will continue investing in React Native.

            Get started with React Native

Native iOS Components

            With React Native, you can use the standard platform components such as UITabBar and UINavigationController on iOS.  This gives your app a consistent look and feel with the rest of the platform ecosystem, and keeps the quality bar high.  These components are easily incorporated into your app using their React component counterparts, such as TabBarIOS and NavigatorIOS.

          <Prism>
{`var React = require('react-native');
var { TabBarIOS, NavigatorIOS } = React;

var App = React.createClass({
  render: function() {
    return (
      <TabBarIOS>
        <TabBarIOS.Item title="React Native" selected={true}>
          <NavigatorIOS initialRoute={{ title: 'React Native' }} />
        </TabBarIOS.Item>
      </TabBarIOS>
    );
  },
});`}
          </Prism>

Asynchronous Execution

            All operations between the JavaScript application code and the native platform are performed asynchronously, and the native modules can also make use of additional threads as well.  This means we can decode images off of the main thread, save to disk in the background, measure text and compute layouts without blocking the UI, and more.  As a result, React Native apps are naturally fluid and responsive.  The communication is also fully serializable, which allows us to leverage Chrome Developer Tools to debug the JavaScript while running the complete app, either in the simulator or on a physical device.

            See Debugging.

Touch Handling

            iOS has a very powerful system called the Responder Chain to negotiate touches in complex view hierarchies which does not have a universal analog on the web. React Native implements a similar responder system and provides high level components such as TouchableHighlight that integrate properly with scroll views and other elements without any additional configuration.

          <Prism>
{`var React = require('react-native');
var { ScrollView, TouchableHighlight, Text } = React;

var TouchDemo = React.createClass({
  render: function() {
    return (
      <ScrollView>
        <TouchableHighlight onPress={() => console.log('pressed')}>
          <Text>Proper Touch Handling</Text>
        </TouchableHighlight>
      </ScrollView>
    );
  },
});`}
          </Prism>

Flexbox and Styling

            Laying out views should be easy, which is why we brought the flexbox layout model from the web to React Native.  Flexbox makes it simple to build the most common UI layouts, such as stacked and nested boxes with margin and padding.  React Native also supports common web syles, such as fontWeight, and the StyleSheet abstraction provides an optimized mechanism to declare all your styles and layout right along with the components that use them and apply them inline.

          <Prism>
{`var React = require('react-native');
var { Image, StyleSheet, Text, View } = React;

var ReactNative = React.createClass({
  render: function() {
    return (
      <View style={styles.row}>
        <Image
          source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}}
          style={styles.image}
        />
        <View style={styles.text}>
          <Text style={styles.title}>
            React Native
          </Text>
          <Text style={styles.subtitle}>
            Build high quality mobile apps using React
          </Text>
        </View>
      </View>
    );
  },
});
var styles = StyleSheet.create({
  row: { flexDirection: 'row', margin: 40 },
  image: { width: 40, height: 40, marginRight: 10 },
  text: { flex: 1, justifyContent: 'center'},
  title: { fontSize: 11, fontWeight: 'bold' },
  subtitle: { fontSize: 10 },
});`}
          </Prism>

Polyfills

            React Native is focused on changing the way view code is written.  For the rest, we look to the web for universal standards and polyfill those APIs where appropriate. You can use npm to install JavaScript libraries that work on top of the functionality baked into React Native, such as XMLHttpRequest, window.requestAnimationFrame, and navigator.geolocation.  We are working on expanding the available APIs, and are excited for the Open Source community to contribute as well.

          <Prism>
{`var React = require('react-native');
var { Text } = React;

var GeoInfo = React.createClass({
  getInitialState: function() {
    return { position: 'unknown' };
  },
  componentDidMount: function() {
    navigator.geolocation.getCurrentPosition(
      (position) => this.setState({position}),
      (error) => console.error(error)
    );
  },
  render: function() {
    return (
      <Text>
        Position: {JSON.stringify(this.state.position)}
      </Text>
    );
  },
});`}
          </Prism>

Extensibility

            It is certainly possible to create a great app using React Native without writing a single line of native code, but React Native is also designed to be easily extended with custom native views and modules - that means you can reuse anything you{"'"}ve already built, and can import and use your favorite native libraries.  To create a simple module in iOS, create a new class that implements the RCTBridgeModule protocol, and wrap the function that you want to make available to JavaScript in RCT_EXPORT_METHOD. Additionally, the class itself must be explicitly exported with RCT_EXPORT_MODULE();.

          <Prism>
{`// Objective-C

#import "RCTBridgeModule.h"

@interface MyCustomModule : NSObject <RCTBridgeModule>
@end

@implementation MyCustomModule

RCT_EXPORT_MODULE();

// Available as NativeModules.MyCustomModule.processString
RCT_EXPORT_METHOD(processString:(NSString *)input callback:(RCTResponseSenderBlock)callback)
{
  callback(@[[input stringByReplacingOccurrencesOfString:@"Goodbye" withString:@"Hello"];]]);
}
@end`}
          </Prism>
          <Prism>
{`// JavaScript

var React = require('react-native');
var { NativeModules, Text } = React;

var Message = React.createClass({
  render: function() {
    getInitialState() {
      return { text: 'Goodbye World.' };
    },
    componentDidMount() {
      NativeModules.MyCustomModule.processString(this.state.text, (text) => {
        this.setState({text});
      });
    },
    return (
      <Text>{this.state.text}</Text>
    );
  },
});`}
          </Prism>

            Custom iOS views can be exposed by subclassing RCTViewManager, implementing a -(UIView *)view method, and exporting properties with the RCT_EXPORT_VIEW_PROPERTY macro.  Then a simple JavaScript file connects the dots.

          <Prism>
{`// Objective-C

#import "RCTViewManager.h"

@interface MyCustomViewManager : RCTViewManager
@end

@implementation MyCustomViewManager

- (UIView *)view
{
  return [[MyCustomView alloc] init];
}

RCT_EXPORT_VIEW_PROPERTY(myCustomProperty);
@end`}
          </Prism>
          <Prism>
{`// JavaScript

module.exports = createReactIOSNativeComponentClass({
  validAttributes: { myCustomProperty: true },
  uiViewClassName: 'MyCustomView',
});`}
          </Prism>

              Get started with React Native

      </Site>
    );
  }
});

module.exports = index;


text:
package com.emistoolbox.server.renderer.pdfreport.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.emistoolbox.common.renderer.pdfreport.PdfText;
import com.emistoolbox.server.renderer.pdfreport.layout.LayoutFrame;

public abstract class PDFAdvancedReportWriter extends PdfBaseReportWriter {
	private boolean showIds = true;

	public boolean isShowIds () {
		return showIds;
	}

	public void setShowIds (boolean showIds) {
		this.showIds = showIds;
	}

	protected static void updateFrameTitle (LayoutFrame frame,String title) {
		if (!StringUtils.isEmpty(title) && StringUtils.isEmpty(frame.getText(PdfText.TEXT_TITLE)))
			frame.putText(PdfText.TEXT_TITLE, title);
	}

	protected static String newPrefix (String oldPrefix,String newSegment) {
		return oldPrefix == null ? newSegment : oldPrefix + " / " + newSegment;
	}

	protected static <T> int getListSize (List<T> list) {
		return list == null ? 0 : list.size ();
	}
}


text:
import React from 'react';
import './Header.scss';
import MenuNavLink from './MenuNavLink';
import classnames from 'classnames';

const pages = {
    "home" : 0,
    "blog" : 1,
    "about" : 2,
    "kashi" : 3,
    "contact": 4
}

class Header extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            collapsed: false
        };
    }

    render() {
        const activePage = this.props.activePage || -1;
        return

                <MenuNavLink active={activePage === pages["about"]} href="about" title="About this blog">About</MenuNavLink>
                {/* <MenuNavLink active={activePage === pages["kashi"]} href="kashi" title="About Kashi">Kashi</MenuNavLink> */}
                <MenuNavLink active={activePage === pages["contact"]} href="contact" title="Contact Kashi">Contact</MenuNavLink>

    }
}

export default Header;


text:
/*
 *	Virtual memory object module.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/proc.h>		/* for curproc, pageproc */
#include <sys/malloc.h>
#include <sys/vnode.h>
#include <sys/mount.h>
#include <sys/vmmeter.h>
#include <sys/mman.h>

#include <vm/vm.h>
#include <vm/vm_param.h>
#include <vm/vm_prot.h>
#include <vm/lock.h>
#include <vm/pmap.h>
#include <vm/vm_map.h>
#include <vm/vm_object.h>
#include <vm/vm_page.h>
#include <vm/vm_pageout.h>
#include <vm/vm_pager.h>
#include <vm/swap_pager.h>
#include <vm/vm_kern.h>
#include <vm/vm_extern.h>

static void	_vm_object_allocate __P((objtype_t, vm_size_t, vm_object_t));
static void	vm_object_qcollapse __P((vm_object_t object));
#ifdef not_used
static void	vm_object_deactivate_pages __P((vm_object_t));
#endif
static void	vm_object_terminate __P((vm_object_t));
static void	vm_object_cache_trim __P((void));

/*
 *	Virtual memory objects maintain the actual data
 *	associated with allocated virtual memory.  A given
 *	page of memory exists within exactly one object.
 *
 *	An object is only deallocated when all "references"
 *	are given up.  Only one "reference" to a given
 *	region of an object should be writeable.
 *
 *	Associated with each object is a list of all resident
 *	memory pages belonging to that object; this list is
 *	maintained by the "vm_page" module, and locked by the object's
 *	lock.
 *
 *	Each object also records a "pager" routine which is
 *	used to retrieve (and store) pages to the proper backing
 *	storage.  In addition, objects may be backed by other
 *	objects from which they were virtual-copied.
 *
 *	The only items within the object structure which are
 *	modified after time of creation are:
 *		reference count		locked by object's lock
 *		pager routine		locked by object's lock
 *
 */

int vm_object_cache_max;
struct object_q vm_object_cached_list;
static int vm_object_cached;
struct object_q vm_object_list;
static long vm_object_count;
vm_object_t kernel_object;
vm_object_t kmem_object;
static struct vm_object kernel_object_store;
static struct vm_object kmem_object_store;
extern int vm_pageout_page_count;

static long object_collapses;
static long object_bypasses;
static int next_index;

static void
_vm_object_allocate(type, size, object)
	objtype_t type;
	vm_size_t size;
	register vm_object_t object;
{
	TAILQ_INIT(&object->memq);
	TAILQ_INIT(&object->shadow_head);

	object->type = type;
	object->size = size;
	object->ref_count = 1;
	object->flags = 0;
	object->behavior = OBJ_NORMAL;
	object->paging_in_progress = 0;
	object->resident_page_count = 0;
	object->shadow_count = 0;
	object->pg_color = next_index;
	next_index = (next_index + PQ_PRIME1) & PQ_L2_MASK;
	object->handle = NULL;
	object->paging_offset = (vm_ooffset_t) 0;
	object->backing_object = NULL;
	object->backing_object_offset = (vm_ooffset_t) 0;
	object->page_hint = NULL;

	object->last_read = 0;

	TAILQ_INSERT_TAIL(&vm_object_list, object, object_list);
	vm_object_count++;
}

/*
 *	vm_object_init:
 *
 *	Initialize the VM objects module.
 */
void
vm_object_init()
{
	TAILQ_INIT(&vm_object_cached_list);
	TAILQ_INIT(&vm_object_list);
	vm_object_count = 0;

	vm_object_cache_max = 84;
	if (cnt.v_page_count > 1000)
		vm_object_cache_max += (cnt.v_page_count - 1000) / 4;

	kernel_object = &kernel_object_store;
	_vm_object_allocate(OBJT_DEFAULT, OFF_TO_IDX(VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS),
	    kernel_object);

	kmem_object = &kmem_object_store;
	_vm_object_allocate(OBJT_DEFAULT, OFF_TO_IDX(VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS),
	    kmem_object);
}

/*
 *	vm_object_allocate:
 *
 *	Returns a new object with the given size.
 */

vm_object_t
vm_object_allocate(type, size)
	objtype_t type;
	vm_size_t size;
{
	register vm_object_t result;

	result = (vm_object_t)
	    malloc((u_long) sizeof *result, M_VMOBJ, M_WAITOK);

	_vm_object_allocate(type, size, result);

	return (result);
}

/*
 *	vm_object_reference:
 *
 *	Gets another reference to the given object.
 */
void
vm_object_reference(object)
	register vm_object_t object;
{
	if (object == NULL)
		return;

	if (object->ref_count == 0) {
		if ((object->flags & OBJ_CANPERSIST) == 0)
			panic("vm_object_reference: non-persistent object with 0 ref_count");
		TAILQ_REMOVE(&vm_object_cached_list, object, cached_list);
		vm_object_cached--;
	}
	object->ref_count++;
}

/*
 *	vm_object_deallocate:
 *
 *	Release a reference to the specified object,
 *	gained either through a vm_object_allocate
 *	or a vm_object_reference call.  When all references
 *	are gone, storage associated with this object
 *	may be relinquished.
 *
 *	No object may be locked.
 */
void
vm_object_deallocate(object)
	vm_object_t object;
{
	vm_object_t temp;

	while (object != NULL) {

		if (object->ref_count == 0)
			panic("vm_object_deallocate: object deallocated too many times");

		/*
		 * Lose the reference
		 */
		object->ref_count--;
		if (object->ref_count != 0) {
			if ((object->ref_count == 1) &&
			    (object->handle == NULL) &&
			    (object->type == OBJT_DEFAULT ||
			     object->type == OBJT_SWAP)) {
				vm_object_t robject;
				robject = TAILQ_FIRST(&object->shadow_head);
				if ((robject != NULL) &&
				    (robject->handle == NULL) &&
				    (robject->type == OBJT_DEFAULT ||
				     robject->type == OBJT_SWAP)) {
					int s;
					robject->ref_count += 2;
					object->ref_count += 2;

					do {
						s = splvm();
						while (robject->paging_in_progress) {
							robject->flags |= OBJ_PIPWNT;
							tsleep(robject, PVM, "objde1", 0);
						}

						while (object->paging_in_progress) {
							object->flags |= OBJ_PIPWNT;
							tsleep(object, PVM, "objde2", 0);
						}
						splx(s);

					} while( object->paging_in_progress || robject->paging_in_progress);

					object->ref_count -= 2;
					robject->ref_count -= 2;
					if( robject->ref_count == 0) {
						robject->ref_count += 1;
						object = robject;
						continue;
					}
					vm_object_collapse(robject);
					return;
				}
			}
			/*
			 * If there are still references, then we are done.
			 */
			return;
		}

		if (object->type == OBJT_VNODE) {
			struct vnode *vp = object->handle;

			vp->v_flag &= ~VTEXT;
		}

		/*
		 * See if this object can persist and has some resident
		 * pages.  If so, enter it in the cache.
		 */
		if (object->flags & OBJ_CANPERSIST) {
			if (object->resident_page_count != 0) {
#if 0
				vm_object_page_clean(object, 0, 0 ,TRUE, TRUE);
#endif
				TAILQ_INSERT_TAIL(&vm_object_cached_list, object,
				    cached_list);
				vm_object_cached++;

				vm_object_cache_trim();
				return;
			} else {
				object->flags &= ~OBJ_CANPERSIST;
			}
		}

		/*
		 * Make sure no one uses us.
		 */
		object->flags |= OBJ_DEAD;

		temp = object->backing_object;
		if (temp) {
			TAILQ_REMOVE(&temp->shadow_head, object, shadow_list);
			--temp->shadow_count;
		}
		vm_object_terminate(object);
		/* unlocks and deallocates object */
		object = temp;
	}
}

/*
 *	vm_object_terminate actually destroys the specified object, freeing
 *	up all previously used resources.
 *
 *	The object must be locked.
 */
static void
vm_object_terminate(object)
	register vm_object_t object;
{
	register vm_page_t p;
	int s;

	/*
	 * wait for the pageout daemon to be done with the object
	 */
	s = splvm();
	while (object->paging_in_progress) {
		object->flags |= OBJ_PIPWNT;
		tsleep(object, PVM, "objtrm", 0);
	}
	splx(s);

	if (object->paging_in_progress != 0)
		panic("vm_object_deallocate: pageout in progress");

	/*
	 * Clean and free the pages, as appropriate. All references to the
	 * object are gone, so we don't need to lock it.
	 */
	if (object->type == OBJT_VNODE) {
		struct vnode *vp = object->handle;
		int waslocked;

		waslocked = VOP_ISLOCKED(vp);
		if (!waslocked)
			VOP_LOCK(vp);
		vm_object_page_clean(object, 0, 0, TRUE, FALSE);
		vinvalbuf(vp, V_SAVE, NOCRED, NULL, 0, 0);
		if (!waslocked)
			VOP_UNLOCK(vp);
	}
	/*
	 * Now free the pages. For internal objects, this also removes them
	 * from paging queues.
	 */
	while ((p = TAILQ_FIRST(&object->memq)) != NULL) {
		if (p->busy || (p->flags & PG_BUSY))
			printf("vm_object_terminate: freeing busy page\n");
		PAGE_WAKEUP(p);
		vm_page_free(p);
		cnt.v_pfree++;
	}

	/*
	 * Let the pager know object is dead.
	 */
	vm_pager_deallocate(object);

	TAILQ_REMOVE(&vm_object_list, object, object_list);
	vm_object_count--;

	wakeup(object);

	/*
	 * Free the space for the object.
	 */
	free((caddr_t) object, M_VMOBJ);
}

/*
 *	vm_object_page_clean
 *
 *	Clean all dirty pages in the specified range of object.
 *	Leaves page on whatever queue it is currently on.
 *
 *	Odd semantics: if start == end, we clean everything.
 *
 *	The object must be locked.
 */

void
vm_object_page_clean(object, start, end, syncio, lockflag)
	vm_object_t object;
	vm_pindex_t start;
	vm_pindex_t end;
	boolean_t syncio;
	boolean_t lockflag;
{
	register vm_page_t p, np, tp;
	register vm_offset_t tstart, tend;
	vm_pindex_t pi;
	int s;
	struct vnode *vp;
	int runlen;
	int maxf;
	int chkb;
	int maxb;
	int i;
	vm_page_t maf[vm_pageout_page_count];
	vm_page_t mab[vm_pageout_page_count];
	vm_page_t ma[vm_pageout_page_count];

	if (object->type != OBJT_VNODE ||
		(object->flags & OBJ_MIGHTBEDIRTY) == 0)
		return;

	vp = object->handle;

	if (lockflag)
		VOP_LOCK(vp);
	object->flags |= OBJ_CLEANING;

	tstart = start;
	if (end == 0) {
		tend = object->size;
	} else {
		tend = end;
	}
	if ((tstart == 0) && (tend == object->size)) {
		object->flags &= ~(OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
	}
	for(p = TAILQ_FIRST(&object->memq); p; p = TAILQ_NEXT(p, listq))
		p->flags |= PG_CLEANCHK;

rescan:
	for(p = TAILQ_FIRST(&object->memq); p; p = np) {
		np = TAILQ_NEXT(p, listq);

		pi = p->pindex;
		if (((p->flags & PG_CLEANCHK) == 0) ||
			(pi < tstart) || (pi >= tend) ||
			(p->valid == 0) ||
			((p->queue - p->pc) == PQ_CACHE)) {
			p->flags &= ~PG_CLEANCHK;
			continue;
		}

		vm_page_test_dirty(p);
		if ((p->dirty & p->valid) == 0) {
			p->flags &= ~PG_CLEANCHK;
			continue;
		}

		s = splvm();
		if ((p->flags & PG_BUSY) || p->busy) {
			p->flags |= PG_WANTED|PG_REFERENCED;
			tsleep(p, PVM, "vpcwai", 0);
			splx(s);
			goto rescan;
		}
		splx(s);

		s = splvm();
		maxf = 0;
		for(i=1;i<vm_pageout_page_count;i++) {
			if (tp = vm_page_lookup(object, pi + i)) {
				if ((tp->flags & PG_BUSY) ||
					(tp->flags & PG_CLEANCHK) == 0)
					break;
				if((tp->queue - tp->pc) == PQ_CACHE) {
					tp->flags &= ~PG_CLEANCHK;
					break;
				}
				vm_page_test_dirty(tp);
				if ((tp->dirty & tp->valid) == 0) {
					tp->flags &= ~PG_CLEANCHK;
					break;
				}
				maf[ i - 1 ] = tp;
				maxf++;
				continue;
			}
			break;
		}

		maxb = 0;
		chkb = vm_pageout_page_count -  maxf;
		if (chkb) {
			for(i = 1; i < chkb;i++) {
				if (tp = vm_page_lookup(object, pi - i)) {
					if ((tp->flags & PG_BUSY) ||
						(tp->flags & PG_CLEANCHK) == 0)
						break;
					if((tp->queue - tp->pc) == PQ_CACHE) {
						tp->flags &= ~PG_CLEANCHK;
						break;
					}
					vm_page_test_dirty(tp);
					if ((tp->dirty & tp->valid) == 0) {
						tp->flags &= ~PG_CLEANCHK;
						break;
					}
					mab[ i - 1 ] = tp;
					maxb++;
					continue;
				}
				break;
			}
		}

		for(i=0;i<maxb;i++) {
			int index = (maxb - i) - 1;
			ma[index] = mab[i];
			ma[index]->flags |= PG_BUSY;
			ma[index]->flags &= ~PG_CLEANCHK;
			vm_page_protect(ma[index], VM_PROT_READ);
		}
		vm_page_protect(p, VM_PROT_READ);
		p->flags |= PG_BUSY;
		p->flags &= ~PG_CLEANCHK;
		ma[maxb] = p;
		for(i=0;i<maxf;i++) {
			int index = (maxb + i) + 1;
			ma[index] = maf[i];
			ma[index]->flags |= PG_BUSY;
			ma[index]->flags &= ~PG_CLEANCHK;
			vm_page_protect(ma[index], VM_PROT_READ);
		}
		runlen = maxb + maxf + 1;
		splx(s);
		vm_pageout_flush(ma, runlen, 0);
		goto rescan;
	}

	VOP_FSYNC(vp, NULL, syncio, curproc);

	if (lockflag)
		VOP_UNLOCK(vp);
	object->flags &= ~OBJ_CLEANING;
	return;
}

#ifdef not_used
/* XXX I cannot tell if this should be an exported symbol */
/*
 *	vm_object_deactivate_pages
 *
 *	Deactivate all pages in the specified object.  (Keep its pages
 *	in memory even though it is no longer referenced.)
 *
 *	The object must be locked.
 */
static void
vm_object_deactivate_pages(object)
	register vm_object_t object;
{
	register vm_page_t p, next;

	for (p = TAILQ_FIRST(&object->memq); p != NULL; p = next) {
		next = TAILQ_NEXT(p, listq);
		vm_page_deactivate(p);
	}
}
#endif

/*
 *	Trim the object cache to size.
 */
static void
vm_object_cache_trim()
{
	register vm_object_t object;

	while (vm_object_cached > vm_object_cache_max) {
		object = TAILQ_FIRST(&vm_object_cached_list);

		vm_object_reference(object);
		pager_cache(object, FALSE);
	}
}

/*
 *	vm_object_pmap_copy:
 *
 *	Makes all physical pages in the specified
 *	object range copy-on-write.  No writeable
 *	references to these pages should remain.
 *
 *	The object must *not* be locked.
 */
void
vm_object_pmap_copy(object, start, end)
	register vm_object_t object;
	register vm_pindex_t start;
	register vm_pindex_t end;
{
	register vm_page_t p;

	if (object == NULL || (object->flags & OBJ_WRITEABLE) == 0)
		return;

	for (p = TAILQ_FIRST(&object->memq);
		p != NULL;
		p = TAILQ_NEXT(p, listq)) {
		vm_page_protect(p, VM_PROT_READ);
	}

	object->flags &= ~OBJ_WRITEABLE;
}

/*
 *	vm_object_pmap_remove:
 *
 *	Removes all physical pages in the specified
 *	object range from all physical maps.
 *
 *	The object must *not* be locked.
 */
void
vm_object_pmap_remove(object, start, end)
	register vm_object_t object;
	register vm_pindex_t start;
	register vm_pindex_t end;
{
	register vm_page_t p;
	if (object == NULL)
		return;
	for (p = TAILQ_FIRST(&object->memq);
		p != NULL;
		p = TAILQ_NEXT(p, listq)) {
		if (p->pindex >= start && p->pindex < end)
			vm_page_protect(p, VM_PROT_NONE);
	}
	if ((start == 0) && (object->size == end))
		object->flags &= ~OBJ_WRITEABLE;
}

/*
 *	vm_object_madvise:
 *
 *	Implements the madvise function at the object/page level.
 */
void
vm_object_madvise(object, pindex, count, advise)
	vm_object_t object;
	vm_pindex_t pindex;
	int count;
	int advise;
{
	int s;
	vm_pindex_t end, tpindex;
	vm_object_t tobject;
	vm_page_t m;

	if (object == NULL)
		return;

	end = pindex + count;

	for (; pindex < end; pindex += 1) {

relookup:
		tobject = object;
		tpindex = pindex;
shadowlookup:
		m = vm_page_lookup(tobject, tpindex);
		if (m == NULL) {
			if (tobject->type != OBJT_DEFAULT) {
				continue;
			}

			tobject = tobject->backing_object;
			if ((tobject == NULL) || (tobject->ref_count != 1)) {
				continue;
			}
			tpindex += OFF_TO_IDX(tobject->backing_object_offset);
			goto shadowlookup;
		}

		/*
		 * If the page is busy or not in a normal active state,
		 * we skip it.  Things can break if we mess with pages
		 * in any of the below states.
		 */
		if (m->hold_count || m->wire_count ||
			m->valid != VM_PAGE_BITS_ALL) {
			continue;
		}

		if (m->busy || (m->flags & PG_BUSY)) {
			s = splvm();
			if (m->busy || (m->flags & PG_BUSY)) {
				m->flags |= PG_WANTED;
				tsleep(m, PVM, "madvpw", 0);
			}
			splx(s);
			goto relookup;
		}

		if (advise == MADV_WILLNEED) {
			if (m->queue != PQ_ACTIVE)
				vm_page_activate(m);
		} else if (advise == MADV_DONTNEED) {
			vm_page_deactivate(m);
		} else if (advise == MADV_FREE) {
			pmap_clear_modify(VM_PAGE_TO_PHYS(m));
			m->dirty = 0;
			/*
			 * Force a demand zero if attempt to read from swap.
			 * We currently don't handle vnode files correctly,
			 * and will reread stale contents unnecessarily.
			 */
			if (object->type == OBJT_SWAP)
				swap_pager_dmzspace(tobject, m->pindex, 1);
		}
	}
}

/*
 *	vm_object_shadow:
 *
 *	Create a new object which is backed by the
 *	specified existing object range.  The source
 *	object reference is deallocated.
 *
 *	The new object and offset into that object
 *	are returned in the source parameters.
 */

void
vm_object_shadow(object, offset, length)
	vm_object_t *object;	/* IN/OUT */
	vm_ooffset_t *offset;	/* IN/OUT */
	vm_size_t length;
{
	register vm_object_t source;
	register vm_object_t result;

	source = *object;

	/*
	 * Allocate a new object with the given length
	 */

	if ((result = vm_object_allocate(OBJT_DEFAULT, length)) == NULL)
		panic("vm_object_shadow: no object for shadowing");

	/*
	 * The new object shadows the source object, adding a reference to it.
	 * Our caller changes his reference to point to the new object,
	 * removing a reference to the source object.  Net result: no change
	 * of reference count.
	 */
	result->backing_object = source;
	if (source) {
		TAILQ_INSERT_TAIL(&source->shadow_head, result, shadow_list);
		++source->shadow_count;
	}

	/*
	 * Store the offset into the source object, and fix up the offset into
	 * the new object.
	 */

	result->backing_object_offset = *offset;

	/*
	 * Return the new things
	 */

	*offset = 0;
	*object = result;
}

/*
 * this version of collapse allows the operation to occur earlier and
 * when paging_in_progress is true for an object...  This is not a complete
 * operation, but should plug 99.9% of the rest of the leaks.
 */
static void
vm_object_qcollapse(object)
	register vm_object_t object;
{
	register vm_object_t backing_object;
	register vm_pindex_t backing_offset_index, paging_offset_index;
	vm_pindex_t backing_object_paging_offset_index;
	vm_pindex_t new_pindex;
	register vm_page_t p, pp;
	register vm_size_t size;

	backing_object = object->backing_object;
	if (backing_object->ref_count != 1)
		return;

	backing_object->ref_count += 2;

	backing_offset_index = OFF_TO_IDX(object->backing_object_offset);
	backing_object_paging_offset_index = OFF_TO_IDX(backing_object->paging_offset);
	paging_offset_index = OFF_TO_IDX(object->paging_offset);
	size = object->size;
	p = TAILQ_FIRST(&backing_object->memq);
	while (p) {
		vm_page_t next;

		next = TAILQ_NEXT(p, listq);
		if ((p->flags & (PG_BUSY | PG_FICTITIOUS)) ||
		    ((p->queue - p->pc) == PQ_CACHE) ||
		    !p->valid || p->hold_count || p->wire_count || p->busy) {
			p = next;
			continue;
		}
		new_pindex = p->pindex - backing_offset_index;
		if (p->pindex < backing_offset_index ||
		    new_pindex >= size) {
			if (backing_object->type == OBJT_SWAP)
				swap_pager_freespace(backing_object,
				    backing_object_paging_offset_index+p->pindex,
				    1);
			vm_page_protect(p, VM_PROT_NONE);
			vm_page_free(p);
		} else {
			pp = vm_page_lookup(object, new_pindex);
			if (pp != NULL || (object->type == OBJT_SWAP && vm_pager_has_page(object,
				    paging_offset_index + new_pindex, NULL, NULL))) {
				if (backing_object->type == OBJT_SWAP)
					swap_pager_freespace(backing_object,
					    backing_object_paging_offset_index + p->pindex, 1);
				vm_page_protect(p, VM_PROT_NONE);
				vm_page_free(p);
			} else {
				if (backing_object->type == OBJT_SWAP)
					swap_pager_freespace(backing_object,
					    backing_object_paging_offset_index + p->pindex, 1);
				vm_page_rename(p, object, new_pindex);
				vm_page_protect(p, VM_PROT_NONE);
				p->dirty = VM_PAGE_BITS_ALL;
			}
		}
		p = next;
	}
	backing_object->ref_count -= 2;
}

/*
 *	vm_object_collapse:
 *
 *	Collapse an object with the object backing it.
 *	Pages in the backing object are moved into the
 *	parent, and the backing object is deallocated.
 */
void
vm_object_collapse(object)
	vm_object_t object;

{
	vm_object_t backing_object;
	vm_ooffset_t backing_offset;
	vm_size_t size;
	vm_pindex_t new_pindex, backing_offset_index;
	vm_page_t p, pp;

	while (TRUE) {
		/*
		 * Verify that the conditions are right for collapse:
		 *
		 * The object exists and no pages in it are currently being paged
		 * out.
		 */
		if (object == NULL)
			return;

		/*
		 * Make sure there is a backing object.
		 */
		if ((backing_object = object->backing_object) == NULL)
			return;

		/*
		 * we check the backing object first, because it is most likely
		 * not collapsable.
		 */
		if (backing_object->handle != NULL ||
		    (backing_object->type != OBJT_DEFAULT &&
		     backing_object->type != OBJT_SWAP) ||
		    (backing_object->flags & OBJ_DEAD) ||
		    object->handle != NULL ||
		    (object->type != OBJT_DEFAULT &&
		     object->type != OBJT_SWAP) ||
		    (object->flags & OBJ_DEAD)) {
			return;
		}

		if (object->paging_in_progress != 0 ||
		    backing_object->paging_in_progress != 0) {
			vm_object_qcollapse(object);
			return;
		}

		/*
		 * We know that we can either collapse the backing object (if
		 * the parent is the only reference to it) or (perhaps) remove
		 * the parent's reference to it.
		 */

		backing_offset = object->backing_object_offset;
		backing_offset_index = OFF_TO_IDX(backing_offset);
		size = object->size;

		/*
		 * If there is exactly one reference to the backing object, we
		 * can collapse it into the parent.
		 */

		if (backing_object->ref_count == 1) {

			backing_object->flags |= OBJ_DEAD;
			/*
			 * We can collapse the backing object.
			 *
			 * Move all in-memory pages from backing_object to the
			 * parent.  Pages that have been paged out will be
			 * overwritten by any of the parent's pages that
			 * shadow them.
			 */

			while ((p = TAILQ_FIRST(&backing_object->memq)) != 0) {

				new_pindex = p->pindex - backing_offset_index;

				/*
				 * If the parent has a page here, or if this
				 * page falls outside the parent, dispose of
				 * it.
				 *
				 * Otherwise, move it as planned.
				 */

				if (p->pindex < backing_offset_index ||
				    new_pindex >= size) {
					vm_page_protect(p, VM_PROT_NONE);
					PAGE_WAKEUP(p);
					vm_page_free(p);
				} else {
					pp = vm_page_lookup(object, new_pindex);
					if (pp != NULL || (object->type == OBJT_SWAP && vm_pager_has_page(object,
					    OFF_TO_IDX(object->paging_offset) + new_pindex, NULL, NULL))) {
						vm_page_protect(p, VM_PROT_NONE);
						PAGE_WAKEUP(p);
						vm_page_free(p);
					} else {
						vm_page_protect(p, VM_PROT_NONE);
						vm_page_rename(p, object, new_pindex);
						p->dirty = VM_PAGE_BITS_ALL;
					}
				}
			}

			/*
			 * Move the pager from backing_object to object.
			 */

			if (backing_object->type == OBJT_SWAP) {
				backing_object->paging_in_progress++;
				if (object->type == OBJT_SWAP) {
					object->paging_in_progress++;
					/*
					 * copy shadow object pages into ours
					 * and destroy unneeded pages in
					 * shadow object.
					 */
					swap_pager_copy(
					    backing_object,
					    OFF_TO_IDX(backing_object->paging_offset),
					    object,
					    OFF_TO_IDX(object->paging_offset),
					    OFF_TO_IDX(object->backing_object_offset));
					vm_object_pip_wakeup(object);
				} else {
					object->paging_in_progress++;
					/*
					 * move the shadow backing_object's pager data to
					 * "object" and convert "object" type to OBJT_SWAP.
					 */
					object->type = OBJT_SWAP;
					object->un_pager.swp.swp_nblocks =
					    backing_object->un_pager.swp.swp_nblocks;
					object->un_pager.swp.swp_allocsize =
					    backing_object->un_pager.swp.swp_allocsize;
					object->un_pager.swp.swp_blocks =
					    backing_object->un_pager.swp.swp_blocks;
					object->un_pager.swp.swp_poip =		/* XXX */
					    backing_object->un_pager.swp.swp_poip;
					object->paging_offset = backing_object->paging_offset + backing_offset;
					TAILQ_INSERT_TAIL(&swap_pager_un_object_list, object, pager_object_list);

					/*
					 * Convert backing object from OBJT_SWAP to
					 * OBJT_DEFAULT. XXX - only the TAILQ_REMOVE is
					 * actually necessary.
					 */
					backing_object->type = OBJT_DEFAULT;
					TAILQ_REMOVE(&swap_pager_un_object_list, backing_object, pager_object_list);
					/*
					 * free unnecessary blocks
					 */
					swap_pager_freespace(object, 0,
						OFF_TO_IDX(object->paging_offset));
					vm_object_pip_wakeup(object);
				}

				vm_object_pip_wakeup(backing_object);
			}
			/*
			 * Object now shadows whatever backing_object did.
			 * Note that the reference to backing_object->backing_object
			 * moves from within backing_object to within object.
			 */

			TAILQ_REMOVE(&object->backing_object->shadow_head, object,
			    shadow_list);
			--object->backing_object->shadow_count;
			if (backing_object->backing_object) {
				TAILQ_REMOVE(&backing_object->backing_object->shadow_head,
				    backing_object, shadow_list);
				--backing_object->backing_object->shadow_count;
			}
			object->backing_object = backing_object->backing_object;
			if (object->backing_object) {
				TAILQ_INSERT_TAIL(&object->backing_object->shadow_head,
				    object, shadow_list);
				++object->backing_object->shadow_count;
			}

			object->backing_object_offset += backing_object->backing_object_offset;
			/*
			 * Discard backing_object.
			 *
			 * Since the backing object has no pages, no pager left,
			 * and no object references within it, all that is
			 * necessary is to dispose of it.
			 */

			TAILQ_REMOVE(&vm_object_list, backing_object,
			    object_list);
			vm_object_count--;

			free((caddr_t) backing_object, M_VMOBJ);

			object_collapses++;
		} else {
			/*
			 * If all of the pages in the backing object are
			 * shadowed by the parent object, the parent object no
			 * longer has to shadow the backing object; it can
			 * shadow the next one in the chain.
			 *
			 * The backing object must not be paged out - we'd have
			 * to check all of the paged-out pages, as well.
			 */

			if (backing_object->type != OBJT_DEFAULT) {
				return;
			}
			/*
			 * Should have a check for a 'small' number of pages
			 * here.
			 */

			for (p = TAILQ_FIRST(&backing_object->memq); p; p = TAILQ_NEXT(p, listq)) {
				new_pindex = p->pindex - backing_offset_index;

				/*
				 * If the parent has a page here, or if this
				 * page falls outside the parent, keep going.
				 *
				 * Otherwise, the backing_object must be left in
				 * the chain.
				 */

				if (p->pindex >= backing_offset_index &&
					new_pindex <= size) {

					pp = vm_page_lookup(object, new_pindex);

					if ((pp == NULL || pp->valid == 0) &&
				   	    !vm_pager_has_page(object, OFF_TO_IDX(object->paging_offset) + new_pindex, NULL, NULL)) {
						/*
						 * Page still needed. Can't go any
						 * further.
						 */
						return;
					}
				}
			}

			/*
			 * Make the parent shadow the next object in the
			 * chain.  Deallocating backing_object will not remove
			 * it, since its reference count is at least 2.
			 */

			TAILQ_REMOVE(&object->backing_object->shadow_head,
			    object, shadow_list);
			--object->backing_object->shadow_count;
			vm_object_reference(object->backing_object = backing_object->backing_object);
			if (object->backing_object) {
				TAILQ_INSERT_TAIL(&object->backing_object->shadow_head,
				    object, shadow_list);
				++object->backing_object->shadow_count;
			}
			object->backing_object_offset += backing_object->backing_object_offset;

			/*
			 * Drop the reference count on backing_object. Since
			 * its ref_count was at least 2, it will not vanish;
			 * so we don't need to call vm_object_deallocate.
			 */
			if (backing_object->ref_count == 1)
				printf("should have called obj deallocate\n");
			backing_object->ref_count--;

			object_bypasses++;

		}

		/*
		 * Try again with this object's new backing object.
		 */
	}
}

/*
 *	vm_object_page_remove: [internal]
 *
 *	Removes all physical pages in the specified
 *	object range from the object's list of pages.
 *
 *	The object must be locked.
 */
void
vm_object_page_remove(object, start, end, clean_only)
	register vm_object_t object;
	register vm_pindex_t start;
	register vm_pindex_t end;
	boolean_t clean_only;
{
	register vm_page_t p, next;
	unsigned int size;
	int s;

	if (object == NULL)
		return;

	object->paging_in_progress++;
again:
	size = end - start;
	if (size > 4 || size >= object->size / 4) {
		for (p = TAILQ_FIRST(&object->memq); p != NULL; p = next) {
			next = TAILQ_NEXT(p, listq);
			if ((start <= p->pindex) && (p->pindex < end)) {
				if (p->wire_count != 0) {
					vm_page_protect(p, VM_PROT_NONE);
					p->valid = 0;
					continue;
				}

				/*
				 * The busy flags are only cleared at
				 * interrupt -- minimize the spl transitions
				 */
				if ((p->flags & PG_BUSY) || p->busy) {
					s = splvm();
					if ((p->flags & PG_BUSY) || p->busy) {
						p->flags |= PG_WANTED;
						tsleep(p, PVM, "vmopar", 0);
						splx(s);
						goto again;
					}
					splx(s);
				}

				if (clean_only) {
					vm_page_test_dirty(p);
					if (p->valid & p->dirty)
						continue;
				}
				vm_page_protect(p, VM_PROT_NONE);
				PAGE_WAKEUP(p);
				vm_page_free(p);
			}
		}
	} else {
		while (size > 0) {
			if ((p = vm_page_lookup(object, start)) != 0) {
				if (p->wire_count != 0) {
					p->valid = 0;
					vm_page_protect(p, VM_PROT_NONE);
					start += 1;
					size -= 1;
					continue;
				}
				/*
				 * The busy flags are only cleared at
				 * interrupt -- minimize the spl transitions
				 */
				if ((p->flags & PG_BUSY) || p->busy) {
					s = splvm();
					if ((p->flags & PG_BUSY) || p->busy) {
						p->flags |= PG_WANTED;
						tsleep(p, PVM, "vmopar", 0);
						splx(s);
						goto again;
					}
					splx(s);
				}
				if (clean_only) {
					vm_page_test_dirty(p);
					if (p->valid & p->dirty) {
						start += 1;
						size -= 1;
						continue;
					}
				}
				vm_page_protect(p, VM_PROT_NONE);
				PAGE_WAKEUP(p);
				vm_page_free(p);
			}
			start += 1;
			size -= 1;
		}
	}
	vm_object_pip_wakeup(object);
}

/*
 *	Routine:	vm_object_coalesce
 *	Function:	Coalesces two objects backing up adjoining
 *			regions of memory into a single object.
 *
 *	returns TRUE if objects were combined.
 *
 *	NOTE:	Only works at the moment if the second object is NULL -
 *		if it's not, which object do we lock first?
 *
 *	Parameters:
 *		prev_object	First object to coalesce
 *		prev_offset	Offset into prev_object
 *		next_object	Second object into coalesce
 *		next_offset	Offset into next_object
 *
 *		prev_size	Size of reference to prev_object
 *		next_size	Size of reference to next_object
 *
 *	Conditions:
 *	The object must *not* be locked.
 */
boolean_t
vm_object_coalesce(prev_object, prev_pindex, prev_size, next_size)
	register vm_object_t prev_object;
	vm_pindex_t prev_pindex;
	vm_size_t prev_size, next_size;
{
	vm_size_t newsize;

	if (prev_object == NULL) {
		return (TRUE);
	}

	if (prev_object->type != OBJT_DEFAULT) {
		return (FALSE);
	}

	/*
	 * Try to collapse the object first
	 */
	vm_object_collapse(prev_object);

	/*
	 * Can't coalesce if: . more than one reference . paged out . shadows
	 * another object . has a copy elsewhere (any of which mean that the
	 * pages not mapped to prev_entry may be in use anyway)
	 */

	if (prev_object->backing_object != NULL) {
		return (FALSE);
	}

	prev_size >>= PAGE_SHIFT;
	next_size >>= PAGE_SHIFT;

	if ((prev_object->ref_count > 1) &&
	    (prev_object->size != prev_pindex + prev_size)) {
		return (FALSE);
	}

	/*
	 * Remove any pages that may still be in the object from a previous
	 * deallocation.
	 */

	vm_object_page_remove(prev_object,
	    prev_pindex + prev_size,
	    prev_pindex + prev_size + next_size, FALSE);

	/*
	 * Extend the object if necessary.
	 */
	newsize = prev_pindex + prev_size + next_size;
	if (newsize > prev_object->size)
		prev_object->size = newsize;

	return (TRUE);
}

#include "opt_ddb.h"
#ifdef DDB
#include <sys/kernel.h>

#include <machine/cons.h>

#include <ddb/ddb.h>

static int	_vm_object_in_map __P((vm_map_t map, vm_object_t object,
				       vm_map_entry_t entry));
static int	vm_object_in_map __P((vm_object_t object));

static int
_vm_object_in_map(map, object, entry)
	vm_map_t map;
	vm_object_t object;
	vm_map_entry_t entry;
{
	vm_map_t tmpm;
	vm_map_entry_t tmpe;
	vm_object_t obj;
	int entcount;

	if (map == 0)
		return 0;

	if (entry == 0) {
		tmpe = map->header.next;
		entcount = map->nentries;
		while (entcount-- && (tmpe != &map->header)) {
			if( _vm_object_in_map(map, object, tmpe)) {
				return 1;
			}
			tmpe = tmpe->next;
		}
	} else if (entry->eflags & (MAP_ENTRY_IS_A_MAP|MAP_ENTRY_IS_SUB_MAP)) {
		tmpm = entry->object.share_map;
		tmpe = tmpm->header.next;
		entcount = tmpm->nentries;
		while (entcount-- && tmpe != &tmpm->header) {
			if( _vm_object_in_map(tmpm, object, tmpe)) {
				return 1;
			}
			tmpe = tmpe->next;
		}
	} else if (obj = entry->object.vm_object) {
		for(; obj; obj=obj->backing_object)
			if( obj == object) {
				return 1;
			}
	}
	return 0;
}

static int
vm_object_in_map( object)
	vm_object_t object;
{
	struct proc *p;
	for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
		if( !p->p_vmspace /* || (p->p_flag & (P_SYSTEM|P_WEXIT)) */)
			continue;
		if( _vm_object_in_map(&p->p_vmspace->vm_map, object, 0))
			return 1;
	}
	if( _vm_object_in_map( kernel_map, object, 0))
		return 1;
	if( _vm_object_in_map( kmem_map, object, 0))
		return 1;
	if( _vm_object_in_map( pager_map, object, 0))
		return 1;
	if( _vm_object_in_map( buffer_map, object, 0))
		return 1;
	if( _vm_object_in_map( io_map, object, 0))
		return 1;
	if( _vm_object_in_map( phys_map, object, 0))
		return 1;
	if( _vm_object_in_map( mb_map, object, 0))
		return 1;
	if( _vm_object_in_map( u_map, object, 0))
		return 1;
	return 0;
}

DB_SHOW_COMMAND(vmochk, vm_object_check)
{
	vm_object_t object;

	/*
	 * make sure that internal objs are in a map somewhere
	 * and none have zero ref counts.
	 */
	for (object = TAILQ_FIRST(&vm_object_list);
			object != NULL;
			object = TAILQ_NEXT(object, object_list)) {
		if (object->handle == NULL &&
		    (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
			if (object->ref_count == 0) {
				db_printf("vmochk: internal obj has zero ref count: %d\n",
					object->size);
			}
			if (!vm_object_in_map(object)) {
				db_printf("vmochk: internal obj is not in a map: "
		"ref: %d, size: %d: 0x%x, backing_object: 0x%x\n",
				    object->ref_count, object->size,
				    object->size, object->backing_object);
			}
		}
	}
}

/*
 *	vm_object_print:	[ debug ]
 */
DB_SHOW_COMMAND(object, vm_object_print_static)
{
	/* XXX convert args. */
	vm_object_t object = (vm_object_t)addr;
	boolean_t full = have_addr;

	register vm_page_t p;

	/* XXX count is an (unused) arg.  Avoid shadowing it. */
#define	count	was_count

	register int count;

	if (object == NULL)
		return;

	db_iprintf("Object 0x%x: size=0x%x, res=%d, ref=%d, ",
	    (int) object, (int) object->size,
	    object->resident_page_count, object->ref_count);
	db_printf("offset=0x%x, backing_object=(0x%x)+0x%x\n",
	    (int) object->paging_offset,
	    (int) object->backing_object, (int) object->backing_object_offset);
	db_printf("cache: next=%p, prev=%p\n",
	    TAILQ_NEXT(object, cached_list), TAILQ_PREV(object, object_q,
							cached_list));

	if (!full)
		return;

	db_indent += 2;
	count = 0;
	for (p = TAILQ_FIRST(&object->memq); p != NULL; p = TAILQ_NEXT(p, listq)) {
		if (count == 0)
			db_iprintf("memory:=");
		else if (count == 6) {
			db_printf("\n");
			db_iprintf(" ...");
			count = 0;
		} else
			db_printf(",");
		count++;

		db_printf("(off=0x%lx,page=0x%lx)",
		    (u_long) p->pindex, (u_long) VM_PAGE_TO_PHYS(p));
	}
	if (count != 0)
		db_printf("\n");
	db_indent -= 2;
}

/* XXX. */
#undef count

/* XXX need this non-static entry for calling from vm_map_print. */
void
vm_object_print(addr, have_addr, count, modif)
	db_expr_t addr;
	boolean_t have_addr;
	db_expr_t count;
	char *modif;
{
	vm_object_print_static(addr, have_addr, count, modif);
}

DB_SHOW_COMMAND(vmopag, vm_object_print_pages)
{
	vm_object_t object;
	int nl = 0;
	int c;
	for (object = TAILQ_FIRST(&vm_object_list);
			object != NULL;
			object = TAILQ_NEXT(object, object_list)) {
		vm_pindex_t idx, fidx;
		vm_pindex_t osize;
		vm_offset_t pa = -1, padiff;
		int rcount;
		vm_page_t m;

		db_printf("new object: 0x%x\n", object);
		if ( nl > 18) {
			c = cngetc();
			if (c != ' ')
				return;
			nl = 0;
		}
		nl++;
		rcount = 0;
		fidx = 0;
		osize = object->size;
		if (osize > 128)
			osize = 128;
		for(idx=0;idx<osize;idx++) {
			m = vm_page_lookup(object, idx);
			if (m == NULL) {
				if (rcount) {
					db_printf(" index(%d)run(%d)pa(0x%x)\n",
						fidx, rcount, pa);
					if ( nl > 18) {
						c = cngetc();
						if (c != ' ')
							return;
						nl = 0;
					}
					nl++;
					rcount = 0;
				}
				continue;
			}

			if (rcount &&
				(VM_PAGE_TO_PHYS(m) == pa + rcount * PAGE_SIZE)) {
				++rcount;
				continue;
			}
			if (rcount) {
				padiff = pa + rcount * PAGE_SIZE - VM_PAGE_TO_PHYS(m);
				padiff >>= PAGE_SHIFT;
				padiff &= PQ_L2_MASK;
				if (padiff == 0) {
					pa = VM_PAGE_TO_PHYS(m) - rcount * PAGE_SIZE;
					++rcount;
					continue;
				}
				db_printf(" index(%d)run(%d)pa(0x%x)", fidx, rcount, pa);
				db_printf("pd(%d)\n", padiff);
				if ( nl > 18) {
					c = cngetc();
					if (c != ' ')
						return;
					nl = 0;
				}
				nl++;
			}
			fidx = idx;
			pa = VM_PAGE_TO_PHYS(m);
			rcount = 1;
		}
		if (rcount) {
			db_printf(" index(%d)run(%d)pa(0x%x)\n", fidx, rcount, pa);
			if ( nl > 18) {
				c = cngetc();
				if (c != ' ')
					return;
				nl = 0;
			}
			nl++;
		}
	}
}
#endif /* DDB */