Merge "Merge release-4-6 into master"
[alexxy/gromacs.git] / src / gromacs / mdlib / nbnxn_search.c
1 /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
2  *
3  *
4  *                This source code is part of
5  *
6  *                 G   R   O   M   A   C   S
7  *
8  *          GROningen MAchine for Chemical Simulations
9  *
10  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
11  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
12  * Copyright (c) 2001-2012, The GROMACS development team,
13  * check out http://www.gromacs.org for more information.
14
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * as published by the Free Software Foundation; either version 2
18  * of the License, or (at your option) any later version.
19  *
20  * If you want to redistribute modifications, please consider that
21  * scientific software is very special. Version control is crucial -
22  * bugs must be traceable. We will be happy to consider code for
23  * inclusion in the official distribution, but derived work must not
24  * be called official GROMACS. Details are found in the README & COPYING
25  * files - if they are missing, get the official version at www.gromacs.org.
26  *
27  * To help us fund GROMACS development, we humbly ask that you cite
28  * the papers on the package - you can find them in the top README file.
29  *
30  * For more info, check our website at http://www.gromacs.org
31  */
32
33 #ifdef HAVE_CONFIG_H
34 #include <config.h>
35 #endif
36
37 #include <math.h>
38 #include <string.h>
39 #include "sysstuff.h"
40 #include "smalloc.h"
41 #include "macros.h"
42 #include "maths.h"
43 #include "vec.h"
44 #include "pbc.h"
45 #include "nbnxn_consts.h"
46 #include "nbnxn_internal.h"
47 #include "nbnxn_atomdata.h"
48 #include "nbnxn_search.h"
49 #include "gmx_cyclecounter.h"
50 #include "gmxfio.h"
51 #include "gmx_omp_nthreads.h"
52 #include "nrnb.h"
53
54
55 /* Pair search box lower and upper corner in x,y,z.
56  * Store this in 4 iso 3 reals, which is useful with SSE.
57  * To avoid complicating the code we also use 4 without SSE.
58  */
59 #define NNBSBB_C         4
60 #define NNBSBB_B         (2*NNBSBB_C)
61 /* Pair search box lower and upper bound in z only. */
62 #define NNBSBB_D         2
63 /* Pair search box lower and upper corner x,y,z indices */
64 #define BBL_X  0
65 #define BBL_Y  1
66 #define BBL_Z  2
67 #define BBU_X  4
68 #define BBU_Y  5
69 #define BBU_Z  6
70
71
72 #ifdef NBNXN_SEARCH_BB_SSE
73 /* We use SSE or AVX-128bit for bounding box calculations */
74
75 #ifndef GMX_DOUBLE
76 /* Single precision BBs + coordinates, we can also load coordinates using SSE */
77 #define NBNXN_SEARCH_SSE_SINGLE
78 #endif
79
80 /* Include basic SSE2 stuff */
81 #include <emmintrin.h>
82
83 #if defined NBNXN_SEARCH_SSE_SINGLE && (GPU_NSUBCELL == 4 || GPU_NSUBCELL == 8)
84 /* Store bounding boxes with x, y and z coordinates in packs of 4 */
85 #define NBNXN_PBB_SSE
86 #endif
87
88 /* The width of SSE/AVX128 with single precision for bounding boxes with GPU.
89  * Here AVX-256 turns out to be slightly slower than AVX-128.
90  */
91 #define STRIDE_PBB        4
92 #define STRIDE_PBB_2LOG   2
93
94 #endif /* NBNXN_SEARCH_BB_SSE */
95
96 #ifdef GMX_NBNXN_SIMD
97
98 /* The functions below are macros as they are performance sensitive */
99
100 /* 4x4 list, pack=4: no complex conversion required */
101 /* i-cluster to j-cluster conversion */
102 #define CI_TO_CJ_J4(ci)   (ci)
103 /* cluster index to coordinate array index conversion */
104 #define X_IND_CI_J4(ci)  ((ci)*STRIDE_P4)
105 #define X_IND_CJ_J4(cj)  ((cj)*STRIDE_P4)
106
107 /* 4x2 list, pack=4: j-cluster size is half the packing width */
108 /* i-cluster to j-cluster conversion */
109 #define CI_TO_CJ_J2(ci)  ((ci)<<1)
110 /* cluster index to coordinate array index conversion */
111 #define X_IND_CI_J2(ci)  ((ci)*STRIDE_P4)
112 #define X_IND_CJ_J2(cj)  (((cj)>>1)*STRIDE_P4 + ((cj) & 1)*(PACK_X4>>1))
113
114 /* 4x8 list, pack=8: i-cluster size is half the packing width */
115 /* i-cluster to j-cluster conversion */
116 #define CI_TO_CJ_J8(ci)  ((ci)>>1)
117 /* cluster index to coordinate array index conversion */
118 #define X_IND_CI_J8(ci)  (((ci)>>1)*STRIDE_P8 + ((ci) & 1)*(PACK_X8>>1))
119 #define X_IND_CJ_J8(cj)  ((cj)*STRIDE_P8)
120
121 /* The j-cluster size is matched to the SIMD width */
122 #if GMX_NBNXN_SIMD_BITWIDTH == 128
123 #ifdef GMX_DOUBLE
124 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J2(ci)
125 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J2(ci)
126 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J2(cj)
127 #else
128 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J4(ci)
129 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J4(ci)
130 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J4(cj)
131 #endif
132 #else
133 #if GMX_NBNXN_SIMD_BITWIDTH == 256
134 #ifdef GMX_DOUBLE
135 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J4(ci)
136 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J4(ci)
137 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J4(cj)
138 #else
139 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J8(ci)
140 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J8(ci)
141 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J8(cj)
142 /* Half SIMD with j-cluster size */
143 #define CI_TO_CJ_SIMD_2XNN(ci) CI_TO_CJ_J4(ci)
144 #define X_IND_CI_SIMD_2XNN(ci) X_IND_CI_J4(ci)
145 #define X_IND_CJ_SIMD_2XNN(cj) X_IND_CJ_J4(cj)
146 #endif
147 #else
148 #error "unsupported GMX_NBNXN_SIMD_WIDTH"
149 #endif
150 #endif
151
152 #endif /* GMX_NBNXN_SIMD */
153
154
155 /* Interaction masks for 4xN atom interactions.
156  * Bit i*CJ_SIZE + j tells if atom i and j interact.
157  */
158 /* All interaction mask is the same for all kernels */
159 #define NBNXN_INT_MASK_ALL        0xffffffff
160 /* 4x4 kernel diagonal mask */
161 #define NBNXN_INT_MASK_DIAG       0x08ce
162 /* 4x2 kernel diagonal masks */
163 #define NBNXN_INT_MASK_DIAG_J2_0  0x0002
164 #define NBNXN_INT_MASK_DIAG_J2_1  0x002F
165 /* 4x8 kernel diagonal masks */
166 #define NBNXN_INT_MASK_DIAG_J8_0  0xf0f8fcfe
167 #define NBNXN_INT_MASK_DIAG_J8_1  0x0080c0e0
168
169
170 #ifdef NBNXN_SEARCH_BB_SSE
171 /* Store bounding boxes corners as quadruplets: xxxxyyyyzzzz */
172 #define NBNXN_BBXXXX
173 /* Size of bounding box corners quadruplet */
174 #define NNBSBB_XXXX      (NNBSBB_D*DIM*STRIDE_PBB)
175 #endif
176
177 /* We shift the i-particles backward for PBC.
178  * This leads to more conditionals than shifting forward.
179  * We do this to get more balanced pair lists.
180  */
181 #define NBNXN_SHIFT_BACKWARD
182
183
184 /* This define is a lazy way to avoid interdependence of the grid
185  * and searching data structures.
186  */
187 #define NBNXN_NA_SC_MAX (GPU_NSUBCELL*NBNXN_GPU_CLUSTER_SIZE)
188
189
190 static void nbs_cycle_clear(nbnxn_cycle_t *cc)
191 {
192     int i;
193
194     for (i = 0; i < enbsCCnr; i++)
195     {
196         cc[i].count = 0;
197         cc[i].c     = 0;
198     }
199 }
200
201 static double Mcyc_av(const nbnxn_cycle_t *cc)
202 {
203     return (double)cc->c*1e-6/cc->count;
204 }
205
206 static void nbs_cycle_print(FILE *fp, const nbnxn_search_t nbs)
207 {
208     int n;
209     int t;
210
211     fprintf(fp, "\n");
212     fprintf(fp, "ns %4d grid %4.1f search %4.1f red.f %5.3f",
213             nbs->cc[enbsCCgrid].count,
214             Mcyc_av(&nbs->cc[enbsCCgrid]),
215             Mcyc_av(&nbs->cc[enbsCCsearch]),
216             Mcyc_av(&nbs->cc[enbsCCreducef]));
217
218     if (nbs->nthread_max > 1)
219     {
220         if (nbs->cc[enbsCCcombine].count > 0)
221         {
222             fprintf(fp, " comb %5.2f",
223                     Mcyc_av(&nbs->cc[enbsCCcombine]));
224         }
225         fprintf(fp, " s. th");
226         for (t = 0; t < nbs->nthread_max; t++)
227         {
228             fprintf(fp, " %4.1f",
229                     Mcyc_av(&nbs->work[t].cc[enbsCCsearch]));
230         }
231     }
232     fprintf(fp, "\n");
233 }
234
235 static void nbnxn_grid_init(nbnxn_grid_t * grid)
236 {
237     grid->cxy_na      = NULL;
238     grid->cxy_ind     = NULL;
239     grid->cxy_nalloc  = 0;
240     grid->bb          = NULL;
241     grid->bbj         = NULL;
242     grid->nc_nalloc   = 0;
243 }
244
245 static int get_2log(int n)
246 {
247     int log2;
248
249     log2 = 0;
250     while ((1<<log2) < n)
251     {
252         log2++;
253     }
254     if ((1<<log2) != n)
255     {
256         gmx_fatal(FARGS, "nbnxn na_c (%d) is not a power of 2", n);
257     }
258
259     return log2;
260 }
261
262 static int nbnxn_kernel_to_ci_size(int nb_kernel_type)
263 {
264     switch (nb_kernel_type)
265     {
266         case nbnxnk4x4_PlainC:
267         case nbnxnk4xN_SIMD_4xN:
268         case nbnxnk4xN_SIMD_2xNN:
269             return NBNXN_CPU_CLUSTER_I_SIZE;
270         case nbnxnk8x8x8_CUDA:
271         case nbnxnk8x8x8_PlainC:
272             /* The cluster size for super/sub lists is only set here.
273              * Any value should work for the pair-search and atomdata code.
274              * The kernels, of course, might require a particular value.
275              */
276             return NBNXN_GPU_CLUSTER_SIZE;
277         default:
278             gmx_incons("unknown kernel type");
279     }
280
281     return 0;
282 }
283
284 int nbnxn_kernel_to_cj_size(int nb_kernel_type)
285 {
286     int nbnxn_simd_width = 0;
287     int cj_size          = 0;
288
289 #ifdef GMX_NBNXN_SIMD
290     nbnxn_simd_width = GMX_NBNXN_SIMD_BITWIDTH/(sizeof(real)*8);
291 #endif
292
293     switch (nb_kernel_type)
294     {
295         case nbnxnk4x4_PlainC:
296             cj_size = NBNXN_CPU_CLUSTER_I_SIZE;
297             break;
298         case nbnxnk4xN_SIMD_4xN:
299             cj_size = nbnxn_simd_width;
300             break;
301         case nbnxnk4xN_SIMD_2xNN:
302             cj_size = nbnxn_simd_width/2;
303             break;
304         case nbnxnk8x8x8_CUDA:
305         case nbnxnk8x8x8_PlainC:
306             cj_size = nbnxn_kernel_to_ci_size(nb_kernel_type);
307             break;
308         default:
309             gmx_incons("unknown kernel type");
310     }
311
312     return cj_size;
313 }
314
315 static int ci_to_cj(int na_cj_2log, int ci)
316 {
317     switch (na_cj_2log)
318     {
319         case 2: return ci;     break;
320         case 1: return (ci<<1); break;
321         case 3: return (ci>>1); break;
322     }
323
324     return 0;
325 }
326
327 gmx_bool nbnxn_kernel_pairlist_simple(int nb_kernel_type)
328 {
329     if (nb_kernel_type == nbnxnkNotSet)
330     {
331         gmx_fatal(FARGS, "Non-bonded kernel type not set for Verlet-style pair-list.");
332     }
333
334     switch (nb_kernel_type)
335     {
336         case nbnxnk8x8x8_CUDA:
337         case nbnxnk8x8x8_PlainC:
338             return FALSE;
339
340         case nbnxnk4x4_PlainC:
341         case nbnxnk4xN_SIMD_4xN:
342         case nbnxnk4xN_SIMD_2xNN:
343             return TRUE;
344
345         default:
346             gmx_incons("Invalid nonbonded kernel type passed!");
347             return FALSE;
348     }
349 }
350
351 void nbnxn_init_search(nbnxn_search_t    * nbs_ptr,
352                        ivec               *n_dd_cells,
353                        gmx_domdec_zones_t *zones,
354                        int                 nthread_max)
355 {
356     nbnxn_search_t nbs;
357     int            d, g, t;
358
359     snew(nbs, 1);
360     *nbs_ptr = nbs;
361
362     nbs->DomDec = (n_dd_cells != NULL);
363
364     clear_ivec(nbs->dd_dim);
365     nbs->ngrid = 1;
366     if (nbs->DomDec)
367     {
368         nbs->zones = zones;
369
370         for (d = 0; d < DIM; d++)
371         {
372             if ((*n_dd_cells)[d] > 1)
373             {
374                 nbs->dd_dim[d] = 1;
375                 /* Each grid matches a DD zone */
376                 nbs->ngrid *= 2;
377             }
378         }
379     }
380
381     snew(nbs->grid, nbs->ngrid);
382     for (g = 0; g < nbs->ngrid; g++)
383     {
384         nbnxn_grid_init(&nbs->grid[g]);
385     }
386     nbs->cell        = NULL;
387     nbs->cell_nalloc = 0;
388     nbs->a           = NULL;
389     nbs->a_nalloc    = 0;
390
391     nbs->nthread_max = nthread_max;
392
393     /* Initialize the work data structures for each thread */
394     snew(nbs->work, nbs->nthread_max);
395     for (t = 0; t < nbs->nthread_max; t++)
396     {
397         nbs->work[t].cxy_na           = NULL;
398         nbs->work[t].cxy_na_nalloc    = 0;
399         nbs->work[t].sort_work        = NULL;
400         nbs->work[t].sort_work_nalloc = 0;
401     }
402
403     /* Initialize detailed nbsearch cycle counting */
404     nbs->print_cycles = (getenv("GMX_NBNXN_CYCLE") != 0);
405     nbs->search_count = 0;
406     nbs_cycle_clear(nbs->cc);
407     for (t = 0; t < nbs->nthread_max; t++)
408     {
409         nbs_cycle_clear(nbs->work[t].cc);
410     }
411 }
412
413 static real grid_atom_density(int n, rvec corner0, rvec corner1)
414 {
415     rvec size;
416
417     rvec_sub(corner1, corner0, size);
418
419     return n/(size[XX]*size[YY]*size[ZZ]);
420 }
421
422 static int set_grid_size_xy(const nbnxn_search_t nbs,
423                             nbnxn_grid_t *grid,
424                             int dd_zone,
425                             int n, rvec corner0, rvec corner1,
426                             real atom_density,
427                             int XFormat)
428 {
429     rvec size;
430     int  na_c;
431     real adens, tlen, tlen_x, tlen_y, nc_max;
432     int  t;
433
434     rvec_sub(corner1, corner0, size);
435
436     if (n > grid->na_sc)
437     {
438         /* target cell length */
439         if (grid->bSimple)
440         {
441             /* To minimize the zero interactions, we should make
442              * the largest of the i/j cell cubic.
443              */
444             na_c = max(grid->na_c, grid->na_cj);
445
446             /* Approximately cubic cells */
447             tlen   = pow(na_c/atom_density, 1.0/3.0);
448             tlen_x = tlen;
449             tlen_y = tlen;
450         }
451         else
452         {
453             /* Approximately cubic sub cells */
454             tlen   = pow(grid->na_c/atom_density, 1.0/3.0);
455             tlen_x = tlen*GPU_NSUBCELL_X;
456             tlen_y = tlen*GPU_NSUBCELL_Y;
457         }
458         /* We round ncx and ncy down, because we get less cell pairs
459          * in the nbsist when the fixed cell dimensions (x,y) are
460          * larger than the variable one (z) than the other way around.
461          */
462         grid->ncx = max(1, (int)(size[XX]/tlen_x));
463         grid->ncy = max(1, (int)(size[YY]/tlen_y));
464     }
465     else
466     {
467         grid->ncx = 1;
468         grid->ncy = 1;
469     }
470
471     grid->sx     = size[XX]/grid->ncx;
472     grid->sy     = size[YY]/grid->ncy;
473     grid->inv_sx = 1/grid->sx;
474     grid->inv_sy = 1/grid->sy;
475
476     if (dd_zone > 0)
477     {
478         /* This is a non-home zone, add an extra row of cells
479          * for particles communicated for bonded interactions.
480          * These can be beyond the cut-off. It doesn't matter where
481          * they end up on the grid, but for performance it's better
482          * if they don't end up in cells that can be within cut-off range.
483          */
484         grid->ncx++;
485         grid->ncy++;
486     }
487
488     /* We need one additional cell entry for particles moved by DD */
489     if (grid->ncx*grid->ncy+1 > grid->cxy_nalloc)
490     {
491         grid->cxy_nalloc = over_alloc_large(grid->ncx*grid->ncy+1);
492         srenew(grid->cxy_na, grid->cxy_nalloc);
493         srenew(grid->cxy_ind, grid->cxy_nalloc+1);
494     }
495     for (t = 0; t < nbs->nthread_max; t++)
496     {
497         if (grid->ncx*grid->ncy+1 > nbs->work[t].cxy_na_nalloc)
498         {
499             nbs->work[t].cxy_na_nalloc = over_alloc_large(grid->ncx*grid->ncy+1);
500             srenew(nbs->work[t].cxy_na, nbs->work[t].cxy_na_nalloc);
501         }
502     }
503
504     /* Worst case scenario of 1 atom in each last cell */
505     if (grid->na_cj <= grid->na_c)
506     {
507         nc_max = n/grid->na_sc + grid->ncx*grid->ncy;
508     }
509     else
510     {
511         nc_max = n/grid->na_sc + grid->ncx*grid->ncy*grid->na_cj/grid->na_c;
512     }
513
514     if (nc_max > grid->nc_nalloc)
515     {
516         int bb_nalloc;
517
518         grid->nc_nalloc = over_alloc_large(nc_max);
519         srenew(grid->nsubc, grid->nc_nalloc);
520         srenew(grid->bbcz, grid->nc_nalloc*NNBSBB_D);
521 #ifdef NBNXN_PBB_SSE
522         bb_nalloc = grid->nc_nalloc*GPU_NSUBCELL/STRIDE_PBB*NNBSBB_XXXX;
523 #else
524         bb_nalloc = grid->nc_nalloc*GPU_NSUBCELL*NNBSBB_B;
525 #endif
526         sfree_aligned(grid->bb);
527         /* This snew also zeros the contents, this avoid possible
528          * floating exceptions in SSE with the unused bb elements.
529          */
530         snew_aligned(grid->bb, bb_nalloc, 16);
531
532         if (grid->bSimple)
533         {
534             if (grid->na_cj == grid->na_c)
535             {
536                 grid->bbj = grid->bb;
537             }
538             else
539             {
540                 sfree_aligned(grid->bbj);
541                 snew_aligned(grid->bbj, bb_nalloc*grid->na_c/grid->na_cj, 16);
542             }
543         }
544
545         srenew(grid->flags, grid->nc_nalloc);
546     }
547
548     copy_rvec(corner0, grid->c0);
549     copy_rvec(corner1, grid->c1);
550
551     return nc_max;
552 }
553
554 /* We need to sort paricles in grid columns on z-coordinate.
555  * As particle are very often distributed homogeneously, we a sorting
556  * algorithm similar to pigeonhole sort. We multiply the z-coordinate
557  * by a factor, cast to an int and try to store in that hole. If the hole
558  * is full, we move this or another particle. A second pass is needed to make
559  * contiguous elements. SORT_GRID_OVERSIZE is the ratio of holes to particles.
560  * 4 is the optimal value for homogeneous particle distribution and allows
561  * for an O(#particles) sort up till distributions were all particles are
562  * concentrated in 1/4 of the space. No NlogN fallback is implemented,
563  * as it can be expensive to detect imhomogeneous particle distributions.
564  * SGSF is the maximum ratio of holes used, in the worst case all particles
565  * end up in the last hole and we need #particles extra holes at the end.
566  */
567 #define SORT_GRID_OVERSIZE 4
568 #define SGSF (SORT_GRID_OVERSIZE + 1)
569
570 /* Sort particle index a on coordinates x along dim.
571  * Backwards tells if we want decreasing iso increasing coordinates.
572  * h0 is the minimum of the coordinate range.
573  * invh is the 1/length of the sorting range.
574  * n_per_h (>=n) is the expected average number of particles per 1/invh
575  * sort is the sorting work array.
576  * sort should have a size of at least n_per_h*SORT_GRID_OVERSIZE + n,
577  * or easier, allocate at least n*SGSF elements.
578  */
579 static void sort_atoms(int dim, gmx_bool Backwards,
580                        int *a, int n, rvec *x,
581                        real h0, real invh, int n_per_h,
582                        int *sort)
583 {
584     int nsort, i, c;
585     int zi, zim, zi_min, zi_max;
586     int cp, tmp;
587
588     if (n <= 1)
589     {
590         /* Nothing to do */
591         return;
592     }
593
594 #ifndef NDEBUG
595     if (n > n_per_h)
596     {
597         gmx_incons("n > n_per_h");
598     }
599 #endif
600
601     /* Transform the inverse range height into the inverse hole height */
602     invh *= n_per_h*SORT_GRID_OVERSIZE;
603
604     /* Set nsort to the maximum possible number of holes used.
605      * In worst case all n elements end up in the last bin.
606      */
607     nsort = n_per_h*SORT_GRID_OVERSIZE + n;
608
609     /* Determine the index range used, so we can limit it for the second pass */
610     zi_min = INT_MAX;
611     zi_max = -1;
612
613     /* Sort the particles using a simple index sort */
614     for (i = 0; i < n; i++)
615     {
616         /* The cast takes care of float-point rounding effects below zero.
617          * This code assumes particles are less than 1/SORT_GRID_OVERSIZE
618          * times the box height out of the box.
619          */
620         zi = (int)((x[a[i]][dim] - h0)*invh);
621
622 #ifndef NDEBUG
623         /* As we can have rounding effect, we use > iso >= here */
624         if (zi < 0 || zi > n_per_h*SORT_GRID_OVERSIZE)
625         {
626             gmx_fatal(FARGS, "(int)((x[%d][%c]=%f - %f)*%f) = %d, not in 0 - %d*%d\n",
627                       a[i], 'x'+dim, x[a[i]][dim], h0, invh, zi,
628                       n_per_h, SORT_GRID_OVERSIZE);
629         }
630 #endif
631
632         /* Ideally this particle should go in sort cell zi,
633          * but that might already be in use,
634          * in that case find the first empty cell higher up
635          */
636         if (sort[zi] < 0)
637         {
638             sort[zi] = a[i];
639             zi_min   = min(zi_min, zi);
640             zi_max   = max(zi_max, zi);
641         }
642         else
643         {
644             /* We have multiple atoms in the same sorting slot.
645              * Sort on real z for minimal bounding box size.
646              * There is an extra check for identical z to ensure
647              * well-defined output order, independent of input order
648              * to ensure binary reproducibility after restarts.
649              */
650             while (sort[zi] >= 0 && ( x[a[i]][dim] >  x[sort[zi]][dim] ||
651                                       (x[a[i]][dim] == x[sort[zi]][dim] &&
652                                        a[i] > sort[zi])))
653             {
654                 zi++;
655             }
656
657             if (sort[zi] >= 0)
658             {
659                 /* Shift all elements by one slot until we find an empty slot */
660                 cp  = sort[zi];
661                 zim = zi + 1;
662                 while (sort[zim] >= 0)
663                 {
664                     tmp       = sort[zim];
665                     sort[zim] = cp;
666                     cp        = tmp;
667                     zim++;
668                 }
669                 sort[zim] = cp;
670                 zi_max    = max(zi_max, zim);
671             }
672             sort[zi] = a[i];
673             zi_max   = max(zi_max, zi);
674         }
675     }
676
677     c = 0;
678     if (!Backwards)
679     {
680         for (zi = 0; zi < nsort; zi++)
681         {
682             if (sort[zi] >= 0)
683             {
684                 a[c++]   = sort[zi];
685                 sort[zi] = -1;
686             }
687         }
688     }
689     else
690     {
691         for (zi = zi_max; zi >= zi_min; zi--)
692         {
693             if (sort[zi] >= 0)
694             {
695                 a[c++]   = sort[zi];
696                 sort[zi] = -1;
697             }
698         }
699     }
700     if (c < n)
701     {
702         gmx_incons("Lost particles while sorting");
703     }
704 }
705
706 #ifdef GMX_DOUBLE
707 #define R2F_D(x) ((float)((x) >= 0 ? ((1-GMX_FLOAT_EPS)*(x)) : ((1+GMX_FLOAT_EPS)*(x))))
708 #define R2F_U(x) ((float)((x) >= 0 ? ((1+GMX_FLOAT_EPS)*(x)) : ((1-GMX_FLOAT_EPS)*(x))))
709 #else
710 #define R2F_D(x) (x)
711 #define R2F_U(x) (x)
712 #endif
713
714 /* Coordinate order x,y,z, bb order xyz0 */
715 static void calc_bounding_box(int na, int stride, const real *x, float *bb)
716 {
717     int  i, j;
718     real xl, xh, yl, yh, zl, zh;
719
720     i  = 0;
721     xl = x[i+XX];
722     xh = x[i+XX];
723     yl = x[i+YY];
724     yh = x[i+YY];
725     zl = x[i+ZZ];
726     zh = x[i+ZZ];
727     i += stride;
728     for (j = 1; j < na; j++)
729     {
730         xl = min(xl, x[i+XX]);
731         xh = max(xh, x[i+XX]);
732         yl = min(yl, x[i+YY]);
733         yh = max(yh, x[i+YY]);
734         zl = min(zl, x[i+ZZ]);
735         zh = max(zh, x[i+ZZ]);
736         i += stride;
737     }
738     /* Note: possible double to float conversion here */
739     bb[BBL_X] = R2F_D(xl);
740     bb[BBL_Y] = R2F_D(yl);
741     bb[BBL_Z] = R2F_D(zl);
742     bb[BBU_X] = R2F_U(xh);
743     bb[BBU_Y] = R2F_U(yh);
744     bb[BBU_Z] = R2F_U(zh);
745 }
746
747 /* Packed coordinates, bb order xyz0 */
748 static void calc_bounding_box_x_x4(int na, const real *x, float *bb)
749 {
750     int  j;
751     real xl, xh, yl, yh, zl, zh;
752
753     xl = x[XX*PACK_X4];
754     xh = x[XX*PACK_X4];
755     yl = x[YY*PACK_X4];
756     yh = x[YY*PACK_X4];
757     zl = x[ZZ*PACK_X4];
758     zh = x[ZZ*PACK_X4];
759     for (j = 1; j < na; j++)
760     {
761         xl = min(xl, x[j+XX*PACK_X4]);
762         xh = max(xh, x[j+XX*PACK_X4]);
763         yl = min(yl, x[j+YY*PACK_X4]);
764         yh = max(yh, x[j+YY*PACK_X4]);
765         zl = min(zl, x[j+ZZ*PACK_X4]);
766         zh = max(zh, x[j+ZZ*PACK_X4]);
767     }
768     /* Note: possible double to float conversion here */
769     bb[BBL_X] = R2F_D(xl);
770     bb[BBL_Y] = R2F_D(yl);
771     bb[BBL_Z] = R2F_D(zl);
772     bb[BBU_X] = R2F_U(xh);
773     bb[BBU_Y] = R2F_U(yh);
774     bb[BBU_Z] = R2F_U(zh);
775 }
776
777 /* Packed coordinates, bb order xyz0 */
778 static void calc_bounding_box_x_x8(int na, const real *x, float *bb)
779 {
780     int  j;
781     real xl, xh, yl, yh, zl, zh;
782
783     xl = x[XX*PACK_X8];
784     xh = x[XX*PACK_X8];
785     yl = x[YY*PACK_X8];
786     yh = x[YY*PACK_X8];
787     zl = x[ZZ*PACK_X8];
788     zh = x[ZZ*PACK_X8];
789     for (j = 1; j < na; j++)
790     {
791         xl = min(xl, x[j+XX*PACK_X8]);
792         xh = max(xh, x[j+XX*PACK_X8]);
793         yl = min(yl, x[j+YY*PACK_X8]);
794         yh = max(yh, x[j+YY*PACK_X8]);
795         zl = min(zl, x[j+ZZ*PACK_X8]);
796         zh = max(zh, x[j+ZZ*PACK_X8]);
797     }
798     /* Note: possible double to float conversion here */
799     bb[BBL_X] = R2F_D(xl);
800     bb[BBL_Y] = R2F_D(yl);
801     bb[BBL_Z] = R2F_D(zl);
802     bb[BBU_X] = R2F_U(xh);
803     bb[BBU_Y] = R2F_U(yh);
804     bb[BBU_Z] = R2F_U(zh);
805 }
806
807 #ifdef NBNXN_SEARCH_BB_SSE
808
809 /* Packed coordinates, bb order xyz0 */
810 static void calc_bounding_box_x_x4_halves(int na, const real *x,
811                                           float *bb, float *bbj)
812 {
813     calc_bounding_box_x_x4(min(na, 2), x, bbj);
814
815     if (na > 2)
816     {
817         calc_bounding_box_x_x4(min(na-2, 2), x+(PACK_X4>>1), bbj+NNBSBB_B);
818     }
819     else
820     {
821         /* Set the "empty" bounding box to the same as the first one,
822          * so we don't need to treat special cases in the rest of the code.
823          */
824         _mm_store_ps(bbj+NNBSBB_B, _mm_load_ps(bbj));
825         _mm_store_ps(bbj+NNBSBB_B+NNBSBB_C, _mm_load_ps(bbj+NNBSBB_C));
826     }
827
828     _mm_store_ps(bb, _mm_min_ps(_mm_load_ps(bbj),
829                                 _mm_load_ps(bbj+NNBSBB_B)));
830     _mm_store_ps(bb+NNBSBB_C, _mm_max_ps(_mm_load_ps(bbj+NNBSBB_C),
831                                          _mm_load_ps(bbj+NNBSBB_B+NNBSBB_C)));
832 }
833
834 /* Coordinate order xyz, bb order xxxxyyyyzzzz */
835 static void calc_bounding_box_xxxx(int na, int stride, const real *x, float *bb)
836 {
837     int  i, j;
838     real xl, xh, yl, yh, zl, zh;
839
840     i  = 0;
841     xl = x[i+XX];
842     xh = x[i+XX];
843     yl = x[i+YY];
844     yh = x[i+YY];
845     zl = x[i+ZZ];
846     zh = x[i+ZZ];
847     i += stride;
848     for (j = 1; j < na; j++)
849     {
850         xl = min(xl, x[i+XX]);
851         xh = max(xh, x[i+XX]);
852         yl = min(yl, x[i+YY]);
853         yh = max(yh, x[i+YY]);
854         zl = min(zl, x[i+ZZ]);
855         zh = max(zh, x[i+ZZ]);
856         i += stride;
857     }
858     /* Note: possible double to float conversion here */
859     bb[0*STRIDE_PBB] = R2F_D(xl);
860     bb[1*STRIDE_PBB] = R2F_D(yl);
861     bb[2*STRIDE_PBB] = R2F_D(zl);
862     bb[3*STRIDE_PBB] = R2F_U(xh);
863     bb[4*STRIDE_PBB] = R2F_U(yh);
864     bb[5*STRIDE_PBB] = R2F_U(zh);
865 }
866
867 #endif /* NBNXN_SEARCH_BB_SSE */
868
869 #ifdef NBNXN_SEARCH_SSE_SINGLE
870
871 /* Coordinate order xyz?, bb order xyz0 */
872 static void calc_bounding_box_sse(int na, const float *x, float *bb)
873 {
874     __m128 bb_0_SSE, bb_1_SSE;
875     __m128 x_SSE;
876
877     int    i;
878
879     bb_0_SSE = _mm_load_ps(x);
880     bb_1_SSE = bb_0_SSE;
881
882     for (i = 1; i < na; i++)
883     {
884         x_SSE    = _mm_load_ps(x+i*NNBSBB_C);
885         bb_0_SSE = _mm_min_ps(bb_0_SSE, x_SSE);
886         bb_1_SSE = _mm_max_ps(bb_1_SSE, x_SSE);
887     }
888
889     _mm_store_ps(bb, bb_0_SSE);
890     _mm_store_ps(bb+4, bb_1_SSE);
891 }
892
893 /* Coordinate order xyz?, bb order xxxxyyyyzzzz */
894 static void calc_bounding_box_xxxx_sse(int na, const float *x,
895                                        float *bb_work,
896                                        real *bb)
897 {
898     calc_bounding_box_sse(na, x, bb_work);
899
900     bb[0*STRIDE_PBB] = bb_work[BBL_X];
901     bb[1*STRIDE_PBB] = bb_work[BBL_Y];
902     bb[2*STRIDE_PBB] = bb_work[BBL_Z];
903     bb[3*STRIDE_PBB] = bb_work[BBU_X];
904     bb[4*STRIDE_PBB] = bb_work[BBU_Y];
905     bb[5*STRIDE_PBB] = bb_work[BBU_Z];
906 }
907
908 #endif /* NBNXN_SEARCH_SSE_SINGLE */
909
910 #ifdef NBNXN_SEARCH_BB_SSE
911
912 /* Combines pairs of consecutive bounding boxes */
913 static void combine_bounding_box_pairs(nbnxn_grid_t *grid, const float *bb)
914 {
915     int    i, j, sc2, nc2, c2;
916     __m128 min_SSE, max_SSE;
917
918     for (i = 0; i < grid->ncx*grid->ncy; i++)
919     {
920         /* Starting bb in a column is expected to be 2-aligned */
921         sc2 = grid->cxy_ind[i]>>1;
922         /* For odd numbers skip the last bb here */
923         nc2 = (grid->cxy_na[i]+3)>>(2+1);
924         for (c2 = sc2; c2 < sc2+nc2; c2++)
925         {
926             min_SSE = _mm_min_ps(_mm_load_ps(bb+(c2*4+0)*NNBSBB_C),
927                                  _mm_load_ps(bb+(c2*4+2)*NNBSBB_C));
928             max_SSE = _mm_max_ps(_mm_load_ps(bb+(c2*4+1)*NNBSBB_C),
929                                  _mm_load_ps(bb+(c2*4+3)*NNBSBB_C));
930             _mm_store_ps(grid->bbj+(c2*2+0)*NNBSBB_C, min_SSE);
931             _mm_store_ps(grid->bbj+(c2*2+1)*NNBSBB_C, max_SSE);
932         }
933         if (((grid->cxy_na[i]+3)>>2) & 1)
934         {
935             /* Copy the last bb for odd bb count in this column */
936             for (j = 0; j < NNBSBB_C; j++)
937             {
938                 grid->bbj[(c2*2+0)*NNBSBB_C+j] = bb[(c2*4+0)*NNBSBB_C+j];
939                 grid->bbj[(c2*2+1)*NNBSBB_C+j] = bb[(c2*4+1)*NNBSBB_C+j];
940             }
941         }
942     }
943 }
944
945 #endif
946
947
948 /* Prints the average bb size, used for debug output */
949 static void print_bbsizes_simple(FILE                *fp,
950                                  const nbnxn_search_t nbs,
951                                  const nbnxn_grid_t  *grid)
952 {
953     int  c, d;
954     dvec ba;
955
956     clear_dvec(ba);
957     for (c = 0; c < grid->nc; c++)
958     {
959         for (d = 0; d < DIM; d++)
960         {
961             ba[d] += grid->bb[c*NNBSBB_B+NNBSBB_C+d] - grid->bb[c*NNBSBB_B+d];
962         }
963     }
964     dsvmul(1.0/grid->nc, ba, ba);
965
966     fprintf(fp, "ns bb: %4.2f %4.2f %4.2f  %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n",
967             nbs->box[XX][XX]/grid->ncx,
968             nbs->box[YY][YY]/grid->ncy,
969             nbs->box[ZZ][ZZ]*grid->ncx*grid->ncy/grid->nc,
970             ba[XX], ba[YY], ba[ZZ],
971             ba[XX]*grid->ncx/nbs->box[XX][XX],
972             ba[YY]*grid->ncy/nbs->box[YY][YY],
973             ba[ZZ]*grid->nc/(grid->ncx*grid->ncy*nbs->box[ZZ][ZZ]));
974 }
975
976 /* Prints the average bb size, used for debug output */
977 static void print_bbsizes_supersub(FILE                *fp,
978                                    const nbnxn_search_t nbs,
979                                    const nbnxn_grid_t  *grid)
980 {
981     int  ns, c, s;
982     dvec ba;
983
984     clear_dvec(ba);
985     ns = 0;
986     for (c = 0; c < grid->nc; c++)
987     {
988 #ifdef NBNXN_BBXXXX
989         for (s = 0; s < grid->nsubc[c]; s += STRIDE_PBB)
990         {
991             int cs_w, i, d;
992
993             cs_w = (c*GPU_NSUBCELL + s)/STRIDE_PBB;
994             for (i = 0; i < STRIDE_PBB; i++)
995             {
996                 for (d = 0; d < DIM; d++)
997                 {
998                     ba[d] +=
999                         grid->bb[cs_w*NNBSBB_XXXX+(DIM+d)*STRIDE_PBB+i] -
1000                         grid->bb[cs_w*NNBSBB_XXXX+     d *STRIDE_PBB+i];
1001                 }
1002             }
1003         }
1004 #else
1005         for (s = 0; s < grid->nsubc[c]; s++)
1006         {
1007             int cs, d;
1008
1009             cs = c*GPU_NSUBCELL + s;
1010             for (d = 0; d < DIM; d++)
1011             {
1012                 ba[d] +=
1013                     grid->bb[cs*NNBSBB_B+NNBSBB_C+d] -
1014                     grid->bb[cs*NNBSBB_B         +d];
1015             }
1016         }
1017 #endif
1018         ns += grid->nsubc[c];
1019     }
1020     dsvmul(1.0/ns, ba, ba);
1021
1022     fprintf(fp, "ns bb: %4.2f %4.2f %4.2f  %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n",
1023             nbs->box[XX][XX]/(grid->ncx*GPU_NSUBCELL_X),
1024             nbs->box[YY][YY]/(grid->ncy*GPU_NSUBCELL_Y),
1025             nbs->box[ZZ][ZZ]*grid->ncx*grid->ncy/(grid->nc*GPU_NSUBCELL_Z),
1026             ba[XX], ba[YY], ba[ZZ],
1027             ba[XX]*grid->ncx*GPU_NSUBCELL_X/nbs->box[XX][XX],
1028             ba[YY]*grid->ncy*GPU_NSUBCELL_Y/nbs->box[YY][YY],
1029             ba[ZZ]*grid->nc*GPU_NSUBCELL_Z/(grid->ncx*grid->ncy*nbs->box[ZZ][ZZ]));
1030 }
1031
1032 /* Potentially sorts atoms on LJ coefficients !=0 and ==0.
1033  * Also sets interaction flags.
1034  */
1035 void sort_on_lj(nbnxn_atomdata_t *nbat, int na_c,
1036                 int a0, int a1, const int *atinfo,
1037                 int *order,
1038                 int *flags)
1039 {
1040     int      subc, s, a, n1, n2, a_lj_max, i, j;
1041     int      sort1[NBNXN_NA_SC_MAX/GPU_NSUBCELL];
1042     int      sort2[NBNXN_NA_SC_MAX/GPU_NSUBCELL];
1043     gmx_bool haveQ;
1044
1045     *flags = 0;
1046
1047     subc = 0;
1048     for (s = a0; s < a1; s += na_c)
1049     {
1050         /* Make lists for this (sub-)cell on atoms with and without LJ */
1051         n1       = 0;
1052         n2       = 0;
1053         haveQ    = FALSE;
1054         a_lj_max = -1;
1055         for (a = s; a < min(s+na_c, a1); a++)
1056         {
1057             haveQ = haveQ || GET_CGINFO_HAS_Q(atinfo[order[a]]);
1058
1059             if (GET_CGINFO_HAS_VDW(atinfo[order[a]]))
1060             {
1061                 sort1[n1++] = order[a];
1062                 a_lj_max    = a;
1063             }
1064             else
1065             {
1066                 sort2[n2++] = order[a];
1067             }
1068         }
1069
1070         /* If we don't have atom with LJ, there's nothing to sort */
1071         if (n1 > 0)
1072         {
1073             *flags |= NBNXN_CI_DO_LJ(subc);
1074
1075             if (2*n1 <= na_c)
1076             {
1077                 /* Only sort when strictly necessary. Ordering particles
1078                  * Ordering particles can lead to less accurate summation
1079                  * due to rounding, both for LJ and Coulomb interactions.
1080                  */
1081                 if (2*(a_lj_max - s) >= na_c)
1082                 {
1083                     for (i = 0; i < n1; i++)
1084                     {
1085                         order[a0+i] = sort1[i];
1086                     }
1087                     for (j = 0; j < n2; j++)
1088                     {
1089                         order[a0+n1+j] = sort2[j];
1090                     }
1091                 }
1092
1093                 *flags |= NBNXN_CI_HALF_LJ(subc);
1094             }
1095         }
1096         if (haveQ)
1097         {
1098             *flags |= NBNXN_CI_DO_COUL(subc);
1099         }
1100         subc++;
1101     }
1102 }
1103
1104 /* Fill a pair search cell with atoms.
1105  * Potentially sorts atoms and sets the interaction flags.
1106  */
1107 void fill_cell(const nbnxn_search_t nbs,
1108                nbnxn_grid_t *grid,
1109                nbnxn_atomdata_t *nbat,
1110                int a0, int a1,
1111                const int *atinfo,
1112                rvec *x,
1113                int sx, int sy, int sz,
1114                float *bb_work)
1115 {
1116     int     na, a;
1117     size_t  offset;
1118     float  *bb_ptr;
1119
1120     na = a1 - a0;
1121
1122     if (grid->bSimple)
1123     {
1124         sort_on_lj(nbat, grid->na_c, a0, a1, atinfo, nbs->a,
1125                    grid->flags+(a0>>grid->na_c_2log)-grid->cell0);
1126     }
1127
1128     /* Now we have sorted the atoms, set the cell indices */
1129     for (a = a0; a < a1; a++)
1130     {
1131         nbs->cell[nbs->a[a]] = a;
1132     }
1133
1134     copy_rvec_to_nbat_real(nbs->a+a0, a1-a0, grid->na_c, x,
1135                            nbat->XFormat, nbat->x, a0,
1136                            sx, sy, sz);
1137
1138     if (nbat->XFormat == nbatX4)
1139     {
1140         /* Store the bounding boxes as xyz.xyz. */
1141         offset = ((a0 - grid->cell0*grid->na_sc)>>grid->na_c_2log)*NNBSBB_B;
1142         bb_ptr = grid->bb + offset;
1143
1144 #if defined GMX_DOUBLE && defined NBNXN_SEARCH_BB_SSE
1145         if (2*grid->na_cj == grid->na_c)
1146         {
1147             calc_bounding_box_x_x4_halves(na, nbat->x+X4_IND_A(a0), bb_ptr,
1148                                           grid->bbj+offset*2);
1149         }
1150         else
1151 #endif
1152         {
1153             calc_bounding_box_x_x4(na, nbat->x+X4_IND_A(a0), bb_ptr);
1154         }
1155     }
1156     else if (nbat->XFormat == nbatX8)
1157     {
1158         /* Store the bounding boxes as xyz.xyz. */
1159         offset = ((a0 - grid->cell0*grid->na_sc)>>grid->na_c_2log)*NNBSBB_B;
1160         bb_ptr = grid->bb + offset;
1161
1162         calc_bounding_box_x_x8(na, nbat->x+X8_IND_A(a0), bb_ptr);
1163     }
1164 #ifdef NBNXN_BBXXXX
1165     else if (!grid->bSimple)
1166     {
1167         /* Store the bounding boxes in a format convenient
1168          * for SSE calculations: xxxxyyyyzzzz...
1169          */
1170         bb_ptr =
1171             grid->bb +
1172             ((a0-grid->cell0*grid->na_sc)>>(grid->na_c_2log+STRIDE_PBB_2LOG))*NNBSBB_XXXX +
1173             (((a0-grid->cell0*grid->na_sc)>>grid->na_c_2log) & (STRIDE_PBB-1));
1174
1175 #ifdef NBNXN_SEARCH_SSE_SINGLE
1176         if (nbat->XFormat == nbatXYZQ)
1177         {
1178             calc_bounding_box_xxxx_sse(na, nbat->x+a0*nbat->xstride,
1179                                        bb_work, bb_ptr);
1180         }
1181         else
1182 #endif
1183         {
1184             calc_bounding_box_xxxx(na, nbat->xstride, nbat->x+a0*nbat->xstride,
1185                                    bb_ptr);
1186         }
1187         if (gmx_debug_at)
1188         {
1189             fprintf(debug, "%2d %2d %2d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n",
1190                     sx, sy, sz,
1191                     bb_ptr[0*STRIDE_PBB], bb_ptr[3*STRIDE_PBB],
1192                     bb_ptr[1*STRIDE_PBB], bb_ptr[4*STRIDE_PBB],
1193                     bb_ptr[2*STRIDE_PBB], bb_ptr[5*STRIDE_PBB]);
1194         }
1195     }
1196 #endif
1197     else
1198     {
1199         /* Store the bounding boxes as xyz.xyz. */
1200         bb_ptr = grid->bb+((a0-grid->cell0*grid->na_sc)>>grid->na_c_2log)*NNBSBB_B;
1201
1202         calc_bounding_box(na, nbat->xstride, nbat->x+a0*nbat->xstride,
1203                           bb_ptr);
1204
1205         if (gmx_debug_at)
1206         {
1207             int bbo;
1208             bbo = (a0 - grid->cell0*grid->na_sc)/grid->na_c;
1209             fprintf(debug, "%2d %2d %2d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n",
1210                     sx, sy, sz,
1211                     (grid->bb+bbo*NNBSBB_B)[BBL_X],
1212                     (grid->bb+bbo*NNBSBB_B)[BBU_X],
1213                     (grid->bb+bbo*NNBSBB_B)[BBL_Y],
1214                     (grid->bb+bbo*NNBSBB_B)[BBU_Y],
1215                     (grid->bb+bbo*NNBSBB_B)[BBL_Z],
1216                     (grid->bb+bbo*NNBSBB_B)[BBU_Z]);
1217         }
1218     }
1219 }
1220
1221 /* Spatially sort the atoms within one grid column */
1222 static void sort_columns_simple(const nbnxn_search_t nbs,
1223                                 int dd_zone,
1224                                 nbnxn_grid_t *grid,
1225                                 int a0, int a1,
1226                                 const int *atinfo,
1227                                 rvec *x,
1228                                 nbnxn_atomdata_t *nbat,
1229                                 int cxy_start, int cxy_end,
1230                                 int *sort_work)
1231 {
1232     int  cxy;
1233     int  cx, cy, cz, ncz, cfilled, c;
1234     int  na, ash, ind, a;
1235     int  na_c, ash_c;
1236
1237     if (debug)
1238     {
1239         fprintf(debug, "cell0 %d sorting columns %d - %d, atoms %d - %d\n",
1240                 grid->cell0, cxy_start, cxy_end, a0, a1);
1241     }
1242
1243     /* Sort the atoms within each x,y column in 3 dimensions */
1244     for (cxy = cxy_start; cxy < cxy_end; cxy++)
1245     {
1246         cx = cxy/grid->ncy;
1247         cy = cxy - cx*grid->ncy;
1248
1249         na  = grid->cxy_na[cxy];
1250         ncz = grid->cxy_ind[cxy+1] - grid->cxy_ind[cxy];
1251         ash = (grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc;
1252
1253         /* Sort the atoms within each x,y column on z coordinate */
1254         sort_atoms(ZZ, FALSE,
1255                    nbs->a+ash, na, x,
1256                    grid->c0[ZZ],
1257                    1.0/nbs->box[ZZ][ZZ], ncz*grid->na_sc,
1258                    sort_work);
1259
1260         /* Fill the ncz cells in this column */
1261         cfilled = grid->cxy_ind[cxy];
1262         for (cz = 0; cz < ncz; cz++)
1263         {
1264             c  = grid->cxy_ind[cxy] + cz;
1265
1266             ash_c = ash + cz*grid->na_sc;
1267             na_c  = min(grid->na_sc, na-(ash_c-ash));
1268
1269             fill_cell(nbs, grid, nbat,
1270                       ash_c, ash_c+na_c, atinfo, x,
1271                       grid->na_sc*cx + (dd_zone >> 2),
1272                       grid->na_sc*cy + (dd_zone & 3),
1273                       grid->na_sc*cz,
1274                       NULL);
1275
1276             /* This copy to bbcz is not really necessary.
1277              * But it allows to use the same grid search code
1278              * for the simple and supersub cell setups.
1279              */
1280             if (na_c > 0)
1281             {
1282                 cfilled = c;
1283             }
1284             grid->bbcz[c*NNBSBB_D  ] = grid->bb[cfilled*NNBSBB_B+2];
1285             grid->bbcz[c*NNBSBB_D+1] = grid->bb[cfilled*NNBSBB_B+6];
1286         }
1287
1288         /* Set the unused atom indices to -1 */
1289         for (ind = na; ind < ncz*grid->na_sc; ind++)
1290         {
1291             nbs->a[ash+ind] = -1;
1292         }
1293     }
1294 }
1295
1296 /* Spatially sort the atoms within one grid column */
1297 static void sort_columns_supersub(const nbnxn_search_t nbs,
1298                                   int dd_zone,
1299                                   nbnxn_grid_t *grid,
1300                                   int a0, int a1,
1301                                   const int *atinfo,
1302                                   rvec *x,
1303                                   nbnxn_atomdata_t *nbat,
1304                                   int cxy_start, int cxy_end,
1305                                   int *sort_work)
1306 {
1307     int  cxy;
1308     int  cx, cy, cz = -1, c = -1, ncz;
1309     int  na, ash, na_c, ind, a;
1310     int  subdiv_z, sub_z, na_z, ash_z;
1311     int  subdiv_y, sub_y, na_y, ash_y;
1312     int  subdiv_x, sub_x, na_x, ash_x;
1313
1314     /* cppcheck-suppress unassignedVariable */
1315     float bb_work_array[NNBSBB_B+3], *bb_work_align;
1316
1317     bb_work_align = (float *)(((size_t)(bb_work_array+3)) & (~((size_t)15)));
1318
1319     if (debug)
1320     {
1321         fprintf(debug, "cell0 %d sorting columns %d - %d, atoms %d - %d\n",
1322                 grid->cell0, cxy_start, cxy_end, a0, a1);
1323     }
1324
1325     subdiv_x = grid->na_c;
1326     subdiv_y = GPU_NSUBCELL_X*subdiv_x;
1327     subdiv_z = GPU_NSUBCELL_Y*subdiv_y;
1328
1329     /* Sort the atoms within each x,y column in 3 dimensions */
1330     for (cxy = cxy_start; cxy < cxy_end; cxy++)
1331     {
1332         cx = cxy/grid->ncy;
1333         cy = cxy - cx*grid->ncy;
1334
1335         na  = grid->cxy_na[cxy];
1336         ncz = grid->cxy_ind[cxy+1] - grid->cxy_ind[cxy];
1337         ash = (grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc;
1338
1339         /* Sort the atoms within each x,y column on z coordinate */
1340         sort_atoms(ZZ, FALSE,
1341                    nbs->a+ash, na, x,
1342                    grid->c0[ZZ],
1343                    1.0/nbs->box[ZZ][ZZ], ncz*grid->na_sc,
1344                    sort_work);
1345
1346         /* This loop goes over the supercells and subcells along z at once */
1347         for (sub_z = 0; sub_z < ncz*GPU_NSUBCELL_Z; sub_z++)
1348         {
1349             ash_z = ash + sub_z*subdiv_z;
1350             na_z  = min(subdiv_z, na-(ash_z-ash));
1351
1352             /* We have already sorted on z */
1353
1354             if (sub_z % GPU_NSUBCELL_Z == 0)
1355             {
1356                 cz = sub_z/GPU_NSUBCELL_Z;
1357                 c  = grid->cxy_ind[cxy] + cz;
1358
1359                 /* The number of atoms in this supercell */
1360                 na_c = min(grid->na_sc, na-(ash_z-ash));
1361
1362                 grid->nsubc[c] = min(GPU_NSUBCELL, (na_c+grid->na_c-1)/grid->na_c);
1363
1364                 /* Store the z-boundaries of the super cell */
1365                 grid->bbcz[c*NNBSBB_D  ] = x[nbs->a[ash_z]][ZZ];
1366                 grid->bbcz[c*NNBSBB_D+1] = x[nbs->a[ash_z+na_c-1]][ZZ];
1367             }
1368
1369 #if GPU_NSUBCELL_Y > 1
1370             /* Sort the atoms along y */
1371             sort_atoms(YY, (sub_z & 1),
1372                        nbs->a+ash_z, na_z, x,
1373                        grid->c0[YY]+cy*grid->sy,
1374                        grid->inv_sy, subdiv_z,
1375                        sort_work);
1376 #endif
1377
1378             for (sub_y = 0; sub_y < GPU_NSUBCELL_Y; sub_y++)
1379             {
1380                 ash_y = ash_z + sub_y*subdiv_y;
1381                 na_y  = min(subdiv_y, na-(ash_y-ash));
1382
1383 #if GPU_NSUBCELL_X > 1
1384                 /* Sort the atoms along x */
1385                 sort_atoms(XX, ((cz*GPU_NSUBCELL_Y + sub_y) & 1),
1386                            nbs->a+ash_y, na_y, x,
1387                            grid->c0[XX]+cx*grid->sx,
1388                            grid->inv_sx, subdiv_y,
1389                            sort_work);
1390 #endif
1391
1392                 for (sub_x = 0; sub_x < GPU_NSUBCELL_X; sub_x++)
1393                 {
1394                     ash_x = ash_y + sub_x*subdiv_x;
1395                     na_x  = min(subdiv_x, na-(ash_x-ash));
1396
1397                     fill_cell(nbs, grid, nbat,
1398                               ash_x, ash_x+na_x, atinfo, x,
1399                               grid->na_c*(cx*GPU_NSUBCELL_X+sub_x) + (dd_zone >> 2),
1400                               grid->na_c*(cy*GPU_NSUBCELL_Y+sub_y) + (dd_zone & 3),
1401                               grid->na_c*sub_z,
1402                               bb_work_align);
1403                 }
1404             }
1405         }
1406
1407         /* Set the unused atom indices to -1 */
1408         for (ind = na; ind < ncz*grid->na_sc; ind++)
1409         {
1410             nbs->a[ash+ind] = -1;
1411         }
1412     }
1413 }
1414
1415 /* Determine in which grid column atoms should go */
1416 static void calc_column_indices(nbnxn_grid_t *grid,
1417                                 int a0, int a1,
1418                                 rvec *x,
1419                                 int dd_zone, const int *move,
1420                                 int thread, int nthread,
1421                                 int *cell,
1422                                 int *cxy_na)
1423 {
1424     int  n0, n1, i;
1425     int  cx, cy;
1426
1427     /* We add one extra cell for particles which moved during DD */
1428     for (i = 0; i < grid->ncx*grid->ncy+1; i++)
1429     {
1430         cxy_na[i] = 0;
1431     }
1432
1433     n0 = a0 + (int)((thread+0)*(a1 - a0))/nthread;
1434     n1 = a0 + (int)((thread+1)*(a1 - a0))/nthread;
1435     if (dd_zone == 0)
1436     {
1437         /* Home zone */
1438         for (i = n0; i < n1; i++)
1439         {
1440             if (move == NULL || move[i] >= 0)
1441             {
1442                 /* We need to be careful with rounding,
1443                  * particles might be a few bits outside the local zone.
1444                  * The int cast takes care of the lower bound,
1445                  * we will explicitly take care of the upper bound.
1446                  */
1447                 cx = (int)((x[i][XX] - grid->c0[XX])*grid->inv_sx);
1448                 cy = (int)((x[i][YY] - grid->c0[YY])*grid->inv_sy);
1449
1450 #ifndef NDEBUG
1451                 if (cx < 0 || cx > grid->ncx ||
1452                     cy < 0 || cy > grid->ncy)
1453                 {
1454                     gmx_fatal(FARGS,
1455                               "grid cell cx %d cy %d out of range (max %d %d)\n"
1456                               "atom %f %f %f, grid->c0 %f %f",
1457                               cx, cy, grid->ncx, grid->ncy,
1458                               x[i][XX], x[i][YY], x[i][ZZ], grid->c0[XX], grid->c0[YY]);
1459                 }
1460 #endif
1461                 /* Take care of potential rouding issues */
1462                 cx = min(cx, grid->ncx - 1);
1463                 cy = min(cy, grid->ncy - 1);
1464
1465                 /* For the moment cell will contain only the, grid local,
1466                  * x and y indices, not z.
1467                  */
1468                 cell[i] = cx*grid->ncy + cy;
1469             }
1470             else
1471             {
1472                 /* Put this moved particle after the end of the grid,
1473                  * so we can process it later without using conditionals.
1474                  */
1475                 cell[i] = grid->ncx*grid->ncy;
1476             }
1477
1478             cxy_na[cell[i]]++;
1479         }
1480     }
1481     else
1482     {
1483         /* Non-home zone */
1484         for (i = n0; i < n1; i++)
1485         {
1486             cx = (int)((x[i][XX] - grid->c0[XX])*grid->inv_sx);
1487             cy = (int)((x[i][YY] - grid->c0[YY])*grid->inv_sy);
1488
1489             /* For non-home zones there could be particles outside
1490              * the non-bonded cut-off range, which have been communicated
1491              * for bonded interactions only. For the result it doesn't
1492              * matter where these end up on the grid. For performance
1493              * we put them in an extra row at the border.
1494              */
1495             cx = max(cx, 0);
1496             cx = min(cx, grid->ncx - 1);
1497             cy = max(cy, 0);
1498             cy = min(cy, grid->ncy - 1);
1499
1500             /* For the moment cell will contain only the, grid local,
1501              * x and y indices, not z.
1502              */
1503             cell[i] = cx*grid->ncy + cy;
1504
1505             cxy_na[cell[i]]++;
1506         }
1507     }
1508 }
1509
1510 /* Determine in which grid cells the atoms should go */
1511 static void calc_cell_indices(const nbnxn_search_t nbs,
1512                               int dd_zone,
1513                               nbnxn_grid_t *grid,
1514                               int a0, int a1,
1515                               const int *atinfo,
1516                               rvec *x,
1517                               const int *move,
1518                               nbnxn_atomdata_t *nbat)
1519 {
1520     int   n0, n1, i;
1521     int   cx, cy, cxy, ncz_max, ncz;
1522     int   nthread, thread;
1523     int  *cxy_na, cxy_na_i;
1524
1525     nthread = gmx_omp_nthreads_get(emntPairsearch);
1526
1527 #pragma omp parallel for num_threads(nthread) schedule(static)
1528     for (thread = 0; thread < nthread; thread++)
1529     {
1530         calc_column_indices(grid, a0, a1, x, dd_zone, move, thread, nthread,
1531                             nbs->cell, nbs->work[thread].cxy_na);
1532     }
1533
1534     /* Make the cell index as a function of x and y */
1535     ncz_max          = 0;
1536     ncz              = 0;
1537     grid->cxy_ind[0] = 0;
1538     for (i = 0; i < grid->ncx*grid->ncy+1; i++)
1539     {
1540         /* We set ncz_max at the beginning of the loop iso at the end
1541          * to skip i=grid->ncx*grid->ncy which are moved particles
1542          * that do not need to be ordered on the grid.
1543          */
1544         if (ncz > ncz_max)
1545         {
1546             ncz_max = ncz;
1547         }
1548         cxy_na_i = nbs->work[0].cxy_na[i];
1549         for (thread = 1; thread < nthread; thread++)
1550         {
1551             cxy_na_i += nbs->work[thread].cxy_na[i];
1552         }
1553         ncz = (cxy_na_i + grid->na_sc - 1)/grid->na_sc;
1554         if (nbat->XFormat == nbatX8)
1555         {
1556             /* Make the number of cell a multiple of 2 */
1557             ncz = (ncz + 1) & ~1;
1558         }
1559         grid->cxy_ind[i+1] = grid->cxy_ind[i] + ncz;
1560         /* Clear cxy_na, so we can reuse the array below */
1561         grid->cxy_na[i] = 0;
1562     }
1563     grid->nc = grid->cxy_ind[grid->ncx*grid->ncy] - grid->cxy_ind[0];
1564
1565     nbat->natoms = (grid->cell0 + grid->nc)*grid->na_sc;
1566
1567     if (debug)
1568     {
1569         fprintf(debug, "ns na_sc %d na_c %d super-cells: %d x %d y %d z %.1f maxz %d\n",
1570                 grid->na_sc, grid->na_c, grid->nc,
1571                 grid->ncx, grid->ncy, grid->nc/((double)(grid->ncx*grid->ncy)),
1572                 ncz_max);
1573         if (gmx_debug_at)
1574         {
1575             i = 0;
1576             for (cy = 0; cy < grid->ncy; cy++)
1577             {
1578                 for (cx = 0; cx < grid->ncx; cx++)
1579                 {
1580                     fprintf(debug, " %2d", grid->cxy_ind[i+1]-grid->cxy_ind[i]);
1581                     i++;
1582                 }
1583                 fprintf(debug, "\n");
1584             }
1585         }
1586     }
1587
1588     /* Make sure the work array for sorting is large enough */
1589     if (ncz_max*grid->na_sc*SGSF > nbs->work[0].sort_work_nalloc)
1590     {
1591         for (thread = 0; thread < nbs->nthread_max; thread++)
1592         {
1593             nbs->work[thread].sort_work_nalloc =
1594                 over_alloc_large(ncz_max*grid->na_sc*SGSF);
1595             srenew(nbs->work[thread].sort_work,
1596                    nbs->work[thread].sort_work_nalloc);
1597             /* When not in use, all elements should be -1 */
1598             for (i = 0; i < nbs->work[thread].sort_work_nalloc; i++)
1599             {
1600                 nbs->work[thread].sort_work[i] = -1;
1601             }
1602         }
1603     }
1604
1605     /* Now we know the dimensions we can fill the grid.
1606      * This is the first, unsorted fill. We sort the columns after this.
1607      */
1608     for (i = a0; i < a1; i++)
1609     {
1610         /* At this point nbs->cell contains the local grid x,y indices */
1611         cxy = nbs->cell[i];
1612         nbs->a[(grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc + grid->cxy_na[cxy]++] = i;
1613     }
1614
1615     if (dd_zone == 0)
1616     {
1617         /* Set the cell indices for the moved particles */
1618         n0 = grid->nc*grid->na_sc;
1619         n1 = grid->nc*grid->na_sc+grid->cxy_na[grid->ncx*grid->ncy];
1620         if (dd_zone == 0)
1621         {
1622             for (i = n0; i < n1; i++)
1623             {
1624                 nbs->cell[nbs->a[i]] = i;
1625             }
1626         }
1627     }
1628
1629     /* Sort the super-cell columns along z into the sub-cells. */
1630 #pragma omp parallel for num_threads(nbs->nthread_max) schedule(static)
1631     for (thread = 0; thread < nbs->nthread_max; thread++)
1632     {
1633         if (grid->bSimple)
1634         {
1635             sort_columns_simple(nbs, dd_zone, grid, a0, a1, atinfo, x, nbat,
1636                                 ((thread+0)*grid->ncx*grid->ncy)/nthread,
1637                                 ((thread+1)*grid->ncx*grid->ncy)/nthread,
1638                                 nbs->work[thread].sort_work);
1639         }
1640         else
1641         {
1642             sort_columns_supersub(nbs, dd_zone, grid, a0, a1, atinfo, x, nbat,
1643                                   ((thread+0)*grid->ncx*grid->ncy)/nthread,
1644                                   ((thread+1)*grid->ncx*grid->ncy)/nthread,
1645                                   nbs->work[thread].sort_work);
1646         }
1647     }
1648
1649 #ifdef NBNXN_SEARCH_BB_SSE
1650     if (grid->bSimple && nbat->XFormat == nbatX8)
1651     {
1652         combine_bounding_box_pairs(grid, grid->bb);
1653     }
1654 #endif
1655
1656     if (!grid->bSimple)
1657     {
1658         grid->nsubc_tot = 0;
1659         for (i = 0; i < grid->nc; i++)
1660         {
1661             grid->nsubc_tot += grid->nsubc[i];
1662         }
1663     }
1664
1665     if (debug)
1666     {
1667         if (grid->bSimple)
1668         {
1669             print_bbsizes_simple(debug, nbs, grid);
1670         }
1671         else
1672         {
1673             fprintf(debug, "ns non-zero sub-cells: %d average atoms %.2f\n",
1674                     grid->nsubc_tot, (a1-a0)/(double)grid->nsubc_tot);
1675
1676             print_bbsizes_supersub(debug, nbs, grid);
1677         }
1678     }
1679 }
1680
1681 static void init_buffer_flags(nbnxn_buffer_flags_t *flags,
1682                               int                   natoms)
1683 {
1684     int b;
1685
1686     flags->nflag = (natoms + NBNXN_BUFFERFLAG_SIZE - 1)/NBNXN_BUFFERFLAG_SIZE;
1687     if (flags->nflag > flags->flag_nalloc)
1688     {
1689         flags->flag_nalloc = over_alloc_large(flags->nflag);
1690         srenew(flags->flag, flags->flag_nalloc);
1691     }
1692     for (b = 0; b < flags->nflag; b++)
1693     {
1694         flags->flag[b] = 0;
1695     }
1696 }
1697
1698 /* Sets up a grid and puts the atoms on the grid.
1699  * This function only operates on one domain of the domain decompostion.
1700  * Note that without domain decomposition there is only one domain.
1701  */
1702 void nbnxn_put_on_grid(nbnxn_search_t nbs,
1703                        int ePBC, matrix box,
1704                        int dd_zone,
1705                        rvec corner0, rvec corner1,
1706                        int a0, int a1,
1707                        real atom_density,
1708                        const int *atinfo,
1709                        rvec *x,
1710                        int nmoved, int *move,
1711                        int nb_kernel_type,
1712                        nbnxn_atomdata_t *nbat)
1713 {
1714     nbnxn_grid_t *grid;
1715     int           n;
1716     int           nc_max_grid, nc_max;
1717
1718     grid = &nbs->grid[dd_zone];
1719
1720     nbs_cycle_start(&nbs->cc[enbsCCgrid]);
1721
1722     grid->bSimple = nbnxn_kernel_pairlist_simple(nb_kernel_type);
1723
1724     grid->na_c      = nbnxn_kernel_to_ci_size(nb_kernel_type);
1725     grid->na_cj     = nbnxn_kernel_to_cj_size(nb_kernel_type);
1726     grid->na_sc     = (grid->bSimple ? 1 : GPU_NSUBCELL)*grid->na_c;
1727     grid->na_c_2log = get_2log(grid->na_c);
1728
1729     nbat->na_c = grid->na_c;
1730
1731     if (dd_zone == 0)
1732     {
1733         grid->cell0 = 0;
1734     }
1735     else
1736     {
1737         grid->cell0 =
1738             (nbs->grid[dd_zone-1].cell0 + nbs->grid[dd_zone-1].nc)*
1739             nbs->grid[dd_zone-1].na_sc/grid->na_sc;
1740     }
1741
1742     n = a1 - a0;
1743
1744     if (dd_zone == 0)
1745     {
1746         nbs->ePBC = ePBC;
1747         copy_mat(box, nbs->box);
1748
1749         if (atom_density >= 0)
1750         {
1751             grid->atom_density = atom_density;
1752         }
1753         else
1754         {
1755             grid->atom_density = grid_atom_density(n-nmoved, corner0, corner1);
1756         }
1757
1758         grid->cell0 = 0;
1759
1760         nbs->natoms_local    = a1 - nmoved;
1761         /* We assume that nbnxn_put_on_grid is called first
1762          * for the local atoms (dd_zone=0).
1763          */
1764         nbs->natoms_nonlocal = a1 - nmoved;
1765     }
1766     else
1767     {
1768         nbs->natoms_nonlocal = max(nbs->natoms_nonlocal, a1);
1769     }
1770
1771     nc_max_grid = set_grid_size_xy(nbs, grid,
1772                                    dd_zone, n-nmoved, corner0, corner1,
1773                                    nbs->grid[0].atom_density,
1774                                    nbat->XFormat);
1775
1776     nc_max = grid->cell0 + nc_max_grid;
1777
1778     if (a1 > nbs->cell_nalloc)
1779     {
1780         nbs->cell_nalloc = over_alloc_large(a1);
1781         srenew(nbs->cell, nbs->cell_nalloc);
1782     }
1783
1784     /* To avoid conditionals we store the moved particles at the end of a,
1785      * make sure we have enough space.
1786      */
1787     if (nc_max*grid->na_sc + nmoved > nbs->a_nalloc)
1788     {
1789         nbs->a_nalloc = over_alloc_large(nc_max*grid->na_sc + nmoved);
1790         srenew(nbs->a, nbs->a_nalloc);
1791     }
1792
1793     /* We need padding up to a multiple of the buffer flag size: simply add */
1794     if (nc_max*grid->na_sc + NBNXN_BUFFERFLAG_SIZE > nbat->nalloc)
1795     {
1796         nbnxn_atomdata_realloc(nbat, nc_max*grid->na_sc+NBNXN_BUFFERFLAG_SIZE);
1797     }
1798
1799     calc_cell_indices(nbs, dd_zone, grid, a0, a1, atinfo, x, move, nbat);
1800
1801     if (dd_zone == 0)
1802     {
1803         nbat->natoms_local = nbat->natoms;
1804     }
1805
1806     nbs_cycle_stop(&nbs->cc[enbsCCgrid]);
1807 }
1808
1809 /* Calls nbnxn_put_on_grid for all non-local domains */
1810 void nbnxn_put_on_grid_nonlocal(nbnxn_search_t            nbs,
1811                                 const gmx_domdec_zones_t *zones,
1812                                 const int                *atinfo,
1813                                 rvec                     *x,
1814                                 int                       nb_kernel_type,
1815                                 nbnxn_atomdata_t         *nbat)
1816 {
1817     int  zone, d;
1818     rvec c0, c1;
1819
1820     for (zone = 1; zone < zones->n; zone++)
1821     {
1822         for (d = 0; d < DIM; d++)
1823         {
1824             c0[d] = zones->size[zone].bb_x0[d];
1825             c1[d] = zones->size[zone].bb_x1[d];
1826         }
1827
1828         nbnxn_put_on_grid(nbs, nbs->ePBC, NULL,
1829                           zone, c0, c1,
1830                           zones->cg_range[zone],
1831                           zones->cg_range[zone+1],
1832                           -1,
1833                           atinfo,
1834                           x,
1835                           0, NULL,
1836                           nb_kernel_type,
1837                           nbat);
1838     }
1839 }
1840
1841 /* Add simple grid type information to the local super/sub grid */
1842 void nbnxn_grid_add_simple(nbnxn_search_t    nbs,
1843                            nbnxn_atomdata_t *nbat)
1844 {
1845     nbnxn_grid_t *grid;
1846     float        *bbcz, *bb;
1847     int           ncd, sc;
1848
1849     grid = &nbs->grid[0];
1850
1851     if (grid->bSimple)
1852     {
1853         gmx_incons("nbnxn_grid_simple called with a simple grid");
1854     }
1855
1856     ncd = grid->na_sc/NBNXN_CPU_CLUSTER_I_SIZE;
1857
1858     if (grid->nc*ncd > grid->nc_nalloc_simple)
1859     {
1860         grid->nc_nalloc_simple = over_alloc_large(grid->nc*ncd);
1861         srenew(grid->bbcz_simple, grid->nc_nalloc_simple*NNBSBB_D);
1862         srenew(grid->bb_simple, grid->nc_nalloc_simple*NNBSBB_B);
1863         srenew(grid->flags_simple, grid->nc_nalloc_simple);
1864         if (nbat->XFormat)
1865         {
1866             sfree_aligned(grid->bbj);
1867             snew_aligned(grid->bbj, grid->nc_nalloc_simple/2, 16);
1868         }
1869     }
1870
1871     bbcz = grid->bbcz_simple;
1872     bb   = grid->bb_simple;
1873
1874 #pragma omp parallel for num_threads(gmx_omp_nthreads_get(emntPairsearch)) schedule(static)
1875     for (sc = 0; sc < grid->nc; sc++)
1876     {
1877         int c, tx, na;
1878
1879         for (c = 0; c < ncd; c++)
1880         {
1881             tx = sc*ncd + c;
1882
1883             na = NBNXN_CPU_CLUSTER_I_SIZE;
1884             while (na > 0 &&
1885                    nbat->type[tx*NBNXN_CPU_CLUSTER_I_SIZE+na-1] == nbat->ntype-1)
1886             {
1887                 na--;
1888             }
1889
1890             if (na > 0)
1891             {
1892                 switch (nbat->XFormat)
1893                 {
1894                     case nbatX4:
1895                         /* PACK_X4==NBNXN_CPU_CLUSTER_I_SIZE, so this is simple */
1896                         calc_bounding_box_x_x4(na, nbat->x+tx*STRIDE_P4,
1897                                                bb+tx*NNBSBB_B);
1898                         break;
1899                     case nbatX8:
1900                         /* PACK_X8>NBNXN_CPU_CLUSTER_I_SIZE, more complicated */
1901                         calc_bounding_box_x_x8(na, nbat->x+X8_IND_A(tx*NBNXN_CPU_CLUSTER_I_SIZE),
1902                                                bb+tx*NNBSBB_B);
1903                         break;
1904                     default:
1905                         calc_bounding_box(na, nbat->xstride,
1906                                           nbat->x+tx*NBNXN_CPU_CLUSTER_I_SIZE*nbat->xstride,
1907                                           bb+tx*NNBSBB_B);
1908                         break;
1909                 }
1910                 bbcz[tx*NNBSBB_D+0] = bb[tx*NNBSBB_B         +ZZ];
1911                 bbcz[tx*NNBSBB_D+1] = bb[tx*NNBSBB_B+NNBSBB_C+ZZ];
1912
1913                 /* No interaction optimization yet here */
1914                 grid->flags_simple[tx] = NBNXN_CI_DO_LJ(0) | NBNXN_CI_DO_COUL(0);
1915             }
1916             else
1917             {
1918                 grid->flags_simple[tx] = 0;
1919             }
1920         }
1921     }
1922
1923 #ifdef NBNXN_SEARCH_BB_SSE
1924     if (grid->bSimple && nbat->XFormat == nbatX8)
1925     {
1926         combine_bounding_box_pairs(grid, grid->bb_simple);
1927     }
1928 #endif
1929 }
1930
1931 void nbnxn_get_ncells(nbnxn_search_t nbs, int *ncx, int *ncy)
1932 {
1933     *ncx = nbs->grid[0].ncx;
1934     *ncy = nbs->grid[0].ncy;
1935 }
1936
1937 void nbnxn_get_atomorder(nbnxn_search_t nbs, int **a, int *n)
1938 {
1939     const nbnxn_grid_t *grid;
1940
1941     grid = &nbs->grid[0];
1942
1943     /* Return the atom order for the home cell (index 0) */
1944     *a  = nbs->a;
1945
1946     *n = grid->cxy_ind[grid->ncx*grid->ncy]*grid->na_sc;
1947 }
1948
1949 void nbnxn_set_atomorder(nbnxn_search_t nbs)
1950 {
1951     nbnxn_grid_t *grid;
1952     int           ao, cx, cy, cxy, cz, j;
1953
1954     /* Set the atom order for the home cell (index 0) */
1955     grid = &nbs->grid[0];
1956
1957     ao = 0;
1958     for (cx = 0; cx < grid->ncx; cx++)
1959     {
1960         for (cy = 0; cy < grid->ncy; cy++)
1961         {
1962             cxy = cx*grid->ncy + cy;
1963             j   = grid->cxy_ind[cxy]*grid->na_sc;
1964             for (cz = 0; cz < grid->cxy_na[cxy]; cz++)
1965             {
1966                 nbs->a[j]     = ao;
1967                 nbs->cell[ao] = j;
1968                 ao++;
1969                 j++;
1970             }
1971         }
1972     }
1973 }
1974
1975 /* Determines the cell range along one dimension that
1976  * the bounding box b0 - b1 sees.
1977  */
1978 static void get_cell_range(real b0, real b1,
1979                            int nc, real c0, real s, real invs,
1980                            real d2, real r2, int *cf, int *cl)
1981 {
1982     *cf = max((int)((b0 - c0)*invs), 0);
1983
1984     while (*cf > 0 && d2 + sqr((b0 - c0) - (*cf-1+1)*s) < r2)
1985     {
1986         (*cf)--;
1987     }
1988
1989     *cl = min((int)((b1 - c0)*invs), nc-1);
1990     while (*cl < nc-1 && d2 + sqr((*cl+1)*s - (b1 - c0)) < r2)
1991     {
1992         (*cl)++;
1993     }
1994 }
1995
1996 /* Reference code calculating the distance^2 between two bounding boxes */
1997 static float box_dist2(float bx0, float bx1, float by0,
1998                        float by1, float bz0, float bz1,
1999                        const float *bb)
2000 {
2001     float d2;
2002     float dl, dh, dm, dm0;
2003
2004     d2 = 0;
2005
2006     dl  = bx0 - bb[BBU_X];
2007     dh  = bb[BBL_X] - bx1;
2008     dm  = max(dl, dh);
2009     dm0 = max(dm, 0);
2010     d2 += dm0*dm0;
2011
2012     dl  = by0 - bb[BBU_Y];
2013     dh  = bb[BBL_Y] - by1;
2014     dm  = max(dl, dh);
2015     dm0 = max(dm, 0);
2016     d2 += dm0*dm0;
2017
2018     dl  = bz0 - bb[BBU_Z];
2019     dh  = bb[BBL_Z] - bz1;
2020     dm  = max(dl, dh);
2021     dm0 = max(dm, 0);
2022     d2 += dm0*dm0;
2023
2024     return d2;
2025 }
2026
2027 /* Plain C code calculating the distance^2 between two bounding boxes */
2028 static float subc_bb_dist2(int si, const float *bb_i_ci,
2029                            int csj, const float *bb_j_all)
2030 {
2031     const float *bb_i, *bb_j;
2032     float        d2;
2033     float        dl, dh, dm, dm0;
2034
2035     bb_i = bb_i_ci  +  si*NNBSBB_B;
2036     bb_j = bb_j_all + csj*NNBSBB_B;
2037
2038     d2 = 0;
2039
2040     dl  = bb_i[BBL_X] - bb_j[BBU_X];
2041     dh  = bb_j[BBL_X] - bb_i[BBU_X];
2042     dm  = max(dl, dh);
2043     dm0 = max(dm, 0);
2044     d2 += dm0*dm0;
2045
2046     dl  = bb_i[BBL_Y] - bb_j[BBU_Y];
2047     dh  = bb_j[BBL_Y] - bb_i[BBU_Y];
2048     dm  = max(dl, dh);
2049     dm0 = max(dm, 0);
2050     d2 += dm0*dm0;
2051
2052     dl  = bb_i[BBL_Z] - bb_j[BBU_Z];
2053     dh  = bb_j[BBL_Z] - bb_i[BBU_Z];
2054     dm  = max(dl, dh);
2055     dm0 = max(dm, 0);
2056     d2 += dm0*dm0;
2057
2058     return d2;
2059 }
2060
2061 #ifdef NBNXN_SEARCH_BB_SSE
2062
2063 /* SSE code for bb distance for bb format xyz0 */
2064 static float subc_bb_dist2_sse(int na_c,
2065                                int si, const float *bb_i_ci,
2066                                int csj, const float *bb_j_all)
2067 {
2068     const float *bb_i, *bb_j;
2069
2070     __m128       bb_i_SSE0, bb_i_SSE1;
2071     __m128       bb_j_SSE0, bb_j_SSE1;
2072     __m128       dl_SSE;
2073     __m128       dh_SSE;
2074     __m128       dm_SSE;
2075     __m128       dm0_SSE;
2076     __m128       d2_SSE;
2077 #ifndef GMX_X86_SSE4_1
2078     float        d2_array[7], *d2_align;
2079
2080     d2_align = (float *)(((size_t)(d2_array+3)) & (~((size_t)15)));
2081 #else
2082     float d2;
2083 #endif
2084
2085     bb_i = bb_i_ci  +  si*NNBSBB_B;
2086     bb_j = bb_j_all + csj*NNBSBB_B;
2087
2088     bb_i_SSE0 = _mm_load_ps(bb_i);
2089     bb_i_SSE1 = _mm_load_ps(bb_i+NNBSBB_C);
2090     bb_j_SSE0 = _mm_load_ps(bb_j);
2091     bb_j_SSE1 = _mm_load_ps(bb_j+NNBSBB_C);
2092
2093     dl_SSE    = _mm_sub_ps(bb_i_SSE0, bb_j_SSE1);
2094     dh_SSE    = _mm_sub_ps(bb_j_SSE0, bb_i_SSE1);
2095
2096     dm_SSE    = _mm_max_ps(dl_SSE, dh_SSE);
2097     dm0_SSE   = _mm_max_ps(dm_SSE, _mm_setzero_ps());
2098 #ifndef GMX_X86_SSE4_1
2099     d2_SSE    = _mm_mul_ps(dm0_SSE, dm0_SSE);
2100
2101     _mm_store_ps(d2_align, d2_SSE);
2102
2103     return d2_align[0] + d2_align[1] + d2_align[2];
2104 #else
2105     /* SSE4.1 dot product of components 0,1,2 */
2106     d2_SSE    = _mm_dp_ps(dm0_SSE, dm0_SSE, 0x71);
2107
2108     _mm_store_ss(&d2, d2_SSE);
2109
2110     return d2;
2111 #endif
2112 }
2113
2114 /* Calculate bb bounding distances of bb_i[si,...,si+3] and store them in d2 */
2115 #define SUBC_BB_DIST2_SSE_XXXX_INNER(si, bb_i, d2) \
2116     {                                                \
2117         int    shi;                                  \
2118                                                  \
2119         __m128 dx_0, dy_0, dz_0;                       \
2120         __m128 dx_1, dy_1, dz_1;                       \
2121                                                  \
2122         __m128 mx, my, mz;                             \
2123         __m128 m0x, m0y, m0z;                          \
2124                                                  \
2125         __m128 d2x, d2y, d2z;                          \
2126         __m128 d2s, d2t;                              \
2127                                                  \
2128         shi = si*NNBSBB_D*DIM;                       \
2129                                                  \
2130         xi_l = _mm_load_ps(bb_i+shi+0*STRIDE_PBB);   \
2131         yi_l = _mm_load_ps(bb_i+shi+1*STRIDE_PBB);   \
2132         zi_l = _mm_load_ps(bb_i+shi+2*STRIDE_PBB);   \
2133         xi_h = _mm_load_ps(bb_i+shi+3*STRIDE_PBB);   \
2134         yi_h = _mm_load_ps(bb_i+shi+4*STRIDE_PBB);   \
2135         zi_h = _mm_load_ps(bb_i+shi+5*STRIDE_PBB);   \
2136                                                  \
2137         dx_0 = _mm_sub_ps(xi_l, xj_h);                \
2138         dy_0 = _mm_sub_ps(yi_l, yj_h);                \
2139         dz_0 = _mm_sub_ps(zi_l, zj_h);                \
2140                                                  \
2141         dx_1 = _mm_sub_ps(xj_l, xi_h);                \
2142         dy_1 = _mm_sub_ps(yj_l, yi_h);                \
2143         dz_1 = _mm_sub_ps(zj_l, zi_h);                \
2144                                                  \
2145         mx   = _mm_max_ps(dx_0, dx_1);                \
2146         my   = _mm_max_ps(dy_0, dy_1);                \
2147         mz   = _mm_max_ps(dz_0, dz_1);                \
2148                                                  \
2149         m0x  = _mm_max_ps(mx, zero);                  \
2150         m0y  = _mm_max_ps(my, zero);                  \
2151         m0z  = _mm_max_ps(mz, zero);                  \
2152                                                  \
2153         d2x  = _mm_mul_ps(m0x, m0x);                  \
2154         d2y  = _mm_mul_ps(m0y, m0y);                  \
2155         d2z  = _mm_mul_ps(m0z, m0z);                  \
2156                                                  \
2157         d2s  = _mm_add_ps(d2x, d2y);                  \
2158         d2t  = _mm_add_ps(d2s, d2z);                  \
2159                                                  \
2160         _mm_store_ps(d2+si, d2t);                     \
2161     }
2162
2163 /* SSE code for nsi bb distances for bb format xxxxyyyyzzzz */
2164 static void subc_bb_dist2_sse_xxxx(const float *bb_j,
2165                                    int nsi, const float *bb_i,
2166                                    float *d2)
2167 {
2168     __m128 xj_l, yj_l, zj_l;
2169     __m128 xj_h, yj_h, zj_h;
2170     __m128 xi_l, yi_l, zi_l;
2171     __m128 xi_h, yi_h, zi_h;
2172
2173     __m128 zero;
2174
2175     zero = _mm_setzero_ps();
2176
2177     xj_l = _mm_set1_ps(bb_j[0*STRIDE_PBB]);
2178     yj_l = _mm_set1_ps(bb_j[1*STRIDE_PBB]);
2179     zj_l = _mm_set1_ps(bb_j[2*STRIDE_PBB]);
2180     xj_h = _mm_set1_ps(bb_j[3*STRIDE_PBB]);
2181     yj_h = _mm_set1_ps(bb_j[4*STRIDE_PBB]);
2182     zj_h = _mm_set1_ps(bb_j[5*STRIDE_PBB]);
2183
2184     /* Here we "loop" over si (0,STRIDE_PBB) from 0 to nsi with step STRIDE_PBB.
2185      * But as we know the number of iterations is 1 or 2, we unroll manually.
2186      */
2187     SUBC_BB_DIST2_SSE_XXXX_INNER(0, bb_i, d2);
2188     if (STRIDE_PBB < nsi)
2189     {
2190         SUBC_BB_DIST2_SSE_XXXX_INNER(STRIDE_PBB, bb_i, d2);
2191     }
2192 }
2193
2194 #endif /* NBNXN_SEARCH_BB_SSE */
2195
2196 /* Plain C function which determines if any atom pair between two cells
2197  * is within distance sqrt(rl2).
2198  */
2199 static gmx_bool subc_in_range_x(int na_c,
2200                                 int si, const real *x_i,
2201                                 int csj, int stride, const real *x_j,
2202                                 real rl2)
2203 {
2204     int  i, j, i0, j0;
2205     real d2;
2206
2207     for (i = 0; i < na_c; i++)
2208     {
2209         i0 = (si*na_c + i)*DIM;
2210         for (j = 0; j < na_c; j++)
2211         {
2212             j0 = (csj*na_c + j)*stride;
2213
2214             d2 = sqr(x_i[i0  ] - x_j[j0  ]) +
2215                 sqr(x_i[i0+1] - x_j[j0+1]) +
2216                 sqr(x_i[i0+2] - x_j[j0+2]);
2217
2218             if (d2 < rl2)
2219             {
2220                 return TRUE;
2221             }
2222         }
2223     }
2224
2225     return FALSE;
2226 }
2227
2228 /* SSE function which determines if any atom pair between two cells,
2229  * both with 8 atoms, is within distance sqrt(rl2).
2230  */
2231 static gmx_bool subc_in_range_sse8(int na_c,
2232                                    int si, const real *x_i,
2233                                    int csj, int stride, const real *x_j,
2234                                    real rl2)
2235 {
2236 #ifdef NBNXN_SEARCH_SSE_SINGLE
2237     __m128 ix_SSE0, iy_SSE0, iz_SSE0;
2238     __m128 ix_SSE1, iy_SSE1, iz_SSE1;
2239
2240     __m128 rc2_SSE;
2241
2242     int    na_c_sse;
2243     int    j0, j1;
2244
2245     rc2_SSE   = _mm_set1_ps(rl2);
2246
2247     na_c_sse = NBNXN_GPU_CLUSTER_SIZE/STRIDE_PBB;
2248     ix_SSE0  = _mm_load_ps(x_i+(si*na_c_sse*DIM+0)*STRIDE_PBB);
2249     iy_SSE0  = _mm_load_ps(x_i+(si*na_c_sse*DIM+1)*STRIDE_PBB);
2250     iz_SSE0  = _mm_load_ps(x_i+(si*na_c_sse*DIM+2)*STRIDE_PBB);
2251     ix_SSE1  = _mm_load_ps(x_i+(si*na_c_sse*DIM+3)*STRIDE_PBB);
2252     iy_SSE1  = _mm_load_ps(x_i+(si*na_c_sse*DIM+4)*STRIDE_PBB);
2253     iz_SSE1  = _mm_load_ps(x_i+(si*na_c_sse*DIM+5)*STRIDE_PBB);
2254
2255     /* We loop from the outer to the inner particles to maximize
2256      * the chance that we find a pair in range quickly and return.
2257      */
2258     j0 = csj*na_c;
2259     j1 = j0 + na_c - 1;
2260     while (j0 < j1)
2261     {
2262         __m128 jx0_SSE, jy0_SSE, jz0_SSE;
2263         __m128 jx1_SSE, jy1_SSE, jz1_SSE;
2264
2265         __m128 dx_SSE0, dy_SSE0, dz_SSE0;
2266         __m128 dx_SSE1, dy_SSE1, dz_SSE1;
2267         __m128 dx_SSE2, dy_SSE2, dz_SSE2;
2268         __m128 dx_SSE3, dy_SSE3, dz_SSE3;
2269
2270         __m128 rsq_SSE0;
2271         __m128 rsq_SSE1;
2272         __m128 rsq_SSE2;
2273         __m128 rsq_SSE3;
2274
2275         __m128 wco_SSE0;
2276         __m128 wco_SSE1;
2277         __m128 wco_SSE2;
2278         __m128 wco_SSE3;
2279         __m128 wco_any_SSE01, wco_any_SSE23, wco_any_SSE;
2280
2281         jx0_SSE = _mm_load1_ps(x_j+j0*stride+0);
2282         jy0_SSE = _mm_load1_ps(x_j+j0*stride+1);
2283         jz0_SSE = _mm_load1_ps(x_j+j0*stride+2);
2284
2285         jx1_SSE = _mm_load1_ps(x_j+j1*stride+0);
2286         jy1_SSE = _mm_load1_ps(x_j+j1*stride+1);
2287         jz1_SSE = _mm_load1_ps(x_j+j1*stride+2);
2288
2289         /* Calculate distance */
2290         dx_SSE0            = _mm_sub_ps(ix_SSE0, jx0_SSE);
2291         dy_SSE0            = _mm_sub_ps(iy_SSE0, jy0_SSE);
2292         dz_SSE0            = _mm_sub_ps(iz_SSE0, jz0_SSE);
2293         dx_SSE1            = _mm_sub_ps(ix_SSE1, jx0_SSE);
2294         dy_SSE1            = _mm_sub_ps(iy_SSE1, jy0_SSE);
2295         dz_SSE1            = _mm_sub_ps(iz_SSE1, jz0_SSE);
2296         dx_SSE2            = _mm_sub_ps(ix_SSE0, jx1_SSE);
2297         dy_SSE2            = _mm_sub_ps(iy_SSE0, jy1_SSE);
2298         dz_SSE2            = _mm_sub_ps(iz_SSE0, jz1_SSE);
2299         dx_SSE3            = _mm_sub_ps(ix_SSE1, jx1_SSE);
2300         dy_SSE3            = _mm_sub_ps(iy_SSE1, jy1_SSE);
2301         dz_SSE3            = _mm_sub_ps(iz_SSE1, jz1_SSE);
2302
2303         /* rsq = dx*dx+dy*dy+dz*dz */
2304         rsq_SSE0           = gmx_mm_calc_rsq_ps(dx_SSE0, dy_SSE0, dz_SSE0);
2305         rsq_SSE1           = gmx_mm_calc_rsq_ps(dx_SSE1, dy_SSE1, dz_SSE1);
2306         rsq_SSE2           = gmx_mm_calc_rsq_ps(dx_SSE2, dy_SSE2, dz_SSE2);
2307         rsq_SSE3           = gmx_mm_calc_rsq_ps(dx_SSE3, dy_SSE3, dz_SSE3);
2308
2309         wco_SSE0           = _mm_cmplt_ps(rsq_SSE0, rc2_SSE);
2310         wco_SSE1           = _mm_cmplt_ps(rsq_SSE1, rc2_SSE);
2311         wco_SSE2           = _mm_cmplt_ps(rsq_SSE2, rc2_SSE);
2312         wco_SSE3           = _mm_cmplt_ps(rsq_SSE3, rc2_SSE);
2313
2314         wco_any_SSE01      = _mm_or_ps(wco_SSE0, wco_SSE1);
2315         wco_any_SSE23      = _mm_or_ps(wco_SSE2, wco_SSE3);
2316         wco_any_SSE        = _mm_or_ps(wco_any_SSE01, wco_any_SSE23);
2317
2318         if (_mm_movemask_ps(wco_any_SSE))
2319         {
2320             return TRUE;
2321         }
2322
2323         j0++;
2324         j1--;
2325     }
2326     return FALSE;
2327
2328 #else
2329     /* No SSE */
2330     gmx_incons("SSE function called without SSE support");
2331
2332     return TRUE;
2333 #endif
2334 }
2335
2336 /* Returns the j sub-cell for index cj_ind */
2337 static int nbl_cj(const nbnxn_pairlist_t *nbl, int cj_ind)
2338 {
2339     return nbl->cj4[cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG].cj[cj_ind & (NBNXN_GPU_JGROUP_SIZE - 1)];
2340 }
2341
2342 /* Returns the i-interaction mask of the j sub-cell for index cj_ind */
2343 static unsigned nbl_imask0(const nbnxn_pairlist_t *nbl, int cj_ind)
2344 {
2345     return nbl->cj4[cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG].imei[0].imask;
2346 }
2347
2348 /* Ensures there is enough space for extra extra exclusion masks */
2349 static void check_excl_space(nbnxn_pairlist_t *nbl, int extra)
2350 {
2351     if (nbl->nexcl+extra > nbl->excl_nalloc)
2352     {
2353         nbl->excl_nalloc = over_alloc_small(nbl->nexcl+extra);
2354         nbnxn_realloc_void((void **)&nbl->excl,
2355                            nbl->nexcl*sizeof(*nbl->excl),
2356                            nbl->excl_nalloc*sizeof(*nbl->excl),
2357                            nbl->alloc, nbl->free);
2358     }
2359 }
2360
2361 /* Ensures there is enough space for ncell extra j-cells in the list */
2362 static void check_subcell_list_space_simple(nbnxn_pairlist_t *nbl,
2363                                             int               ncell)
2364 {
2365     int cj_max;
2366
2367     cj_max = nbl->ncj + ncell;
2368
2369     if (cj_max > nbl->cj_nalloc)
2370     {
2371         nbl->cj_nalloc = over_alloc_small(cj_max);
2372         nbnxn_realloc_void((void **)&nbl->cj,
2373                            nbl->ncj*sizeof(*nbl->cj),
2374                            nbl->cj_nalloc*sizeof(*nbl->cj),
2375                            nbl->alloc, nbl->free);
2376     }
2377 }
2378
2379 /* Ensures there is enough space for ncell extra j-subcells in the list */
2380 static void check_subcell_list_space_supersub(nbnxn_pairlist_t *nbl,
2381                                               int               nsupercell)
2382 {
2383     int ncj4_max, j4, j, w, t;
2384
2385 #define NWARP       2
2386 #define WARP_SIZE  32
2387
2388     /* We can have maximally nsupercell*GPU_NSUBCELL sj lists */
2389     /* We can store 4 j-subcell - i-supercell pairs in one struct.
2390      * since we round down, we need one extra entry.
2391      */
2392     ncj4_max = ((nbl->work->cj_ind + nsupercell*GPU_NSUBCELL + NBNXN_GPU_JGROUP_SIZE - 1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
2393
2394     if (ncj4_max > nbl->cj4_nalloc)
2395     {
2396         nbl->cj4_nalloc = over_alloc_small(ncj4_max);
2397         nbnxn_realloc_void((void **)&nbl->cj4,
2398                            nbl->work->cj4_init*sizeof(*nbl->cj4),
2399                            nbl->cj4_nalloc*sizeof(*nbl->cj4),
2400                            nbl->alloc, nbl->free);
2401     }
2402
2403     if (ncj4_max > nbl->work->cj4_init)
2404     {
2405         for (j4 = nbl->work->cj4_init; j4 < ncj4_max; j4++)
2406         {
2407             /* No i-subcells and no excl's in the list initially */
2408             for (w = 0; w < NWARP; w++)
2409             {
2410                 nbl->cj4[j4].imei[w].imask    = 0U;
2411                 nbl->cj4[j4].imei[w].excl_ind = 0;
2412
2413             }
2414         }
2415         nbl->work->cj4_init = ncj4_max;
2416     }
2417 }
2418
2419 /* Set all excl masks for one GPU warp no exclusions */
2420 static void set_no_excls(nbnxn_excl_t *excl)
2421 {
2422     int t;
2423
2424     for (t = 0; t < WARP_SIZE; t++)
2425     {
2426         /* Turn all interaction bits on */
2427         excl->pair[t] = NBNXN_INT_MASK_ALL;
2428     }
2429 }
2430
2431 /* Initializes a single nbnxn_pairlist_t data structure */
2432 static void nbnxn_init_pairlist(nbnxn_pairlist_t *nbl,
2433                                 gmx_bool          bSimple,
2434                                 nbnxn_alloc_t    *alloc,
2435                                 nbnxn_free_t     *free)
2436 {
2437     if (alloc == NULL)
2438     {
2439         nbl->alloc = nbnxn_alloc_aligned;
2440     }
2441     else
2442     {
2443         nbl->alloc = alloc;
2444     }
2445     if (free == NULL)
2446     {
2447         nbl->free = nbnxn_free_aligned;
2448     }
2449     else
2450     {
2451         nbl->free = free;
2452     }
2453
2454     nbl->bSimple     = bSimple;
2455     nbl->na_sc       = 0;
2456     nbl->na_ci       = 0;
2457     nbl->na_cj       = 0;
2458     nbl->nci         = 0;
2459     nbl->ci          = NULL;
2460     nbl->ci_nalloc   = 0;
2461     nbl->ncj         = 0;
2462     nbl->cj          = NULL;
2463     nbl->cj_nalloc   = 0;
2464     nbl->ncj4        = 0;
2465     /* We need one element extra in sj, so alloc initially with 1 */
2466     nbl->cj4_nalloc  = 0;
2467     nbl->cj4         = NULL;
2468     nbl->nci_tot     = 0;
2469
2470     if (!nbl->bSimple)
2471     {
2472         nbl->excl        = NULL;
2473         nbl->excl_nalloc = 0;
2474         nbl->nexcl       = 0;
2475         check_excl_space(nbl, 1);
2476         nbl->nexcl       = 1;
2477         set_no_excls(&nbl->excl[0]);
2478     }
2479
2480     snew(nbl->work, 1);
2481 #ifdef NBNXN_BBXXXX
2482     snew_aligned(nbl->work->bb_ci, GPU_NSUBCELL/STRIDE_PBB*NNBSBB_XXXX, NBNXN_MEM_ALIGN);
2483 #else
2484     snew_aligned(nbl->work->bb_ci, GPU_NSUBCELL*NNBSBB_B, NBNXN_MEM_ALIGN);
2485 #endif
2486     snew_aligned(nbl->work->x_ci, NBNXN_NA_SC_MAX*DIM, NBNXN_MEM_ALIGN);
2487 #ifdef GMX_NBNXN_SIMD
2488     snew_aligned(nbl->work->x_ci_simd_4xn, 1, NBNXN_MEM_ALIGN);
2489     snew_aligned(nbl->work->x_ci_simd_2xnn, 1, NBNXN_MEM_ALIGN);
2490 #endif
2491     snew_aligned(nbl->work->d2, GPU_NSUBCELL, NBNXN_MEM_ALIGN);
2492
2493     nbl->work->sort            = NULL;
2494     nbl->work->sort_nalloc     = 0;
2495     nbl->work->sci_sort        = NULL;
2496     nbl->work->sci_sort_nalloc = 0;
2497 }
2498
2499 void nbnxn_init_pairlist_set(nbnxn_pairlist_set_t *nbl_list,
2500                              gmx_bool bSimple, gmx_bool bCombined,
2501                              nbnxn_alloc_t *alloc,
2502                              nbnxn_free_t  *free)
2503 {
2504     int i;
2505
2506     nbl_list->bSimple   = bSimple;
2507     nbl_list->bCombined = bCombined;
2508
2509     nbl_list->nnbl = gmx_omp_nthreads_get(emntNonbonded);
2510
2511     if (!nbl_list->bCombined &&
2512         nbl_list->nnbl > NBNXN_BUFFERFLAG_MAX_THREADS)
2513     {
2514         gmx_fatal(FARGS, "%d OpenMP threads were requested. Since the non-bonded force buffer reduction is prohibitively slow with more than %d threads, we do not allow this. Use %d or less OpenMP threads.",
2515                   nbl_list->nnbl, NBNXN_BUFFERFLAG_MAX_THREADS, NBNXN_BUFFERFLAG_MAX_THREADS);
2516     }
2517
2518     snew(nbl_list->nbl, nbl_list->nnbl);
2519     /* Execute in order to avoid memory interleaving between threads */
2520 #pragma omp parallel for num_threads(nbl_list->nnbl) schedule(static)
2521     for (i = 0; i < nbl_list->nnbl; i++)
2522     {
2523         /* Allocate the nblist data structure locally on each thread
2524          * to optimize memory access for NUMA architectures.
2525          */
2526         snew(nbl_list->nbl[i], 1);
2527
2528         /* Only list 0 is used on the GPU, use normal allocation for i>0 */
2529         if (i == 0)
2530         {
2531             nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, alloc, free);
2532         }
2533         else
2534         {
2535             nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, NULL, NULL);
2536         }
2537     }
2538 }
2539
2540 /* Print statistics of a pair list, used for debug output */
2541 static void print_nblist_statistics_simple(FILE *fp, const nbnxn_pairlist_t *nbl,
2542                                            const nbnxn_search_t nbs, real rl)
2543 {
2544     const nbnxn_grid_t *grid;
2545     int                 cs[SHIFTS];
2546     int                 s, i, j;
2547     int                 npexcl;
2548
2549     /* This code only produces correct statistics with domain decomposition */
2550     grid = &nbs->grid[0];
2551
2552     fprintf(fp, "nbl nci %d ncj %d\n",
2553             nbl->nci, nbl->ncj);
2554     fprintf(fp, "nbl na_sc %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
2555             nbl->na_sc, rl, nbl->ncj, nbl->ncj/(double)grid->nc,
2556             nbl->ncj/(double)grid->nc*grid->na_sc,
2557             nbl->ncj/(double)grid->nc*grid->na_sc/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nc*grid->na_sc/det(nbs->box)));
2558
2559     fprintf(fp, "nbl average j cell list length %.1f\n",
2560             0.25*nbl->ncj/(double)nbl->nci);
2561
2562     for (s = 0; s < SHIFTS; s++)
2563     {
2564         cs[s] = 0;
2565     }
2566     npexcl = 0;
2567     for (i = 0; i < nbl->nci; i++)
2568     {
2569         cs[nbl->ci[i].shift & NBNXN_CI_SHIFT] +=
2570             nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start;
2571
2572         j = nbl->ci[i].cj_ind_start;
2573         while (j < nbl->ci[i].cj_ind_end &&
2574                nbl->cj[j].excl != NBNXN_INT_MASK_ALL)
2575         {
2576             npexcl++;
2577             j++;
2578         }
2579     }
2580     fprintf(fp, "nbl cell pairs, total: %d excl: %d %.1f%%\n",
2581             nbl->ncj, npexcl, 100*npexcl/(double)nbl->ncj);
2582     for (s = 0; s < SHIFTS; s++)
2583     {
2584         if (cs[s] > 0)
2585         {
2586             fprintf(fp, "nbl shift %2d ncj %3d\n", s, cs[s]);
2587         }
2588     }
2589 }
2590
2591 /* Print statistics of a pair lists, used for debug output */
2592 static void print_nblist_statistics_supersub(FILE *fp, const nbnxn_pairlist_t *nbl,
2593                                              const nbnxn_search_t nbs, real rl)
2594 {
2595     const nbnxn_grid_t *grid;
2596     int                 i, j4, j, si, b;
2597     int                 c[GPU_NSUBCELL+1];
2598
2599     /* This code only produces correct statistics with domain decomposition */
2600     grid = &nbs->grid[0];
2601
2602     fprintf(fp, "nbl nsci %d ncj4 %d nsi %d excl4 %d\n",
2603             nbl->nsci, nbl->ncj4, nbl->nci_tot, nbl->nexcl);
2604     fprintf(fp, "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
2605             nbl->na_ci, rl, nbl->nci_tot, nbl->nci_tot/(double)grid->nsubc_tot,
2606             nbl->nci_tot/(double)grid->nsubc_tot*grid->na_c,
2607             nbl->nci_tot/(double)grid->nsubc_tot*grid->na_c/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nsubc_tot*grid->na_c/det(nbs->box)));
2608
2609     fprintf(fp, "nbl average j super cell list length %.1f\n",
2610             0.25*nbl->ncj4/(double)nbl->nsci);
2611     fprintf(fp, "nbl average i sub cell list length %.1f\n",
2612             nbl->nci_tot/((double)nbl->ncj4));
2613
2614     for (si = 0; si <= GPU_NSUBCELL; si++)
2615     {
2616         c[si] = 0;
2617     }
2618     for (i = 0; i < nbl->nsci; i++)
2619     {
2620         for (j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
2621         {
2622             for (j = 0; j < NBNXN_GPU_JGROUP_SIZE; j++)
2623             {
2624                 b = 0;
2625                 for (si = 0; si < GPU_NSUBCELL; si++)
2626                 {
2627                     if (nbl->cj4[j4].imei[0].imask & (1U << (j*GPU_NSUBCELL + si)))
2628                     {
2629                         b++;
2630                     }
2631                 }
2632                 c[b]++;
2633             }
2634         }
2635     }
2636     for (b = 0; b <= GPU_NSUBCELL; b++)
2637     {
2638         fprintf(fp, "nbl j-list #i-subcell %d %7d %4.1f\n",
2639                 b, c[b], 100.0*c[b]/(double)(nbl->ncj4*NBNXN_GPU_JGROUP_SIZE));
2640     }
2641 }
2642
2643 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp */
2644 static void low_get_nbl_exclusions(nbnxn_pairlist_t *nbl, int cj4,
2645                                    int warp, nbnxn_excl_t **excl)
2646 {
2647     if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
2648     {
2649         /* No exclusions set, make a new list entry */
2650         nbl->cj4[cj4].imei[warp].excl_ind = nbl->nexcl;
2651         nbl->nexcl++;
2652         *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
2653         set_no_excls(*excl);
2654     }
2655     else
2656     {
2657         /* We already have some exclusions, new ones can be added to the list */
2658         *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
2659     }
2660 }
2661
2662 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp,
2663  * allocates extra memory, if necessary.
2664  */
2665 static void get_nbl_exclusions_1(nbnxn_pairlist_t *nbl, int cj4,
2666                                  int warp, nbnxn_excl_t **excl)
2667 {
2668     if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
2669     {
2670         /* We need to make a new list entry, check if we have space */
2671         check_excl_space(nbl, 1);
2672     }
2673     low_get_nbl_exclusions(nbl, cj4, warp, excl);
2674 }
2675
2676 /* Returns pointers to the exclusion mask for cj4-unit cj4 for both warps,
2677  * allocates extra memory, if necessary.
2678  */
2679 static void get_nbl_exclusions_2(nbnxn_pairlist_t *nbl, int cj4,
2680                                  nbnxn_excl_t **excl_w0,
2681                                  nbnxn_excl_t **excl_w1)
2682 {
2683     /* Check for space we might need */
2684     check_excl_space(nbl, 2);
2685
2686     low_get_nbl_exclusions(nbl, cj4, 0, excl_w0);
2687     low_get_nbl_exclusions(nbl, cj4, 1, excl_w1);
2688 }
2689
2690 /* Sets the self exclusions i=j and pair exclusions i>j */
2691 static void set_self_and_newton_excls_supersub(nbnxn_pairlist_t *nbl,
2692                                                int cj4_ind, int sj_offset,
2693                                                int si)
2694 {
2695     nbnxn_excl_t *excl[2];
2696     int           ei, ej, w;
2697
2698     /* Here we only set the set self and double pair exclusions */
2699
2700     get_nbl_exclusions_2(nbl, cj4_ind, &excl[0], &excl[1]);
2701
2702     /* Only minor < major bits set */
2703     for (ej = 0; ej < nbl->na_ci; ej++)
2704     {
2705         w = (ej>>2);
2706         for (ei = ej; ei < nbl->na_ci; ei++)
2707         {
2708             excl[w]->pair[(ej & (NBNXN_GPU_JGROUP_SIZE-1))*nbl->na_ci + ei] &=
2709                 ~(1U << (sj_offset*GPU_NSUBCELL + si));
2710         }
2711     }
2712 }
2713
2714 /* Returns a diagonal or off-diagonal interaction mask for plain C lists */
2715 static unsigned int get_imask(gmx_bool rdiag, int ci, int cj)
2716 {
2717     return (rdiag && ci == cj ? NBNXN_INT_MASK_DIAG : NBNXN_INT_MASK_ALL);
2718 }
2719
2720 /* Returns a diagonal or off-diagonal interaction mask for SIMD128 lists */
2721 static unsigned int get_imask_x86_simd128(gmx_bool rdiag, int ci, int cj)
2722 {
2723 #ifndef GMX_DOUBLE /* cj-size = 4 */
2724     return (rdiag && ci == cj ? NBNXN_INT_MASK_DIAG : NBNXN_INT_MASK_ALL);
2725 #else              /* cj-size = 2 */
2726     return (rdiag && ci*2 == cj ? NBNXN_INT_MASK_DIAG_J2_0 :
2727             (rdiag && ci*2+1 == cj ? NBNXN_INT_MASK_DIAG_J2_1 :
2728              NBNXN_INT_MASK_ALL));
2729 #endif
2730 }
2731
2732 /* Returns a diagonal or off-diagonal interaction mask for SIMD256 lists */
2733 static unsigned int get_imask_x86_simd256(gmx_bool rdiag, int ci, int cj)
2734 {
2735 #ifndef GMX_DOUBLE /* cj-size = 8 */
2736     return (rdiag && ci == cj*2 ? NBNXN_INT_MASK_DIAG_J8_0 :
2737             (rdiag && ci == cj*2+1 ? NBNXN_INT_MASK_DIAG_J8_1 :
2738              NBNXN_INT_MASK_ALL));
2739 #else              /* cj-size = 4 */
2740     return (rdiag && ci == cj ? NBNXN_INT_MASK_DIAG : NBNXN_INT_MASK_ALL);
2741 #endif
2742 }
2743
2744 #ifdef GMX_NBNXN_SIMD
2745 #if GMX_NBNXN_SIMD_BITWIDTH == 128
2746 #define get_imask_x86_simd_4xn  get_imask_x86_simd128
2747 #else
2748 #if GMX_NBNXN_SIMD_BITWIDTH == 256
2749 #define get_imask_x86_simd_4xn  get_imask_x86_simd256
2750 #define get_imask_x86_simd_2xnn get_imask_x86_simd128
2751 #else
2752 #error "unsupported GMX_NBNXN_SIMD_BITWIDTH"
2753 #endif
2754 #endif
2755 #endif
2756
2757 /* Plain C code for making a pair list of cell ci vs cell cjf-cjl.
2758  * Checks bounding box distances and possibly atom pair distances.
2759  */
2760 static void make_cluster_list_simple(const nbnxn_grid_t *gridj,
2761                                      nbnxn_pairlist_t *nbl,
2762                                      int ci, int cjf, int cjl,
2763                                      gmx_bool remove_sub_diag,
2764                                      const real *x_j,
2765                                      real rl2, float rbb2,
2766                                      int *ndistc)
2767 {
2768     const nbnxn_list_work_t *work;
2769
2770     const float             *bb_ci;
2771     const real              *x_ci;
2772
2773     gmx_bool                 InRange;
2774     real                     d2;
2775     int                      cjf_gl, cjl_gl, cj;
2776
2777     work = nbl->work;
2778
2779     bb_ci = nbl->work->bb_ci;
2780     x_ci  = nbl->work->x_ci;
2781
2782     InRange = FALSE;
2783     while (!InRange && cjf <= cjl)
2784     {
2785         d2       = subc_bb_dist2(0, bb_ci, cjf, gridj->bb);
2786         *ndistc += 2;
2787
2788         /* Check if the distance is within the distance where
2789          * we use only the bounding box distance rbb,
2790          * or within the cut-off and there is at least one atom pair
2791          * within the cut-off.
2792          */
2793         if (d2 < rbb2)
2794         {
2795             InRange = TRUE;
2796         }
2797         else if (d2 < rl2)
2798         {
2799             int i, j;
2800
2801             cjf_gl = gridj->cell0 + cjf;
2802             for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
2803             {
2804                 for (j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
2805                 {
2806                     InRange = InRange ||
2807                         (sqr(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
2808                          sqr(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
2809                          sqr(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rl2);
2810                 }
2811             }
2812             *ndistc += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
2813         }
2814         if (!InRange)
2815         {
2816             cjf++;
2817         }
2818     }
2819     if (!InRange)
2820     {
2821         return;
2822     }
2823
2824     InRange = FALSE;
2825     while (!InRange && cjl > cjf)
2826     {
2827         d2       = subc_bb_dist2(0, bb_ci, cjl, gridj->bb);
2828         *ndistc += 2;
2829
2830         /* Check if the distance is within the distance where
2831          * we use only the bounding box distance rbb,
2832          * or within the cut-off and there is at least one atom pair
2833          * within the cut-off.
2834          */
2835         if (d2 < rbb2)
2836         {
2837             InRange = TRUE;
2838         }
2839         else if (d2 < rl2)
2840         {
2841             int i, j;
2842
2843             cjl_gl = gridj->cell0 + cjl;
2844             for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
2845             {
2846                 for (j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
2847                 {
2848                     InRange = InRange ||
2849                         (sqr(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
2850                          sqr(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
2851                          sqr(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rl2);
2852                 }
2853             }
2854             *ndistc += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
2855         }
2856         if (!InRange)
2857         {
2858             cjl--;
2859         }
2860     }
2861
2862     if (cjf <= cjl)
2863     {
2864         for (cj = cjf; cj <= cjl; cj++)
2865         {
2866             /* Store cj and the interaction mask */
2867             nbl->cj[nbl->ncj].cj   = gridj->cell0 + cj;
2868             nbl->cj[nbl->ncj].excl = get_imask(remove_sub_diag, ci, cj);
2869             nbl->ncj++;
2870         }
2871         /* Increase the closing index in i super-cell list */
2872         nbl->ci[nbl->nci].cj_ind_end = nbl->ncj;
2873     }
2874 }
2875
2876 #ifdef GMX_NBNXN_SIMD_4XN
2877 #include "nbnxn_search_simd_4xn.h"
2878 #endif
2879 #ifdef GMX_NBNXN_SIMD_2XNN
2880 #include "nbnxn_search_simd_2xnn.h"
2881 #endif
2882
2883 /* Plain C or SSE code for making a pair list of super-cell sci vs scj.
2884  * Checks bounding box distances and possibly atom pair distances.
2885  */
2886 static void make_cluster_list_supersub(const nbnxn_search_t nbs,
2887                                        const nbnxn_grid_t *gridi,
2888                                        const nbnxn_grid_t *gridj,
2889                                        nbnxn_pairlist_t *nbl,
2890                                        int sci, int scj,
2891                                        gmx_bool sci_equals_scj,
2892                                        int stride, const real *x,
2893                                        real rl2, float rbb2,
2894                                        int *ndistc)
2895 {
2896     int          na_c;
2897     int          npair;
2898     int          cjo, ci1, ci, cj, cj_gl;
2899     int          cj4_ind, cj_offset;
2900     unsigned     imask;
2901     nbnxn_cj4_t *cj4;
2902     const float *bb_ci;
2903     const real  *x_ci;
2904     float       *d2l, d2;
2905     int          w;
2906 #define PRUNE_LIST_CPU_ONE
2907 #ifdef PRUNE_LIST_CPU_ONE
2908     int  ci_last = -1;
2909 #endif
2910
2911     d2l = nbl->work->d2;
2912
2913     bb_ci = nbl->work->bb_ci;
2914     x_ci  = nbl->work->x_ci;
2915
2916     na_c = gridj->na_c;
2917
2918     for (cjo = 0; cjo < gridj->nsubc[scj]; cjo++)
2919     {
2920         cj4_ind   = (nbl->work->cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG);
2921         cj_offset = nbl->work->cj_ind - cj4_ind*NBNXN_GPU_JGROUP_SIZE;
2922         cj4       = &nbl->cj4[cj4_ind];
2923
2924         cj = scj*GPU_NSUBCELL + cjo;
2925
2926         cj_gl = gridj->cell0*GPU_NSUBCELL + cj;
2927
2928         /* Initialize this j-subcell i-subcell list */
2929         cj4->cj[cj_offset] = cj_gl;
2930         imask              = 0;
2931
2932         if (sci_equals_scj)
2933         {
2934             ci1 = cjo + 1;
2935         }
2936         else
2937         {
2938             ci1 = gridi->nsubc[sci];
2939         }
2940
2941 #ifdef NBNXN_BBXXXX
2942         /* Determine all ci1 bb distances in one call with SSE */
2943         subc_bb_dist2_sse_xxxx(gridj->bb+(cj>>STRIDE_PBB_2LOG)*NNBSBB_XXXX+(cj & (STRIDE_PBB-1)),
2944                                ci1, bb_ci, d2l);
2945         *ndistc += na_c*2;
2946 #endif
2947
2948         npair = 0;
2949         /* We use a fixed upper-bound instead of ci1 to help optimization */
2950         for (ci = 0; ci < GPU_NSUBCELL; ci++)
2951         {
2952             if (ci == ci1)
2953             {
2954                 break;
2955             }
2956
2957 #ifndef NBNXN_BBXXXX
2958             /* Determine the bb distance between ci and cj */
2959             d2l[ci]  = subc_bb_dist2(ci, bb_ci, cj, gridj->bb);
2960             *ndistc += 2;
2961 #endif
2962             d2 = d2l[ci];
2963
2964 #ifdef PRUNE_LIST_CPU_ALL
2965             /* Check if the distance is within the distance where
2966              * we use only the bounding box distance rbb,
2967              * or within the cut-off and there is at least one atom pair
2968              * within the cut-off. This check is very costly.
2969              */
2970             *ndistc += na_c*na_c;
2971             if (d2 < rbb2 ||
2972                 (d2 < rl2 &&
2973 #ifdef NBNXN_PBB_SSE
2974                  subc_in_range_sse8
2975 #else
2976                  subc_in_range_x
2977 #endif
2978                      (na_c, ci, x_ci, cj_gl, stride, x, rl2)))
2979 #else
2980             /* Check if the distance between the two bounding boxes
2981              * in within the pair-list cut-off.
2982              */
2983             if (d2 < rl2)
2984 #endif
2985             {
2986                 /* Flag this i-subcell to be taken into account */
2987                 imask |= (1U << (cj_offset*GPU_NSUBCELL+ci));
2988
2989 #ifdef PRUNE_LIST_CPU_ONE
2990                 ci_last = ci;
2991 #endif
2992
2993                 npair++;
2994             }
2995         }
2996
2997 #ifdef PRUNE_LIST_CPU_ONE
2998         /* If we only found 1 pair, check if any atoms are actually
2999          * within the cut-off, so we could get rid of it.
3000          */
3001         if (npair == 1 && d2l[ci_last] >= rbb2)
3002         {
3003             /* Avoid using function pointers here, as it's slower */
3004             if (
3005 #ifdef NBNXN_PBB_SSE
3006                 !subc_in_range_sse8
3007 #else
3008                 !subc_in_range_x
3009 #endif
3010                     (na_c, ci_last, x_ci, cj_gl, stride, x, rl2))
3011             {
3012                 imask &= ~(1U << (cj_offset*GPU_NSUBCELL+ci_last));
3013                 npair--;
3014             }
3015         }
3016 #endif
3017
3018         if (npair > 0)
3019         {
3020             /* We have a useful sj entry, close it now */
3021
3022             /* Set the exclucions for the ci== sj entry.
3023              * Here we don't bother to check if this entry is actually flagged,
3024              * as it will nearly always be in the list.
3025              */
3026             if (sci_equals_scj)
3027             {
3028                 set_self_and_newton_excls_supersub(nbl, cj4_ind, cj_offset, cjo);
3029             }
3030
3031             /* Copy the cluster interaction mask to the list */
3032             for (w = 0; w < NWARP; w++)
3033             {
3034                 cj4->imei[w].imask |= imask;
3035             }
3036
3037             nbl->work->cj_ind++;
3038
3039             /* Keep the count */
3040             nbl->nci_tot += npair;
3041
3042             /* Increase the closing index in i super-cell list */
3043             nbl->sci[nbl->nsci].cj4_ind_end =
3044                 ((nbl->work->cj_ind+NBNXN_GPU_JGROUP_SIZE-1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
3045         }
3046     }
3047 }
3048
3049 /* Set all atom-pair exclusions from the topology stored in excl
3050  * as masks in the pair-list for simple list i-entry nbl_ci
3051  */
3052 static void set_ci_top_excls(const nbnxn_search_t nbs,
3053                              nbnxn_pairlist_t    *nbl,
3054                              gmx_bool             diagRemoved,
3055                              int                  na_ci_2log,
3056                              int                  na_cj_2log,
3057                              const nbnxn_ci_t    *nbl_ci,
3058                              const t_blocka      *excl)
3059 {
3060     const int    *cell;
3061     int           ci;
3062     int           cj_ind_first, cj_ind_last;
3063     int           cj_first, cj_last;
3064     int           ndirect;
3065     int           i, ai, aj, si, eind, ge, se;
3066     int           found, cj_ind_0, cj_ind_1, cj_ind_m;
3067     int           cj_m;
3068     gmx_bool      Found_si;
3069     int           si_ind;
3070     nbnxn_excl_t *nbl_excl;
3071     int           inner_i, inner_e;
3072
3073     cell = nbs->cell;
3074
3075     if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
3076     {
3077         /* Empty list */
3078         return;
3079     }
3080
3081     ci = nbl_ci->ci;
3082
3083     cj_ind_first = nbl_ci->cj_ind_start;
3084     cj_ind_last  = nbl->ncj - 1;
3085
3086     cj_first = nbl->cj[cj_ind_first].cj;
3087     cj_last  = nbl->cj[cj_ind_last].cj;
3088
3089     /* Determine how many contiguous j-cells we have starting
3090      * from the first i-cell. This number can be used to directly
3091      * calculate j-cell indices for excluded atoms.
3092      */
3093     ndirect = 0;
3094     if (na_ci_2log == na_cj_2log)
3095     {
3096         while (cj_ind_first + ndirect <= cj_ind_last &&
3097                nbl->cj[cj_ind_first+ndirect].cj == ci + ndirect)
3098         {
3099             ndirect++;
3100         }
3101     }
3102 #ifdef NBNXN_SEARCH_BB_SSE
3103     else
3104     {
3105         while (cj_ind_first + ndirect <= cj_ind_last &&
3106                nbl->cj[cj_ind_first+ndirect].cj == ci_to_cj(na_cj_2log, ci) + ndirect)
3107         {
3108             ndirect++;
3109         }
3110     }
3111 #endif
3112
3113     /* Loop over the atoms in the i super-cell */
3114     for (i = 0; i < nbl->na_sc; i++)
3115     {
3116         ai = nbs->a[ci*nbl->na_sc+i];
3117         if (ai >= 0)
3118         {
3119             si  = (i>>na_ci_2log);
3120
3121             /* Loop over the topology-based exclusions for this i-atom */
3122             for (eind = excl->index[ai]; eind < excl->index[ai+1]; eind++)
3123             {
3124                 aj = excl->a[eind];
3125
3126                 if (aj == ai)
3127                 {
3128                     /* The self exclusion are already set, save some time */
3129                     continue;
3130                 }
3131
3132                 ge = cell[aj];
3133
3134                 /* Without shifts we only calculate interactions j>i
3135                  * for one-way pair-lists.
3136                  */
3137                 if (diagRemoved && ge <= ci*nbl->na_sc + i)
3138                 {
3139                     continue;
3140                 }
3141
3142                 se = (ge >> na_cj_2log);
3143
3144                 /* Could the cluster se be in our list? */
3145                 if (se >= cj_first && se <= cj_last)
3146                 {
3147                     if (se < cj_first + ndirect)
3148                     {
3149                         /* We can calculate cj_ind directly from se */
3150                         found = cj_ind_first + se - cj_first;
3151                     }
3152                     else
3153                     {
3154                         /* Search for se using bisection */
3155                         found    = -1;
3156                         cj_ind_0 = cj_ind_first + ndirect;
3157                         cj_ind_1 = cj_ind_last + 1;
3158                         while (found == -1 && cj_ind_0 < cj_ind_1)
3159                         {
3160                             cj_ind_m = (cj_ind_0 + cj_ind_1)>>1;
3161
3162                             cj_m = nbl->cj[cj_ind_m].cj;
3163
3164                             if (se == cj_m)
3165                             {
3166                                 found = cj_ind_m;
3167                             }
3168                             else if (se < cj_m)
3169                             {
3170                                 cj_ind_1 = cj_ind_m;
3171                             }
3172                             else
3173                             {
3174                                 cj_ind_0 = cj_ind_m + 1;
3175                             }
3176                         }
3177                     }
3178
3179                     if (found >= 0)
3180                     {
3181                         inner_i = i  - (si << na_ci_2log);
3182                         inner_e = ge - (se << na_cj_2log);
3183
3184                         nbl->cj[found].excl &= ~(1U<<((inner_i<<na_cj_2log) + inner_e));
3185                     }
3186                 }
3187             }
3188         }
3189     }
3190 }
3191
3192 /* Set all atom-pair exclusions from the topology stored in excl
3193  * as masks in the pair-list for i-super-cell entry nbl_sci
3194  */
3195 static void set_sci_top_excls(const nbnxn_search_t nbs,
3196                               nbnxn_pairlist_t    *nbl,
3197                               gmx_bool             diagRemoved,
3198                               int                  na_c_2log,
3199                               const nbnxn_sci_t   *nbl_sci,
3200                               const t_blocka      *excl)
3201 {
3202     const int    *cell;
3203     int           na_c;
3204     int           sci;
3205     int           cj_ind_first, cj_ind_last;
3206     int           cj_first, cj_last;
3207     int           ndirect;
3208     int           i, ai, aj, si, eind, ge, se;
3209     int           found, cj_ind_0, cj_ind_1, cj_ind_m;
3210     int           cj_m;
3211     gmx_bool      Found_si;
3212     int           si_ind;
3213     nbnxn_excl_t *nbl_excl;
3214     int           inner_i, inner_e, w;
3215
3216     cell = nbs->cell;
3217
3218     na_c = nbl->na_ci;
3219
3220     if (nbl_sci->cj4_ind_end == nbl_sci->cj4_ind_start)
3221     {
3222         /* Empty list */
3223         return;
3224     }
3225
3226     sci = nbl_sci->sci;
3227
3228     cj_ind_first = nbl_sci->cj4_ind_start*NBNXN_GPU_JGROUP_SIZE;
3229     cj_ind_last  = nbl->work->cj_ind - 1;
3230
3231     cj_first = nbl->cj4[nbl_sci->cj4_ind_start].cj[0];
3232     cj_last  = nbl_cj(nbl, cj_ind_last);
3233
3234     /* Determine how many contiguous j-clusters we have starting
3235      * from the first i-cluster. This number can be used to directly
3236      * calculate j-cluster indices for excluded atoms.
3237      */
3238     ndirect = 0;
3239     while (cj_ind_first + ndirect <= cj_ind_last &&
3240            nbl_cj(nbl, cj_ind_first+ndirect) == sci*GPU_NSUBCELL + ndirect)
3241     {
3242         ndirect++;
3243     }
3244
3245     /* Loop over the atoms in the i super-cell */
3246     for (i = 0; i < nbl->na_sc; i++)
3247     {
3248         ai = nbs->a[sci*nbl->na_sc+i];
3249         if (ai >= 0)
3250         {
3251             si  = (i>>na_c_2log);
3252
3253             /* Loop over the topology-based exclusions for this i-atom */
3254             for (eind = excl->index[ai]; eind < excl->index[ai+1]; eind++)
3255             {
3256                 aj = excl->a[eind];
3257
3258                 if (aj == ai)
3259                 {
3260                     /* The self exclusion are already set, save some time */
3261                     continue;
3262                 }
3263
3264                 ge = cell[aj];
3265
3266                 /* Without shifts we only calculate interactions j>i
3267                  * for one-way pair-lists.
3268                  */
3269                 if (diagRemoved && ge <= sci*nbl->na_sc + i)
3270                 {
3271                     continue;
3272                 }
3273
3274                 se = ge>>na_c_2log;
3275                 /* Could the cluster se be in our list? */
3276                 if (se >= cj_first && se <= cj_last)
3277                 {
3278                     if (se < cj_first + ndirect)
3279                     {
3280                         /* We can calculate cj_ind directly from se */
3281                         found = cj_ind_first + se - cj_first;
3282                     }
3283                     else
3284                     {
3285                         /* Search for se using bisection */
3286                         found    = -1;
3287                         cj_ind_0 = cj_ind_first + ndirect;
3288                         cj_ind_1 = cj_ind_last + 1;
3289                         while (found == -1 && cj_ind_0 < cj_ind_1)
3290                         {
3291                             cj_ind_m = (cj_ind_0 + cj_ind_1)>>1;
3292
3293                             cj_m = nbl_cj(nbl, cj_ind_m);
3294
3295                             if (se == cj_m)
3296                             {
3297                                 found = cj_ind_m;
3298                             }
3299                             else if (se < cj_m)
3300                             {
3301                                 cj_ind_1 = cj_ind_m;
3302                             }
3303                             else
3304                             {
3305                                 cj_ind_0 = cj_ind_m + 1;
3306                             }
3307                         }
3308                     }
3309
3310                     if (found >= 0)
3311                     {
3312                         inner_i = i  - si*na_c;
3313                         inner_e = ge - se*na_c;
3314
3315 /* Macro for getting the index of atom a within a cluster */
3316 #define AMODCJ4(a)  ((a) & (NBNXN_GPU_JGROUP_SIZE - 1))
3317 /* Macro for converting an atom number to a cluster number */
3318 #define A2CJ4(a)    ((a) >> NBNXN_GPU_JGROUP_SIZE_2LOG)
3319 /* Macro for getting the index of an i-atom within a warp */
3320 #define AMODWI(a)   ((a) & (NBNXN_GPU_CLUSTER_SIZE/2 - 1))
3321
3322                         if (nbl_imask0(nbl, found) & (1U << (AMODCJ4(found)*GPU_NSUBCELL + si)))
3323                         {
3324                             w       = (inner_e >> 2);
3325
3326                             get_nbl_exclusions_1(nbl, A2CJ4(found), w, &nbl_excl);
3327
3328                             nbl_excl->pair[AMODWI(inner_e)*nbl->na_ci+inner_i] &=
3329                                 ~(1U << (AMODCJ4(found)*GPU_NSUBCELL + si));
3330                         }
3331
3332 #undef AMODCJ4
3333 #undef A2CJ4
3334 #undef AMODWI
3335                     }
3336                 }
3337             }
3338         }
3339     }
3340 }
3341
3342 /* Reallocate the simple ci list for at least n entries */
3343 static void nb_realloc_ci(nbnxn_pairlist_t *nbl, int n)
3344 {
3345     nbl->ci_nalloc = over_alloc_small(n);
3346     nbnxn_realloc_void((void **)&nbl->ci,
3347                        nbl->nci*sizeof(*nbl->ci),
3348                        nbl->ci_nalloc*sizeof(*nbl->ci),
3349                        nbl->alloc, nbl->free);
3350 }
3351
3352 /* Reallocate the super-cell sci list for at least n entries */
3353 static void nb_realloc_sci(nbnxn_pairlist_t *nbl, int n)
3354 {
3355     nbl->sci_nalloc = over_alloc_small(n);
3356     nbnxn_realloc_void((void **)&nbl->sci,
3357                        nbl->nsci*sizeof(*nbl->sci),
3358                        nbl->sci_nalloc*sizeof(*nbl->sci),
3359                        nbl->alloc, nbl->free);
3360 }
3361
3362 /* Make a new ci entry at index nbl->nci */
3363 static void new_ci_entry(nbnxn_pairlist_t *nbl, int ci, int shift, int flags,
3364                          nbnxn_list_work_t *work)
3365 {
3366     if (nbl->nci + 1 > nbl->ci_nalloc)
3367     {
3368         nb_realloc_ci(nbl, nbl->nci+1);
3369     }
3370     nbl->ci[nbl->nci].ci            = ci;
3371     nbl->ci[nbl->nci].shift         = shift;
3372     /* Store the interaction flags along with the shift */
3373     nbl->ci[nbl->nci].shift        |= flags;
3374     nbl->ci[nbl->nci].cj_ind_start  = nbl->ncj;
3375     nbl->ci[nbl->nci].cj_ind_end    = nbl->ncj;
3376 }
3377
3378 /* Make a new sci entry at index nbl->nsci */
3379 static void new_sci_entry(nbnxn_pairlist_t *nbl, int sci, int shift, int flags,
3380                           nbnxn_list_work_t *work)
3381 {
3382     if (nbl->nsci + 1 > nbl->sci_nalloc)
3383     {
3384         nb_realloc_sci(nbl, nbl->nsci+1);
3385     }
3386     nbl->sci[nbl->nsci].sci           = sci;
3387     nbl->sci[nbl->nsci].shift         = shift;
3388     nbl->sci[nbl->nsci].cj4_ind_start = nbl->ncj4;
3389     nbl->sci[nbl->nsci].cj4_ind_end   = nbl->ncj4;
3390 }
3391
3392 /* Sort the simple j-list cj on exclusions.
3393  * Entries with exclusions will all be sorted to the beginning of the list.
3394  */
3395 static void sort_cj_excl(nbnxn_cj_t *cj, int ncj,
3396                          nbnxn_list_work_t *work)
3397 {
3398     int jnew, j;
3399
3400     if (ncj > work->cj_nalloc)
3401     {
3402         work->cj_nalloc = over_alloc_large(ncj);
3403         srenew(work->cj, work->cj_nalloc);
3404     }
3405
3406     /* Make a list of the j-cells involving exclusions */
3407     jnew = 0;
3408     for (j = 0; j < ncj; j++)
3409     {
3410         if (cj[j].excl != NBNXN_INT_MASK_ALL)
3411         {
3412             work->cj[jnew++] = cj[j];
3413         }
3414     }
3415     /* Check if there are exclusions at all or not just the first entry */
3416     if (!((jnew == 0) ||
3417           (jnew == 1 && cj[0].excl != NBNXN_INT_MASK_ALL)))
3418     {
3419         for (j = 0; j < ncj; j++)
3420         {
3421             if (cj[j].excl == NBNXN_INT_MASK_ALL)
3422             {
3423                 work->cj[jnew++] = cj[j];
3424             }
3425         }
3426         for (j = 0; j < ncj; j++)
3427         {
3428             cj[j] = work->cj[j];
3429         }
3430     }
3431 }
3432
3433 /* Close this simple list i entry */
3434 static void close_ci_entry_simple(nbnxn_pairlist_t *nbl)
3435 {
3436     int jlen;
3437
3438     /* All content of the new ci entry have already been filled correctly,
3439      * we only need to increase the count here (for non empty lists).
3440      */
3441     jlen = nbl->ci[nbl->nci].cj_ind_end - nbl->ci[nbl->nci].cj_ind_start;
3442     if (jlen > 0)
3443     {
3444         sort_cj_excl(nbl->cj+nbl->ci[nbl->nci].cj_ind_start, jlen, nbl->work);
3445
3446         /* The counts below are used for non-bonded pair/flop counts
3447          * and should therefore match the available kernel setups.
3448          */
3449         if (!(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_COUL(0)))
3450         {
3451             nbl->work->ncj_noq += jlen;
3452         }
3453         else if ((nbl->ci[nbl->nci].shift & NBNXN_CI_HALF_LJ(0)) ||
3454                  !(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_LJ(0)))
3455         {
3456             nbl->work->ncj_hlj += jlen;
3457         }
3458
3459         nbl->nci++;
3460     }
3461 }
3462
3463 /* Split sci entry for load balancing on the GPU.
3464  * Splitting ensures we have enough lists to fully utilize the whole GPU.
3465  * With progBal we generate progressively smaller lists, which improves
3466  * load balancing. As we only know the current count on our own thread,
3467  * we will need to estimate the current total amount of i-entries.
3468  * As the lists get concatenated later, this estimate depends
3469  * both on nthread and our own thread index.
3470  */
3471 static void split_sci_entry(nbnxn_pairlist_t *nbl,
3472                             int nsp_max_av, gmx_bool progBal, int nc_bal,
3473                             int thread, int nthread)
3474 {
3475     int nsci_est;
3476     int nsp_max;
3477     int cj4_start, cj4_end, j4len, cj4;
3478     int sci;
3479     int nsp, nsp_sci, nsp_cj4, nsp_cj4_e, nsp_cj4_p;
3480     int p;
3481
3482     if (progBal)
3483     {
3484         /* Estimate the total numbers of ci's of the nblist combined
3485          * over all threads using the target number of ci's.
3486          */
3487         nsci_est = nc_bal*thread/nthread + nbl->nsci;
3488
3489         /* The first ci blocks should be larger, to avoid overhead.
3490          * The last ci blocks should be smaller, to improve load balancing.
3491          */
3492         nsp_max = max(1,
3493                       nsp_max_av*nc_bal*3/(2*(nsci_est - 1 + nc_bal)));
3494     }
3495     else
3496     {
3497         nsp_max = nsp_max_av;
3498     }
3499
3500     cj4_start = nbl->sci[nbl->nsci-1].cj4_ind_start;
3501     cj4_end   = nbl->sci[nbl->nsci-1].cj4_ind_end;
3502     j4len     = cj4_end - cj4_start;
3503
3504     if (j4len > 1 && j4len*GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE > nsp_max)
3505     {
3506         /* Remove the last ci entry and process the cj4's again */
3507         nbl->nsci -= 1;
3508
3509         sci        = nbl->nsci;
3510         nsp        = 0;
3511         nsp_sci    = 0;
3512         nsp_cj4_e  = 0;
3513         nsp_cj4    = 0;
3514         for (cj4 = cj4_start; cj4 < cj4_end; cj4++)
3515         {
3516             nsp_cj4_p = nsp_cj4;
3517             /* Count the number of cluster pairs in this cj4 group */
3518             nsp_cj4   = 0;
3519             for (p = 0; p < GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE; p++)
3520             {
3521                 nsp_cj4 += (nbl->cj4[cj4].imei[0].imask >> p) & 1;
3522             }
3523
3524             if (nsp_cj4 > 0 && nsp + nsp_cj4 > nsp_max)
3525             {
3526                 /* Split the list at cj4 */
3527                 nbl->sci[sci].cj4_ind_end = cj4;
3528                 /* Create a new sci entry */
3529                 sci++;
3530                 nbl->nsci++;
3531                 if (nbl->nsci+1 > nbl->sci_nalloc)
3532                 {
3533                     nb_realloc_sci(nbl, nbl->nsci+1);
3534                 }
3535                 nbl->sci[sci].sci           = nbl->sci[nbl->nsci-1].sci;
3536                 nbl->sci[sci].shift         = nbl->sci[nbl->nsci-1].shift;
3537                 nbl->sci[sci].cj4_ind_start = cj4;
3538                 nsp_sci                     = nsp;
3539                 nsp_cj4_e                   = nsp_cj4_p;
3540                 nsp                         = 0;
3541             }
3542             nsp += nsp_cj4;
3543         }
3544
3545         /* Put the remaining cj4's in the last sci entry */
3546         nbl->sci[sci].cj4_ind_end = cj4_end;
3547
3548         /* Possibly balance out the last two sci's
3549          * by moving the last cj4 of the second last sci.
3550          */
3551         if (nsp_sci - nsp_cj4_e >= nsp + nsp_cj4_e)
3552         {
3553             nbl->sci[sci-1].cj4_ind_end--;
3554             nbl->sci[sci].cj4_ind_start--;
3555         }
3556
3557         nbl->nsci++;
3558     }
3559 }
3560
3561 /* Clost this super/sub list i entry */
3562 static void close_ci_entry_supersub(nbnxn_pairlist_t *nbl,
3563                                     int nsp_max_av,
3564                                     gmx_bool progBal, int nc_bal,
3565                                     int thread, int nthread)
3566 {
3567     int j4len, tlen;
3568     int nb, b;
3569
3570     /* All content of the new ci entry have already been filled correctly,
3571      * we only need to increase the count here (for non empty lists).
3572      */
3573     j4len = nbl->sci[nbl->nsci].cj4_ind_end - nbl->sci[nbl->nsci].cj4_ind_start;
3574     if (j4len > 0)
3575     {
3576         /* We can only have complete blocks of 4 j-entries in a list,
3577          * so round the count up before closing.
3578          */
3579         nbl->ncj4         = ((nbl->work->cj_ind + NBNXN_GPU_JGROUP_SIZE - 1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
3580         nbl->work->cj_ind = nbl->ncj4*NBNXN_GPU_JGROUP_SIZE;
3581
3582         nbl->nsci++;
3583
3584         if (nsp_max_av > 0)
3585         {
3586             /* Measure the size of the new entry and potentially split it */
3587             split_sci_entry(nbl, nsp_max_av, progBal, nc_bal, thread, nthread);
3588         }
3589     }
3590 }
3591
3592 /* Syncs the working array before adding another grid pair to the list */
3593 static void sync_work(nbnxn_pairlist_t *nbl)
3594 {
3595     if (!nbl->bSimple)
3596     {
3597         nbl->work->cj_ind   = nbl->ncj4*NBNXN_GPU_JGROUP_SIZE;
3598         nbl->work->cj4_init = nbl->ncj4;
3599     }
3600 }
3601
3602 /* Clears an nbnxn_pairlist_t data structure */
3603 static void clear_pairlist(nbnxn_pairlist_t *nbl)
3604 {
3605     nbl->nci           = 0;
3606     nbl->nsci          = 0;
3607     nbl->ncj           = 0;
3608     nbl->ncj4          = 0;
3609     nbl->nci_tot       = 0;
3610     nbl->nexcl         = 1;
3611
3612     nbl->work->ncj_noq = 0;
3613     nbl->work->ncj_hlj = 0;
3614 }
3615
3616 /* Sets a simple list i-cell bounding box, including PBC shift */
3617 static void set_icell_bb_simple(const float *bb, int ci,
3618                                 real shx, real shy, real shz,
3619                                 float *bb_ci)
3620 {
3621     int ia;
3622
3623     ia           = ci*NNBSBB_B;
3624     bb_ci[BBL_X] = bb[ia+BBL_X] + shx;
3625     bb_ci[BBL_Y] = bb[ia+BBL_Y] + shy;
3626     bb_ci[BBL_Z] = bb[ia+BBL_Z] + shz;
3627     bb_ci[BBU_X] = bb[ia+BBU_X] + shx;
3628     bb_ci[BBU_Y] = bb[ia+BBU_Y] + shy;
3629     bb_ci[BBU_Z] = bb[ia+BBU_Z] + shz;
3630 }
3631
3632 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
3633 static void set_icell_bb_supersub(const float *bb, int ci,
3634                                   real shx, real shy, real shz,
3635                                   float *bb_ci)
3636 {
3637     int ia, m, i;
3638
3639 #ifdef NBNXN_BBXXXX
3640     ia = ci*(GPU_NSUBCELL>>STRIDE_PBB_2LOG)*NNBSBB_XXXX;
3641     for (m = 0; m < (GPU_NSUBCELL>>STRIDE_PBB_2LOG)*NNBSBB_XXXX; m += NNBSBB_XXXX)
3642     {
3643         for (i = 0; i < STRIDE_PBB; i++)
3644         {
3645             bb_ci[m+0*STRIDE_PBB+i] = bb[ia+m+0*STRIDE_PBB+i] + shx;
3646             bb_ci[m+1*STRIDE_PBB+i] = bb[ia+m+1*STRIDE_PBB+i] + shy;
3647             bb_ci[m+2*STRIDE_PBB+i] = bb[ia+m+2*STRIDE_PBB+i] + shz;
3648             bb_ci[m+3*STRIDE_PBB+i] = bb[ia+m+3*STRIDE_PBB+i] + shx;
3649             bb_ci[m+4*STRIDE_PBB+i] = bb[ia+m+4*STRIDE_PBB+i] + shy;
3650             bb_ci[m+5*STRIDE_PBB+i] = bb[ia+m+5*STRIDE_PBB+i] + shz;
3651         }
3652     }
3653 #else
3654     ia = ci*GPU_NSUBCELL*NNBSBB_B;
3655     for (i = 0; i < GPU_NSUBCELL*NNBSBB_B; i += NNBSBB_B)
3656     {
3657         bb_ci[i+BBL_X] = bb[ia+i+BBL_X] + shx;
3658         bb_ci[i+BBL_Y] = bb[ia+i+BBL_Y] + shy;
3659         bb_ci[i+BBL_Z] = bb[ia+i+BBL_Z] + shz;
3660         bb_ci[i+BBU_X] = bb[ia+i+BBU_X] + shx;
3661         bb_ci[i+BBU_Y] = bb[ia+i+BBU_Y] + shy;
3662         bb_ci[i+BBU_Z] = bb[ia+i+BBU_Z] + shz;
3663     }
3664 #endif
3665 }
3666
3667 /* Copies PBC shifted i-cell atom coordinates x,y,z to working array */
3668 static void icell_set_x_simple(int ci,
3669                                real shx, real shy, real shz,
3670                                int na_c,
3671                                int stride, const real *x,
3672                                nbnxn_list_work_t *work)
3673 {
3674     int  ia, i;
3675
3676     ia = ci*NBNXN_CPU_CLUSTER_I_SIZE;
3677
3678     for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE; i++)
3679     {
3680         work->x_ci[i*STRIDE_XYZ+XX] = x[(ia+i)*stride+XX] + shx;
3681         work->x_ci[i*STRIDE_XYZ+YY] = x[(ia+i)*stride+YY] + shy;
3682         work->x_ci[i*STRIDE_XYZ+ZZ] = x[(ia+i)*stride+ZZ] + shz;
3683     }
3684 }
3685
3686 /* Copies PBC shifted super-cell atom coordinates x,y,z to working array */
3687 static void icell_set_x_supersub(int ci,
3688                                  real shx, real shy, real shz,
3689                                  int na_c,
3690                                  int stride, const real *x,
3691                                  nbnxn_list_work_t *work)
3692 {
3693     int  ia, i;
3694     real *x_ci;
3695
3696     x_ci = work->x_ci;
3697
3698     ia = ci*GPU_NSUBCELL*na_c;
3699     for (i = 0; i < GPU_NSUBCELL*na_c; i++)
3700     {
3701         x_ci[i*DIM + XX] = x[(ia+i)*stride + XX] + shx;
3702         x_ci[i*DIM + YY] = x[(ia+i)*stride + YY] + shy;
3703         x_ci[i*DIM + ZZ] = x[(ia+i)*stride + ZZ] + shz;
3704     }
3705 }
3706
3707 #ifdef NBNXN_SEARCH_BB_SSE
3708 /* Copies PBC shifted super-cell packed atom coordinates to working array */
3709 static void icell_set_x_supersub_sse8(int ci,
3710                                       real shx, real shy, real shz,
3711                                       int na_c,
3712                                       int stride, const real *x,
3713                                       nbnxn_list_work_t *work)
3714 {
3715     int  si, io, ia, i, j;
3716     real *x_ci;
3717
3718     x_ci = work->x_ci;
3719
3720     for (si = 0; si < GPU_NSUBCELL; si++)
3721     {
3722         for (i = 0; i < na_c; i += STRIDE_PBB)
3723         {
3724             io = si*na_c + i;
3725             ia = ci*GPU_NSUBCELL*na_c + io;
3726             for (j = 0; j < STRIDE_PBB; j++)
3727             {
3728                 x_ci[io*DIM + j + XX*STRIDE_PBB] = x[(ia+j)*stride+XX] + shx;
3729                 x_ci[io*DIM + j + YY*STRIDE_PBB] = x[(ia+j)*stride+YY] + shy;
3730                 x_ci[io*DIM + j + ZZ*STRIDE_PBB] = x[(ia+j)*stride+ZZ] + shz;
3731             }
3732         }
3733     }
3734 }
3735 #endif
3736
3737 static real nbnxn_rlist_inc_nonloc_fac = 0.6;
3738
3739 /* Due to the cluster size the effective pair-list is longer than
3740  * that of a simple atom pair-list. This function gives the extra distance.
3741  */
3742 real nbnxn_get_rlist_effective_inc(int cluster_size, real atom_density)
3743 {
3744     return ((0.5 + nbnxn_rlist_inc_nonloc_fac)*sqr(((cluster_size) - 1.0)/(cluster_size))*pow((cluster_size)/(atom_density), 1.0/3.0));
3745 }
3746
3747 /* Estimates the interaction volume^2 for non-local interactions */
3748 static real nonlocal_vol2(const gmx_domdec_zones_t *zones, rvec ls, real r)
3749 {
3750     int  z, d;
3751     real cl, ca, za;
3752     real vold_est;
3753     real vol2_est_tot;
3754
3755     vol2_est_tot = 0;
3756
3757     /* Here we simply add up the volumes of 1, 2 or 3 1D decomposition
3758      * not home interaction volume^2. As these volumes are not additive,
3759      * this is an overestimate, but it would only be significant in the limit
3760      * of small cells, where we anyhow need to split the lists into
3761      * as small parts as possible.
3762      */
3763
3764     for (z = 0; z < zones->n; z++)
3765     {
3766         if (zones->shift[z][XX] + zones->shift[z][YY] + zones->shift[z][ZZ] == 1)
3767         {
3768             cl = 0;
3769             ca = 1;
3770             za = 1;
3771             for (d = 0; d < DIM; d++)
3772             {
3773                 if (zones->shift[z][d] == 0)
3774                 {
3775                     cl += 0.5*ls[d];
3776                     ca *= ls[d];
3777                     za *= zones->size[z].x1[d] - zones->size[z].x0[d];
3778                 }
3779             }
3780
3781             /* 4 octants of a sphere */
3782             vold_est  = 0.25*M_PI*r*r*r*r;
3783             /* 4 quarter pie slices on the edges */
3784             vold_est += 4*cl*M_PI/6.0*r*r*r;
3785             /* One rectangular volume on a face */
3786             vold_est += ca*0.5*r*r;
3787
3788             vol2_est_tot += vold_est*za;
3789         }
3790     }
3791
3792     return vol2_est_tot;
3793 }
3794
3795 /* Estimates the average size of a full j-list for super/sub setup */
3796 static int get_nsubpair_max(const nbnxn_search_t nbs,
3797                             int                  iloc,
3798                             real                 rlist,
3799                             int                  min_ci_balanced)
3800 {
3801     const nbnxn_grid_t *grid;
3802     rvec ls;
3803     real xy_diag2, r_eff_sup, vol_est, nsp_est, nsp_est_nl;
3804     int  nsubpair_max;
3805
3806     grid = &nbs->grid[0];
3807
3808     ls[XX] = (grid->c1[XX] - grid->c0[XX])/(grid->ncx*GPU_NSUBCELL_X);
3809     ls[YY] = (grid->c1[YY] - grid->c0[YY])/(grid->ncy*GPU_NSUBCELL_Y);
3810     ls[ZZ] = (grid->c1[ZZ] - grid->c0[ZZ])*grid->ncx*grid->ncy/(grid->nc*GPU_NSUBCELL_Z);
3811
3812     /* The average squared length of the diagonal of a sub cell */
3813     xy_diag2 = ls[XX]*ls[XX] + ls[YY]*ls[YY] + ls[ZZ]*ls[ZZ];
3814
3815     /* The formulas below are a heuristic estimate of the average nsj per si*/
3816     r_eff_sup = rlist + nbnxn_rlist_inc_nonloc_fac*sqr((grid->na_c - 1.0)/grid->na_c)*sqrt(xy_diag2/3);
3817
3818     if (!nbs->DomDec || nbs->zones->n == 1)
3819     {
3820         nsp_est_nl = 0;
3821     }
3822     else
3823     {
3824         nsp_est_nl =
3825             sqr(grid->atom_density/grid->na_c)*
3826             nonlocal_vol2(nbs->zones, ls, r_eff_sup);
3827     }
3828
3829     if (LOCAL_I(iloc))
3830     {
3831         /* Sub-cell interacts with itself */
3832         vol_est  = ls[XX]*ls[YY]*ls[ZZ];
3833         /* 6/2 rectangular volume on the faces */
3834         vol_est += (ls[XX]*ls[YY] + ls[XX]*ls[ZZ] + ls[YY]*ls[ZZ])*r_eff_sup;
3835         /* 12/2 quarter pie slices on the edges */
3836         vol_est += 2*(ls[XX] + ls[YY] + ls[ZZ])*0.25*M_PI*sqr(r_eff_sup);
3837         /* 4 octants of a sphere */
3838         vol_est += 0.5*4.0/3.0*M_PI*pow(r_eff_sup, 3);
3839
3840         nsp_est = grid->nsubc_tot*vol_est*grid->atom_density/grid->na_c;
3841
3842         /* Subtract the non-local pair count */
3843         nsp_est -= nsp_est_nl;
3844
3845         if (debug)
3846         {
3847             fprintf(debug, "nsp_est local %5.1f non-local %5.1f\n",
3848                     nsp_est, nsp_est_nl);
3849         }
3850     }
3851     else
3852     {
3853         nsp_est = nsp_est_nl;
3854     }
3855
3856     if (min_ci_balanced <= 0 || grid->nc >= min_ci_balanced || grid->nc == 0)
3857     {
3858         /* We don't need to worry */
3859         nsubpair_max = -1;
3860     }
3861     else
3862     {
3863         /* Thus the (average) maximum j-list size should be as follows */
3864         nsubpair_max = max(1, (int)(nsp_est/min_ci_balanced+0.5));
3865
3866         /* Since the target value is a maximum (this avoids high outliers,
3867          * which lead to load imbalance), not average, we add half the
3868          * number of pairs in a cj4 block to get the average about right.
3869          */
3870         nsubpair_max += GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE/2;
3871     }
3872
3873     if (debug)
3874     {
3875         fprintf(debug, "nbl nsp estimate %.1f, nsubpair_max %d\n",
3876                 nsp_est, nsubpair_max);
3877     }
3878
3879     return nsubpair_max;
3880 }
3881
3882 /* Debug list print function */
3883 static void print_nblist_ci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
3884 {
3885     int i, j;
3886
3887     for (i = 0; i < nbl->nci; i++)
3888     {
3889         fprintf(fp, "ci %4d  shift %2d  ncj %3d\n",
3890                 nbl->ci[i].ci, nbl->ci[i].shift,
3891                 nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start);
3892
3893         for (j = nbl->ci[i].cj_ind_start; j < nbl->ci[i].cj_ind_end; j++)
3894         {
3895             fprintf(fp, "  cj %5d  imask %x\n",
3896                     nbl->cj[j].cj,
3897                     nbl->cj[j].excl);
3898         }
3899     }
3900 }
3901
3902 /* Debug list print function */
3903 static void print_nblist_sci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
3904 {
3905     int i, j4, j, ncp, si;
3906
3907     for (i = 0; i < nbl->nsci; i++)
3908     {
3909         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d\n",
3910                 nbl->sci[i].sci, nbl->sci[i].shift,
3911                 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start);
3912
3913         ncp = 0;
3914         for (j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
3915         {
3916             for (j = 0; j < NBNXN_GPU_JGROUP_SIZE; j++)
3917             {
3918                 fprintf(fp, "  sj %5d  imask %x\n",
3919                         nbl->cj4[j4].cj[j],
3920                         nbl->cj4[j4].imei[0].imask);
3921                 for (si = 0; si < GPU_NSUBCELL; si++)
3922                 {
3923                     if (nbl->cj4[j4].imei[0].imask & (1U << (j*GPU_NSUBCELL + si)))
3924                     {
3925                         ncp++;
3926                     }
3927                 }
3928             }
3929         }
3930         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d ncp %3d\n",
3931                 nbl->sci[i].sci, nbl->sci[i].shift,
3932                 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start,
3933                 ncp);
3934     }
3935 }
3936
3937 /* Combine pair lists *nbl generated on multiple threads nblc */
3938 static void combine_nblists(int nnbl, nbnxn_pairlist_t **nbl,
3939                             nbnxn_pairlist_t *nblc)
3940 {
3941     int nsci, ncj4, nexcl;
3942     int n, i;
3943
3944     if (nblc->bSimple)
3945     {
3946         gmx_incons("combine_nblists does not support simple lists");
3947     }
3948
3949     nsci  = nblc->nsci;
3950     ncj4  = nblc->ncj4;
3951     nexcl = nblc->nexcl;
3952     for (i = 0; i < nnbl; i++)
3953     {
3954         nsci  += nbl[i]->nsci;
3955         ncj4  += nbl[i]->ncj4;
3956         nexcl += nbl[i]->nexcl;
3957     }
3958
3959     if (nsci > nblc->sci_nalloc)
3960     {
3961         nb_realloc_sci(nblc, nsci);
3962     }
3963     if (ncj4 > nblc->cj4_nalloc)
3964     {
3965         nblc->cj4_nalloc = over_alloc_small(ncj4);
3966         nbnxn_realloc_void((void **)&nblc->cj4,
3967                            nblc->ncj4*sizeof(*nblc->cj4),
3968                            nblc->cj4_nalloc*sizeof(*nblc->cj4),
3969                            nblc->alloc, nblc->free);
3970     }
3971     if (nexcl > nblc->excl_nalloc)
3972     {
3973         nblc->excl_nalloc = over_alloc_small(nexcl);
3974         nbnxn_realloc_void((void **)&nblc->excl,
3975                            nblc->nexcl*sizeof(*nblc->excl),
3976                            nblc->excl_nalloc*sizeof(*nblc->excl),
3977                            nblc->alloc, nblc->free);
3978     }
3979
3980     /* Each thread should copy its own data to the combined arrays,
3981      * as otherwise data will go back and forth between different caches.
3982      */
3983 #pragma omp parallel for num_threads(gmx_omp_nthreads_get(emntPairsearch)) schedule(static)
3984     for (n = 0; n < nnbl; n++)
3985     {
3986         int sci_offset;
3987         int cj4_offset;
3988         int ci_offset;
3989         int excl_offset;
3990         int i, j4;
3991         const nbnxn_pairlist_t *nbli;
3992
3993         /* Determine the offset in the combined data for our thread */
3994         sci_offset  = nblc->nsci;
3995         cj4_offset  = nblc->ncj4;
3996         ci_offset   = nblc->nci_tot;
3997         excl_offset = nblc->nexcl;
3998
3999         for (i = 0; i < n; i++)
4000         {
4001             sci_offset  += nbl[i]->nsci;
4002             cj4_offset  += nbl[i]->ncj4;
4003             ci_offset   += nbl[i]->nci_tot;
4004             excl_offset += nbl[i]->nexcl;
4005         }
4006
4007         nbli = nbl[n];
4008
4009         for (i = 0; i < nbli->nsci; i++)
4010         {
4011             nblc->sci[sci_offset+i]                = nbli->sci[i];
4012             nblc->sci[sci_offset+i].cj4_ind_start += cj4_offset;
4013             nblc->sci[sci_offset+i].cj4_ind_end   += cj4_offset;
4014         }
4015
4016         for (j4 = 0; j4 < nbli->ncj4; j4++)
4017         {
4018             nblc->cj4[cj4_offset+j4]                   = nbli->cj4[j4];
4019             nblc->cj4[cj4_offset+j4].imei[0].excl_ind += excl_offset;
4020             nblc->cj4[cj4_offset+j4].imei[1].excl_ind += excl_offset;
4021         }
4022
4023         for (j4 = 0; j4 < nbli->nexcl; j4++)
4024         {
4025             nblc->excl[excl_offset+j4] = nbli->excl[j4];
4026         }
4027     }
4028
4029     for (n = 0; n < nnbl; n++)
4030     {
4031         nblc->nsci    += nbl[n]->nsci;
4032         nblc->ncj4    += nbl[n]->ncj4;
4033         nblc->nci_tot += nbl[n]->nci_tot;
4034         nblc->nexcl   += nbl[n]->nexcl;
4035     }
4036 }
4037
4038 /* Returns the next ci to be processes by our thread */
4039 static gmx_bool next_ci(const nbnxn_grid_t *grid,
4040                         int conv,
4041                         int nth, int ci_block,
4042                         int *ci_x, int *ci_y,
4043                         int *ci_b, int *ci)
4044 {
4045     (*ci_b)++;
4046     (*ci)++;
4047
4048     if (*ci_b == ci_block)
4049     {
4050         /* Jump to the next block assigned to this task */
4051         *ci   += (nth - 1)*ci_block;
4052         *ci_b  = 0;
4053     }
4054
4055     if (*ci >= grid->nc*conv)
4056     {
4057         return FALSE;
4058     }
4059
4060     while (*ci >= grid->cxy_ind[*ci_x*grid->ncy + *ci_y + 1]*conv)
4061     {
4062         *ci_y += 1;
4063         if (*ci_y == grid->ncy)
4064         {
4065             *ci_x += 1;
4066             *ci_y  = 0;
4067         }
4068     }
4069
4070     return TRUE;
4071 }
4072
4073 /* Returns the distance^2 for which we put cell pairs in the list
4074  * without checking atom pair distances. This is usually < rlist^2.
4075  */
4076 static float boundingbox_only_distance2(const nbnxn_grid_t *gridi,
4077                                         const nbnxn_grid_t *gridj,
4078                                         real                rlist,
4079                                         gmx_bool            simple)
4080 {
4081     /* If the distance between two sub-cell bounding boxes is less
4082      * than this distance, do not check the distance between
4083      * all particle pairs in the sub-cell, since then it is likely
4084      * that the box pair has atom pairs within the cut-off.
4085      * We use the nblist cut-off minus 0.5 times the average x/y diagonal
4086      * spacing of the sub-cells. Around 40% of the checked pairs are pruned.
4087      * Using more than 0.5 gains at most 0.5%.
4088      * If forces are calculated more than twice, the performance gain
4089      * in the force calculation outweighs the cost of checking.
4090      * Note that with subcell lists, the atom-pair distance check
4091      * is only performed when only 1 out of 8 sub-cells in within range,
4092      * this is because the GPU is much faster than the cpu.
4093      */
4094     real bbx, bby;
4095     real rbb2;
4096
4097     bbx = 0.5*(gridi->sx + gridj->sx);
4098     bby = 0.5*(gridi->sy + gridj->sy);
4099     if (!simple)
4100     {
4101         bbx /= GPU_NSUBCELL_X;
4102         bby /= GPU_NSUBCELL_Y;
4103     }
4104
4105     rbb2 = sqr(max(0, rlist - 0.5*sqrt(bbx*bbx + bby*bby)));
4106
4107 #ifndef GMX_DOUBLE
4108     return rbb2;
4109 #else
4110     return (float)((1+GMX_FLOAT_EPS)*rbb2);
4111 #endif
4112 }
4113
4114 static int get_ci_block_size(const nbnxn_grid_t *gridi,
4115                              gmx_bool bDomDec, int nth)
4116 {
4117     const int ci_block_enum      = 5;
4118     const int ci_block_denom     = 11;
4119     const int ci_block_min_atoms = 16;
4120     int ci_block;
4121
4122     /* Here we decide how to distribute the blocks over the threads.
4123      * We use prime numbers to try to avoid that the grid size becomes
4124      * a multiple of the number of threads, which would lead to some
4125      * threads getting "inner" pairs and others getting boundary pairs,
4126      * which in turns will lead to load imbalance between threads.
4127      * Set the block size as 5/11/ntask times the average number of cells
4128      * in a y,z slab. This should ensure a quite uniform distribution
4129      * of the grid parts of the different thread along all three grid
4130      * zone boundaries with 3D domain decomposition. At the same time
4131      * the blocks will not become too small.
4132      */
4133     ci_block = (gridi->nc*ci_block_enum)/(ci_block_denom*gridi->ncx*nth);
4134
4135     /* Ensure the blocks are not too small: avoids cache invalidation */
4136     if (ci_block*gridi->na_sc < ci_block_min_atoms)
4137     {
4138         ci_block = (ci_block_min_atoms + gridi->na_sc - 1)/gridi->na_sc;
4139     }
4140
4141     /* Without domain decomposition
4142      * or with less than 3 blocks per task, divide in nth blocks.
4143      */
4144     if (!bDomDec || ci_block*3*nth > gridi->nc)
4145     {
4146         ci_block = (gridi->nc + nth - 1)/nth;
4147     }
4148
4149     return ci_block;
4150 }
4151
4152 /* Generates the part of pair-list nbl assigned to our thread */
4153 static void nbnxn_make_pairlist_part(const nbnxn_search_t nbs,
4154                                      const nbnxn_grid_t *gridi,
4155                                      const nbnxn_grid_t *gridj,
4156                                      nbnxn_search_work_t *work,
4157                                      const nbnxn_atomdata_t *nbat,
4158                                      const t_blocka *excl,
4159                                      real rlist,
4160                                      int nb_kernel_type,
4161                                      int ci_block,
4162                                      gmx_bool bFBufferFlag,
4163                                      int nsubpair_max,
4164                                      gmx_bool progBal,
4165                                      int min_ci_balanced,
4166                                      int th, int nth,
4167                                      nbnxn_pairlist_t *nbl)
4168 {
4169     int  na_cj_2log;
4170     matrix box;
4171     real rl2;
4172     float rbb2;
4173     int  d;
4174     int  ci_b, ci, ci_x, ci_y, ci_xy, cj;
4175     ivec shp;
4176     int  tx, ty, tz;
4177     int  shift;
4178     gmx_bool bMakeList;
4179     real shx, shy, shz;
4180     int  conv_i, cell0_i;
4181     const float *bb_i, *bbcz_i, *bbcz_j;
4182     const int *flags_i;
4183     real bx0, bx1, by0, by1, bz0, bz1;
4184     real bz1_frac;
4185     real d2cx, d2z, d2z_cx, d2z_cy, d2zx, d2zxy, d2xy;
4186     int  cxf, cxl, cyf, cyf_x, cyl;
4187     int  cx, cy;
4188     int  c0, c1, cs, cf, cl;
4189     int  ndistc;
4190     int  ncpcheck;
4191     int  gridi_flag_shift = 0, gridj_flag_shift = 0;
4192     unsigned *gridj_flag  = NULL;
4193     int  ncj_old_i, ncj_old_j;
4194
4195     nbs_cycle_start(&work->cc[enbsCCsearch]);
4196
4197     if (gridj->bSimple != nbl->bSimple)
4198     {
4199         gmx_incons("Grid incompatible with pair-list");
4200     }
4201
4202     sync_work(nbl);
4203     nbl->na_sc = gridj->na_sc;
4204     nbl->na_ci = gridj->na_c;
4205     nbl->na_cj = nbnxn_kernel_to_cj_size(nb_kernel_type);
4206     na_cj_2log = get_2log(nbl->na_cj);
4207
4208     nbl->rlist  = rlist;
4209
4210     if (bFBufferFlag)
4211     {
4212         /* Determine conversion of clusters to flag blocks */
4213         gridi_flag_shift = 0;
4214         while ((nbl->na_ci<<gridi_flag_shift) < NBNXN_BUFFERFLAG_SIZE)
4215         {
4216             gridi_flag_shift++;
4217         }
4218         gridj_flag_shift = 0;
4219         while ((nbl->na_cj<<gridj_flag_shift) < NBNXN_BUFFERFLAG_SIZE)
4220         {
4221             gridj_flag_shift++;
4222         }
4223
4224         gridj_flag = work->buffer_flags.flag;
4225     }
4226
4227     copy_mat(nbs->box, box);
4228
4229     rl2 = nbl->rlist*nbl->rlist;
4230
4231     rbb2 = boundingbox_only_distance2(gridi, gridj, nbl->rlist, nbl->bSimple);
4232
4233     if (debug)
4234     {
4235         fprintf(debug, "nbl bounding box only distance %f\n", sqrt(rbb2));
4236     }
4237
4238     /* Set the shift range */
4239     for (d = 0; d < DIM; d++)
4240     {
4241         /* Check if we need periodicity shifts.
4242          * Without PBC or with domain decomposition we don't need them.
4243          */
4244         if (d >= ePBC2npbcdim(nbs->ePBC) || nbs->dd_dim[d])
4245         {
4246             shp[d] = 0;
4247         }
4248         else
4249         {
4250             if (d == XX &&
4251                 box[XX][XX] - fabs(box[YY][XX]) - fabs(box[ZZ][XX]) < sqrt(rl2))
4252             {
4253                 shp[d] = 2;
4254             }
4255             else
4256             {
4257                 shp[d] = 1;
4258             }
4259         }
4260     }
4261
4262     if (nbl->bSimple && !gridi->bSimple)
4263     {
4264         conv_i  = gridi->na_sc/gridj->na_sc;
4265         bb_i    = gridi->bb_simple;
4266         bbcz_i  = gridi->bbcz_simple;
4267         flags_i = gridi->flags_simple;
4268     }
4269     else
4270     {
4271         conv_i  = 1;
4272         bb_i    = gridi->bb;
4273         bbcz_i  = gridi->bbcz;
4274         flags_i = gridi->flags;
4275     }
4276     cell0_i = gridi->cell0*conv_i;
4277
4278     bbcz_j = gridj->bbcz;
4279
4280     if (conv_i != 1)
4281     {
4282         /* Blocks of the conversion factor - 1 give a large repeat count
4283          * combined with a small block size. This should result in good
4284          * load balancing for both small and large domains.
4285          */
4286         ci_block = conv_i - 1;
4287     }
4288     if (debug)
4289     {
4290         fprintf(debug, "nbl nc_i %d col.av. %.1f ci_block %d\n",
4291                 gridi->nc, gridi->nc/(double)(gridi->ncx*gridi->ncy), ci_block);
4292     }
4293
4294     ndistc   = 0;
4295     ncpcheck = 0;
4296
4297     /* Initially ci_b and ci to 1 before where we want them to start,
4298      * as they will both be incremented in next_ci.
4299      */
4300     ci_b = -1;
4301     ci   = th*ci_block - 1;
4302     ci_x = 0;
4303     ci_y = 0;
4304     while (next_ci(gridi, conv_i, nth, ci_block, &ci_x, &ci_y, &ci_b, &ci))
4305     {
4306         if (nbl->bSimple && flags_i[ci] == 0)
4307         {
4308             continue;
4309         }
4310
4311         ncj_old_i = nbl->ncj;
4312
4313         d2cx = 0;
4314         if (gridj != gridi && shp[XX] == 0)
4315         {
4316             if (nbl->bSimple)
4317             {
4318                 bx1 = bb_i[ci*NNBSBB_B+NNBSBB_C+XX];
4319             }
4320             else
4321             {
4322                 bx1 = gridi->c0[XX] + (ci_x+1)*gridi->sx;
4323             }
4324             if (bx1 < gridj->c0[XX])
4325             {
4326                 d2cx = sqr(gridj->c0[XX] - bx1);
4327
4328                 if (d2cx >= rl2)
4329                 {
4330                     continue;
4331                 }
4332             }
4333         }
4334
4335         ci_xy = ci_x*gridi->ncy + ci_y;
4336
4337         /* Loop over shift vectors in three dimensions */
4338         for (tz = -shp[ZZ]; tz <= shp[ZZ]; tz++)
4339         {
4340             shz = tz*box[ZZ][ZZ];
4341
4342             bz0 = bbcz_i[ci*NNBSBB_D  ] + shz;
4343             bz1 = bbcz_i[ci*NNBSBB_D+1] + shz;
4344
4345             if (tz == 0)
4346             {
4347                 d2z = 0;
4348             }
4349             else if (tz < 0)
4350             {
4351                 d2z = sqr(bz1);
4352             }
4353             else
4354             {
4355                 d2z = sqr(bz0 - box[ZZ][ZZ]);
4356             }
4357
4358             d2z_cx = d2z + d2cx;
4359
4360             if (d2z_cx >= rl2)
4361             {
4362                 continue;
4363             }
4364
4365             bz1_frac =
4366                 bz1/((real)(gridi->cxy_ind[ci_xy+1] - gridi->cxy_ind[ci_xy]));
4367             if (bz1_frac < 0)
4368             {
4369                 bz1_frac = 0;
4370             }
4371             /* The check with bz1_frac close to or larger than 1 comes later */
4372
4373             for (ty = -shp[YY]; ty <= shp[YY]; ty++)
4374             {
4375                 shy = ty*box[YY][YY] + tz*box[ZZ][YY];
4376
4377                 if (nbl->bSimple)
4378                 {
4379                     by0 = bb_i[ci*NNBSBB_B         +YY] + shy;
4380                     by1 = bb_i[ci*NNBSBB_B+NNBSBB_C+YY] + shy;
4381                 }
4382                 else
4383                 {
4384                     by0 = gridi->c0[YY] + (ci_y  )*gridi->sy + shy;
4385                     by1 = gridi->c0[YY] + (ci_y+1)*gridi->sy + shy;
4386                 }
4387
4388                 get_cell_range(by0, by1,
4389                                gridj->ncy, gridj->c0[YY], gridj->sy, gridj->inv_sy,
4390                                d2z_cx, rl2,
4391                                &cyf, &cyl);
4392
4393                 if (cyf > cyl)
4394                 {
4395                     continue;
4396                 }
4397
4398                 d2z_cy = d2z;
4399                 if (by1 < gridj->c0[YY])
4400                 {
4401                     d2z_cy += sqr(gridj->c0[YY] - by1);
4402                 }
4403                 else if (by0 > gridj->c1[YY])
4404                 {
4405                     d2z_cy += sqr(by0 - gridj->c1[YY]);
4406                 }
4407
4408                 for (tx = -shp[XX]; tx <= shp[XX]; tx++)
4409                 {
4410                     shift = XYZ2IS(tx, ty, tz);
4411
4412 #ifdef NBNXN_SHIFT_BACKWARD
4413                     if (gridi == gridj && shift > CENTRAL)
4414                     {
4415                         continue;
4416                     }
4417 #endif
4418
4419                     shx = tx*box[XX][XX] + ty*box[YY][XX] + tz*box[ZZ][XX];
4420
4421                     if (nbl->bSimple)
4422                     {
4423                         bx0 = bb_i[ci*NNBSBB_B         +XX] + shx;
4424                         bx1 = bb_i[ci*NNBSBB_B+NNBSBB_C+XX] + shx;
4425                     }
4426                     else
4427                     {
4428                         bx0 = gridi->c0[XX] + (ci_x  )*gridi->sx + shx;
4429                         bx1 = gridi->c0[XX] + (ci_x+1)*gridi->sx + shx;
4430                     }
4431
4432                     get_cell_range(bx0, bx1,
4433                                    gridj->ncx, gridj->c0[XX], gridj->sx, gridj->inv_sx,
4434                                    d2z_cy, rl2,
4435                                    &cxf, &cxl);
4436
4437                     if (cxf > cxl)
4438                     {
4439                         continue;
4440                     }
4441
4442                     if (nbl->bSimple)
4443                     {
4444                         new_ci_entry(nbl, cell0_i+ci, shift, flags_i[ci],
4445                                      nbl->work);
4446                     }
4447                     else
4448                     {
4449                         new_sci_entry(nbl, cell0_i+ci, shift, flags_i[ci],
4450                                       nbl->work);
4451                     }
4452
4453 #ifndef NBNXN_SHIFT_BACKWARD
4454                     if (cxf < ci_x)
4455 #else
4456                     if (shift == CENTRAL && gridi == gridj &&
4457                         cxf < ci_x)
4458 #endif
4459                     {
4460                         /* Leave the pairs with i > j.
4461                          * x is the major index, so skip half of it.
4462                          */
4463                         cxf = ci_x;
4464                     }
4465
4466                     if (nbl->bSimple)
4467                     {
4468                         set_icell_bb_simple(bb_i, ci, shx, shy, shz,
4469                                             nbl->work->bb_ci);
4470                     }
4471                     else
4472                     {
4473                         set_icell_bb_supersub(bb_i, ci, shx, shy, shz,
4474                                               nbl->work->bb_ci);
4475                     }
4476
4477                     nbs->icell_set_x(cell0_i+ci, shx, shy, shz,
4478                                      gridi->na_c, nbat->xstride, nbat->x,
4479                                      nbl->work);
4480
4481                     for (cx = cxf; cx <= cxl; cx++)
4482                     {
4483                         d2zx = d2z;
4484                         if (gridj->c0[XX] + cx*gridj->sx > bx1)
4485                         {
4486                             d2zx += sqr(gridj->c0[XX] + cx*gridj->sx - bx1);
4487                         }
4488                         else if (gridj->c0[XX] + (cx+1)*gridj->sx < bx0)
4489                         {
4490                             d2zx += sqr(gridj->c0[XX] + (cx+1)*gridj->sx - bx0);
4491                         }
4492
4493 #ifndef NBNXN_SHIFT_BACKWARD
4494                         if (gridi == gridj &&
4495                             cx == 0 && cyf < ci_y)
4496 #else
4497                         if (gridi == gridj &&
4498                             cx == 0 && shift == CENTRAL && cyf < ci_y)
4499 #endif
4500                         {
4501                             /* Leave the pairs with i > j.
4502                              * Skip half of y when i and j have the same x.
4503                              */
4504                             cyf_x = ci_y;
4505                         }
4506                         else
4507                         {
4508                             cyf_x = cyf;
4509                         }
4510
4511                         for (cy = cyf_x; cy <= cyl; cy++)
4512                         {
4513                             c0 = gridj->cxy_ind[cx*gridj->ncy+cy];
4514                             c1 = gridj->cxy_ind[cx*gridj->ncy+cy+1];
4515 #ifdef NBNXN_SHIFT_BACKWARD
4516                             if (gridi == gridj &&
4517                                 shift == CENTRAL && c0 < ci)
4518                             {
4519                                 c0 = ci;
4520                             }
4521 #endif
4522
4523                             d2zxy = d2zx;
4524                             if (gridj->c0[YY] + cy*gridj->sy > by1)
4525                             {
4526                                 d2zxy += sqr(gridj->c0[YY] + cy*gridj->sy - by1);
4527                             }
4528                             else if (gridj->c0[YY] + (cy+1)*gridj->sy < by0)
4529                             {
4530                                 d2zxy += sqr(gridj->c0[YY] + (cy+1)*gridj->sy - by0);
4531                             }
4532                             if (c1 > c0 && d2zxy < rl2)
4533                             {
4534                                 cs = c0 + (int)(bz1_frac*(c1 - c0));
4535                                 if (cs >= c1)
4536                                 {
4537                                     cs = c1 - 1;
4538                                 }
4539
4540                                 d2xy = d2zxy - d2z;
4541
4542                                 /* Find the lowest cell that can possibly
4543                                  * be within range.
4544                                  */
4545                                 cf = cs;
4546                                 while (cf > c0 &&
4547                                        (bbcz_j[cf*NNBSBB_D+1] >= bz0 ||
4548                                         d2xy + sqr(bbcz_j[cf*NNBSBB_D+1] - bz0) < rl2))
4549                                 {
4550                                     cf--;
4551                                 }
4552
4553                                 /* Find the highest cell that can possibly
4554                                  * be within range.
4555                                  */
4556                                 cl = cs;
4557                                 while (cl < c1-1 &&
4558                                        (bbcz_j[cl*NNBSBB_D] <= bz1 ||
4559                                         d2xy + sqr(bbcz_j[cl*NNBSBB_D] - bz1) < rl2))
4560                                 {
4561                                     cl++;
4562                                 }
4563
4564 #ifdef NBNXN_REFCODE
4565                                 {
4566                                     /* Simple reference code, for debugging,
4567                                      * overrides the more complex code above.
4568                                      */
4569                                     int k;
4570                                     cf = c1;
4571                                     cl = -1;
4572                                     for (k = c0; k < c1; k++)
4573                                     {
4574                                         if (box_dist2(bx0, bx1, by0, by1, bz0, bz1,
4575                                                       bb+k*NNBSBB_B) < rl2 &&
4576                                             k < cf)
4577                                         {
4578                                             cf = k;
4579                                         }
4580                                         if (box_dist2(bx0, bx1, by0, by1, bz0, bz1,
4581                                                       bb+k*NNBSBB_B) < rl2 &&
4582                                             k > cl)
4583                                         {
4584                                             cl = k;
4585                                         }
4586                                     }
4587                                 }
4588 #endif
4589
4590                                 if (gridi == gridj)
4591                                 {
4592                                     /* We want each atom/cell pair only once,
4593                                      * only use cj >= ci.
4594                                      */
4595 #ifndef NBNXN_SHIFT_BACKWARD
4596                                     cf = max(cf, ci);
4597 #else
4598                                     if (shift == CENTRAL)
4599                                     {
4600                                         cf = max(cf, ci);
4601                                     }
4602 #endif
4603                                 }
4604
4605                                 if (cf <= cl)
4606                                 {
4607                                     /* For f buffer flags with simple lists */
4608                                     ncj_old_j = nbl->ncj;
4609
4610                                     switch (nb_kernel_type)
4611                                     {
4612                                         case nbnxnk4x4_PlainC:
4613                                             check_subcell_list_space_simple(nbl, cl-cf+1);
4614
4615                                             make_cluster_list_simple(gridj,
4616                                                                      nbl, ci, cf, cl,
4617                                                                      (gridi == gridj && shift == CENTRAL),
4618                                                                      nbat->x,
4619                                                                      rl2, rbb2,
4620                                                                      &ndistc);
4621                                             break;
4622 #ifdef GMX_NBNXN_SIMD_4XN
4623                                         case nbnxnk4xN_SIMD_4xN:
4624                                             check_subcell_list_space_simple(nbl, ci_to_cj(na_cj_2log, cl-cf)+2);
4625                                             make_cluster_list_simd_4xn(gridj,
4626                                                                        nbl, ci, cf, cl,
4627                                                                        (gridi == gridj && shift == CENTRAL),
4628                                                                        nbat->x,
4629                                                                        rl2, rbb2,
4630                                                                        &ndistc);
4631                                             break;
4632 #endif
4633 #ifdef GMX_NBNXN_SIMD_2XNN
4634                                         case nbnxnk4xN_SIMD_2xNN:
4635                                             check_subcell_list_space_simple(nbl, ci_to_cj(na_cj_2log, cl-cf)+2);
4636                                             make_cluster_list_simd_2xnn(gridj,
4637                                                                         nbl, ci, cf, cl,
4638                                                                         (gridi == gridj && shift == CENTRAL),
4639                                                                         nbat->x,
4640                                                                         rl2, rbb2,
4641                                                                         &ndistc);
4642                                             break;
4643 #endif
4644                                         case nbnxnk8x8x8_PlainC:
4645                                         case nbnxnk8x8x8_CUDA:
4646                                             check_subcell_list_space_supersub(nbl, cl-cf+1);
4647                                             for (cj = cf; cj <= cl; cj++)
4648                                             {
4649                                                 make_cluster_list_supersub(nbs, gridi, gridj,
4650                                                                            nbl, ci, cj,
4651                                                                            (gridi == gridj && shift == CENTRAL && ci == cj),
4652                                                                            nbat->xstride, nbat->x,
4653                                                                            rl2, rbb2,
4654                                                                            &ndistc);
4655                                             }
4656                                             break;
4657                                     }
4658                                     ncpcheck += cl - cf + 1;
4659
4660                                     if (bFBufferFlag && nbl->ncj > ncj_old_j)
4661                                     {
4662                                         int cbf, cbl, cb;
4663
4664                                         cbf = nbl->cj[ncj_old_j].cj >> gridj_flag_shift;
4665                                         cbl = nbl->cj[nbl->ncj-1].cj >> gridj_flag_shift;
4666                                         for (cb = cbf; cb <= cbl; cb++)
4667                                         {
4668                                             gridj_flag[cb] = 1U<<th;
4669                                         }
4670                                     }
4671                                 }
4672                             }
4673                         }
4674                     }
4675
4676                     /* Set the exclusions for this ci list */
4677                     if (nbl->bSimple)
4678                     {
4679                         set_ci_top_excls(nbs,
4680                                          nbl,
4681                                          shift == CENTRAL && gridi == gridj,
4682                                          gridj->na_c_2log,
4683                                          na_cj_2log,
4684                                          &(nbl->ci[nbl->nci]),
4685                                          excl);
4686                     }
4687                     else
4688                     {
4689                         set_sci_top_excls(nbs,
4690                                           nbl,
4691                                           shift == CENTRAL && gridi == gridj,
4692                                           gridj->na_c_2log,
4693                                           &(nbl->sci[nbl->nsci]),
4694                                           excl);
4695                     }
4696
4697                     /* Close this ci list */
4698                     if (nbl->bSimple)
4699                     {
4700                         close_ci_entry_simple(nbl);
4701                     }
4702                     else
4703                     {
4704                         close_ci_entry_supersub(nbl,
4705                                                 nsubpair_max,
4706                                                 progBal, min_ci_balanced,
4707                                                 th, nth);
4708                     }
4709                 }
4710             }
4711         }
4712
4713         if (bFBufferFlag && nbl->ncj > ncj_old_i)
4714         {
4715             work->buffer_flags.flag[(gridi->cell0+ci)>>gridi_flag_shift] = 1U<<th;
4716         }
4717     }
4718
4719     work->ndistc = ndistc;
4720
4721     nbs_cycle_stop(&work->cc[enbsCCsearch]);
4722
4723     if (debug)
4724     {
4725         fprintf(debug, "number of distance checks %d\n", ndistc);
4726         fprintf(debug, "ncpcheck %s %d\n", gridi == gridj ? "local" : "non-local",
4727                 ncpcheck);
4728
4729         if (nbl->bSimple)
4730         {
4731             print_nblist_statistics_simple(debug, nbl, nbs, rlist);
4732         }
4733         else
4734         {
4735             print_nblist_statistics_supersub(debug, nbl, nbs, rlist);
4736         }
4737
4738     }
4739 }
4740
4741 static void reduce_buffer_flags(const nbnxn_search_t        nbs,
4742                                 int                         nsrc,
4743                                 const nbnxn_buffer_flags_t *dest)
4744 {
4745     int s, b;
4746     const unsigned *flag;
4747
4748     for (s = 0; s < nsrc; s++)
4749     {
4750         flag = nbs->work[s].buffer_flags.flag;
4751
4752         for (b = 0; b < dest->nflag; b++)
4753         {
4754             dest->flag[b] |= flag[b];
4755         }
4756     }
4757 }
4758
4759 static void print_reduction_cost(const nbnxn_buffer_flags_t *flags, int nout)
4760 {
4761     int nelem, nkeep, ncopy, nred, b, c, out;
4762
4763     nelem = 0;
4764     nkeep = 0;
4765     ncopy = 0;
4766     nred  = 0;
4767     for (b = 0; b < flags->nflag; b++)
4768     {
4769         if (flags->flag[b] == 1)
4770         {
4771             /* Only flag 0 is set, no copy of reduction required */
4772             nelem++;
4773             nkeep++;
4774         }
4775         else if (flags->flag[b] > 0)
4776         {
4777             c = 0;
4778             for (out = 0; out < nout; out++)
4779             {
4780                 if (flags->flag[b] & (1U<<out))
4781                 {
4782                     c++;
4783                 }
4784             }
4785             nelem += c;
4786             if (c == 1)
4787             {
4788                 ncopy++;
4789             }
4790             else
4791             {
4792                 nred += c;
4793             }
4794         }
4795     }
4796
4797     fprintf(debug, "nbnxn reduction: #flag %d #list %d elem %4.2f, keep %4.2f copy %4.2f red %4.2f\n",
4798             flags->nflag, nout,
4799             nelem/(double)(flags->nflag),
4800             nkeep/(double)(flags->nflag),
4801             ncopy/(double)(flags->nflag),
4802             nred/(double)(flags->nflag));
4803 }
4804
4805 /* Perform a count (linear) sort to sort the smaller lists to the end.
4806  * This avoids load imbalance on the GPU, as large lists will be
4807  * scheduled and executed first and the smaller lists later.
4808  * Load balancing between multi-processors only happens at the end
4809  * and there smaller lists lead to more effective load balancing.
4810  * The sorting is done on the cj4 count, not on the actual pair counts.
4811  * Not only does this make the sort faster, but it also results in
4812  * better load balancing than using a list sorted on exact load.
4813  * This function swaps the pointer in the pair list to avoid a copy operation.
4814  */
4815 static void sort_sci(nbnxn_pairlist_t *nbl)
4816 {
4817     nbnxn_list_work_t *work;
4818     int                m, i, s, s0, s1;
4819     nbnxn_sci_t       *sci_sort;
4820
4821     if (nbl->ncj4 <= nbl->nsci)
4822     {
4823         /* nsci = 0 or all sci have size 1, sorting won't change the order */
4824         return;
4825     }
4826
4827     work = nbl->work;
4828
4829     /* We will distinguish differences up to double the average */
4830     m = (2*nbl->ncj4)/nbl->nsci;
4831
4832     if (m + 1 > work->sort_nalloc)
4833     {
4834         work->sort_nalloc = over_alloc_large(m + 1);
4835         srenew(work->sort, work->sort_nalloc);
4836     }
4837
4838     if (work->sci_sort_nalloc != nbl->sci_nalloc)
4839     {
4840         work->sci_sort_nalloc = nbl->sci_nalloc;
4841         nbnxn_realloc_void((void **)&work->sci_sort,
4842                            0,
4843                            work->sci_sort_nalloc*sizeof(*work->sci_sort),
4844                            nbl->alloc, nbl->free);
4845     }
4846
4847     /* Count the entries of each size */
4848     for (i = 0; i <= m; i++)
4849     {
4850         work->sort[i] = 0;
4851     }
4852     for (s = 0; s < nbl->nsci; s++)
4853     {
4854         i = min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
4855         work->sort[i]++;
4856     }
4857     /* Calculate the offset for each count */
4858     s0            = work->sort[m];
4859     work->sort[m] = 0;
4860     for (i = m - 1; i >= 0; i--)
4861     {
4862         s1            = work->sort[i];
4863         work->sort[i] = work->sort[i + 1] + s0;
4864         s0            = s1;
4865     }
4866
4867     /* Sort entries directly into place */
4868     sci_sort = work->sci_sort;
4869     for (s = 0; s < nbl->nsci; s++)
4870     {
4871         i = min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
4872         sci_sort[work->sort[i]++] = nbl->sci[s];
4873     }
4874
4875     /* Swap the sci pointers so we use the new, sorted list */
4876     work->sci_sort = nbl->sci;
4877     nbl->sci       = sci_sort;
4878 }
4879
4880 /* Make a local or non-local pair-list, depending on iloc */
4881 void nbnxn_make_pairlist(const nbnxn_search_t  nbs,
4882                          nbnxn_atomdata_t     *nbat,
4883                          const t_blocka       *excl,
4884                          real                  rlist,
4885                          int                   min_ci_balanced,
4886                          nbnxn_pairlist_set_t *nbl_list,
4887                          int                   iloc,
4888                          int                   nb_kernel_type,
4889                          t_nrnb               *nrnb)
4890 {
4891     nbnxn_grid_t *gridi, *gridj;
4892     gmx_bool bGPUCPU;
4893     int nzi, zi, zj0, zj1, zj;
4894     int nsubpair_max;
4895     int th;
4896     int nnbl;
4897     nbnxn_pairlist_t **nbl;
4898     int ci_block;
4899     gmx_bool CombineNBLists;
4900     gmx_bool progBal;
4901     int np_tot, np_noq, np_hlj, nap;
4902
4903     /* Check if we are running hybrid GPU + CPU nbnxn mode */
4904     bGPUCPU = (!nbs->grid[0].bSimple && nbl_list->bSimple);
4905
4906     nnbl            = nbl_list->nnbl;
4907     nbl             = nbl_list->nbl;
4908     CombineNBLists  = nbl_list->bCombined;
4909
4910     if (debug)
4911     {
4912         fprintf(debug, "ns making %d nblists\n", nnbl);
4913     }
4914
4915     nbat->bUseBufferFlags = (nbat->nout > 1);
4916     /* We should re-init the flags before making the first list */
4917     if (nbat->bUseBufferFlags && (LOCAL_I(iloc) || bGPUCPU))
4918     {
4919         init_buffer_flags(&nbat->buffer_flags, nbat->natoms);
4920     }
4921
4922     if (nbl_list->bSimple)
4923     {
4924         switch (nb_kernel_type)
4925         {
4926 #ifdef GMX_NBNXN_SIMD_4XN
4927             case nbnxnk4xN_SIMD_4xN:
4928                 nbs->icell_set_x = icell_set_x_simd_4xn;
4929                 break;
4930 #endif
4931 #ifdef GMX_NBNXN_SIMD_2XNN
4932             case nbnxnk4xN_SIMD_2xNN:
4933                 nbs->icell_set_x = icell_set_x_simd_2xnn;
4934                 break;
4935 #endif
4936             default:
4937                 nbs->icell_set_x = icell_set_x_simple;
4938                 break;
4939         }
4940     }
4941     else
4942     {
4943 #ifdef NBNXN_SEARCH_BB_SSE
4944         nbs->icell_set_x = icell_set_x_supersub_sse8;
4945 #else
4946         nbs->icell_set_x = icell_set_x_supersub;
4947 #endif
4948     }
4949
4950     if (LOCAL_I(iloc))
4951     {
4952         /* Only zone (grid) 0 vs 0 */
4953         nzi = 1;
4954         zj0 = 0;
4955         zj1 = 1;
4956     }
4957     else
4958     {
4959         nzi = nbs->zones->nizone;
4960     }
4961
4962     if (!nbl_list->bSimple && min_ci_balanced > 0)
4963     {
4964         nsubpair_max = get_nsubpair_max(nbs, iloc, rlist, min_ci_balanced);
4965     }
4966     else
4967     {
4968         nsubpair_max = 0;
4969     }
4970
4971     /* Clear all pair-lists */
4972     for (th = 0; th < nnbl; th++)
4973     {
4974         clear_pairlist(nbl[th]);
4975     }
4976
4977     for (zi = 0; zi < nzi; zi++)
4978     {
4979         gridi = &nbs->grid[zi];
4980
4981         if (NONLOCAL_I(iloc))
4982         {
4983             zj0 = nbs->zones->izone[zi].j0;
4984             zj1 = nbs->zones->izone[zi].j1;
4985             if (zi == 0)
4986             {
4987                 zj0++;
4988             }
4989         }
4990         for (zj = zj0; zj < zj1; zj++)
4991         {
4992             gridj = &nbs->grid[zj];
4993
4994             if (debug)
4995             {
4996                 fprintf(debug, "ns search grid %d vs %d\n", zi, zj);
4997             }
4998
4999             nbs_cycle_start(&nbs->cc[enbsCCsearch]);
5000
5001             if (nbl[0]->bSimple && !gridi->bSimple)
5002             {
5003                 /* Hybrid list, determine blocking later */
5004                 ci_block = 0;
5005             }
5006             else
5007             {
5008                 ci_block = get_ci_block_size(gridi, nbs->DomDec, nnbl);
5009             }
5010
5011 #pragma omp parallel for num_threads(nnbl) schedule(static)
5012             for (th = 0; th < nnbl; th++)
5013             {
5014                 /* Re-init the thread-local work flag data before making
5015                  * the first list (not an elegant conditional).
5016                  */
5017                 if (nbat->bUseBufferFlags && ((zi == 0 && zj == 0) ||
5018                                               (bGPUCPU && zi == 0 && zj == 1)))
5019                 {
5020                     init_buffer_flags(&nbs->work[th].buffer_flags, nbat->natoms);
5021                 }
5022
5023                 if (CombineNBLists && th > 0)
5024                 {
5025                     clear_pairlist(nbl[th]);
5026                 }
5027
5028                 /* With GPU: generate progressively smaller lists for
5029                  * load balancing for local only or non-local with 2 zones.
5030                  */
5031                 progBal = (LOCAL_I(iloc) || nbs->zones->n <= 2);
5032
5033                 /* Divide the i super cell equally over the nblists */
5034                 nbnxn_make_pairlist_part(nbs, gridi, gridj,
5035                                          &nbs->work[th], nbat, excl,
5036                                          rlist,
5037                                          nb_kernel_type,
5038                                          ci_block,
5039                                          nbat->bUseBufferFlags,
5040                                          nsubpair_max,
5041                                          progBal, min_ci_balanced,
5042                                          th, nnbl,
5043                                          nbl[th]);
5044             }
5045             nbs_cycle_stop(&nbs->cc[enbsCCsearch]);
5046
5047             np_tot = 0;
5048             np_noq = 0;
5049             np_hlj = 0;
5050             for (th = 0; th < nnbl; th++)
5051             {
5052                 inc_nrnb(nrnb, eNR_NBNXN_DIST2, nbs->work[th].ndistc);
5053
5054                 if (nbl_list->bSimple)
5055                 {
5056                     np_tot += nbl[th]->ncj;
5057                     np_noq += nbl[th]->work->ncj_noq;
5058                     np_hlj += nbl[th]->work->ncj_hlj;
5059                 }
5060                 else
5061                 {
5062                     /* This count ignores potential subsequent pair pruning */
5063                     np_tot += nbl[th]->nci_tot;
5064                 }
5065             }
5066             nap                   = nbl[0]->na_ci*nbl[0]->na_cj;
5067             nbl_list->natpair_ljq = (np_tot - np_noq)*nap - np_hlj*nap/2;
5068             nbl_list->natpair_lj  = np_noq*nap;
5069             nbl_list->natpair_q   = np_hlj*nap/2;
5070
5071             if (CombineNBLists && nnbl > 1)
5072             {
5073                 nbs_cycle_start(&nbs->cc[enbsCCcombine]);
5074
5075                 combine_nblists(nnbl-1, nbl+1, nbl[0]);
5076
5077                 nbs_cycle_stop(&nbs->cc[enbsCCcombine]);
5078             }
5079         }
5080     }
5081
5082     if (!nbl_list->bSimple)
5083     {
5084         /* Sort the entries on size, large ones first */
5085         if (CombineNBLists || nnbl == 1)
5086         {
5087             sort_sci(nbl[0]);
5088         }
5089         else
5090         {
5091 #pragma omp parallel for num_threads(nnbl) schedule(static)
5092             for (th = 0; th < nnbl; th++)
5093             {
5094                 sort_sci(nbl[th]);
5095             }
5096         }
5097     }
5098
5099     if (nbat->bUseBufferFlags)
5100     {
5101         reduce_buffer_flags(nbs, nnbl, &nbat->buffer_flags);
5102     }
5103
5104     /* Special performance logging stuff (env.var. GMX_NBNXN_CYCLE) */
5105     if (LOCAL_I(iloc))
5106     {
5107         nbs->search_count++;
5108     }
5109     if (nbs->print_cycles &&
5110         (!nbs->DomDec || (nbs->DomDec && !LOCAL_I(iloc))) &&
5111         nbs->search_count % 100 == 0)
5112     {
5113         nbs_cycle_print(stderr, nbs);
5114     }
5115
5116     if (debug && (CombineNBLists && nnbl > 1))
5117     {
5118         if (nbl[0]->bSimple)
5119         {
5120             print_nblist_statistics_simple(debug, nbl[0], nbs, rlist);
5121         }
5122         else
5123         {
5124             print_nblist_statistics_supersub(debug, nbl[0], nbs, rlist);
5125         }
5126     }
5127
5128     if (debug)
5129     {
5130         if (gmx_debug_at)
5131         {
5132             if (nbl[0]->bSimple)
5133             {
5134                 print_nblist_ci_cj(debug, nbl[0]);
5135             }
5136             else
5137             {
5138                 print_nblist_sci_cj(debug, nbl[0]);
5139             }
5140         }
5141
5142         if (nbat->bUseBufferFlags)
5143         {
5144             print_reduction_cost(&nbat->buffer_flags, nnbl);
5145         }
5146     }
5147 }