+static struct lnet_ni *
+lnet_get_best_ni(struct lnet_net *local_net, struct lnet_ni *cur_ni,
+ int md_cpt)
+{
+ struct lnet_ni *ni = NULL, *best_ni = cur_ni;
+ unsigned int shortest_distance;
+ int best_credits;
+
+ if (best_ni == NULL) {
+ shortest_distance = UINT_MAX;
+ best_credits = INT_MIN;
+ } else {
+ shortest_distance = cfs_cpt_distance(lnet_cpt_table(), md_cpt,
+ best_ni->ni_dev_cpt);
+ best_credits = atomic_read(&best_ni->ni_tx_credits);
+ }
+
+ while ((ni = lnet_get_next_ni_locked(local_net, ni))) {
+ unsigned int distance;
+ int ni_credits;
+
+ if (!lnet_is_ni_healthy_locked(ni))
+ continue;
+
+ ni_credits = atomic_read(&ni->ni_tx_credits);
+
+ /*
+ * calculate the distance from the CPT on which
+ * the message memory is allocated to the CPT of
+ * the NI's physical device
+ */
+ distance = cfs_cpt_distance(lnet_cpt_table(),
+ md_cpt,
+ ni->ni_dev_cpt);
+
+ /*
+ * All distances smaller than the NUMA range
+ * are treated equally.
+ */
+ if (distance < lnet_numa_range)
+ distance = lnet_numa_range;
+
+ /*
+ * Select on shorter distance, then available
+ * credits, then round-robin.
+ */
+ if (distance > shortest_distance) {
+ continue;
+ } else if (distance < shortest_distance) {
+ shortest_distance = distance;
+ } else if (ni_credits < best_credits) {
+ continue;
+ } else if (ni_credits == best_credits) {
+ if (best_ni && (best_ni)->ni_seq <= ni->ni_seq)
+ continue;
+ }
+ best_ni = ni;
+ best_credits = ni_credits;
+ }
+
+ return best_ni;
+}
+