Index: src/wp-includes/functions.php
===================================================================
--- src/wp-includes/functions.php	(revision 32511)
+++ src/wp-includes/functions.php	(working copy)
@@ -3852,32 +3852,59 @@
  * @return bool True if $network_id is the main network, or if not running Multisite.
  */
 function is_main_network( $network_id = null ) {
-	global $wpdb;
 
-	if ( ! is_multisite() )
+	// Always return true if not a multisite installation
+	if ( ! is_multisite() ) {
 		return true;
+	}
 
 	$current_network_id = (int) get_current_site()->id;
 
-	if ( ! $network_id )
+	if ( null === $network_id ) {
 		$network_id = $current_network_id;
+	}
+
 	$network_id = (int) $network_id;
 
-	if ( defined( 'PRIMARY_NETWORK_ID' ) )
-		return $network_id === (int) PRIMARY_NETWORK_ID;
+	return ( $network_id === get_main_network_id() );
+}
 
-	if ( 1 === $current_network_id )
-		return $network_id === $current_network_id;
+/**
+ * Get the main network ID.
+ *
+ * @since 4.3.0
+ *
+ * @return int  
+ */
+function get_main_network_id() {
+	global $wpdb;
 
-	$primary_network_id = (int) wp_cache_get( 'primary_network_id', 'site-options' );
+	// Use constant if explicitly set.
+	if ( defined( 'MAIN_NETWORK_ID' ) ) {
+		$main_network_id = MAIN_NETWORK_ID;
 
-	if ( $primary_network_id )
-		return $network_id === $primary_network_id;
+	// If the current network has an ID of 1, assume it is the main network.
+	} elseif ( 1 === (int) get_current_site()->id ) {
+		$main_network_id = 1;
 
-	$primary_network_id = (int) $wpdb->get_var( "SELECT id FROM $wpdb->site ORDER BY id LIMIT 1" );
-	wp_cache_add( 'primary_network_id', $primary_network_id, 'site-options' );
+	// Fallback on cached value, queried from sites table.
+	} else {
+		$main_network_id = wp_cache_get( 'main_network_id', 'site-options' );
 
-	return $network_id === $primary_network_id;
+		if ( false === $main_network_id ) {
+			$main_network_id = (int) $wpdb->get_var( "SELECT id FROM {$wpdb->site} ORDER BY id LIMIT 1" );
+			wp_cache_add( 'main_network_id', $main_network_id, 'site-options' );
+		}
+	}
+
+	/**
+	 * Filter the main network ID.
+	 *
+	 * @since 4.3.0
+	 *
+	 * @param int $main_network_id The ID of the main network.
+	 */
+	return (int) apply_filters( 'get_main_network_id', $main_network_id );
 }
 
 /**
