]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/block/drbd/drbd_nl.c
drbd: Remove obsolete drbd_crypto_is_hash()
[karo-tx-linux.git] / drivers / block / drbd / drbd_nl.c
1 /*
2    drbd_nl.c
3
4    This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
5
6    Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
7    Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
8    Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
9
10    drbd is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2, or (at your option)
13    any later version.
14
15    drbd is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with drbd; see the file COPYING.  If not, write to
22    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24  */
25
26 #include <linux/module.h>
27 #include <linux/drbd.h>
28 #include <linux/in.h>
29 #include <linux/fs.h>
30 #include <linux/file.h>
31 #include <linux/slab.h>
32 #include <linux/blkpg.h>
33 #include <linux/cpumask.h>
34 #include "drbd_int.h"
35 #include "drbd_req.h"
36 #include "drbd_wrappers.h"
37 #include <asm/unaligned.h>
38 #include <linux/drbd_limits.h>
39 #include <linux/kthread.h>
40
41 #include <net/genetlink.h>
42
43 /* .doit */
44 // int drbd_adm_create_resource(struct sk_buff *skb, struct genl_info *info);
45 // int drbd_adm_delete_resource(struct sk_buff *skb, struct genl_info *info);
46
47 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info);
48 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info);
49
50 int drbd_adm_create_connection(struct sk_buff *skb, struct genl_info *info);
51 int drbd_adm_delete_connection(struct sk_buff *skb, struct genl_info *info);
52 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info);
53
54 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info);
55 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info);
56 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info);
57 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info);
58 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info);
59 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info);
60 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info);
61 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info);
62 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info);
63 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info);
64 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info);
65 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info);
66 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info);
67 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info);
68 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info);
69 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info);
70 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info);
71 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info);
72 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info);
73 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info);
74 /* .dumpit */
75 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb);
76
77 #include <linux/drbd_genl_api.h>
78 #include <linux/genl_magic_func.h>
79
80 /* used blkdev_get_by_path, to claim our meta data device(s) */
81 static char *drbd_m_holder = "Hands off! this is DRBD's meta data device.";
82
83 /* Configuration is strictly serialized, because generic netlink message
84  * processing is strictly serialized by the genl_lock().
85  * Which means we can use one static global drbd_config_context struct.
86  */
87 static struct drbd_config_context {
88         /* assigned from drbd_genlmsghdr */
89         unsigned int minor;
90         /* assigned from request attributes, if present */
91         unsigned int volume;
92 #define VOLUME_UNSPECIFIED              (-1U)
93         /* pointer into the request skb,
94          * limited lifetime! */
95         char *conn_name;
96
97         /* reply buffer */
98         struct sk_buff *reply_skb;
99         /* pointer into reply buffer */
100         struct drbd_genlmsghdr *reply_dh;
101         /* resolved from attributes, if possible */
102         struct drbd_conf *mdev;
103         struct drbd_tconn *tconn;
104 } adm_ctx;
105
106 static void drbd_adm_send_reply(struct sk_buff *skb, struct genl_info *info)
107 {
108         genlmsg_end(skb, genlmsg_data(nlmsg_data(nlmsg_hdr(skb))));
109         if (genlmsg_reply(skb, info))
110                 printk(KERN_ERR "drbd: error sending genl reply\n");
111 }
112
113 /* Used on a fresh "drbd_adm_prepare"d reply_skb, this cannot fail: The only
114  * reason it could fail was no space in skb, and there are 4k available. */
115 int drbd_msg_put_info(const char *info)
116 {
117         struct sk_buff *skb = adm_ctx.reply_skb;
118         struct nlattr *nla;
119         int err = -EMSGSIZE;
120
121         if (!info || !info[0])
122                 return 0;
123
124         nla = nla_nest_start(skb, DRBD_NLA_CFG_REPLY);
125         if (!nla)
126                 return err;
127
128         err = nla_put_string(skb, T_info_text, info);
129         if (err) {
130                 nla_nest_cancel(skb, nla);
131                 return err;
132         } else
133                 nla_nest_end(skb, nla);
134         return 0;
135 }
136
137 /* This would be a good candidate for a "pre_doit" hook,
138  * and per-family private info->pointers.
139  * But we need to stay compatible with older kernels.
140  * If it returns successfully, adm_ctx members are valid.
141  */
142 #define DRBD_ADM_NEED_MINOR     1
143 #define DRBD_ADM_NEED_CONN      2
144 static int drbd_adm_prepare(struct sk_buff *skb, struct genl_info *info,
145                 unsigned flags)
146 {
147         struct drbd_genlmsghdr *d_in = info->userhdr;
148         const u8 cmd = info->genlhdr->cmd;
149         int err;
150
151         memset(&adm_ctx, 0, sizeof(adm_ctx));
152
153         /* genl_rcv_msg only checks for CAP_NET_ADMIN on "GENL_ADMIN_PERM" :( */
154         if (cmd != DRBD_ADM_GET_STATUS
155         && security_netlink_recv(skb, CAP_SYS_ADMIN))
156                return -EPERM;
157
158         adm_ctx.reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
159         if (!adm_ctx.reply_skb)
160                 goto fail;
161
162         adm_ctx.reply_dh = genlmsg_put_reply(adm_ctx.reply_skb,
163                                         info, &drbd_genl_family, 0, cmd);
164         /* put of a few bytes into a fresh skb of >= 4k will always succeed.
165          * but anyways */
166         if (!adm_ctx.reply_dh)
167                 goto fail;
168
169         adm_ctx.reply_dh->minor = d_in->minor;
170         adm_ctx.reply_dh->ret_code = NO_ERROR;
171
172         if (info->attrs[DRBD_NLA_CFG_CONTEXT]) {
173                 struct nlattr *nla;
174                 /* parse and validate only */
175                 err = drbd_cfg_context_from_attrs(NULL, info);
176                 if (err)
177                         goto fail;
178
179                 /* It was present, and valid,
180                  * copy it over to the reply skb. */
181                 err = nla_put_nohdr(adm_ctx.reply_skb,
182                                 info->attrs[DRBD_NLA_CFG_CONTEXT]->nla_len,
183                                 info->attrs[DRBD_NLA_CFG_CONTEXT]);
184                 if (err)
185                         goto fail;
186
187                 /* and assign stuff to the global adm_ctx */
188                 nla = nested_attr_tb[__nla_type(T_ctx_volume)];
189                 adm_ctx.volume = nla ? nla_get_u32(nla) : VOLUME_UNSPECIFIED;
190                 nla = nested_attr_tb[__nla_type(T_ctx_conn_name)];
191                 if (nla)
192                         adm_ctx.conn_name = nla_data(nla);
193         } else
194                 adm_ctx.volume = VOLUME_UNSPECIFIED;
195
196         adm_ctx.minor = d_in->minor;
197         adm_ctx.mdev = minor_to_mdev(d_in->minor);
198         adm_ctx.tconn = conn_get_by_name(adm_ctx.conn_name);
199
200         if (!adm_ctx.mdev && (flags & DRBD_ADM_NEED_MINOR)) {
201                 drbd_msg_put_info("unknown minor");
202                 return ERR_MINOR_INVALID;
203         }
204         if (!adm_ctx.tconn && (flags & DRBD_ADM_NEED_CONN)) {
205                 drbd_msg_put_info("unknown connection");
206                 return ERR_INVALID_REQUEST;
207         }
208
209         /* some more paranoia, if the request was over-determined */
210         if (adm_ctx.mdev && adm_ctx.tconn &&
211             adm_ctx.mdev->tconn != adm_ctx.tconn) {
212                 pr_warning("request: minor=%u, conn=%s; but that minor belongs to connection %s\n",
213                                 adm_ctx.minor, adm_ctx.conn_name, adm_ctx.mdev->tconn->name);
214                 drbd_msg_put_info("minor exists in different connection");
215                 return ERR_INVALID_REQUEST;
216         }
217         if (adm_ctx.mdev &&
218             adm_ctx.volume != VOLUME_UNSPECIFIED &&
219             adm_ctx.volume != adm_ctx.mdev->vnr) {
220                 pr_warning("request: minor=%u, volume=%u; but that minor is volume %u in %s\n",
221                                 adm_ctx.minor, adm_ctx.volume,
222                                 adm_ctx.mdev->vnr, adm_ctx.mdev->tconn->name);
223                 drbd_msg_put_info("minor exists as different volume");
224                 return ERR_INVALID_REQUEST;
225         }
226
227         return NO_ERROR;
228
229 fail:
230         nlmsg_free(adm_ctx.reply_skb);
231         adm_ctx.reply_skb = NULL;
232         return -ENOMEM;
233 }
234
235 static int drbd_adm_finish(struct genl_info *info, int retcode)
236 {
237         struct nlattr *nla;
238         const char *conn_name = NULL;
239
240         if (adm_ctx.tconn) {
241                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
242                 adm_ctx.tconn = NULL;
243         }
244
245         if (!adm_ctx.reply_skb)
246                 return -ENOMEM;
247
248         adm_ctx.reply_dh->ret_code = retcode;
249
250         nla = info->attrs[DRBD_NLA_CFG_CONTEXT];
251         if (nla) {
252                 nla = nla_find_nested(nla, __nla_type(T_ctx_conn_name));
253                 if (nla)
254                         conn_name = nla_data(nla);
255         }
256
257         drbd_adm_send_reply(adm_ctx.reply_skb, info);
258         return 0;
259 }
260
261 static void setup_khelper_env(struct drbd_tconn *tconn, char **envp)
262 {
263         char *afs;
264         struct net_conf *nc;
265
266         rcu_read_lock();
267         nc = rcu_dereference(tconn->net_conf);
268         if (nc) {
269                 switch (((struct sockaddr *)nc->peer_addr)->sa_family) {
270                 case AF_INET6:
271                         afs = "ipv6";
272                         snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI6",
273                                  &((struct sockaddr_in6 *)nc->peer_addr)->sin6_addr);
274                         break;
275                 case AF_INET:
276                         afs = "ipv4";
277                         snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
278                                  &((struct sockaddr_in *)nc->peer_addr)->sin_addr);
279                         break;
280                 default:
281                         afs = "ssocks";
282                         snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
283                                  &((struct sockaddr_in *)nc->peer_addr)->sin_addr);
284                 }
285                 snprintf(envp[3], 20, "DRBD_PEER_AF=%s", afs);
286         }
287         rcu_read_unlock();
288 }
289
290 int drbd_khelper(struct drbd_conf *mdev, char *cmd)
291 {
292         char *envp[] = { "HOME=/",
293                         "TERM=linux",
294                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
295                          (char[20]) { }, /* address family */
296                          (char[60]) { }, /* address */
297                         NULL };
298         char mb[12];
299         char *argv[] = {usermode_helper, cmd, mb, NULL };
300         struct sib_info sib;
301         int ret;
302
303         snprintf(mb, 12, "minor-%d", mdev_to_minor(mdev));
304         setup_khelper_env(mdev->tconn, envp);
305
306         /* The helper may take some time.
307          * write out any unsynced meta data changes now */
308         drbd_md_sync(mdev);
309
310         dev_info(DEV, "helper command: %s %s %s\n", usermode_helper, cmd, mb);
311         sib.sib_reason = SIB_HELPER_PRE;
312         sib.helper_name = cmd;
313         drbd_bcast_event(mdev, &sib);
314         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
315         if (ret)
316                 dev_warn(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
317                                 usermode_helper, cmd, mb,
318                                 (ret >> 8) & 0xff, ret);
319         else
320                 dev_info(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
321                                 usermode_helper, cmd, mb,
322                                 (ret >> 8) & 0xff, ret);
323         sib.sib_reason = SIB_HELPER_POST;
324         sib.helper_exit_code = ret;
325         drbd_bcast_event(mdev, &sib);
326
327         if (ret < 0) /* Ignore any ERRNOs we got. */
328                 ret = 0;
329
330         return ret;
331 }
332
333 static void conn_md_sync(struct drbd_tconn *tconn)
334 {
335         struct drbd_conf *mdev;
336         int vnr;
337
338         down_read(&drbd_cfg_rwsem);
339         idr_for_each_entry(&tconn->volumes, mdev, vnr)
340                 drbd_md_sync(mdev);
341         up_read(&drbd_cfg_rwsem);
342 }
343
344 int conn_khelper(struct drbd_tconn *tconn, char *cmd)
345 {
346         char *envp[] = { "HOME=/",
347                         "TERM=linux",
348                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
349                          (char[20]) { }, /* address family */
350                          (char[60]) { }, /* address */
351                         NULL };
352         char *argv[] = {usermode_helper, cmd, tconn->name, NULL };
353         int ret;
354
355         setup_khelper_env(tconn, envp);
356         conn_md_sync(tconn);
357
358         conn_info(tconn, "helper command: %s %s %s\n", usermode_helper, cmd, tconn->name);
359         /* TODO: conn_bcast_event() ?? */
360
361         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
362         if (ret)
363                 conn_warn(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
364                           usermode_helper, cmd, tconn->name,
365                           (ret >> 8) & 0xff, ret);
366         else
367                 conn_info(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
368                           usermode_helper, cmd, tconn->name,
369                           (ret >> 8) & 0xff, ret);
370         /* TODO: conn_bcast_event() ?? */
371
372         if (ret < 0) /* Ignore any ERRNOs we got. */
373                 ret = 0;
374
375         return ret;
376 }
377
378 static enum drbd_fencing_p highest_fencing_policy(struct drbd_tconn *tconn)
379 {
380         enum drbd_fencing_p fp = FP_NOT_AVAIL;
381         struct drbd_conf *mdev;
382         int vnr;
383
384         rcu_read_lock();
385         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
386                 if (get_ldev_if_state(mdev, D_CONSISTENT)) {
387                         fp = max_t(enum drbd_fencing_p, fp, mdev->ldev->dc.fencing);
388                         put_ldev(mdev);
389                 }
390         }
391         rcu_read_unlock();
392
393         return fp;
394 }
395
396 bool conn_try_outdate_peer(struct drbd_tconn *tconn)
397 {
398         union drbd_state mask = { };
399         union drbd_state val = { };
400         enum drbd_fencing_p fp;
401         char *ex_to_string;
402         int r;
403
404         if (tconn->cstate >= C_WF_REPORT_PARAMS) {
405                 conn_err(tconn, "Expected cstate < C_WF_REPORT_PARAMS\n");
406                 return false;
407         }
408
409         fp = highest_fencing_policy(tconn);
410         switch (fp) {
411         case FP_NOT_AVAIL:
412                 conn_warn(tconn, "Not fencing peer, I'm not even Consistent myself.\n");
413                 goto out;
414         case FP_DONT_CARE:
415                 return true;
416         default: ;
417         }
418
419         r = conn_khelper(tconn, "fence-peer");
420
421         switch ((r>>8) & 0xff) {
422         case 3: /* peer is inconsistent */
423                 ex_to_string = "peer is inconsistent or worse";
424                 mask.pdsk = D_MASK;
425                 val.pdsk = D_INCONSISTENT;
426                 break;
427         case 4: /* peer got outdated, or was already outdated */
428                 ex_to_string = "peer was fenced";
429                 mask.pdsk = D_MASK;
430                 val.pdsk = D_OUTDATED;
431                 break;
432         case 5: /* peer was down */
433                 if (conn_highest_disk(tconn) == D_UP_TO_DATE) {
434                         /* we will(have) create(d) a new UUID anyways... */
435                         ex_to_string = "peer is unreachable, assumed to be dead";
436                         mask.pdsk = D_MASK;
437                         val.pdsk = D_OUTDATED;
438                 } else {
439                         ex_to_string = "peer unreachable, doing nothing since disk != UpToDate";
440                 }
441                 break;
442         case 6: /* Peer is primary, voluntarily outdate myself.
443                  * This is useful when an unconnected R_SECONDARY is asked to
444                  * become R_PRIMARY, but finds the other peer being active. */
445                 ex_to_string = "peer is active";
446                 conn_warn(tconn, "Peer is primary, outdating myself.\n");
447                 mask.disk = D_MASK;
448                 val.disk = D_OUTDATED;
449                 break;
450         case 7:
451                 if (fp != FP_STONITH)
452                         conn_err(tconn, "fence-peer() = 7 && fencing != Stonith !!!\n");
453                 ex_to_string = "peer was stonithed";
454                 mask.pdsk = D_MASK;
455                 val.pdsk = D_OUTDATED;
456                 break;
457         default:
458                 /* The script is broken ... */
459                 conn_err(tconn, "fence-peer helper broken, returned %d\n", (r>>8)&0xff);
460                 return false; /* Eventually leave IO frozen */
461         }
462
463         conn_info(tconn, "fence-peer helper returned %d (%s)\n",
464                   (r>>8) & 0xff, ex_to_string);
465
466  out:
467
468         /* Not using
469            conn_request_state(tconn, mask, val, CS_VERBOSE);
470            here, because we might were able to re-establish the connection in the
471            meantime. */
472         spin_lock_irq(&tconn->req_lock);
473         if (tconn->cstate < C_WF_REPORT_PARAMS)
474                 _conn_request_state(tconn, mask, val, CS_VERBOSE);
475         spin_unlock_irq(&tconn->req_lock);
476
477         return conn_highest_pdsk(tconn) <= D_OUTDATED;
478 }
479
480 static int _try_outdate_peer_async(void *data)
481 {
482         struct drbd_tconn *tconn = (struct drbd_tconn *)data;
483
484         conn_try_outdate_peer(tconn);
485
486         kref_put(&tconn->kref, &conn_destroy);
487         return 0;
488 }
489
490 void conn_try_outdate_peer_async(struct drbd_tconn *tconn)
491 {
492         struct task_struct *opa;
493
494         kref_get(&tconn->kref);
495         opa = kthread_run(_try_outdate_peer_async, tconn, "drbd_async_h");
496         if (IS_ERR(opa)) {
497                 conn_err(tconn, "out of mem, failed to invoke fence-peer helper\n");
498                 kref_put(&tconn->kref, &conn_destroy);
499         }
500 }
501
502 enum drbd_state_rv
503 drbd_set_role(struct drbd_conf *mdev, enum drbd_role new_role, int force)
504 {
505         const int max_tries = 4;
506         enum drbd_state_rv rv = SS_UNKNOWN_ERROR;
507         struct net_conf *nc;
508         int try = 0;
509         int forced = 0;
510         union drbd_state mask, val;
511
512         if (new_role == R_PRIMARY)
513                 request_ping(mdev->tconn); /* Detect a dead peer ASAP */
514
515         mutex_lock(mdev->state_mutex);
516
517         mask.i = 0; mask.role = R_MASK;
518         val.i  = 0; val.role  = new_role;
519
520         while (try++ < max_tries) {
521                 rv = _drbd_request_state(mdev, mask, val, CS_WAIT_COMPLETE);
522
523                 /* in case we first succeeded to outdate,
524                  * but now suddenly could establish a connection */
525                 if (rv == SS_CW_FAILED_BY_PEER && mask.pdsk != 0) {
526                         val.pdsk = 0;
527                         mask.pdsk = 0;
528                         continue;
529                 }
530
531                 if (rv == SS_NO_UP_TO_DATE_DISK && force &&
532                     (mdev->state.disk < D_UP_TO_DATE &&
533                      mdev->state.disk >= D_INCONSISTENT)) {
534                         mask.disk = D_MASK;
535                         val.disk  = D_UP_TO_DATE;
536                         forced = 1;
537                         continue;
538                 }
539
540                 if (rv == SS_NO_UP_TO_DATE_DISK &&
541                     mdev->state.disk == D_CONSISTENT && mask.pdsk == 0) {
542                         D_ASSERT(mdev->state.pdsk == D_UNKNOWN);
543
544                         if (conn_try_outdate_peer(mdev->tconn)) {
545                                 val.disk = D_UP_TO_DATE;
546                                 mask.disk = D_MASK;
547                         }
548                         continue;
549                 }
550
551                 if (rv == SS_NOTHING_TO_DO)
552                         goto out;
553                 if (rv == SS_PRIMARY_NOP && mask.pdsk == 0) {
554                         if (!conn_try_outdate_peer(mdev->tconn) && force) {
555                                 dev_warn(DEV, "Forced into split brain situation!\n");
556                                 mask.pdsk = D_MASK;
557                                 val.pdsk  = D_OUTDATED;
558
559                         }
560                         continue;
561                 }
562                 if (rv == SS_TWO_PRIMARIES) {
563                         /* Maybe the peer is detected as dead very soon...
564                            retry at most once more in this case. */
565                         int timeo;
566                         rcu_read_lock();
567                         nc = rcu_dereference(mdev->tconn->net_conf);
568                         timeo = nc ? (nc->ping_timeo + 1) * HZ / 10 : 1;
569                         rcu_read_unlock();
570                         schedule_timeout_interruptible(timeo);
571                         if (try < max_tries)
572                                 try = max_tries - 1;
573                         continue;
574                 }
575                 if (rv < SS_SUCCESS) {
576                         rv = _drbd_request_state(mdev, mask, val,
577                                                 CS_VERBOSE + CS_WAIT_COMPLETE);
578                         if (rv < SS_SUCCESS)
579                                 goto out;
580                 }
581                 break;
582         }
583
584         if (rv < SS_SUCCESS)
585                 goto out;
586
587         if (forced)
588                 dev_warn(DEV, "Forced to consider local data as UpToDate!\n");
589
590         /* Wait until nothing is on the fly :) */
591         wait_event(mdev->misc_wait, atomic_read(&mdev->ap_pending_cnt) == 0);
592
593         if (new_role == R_SECONDARY) {
594                 set_disk_ro(mdev->vdisk, true);
595                 if (get_ldev(mdev)) {
596                         mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
597                         put_ldev(mdev);
598                 }
599         } else {
600                 mutex_lock(&mdev->tconn->net_conf_update);
601                 nc = mdev->tconn->net_conf;
602                 if (nc)
603                         nc->want_lose = 0; /* without copy; single bit op is atomic */
604                 mutex_unlock(&mdev->tconn->net_conf_update);
605
606                 set_disk_ro(mdev->vdisk, false);
607                 if (get_ldev(mdev)) {
608                         if (((mdev->state.conn < C_CONNECTED ||
609                                mdev->state.pdsk <= D_FAILED)
610                               && mdev->ldev->md.uuid[UI_BITMAP] == 0) || forced)
611                                 drbd_uuid_new_current(mdev);
612
613                         mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
614                         put_ldev(mdev);
615                 }
616         }
617
618         /* writeout of activity log covered areas of the bitmap
619          * to stable storage done in after state change already */
620
621         if (mdev->state.conn >= C_WF_REPORT_PARAMS) {
622                 /* if this was forced, we should consider sync */
623                 if (forced)
624                         drbd_send_uuids(mdev);
625                 drbd_send_state(mdev);
626         }
627
628         drbd_md_sync(mdev);
629
630         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
631 out:
632         mutex_unlock(mdev->state_mutex);
633         return rv;
634 }
635
636 static const char *from_attrs_err_to_txt(int err)
637 {
638         return  err == -ENOMSG ? "required attribute missing" :
639                 err == -EOPNOTSUPP ? "unknown mandatory attribute" :
640                 err == -EEXIST ? "can not change invariant setting" :
641                 "invalid attribute value";
642 }
643
644 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info)
645 {
646         struct set_role_parms parms;
647         int err;
648         enum drbd_ret_code retcode;
649
650         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
651         if (!adm_ctx.reply_skb)
652                 return retcode;
653         if (retcode != NO_ERROR)
654                 goto out;
655
656         memset(&parms, 0, sizeof(parms));
657         if (info->attrs[DRBD_NLA_SET_ROLE_PARMS]) {
658                 err = set_role_parms_from_attrs(&parms, info);
659                 if (err) {
660                         retcode = ERR_MANDATORY_TAG;
661                         drbd_msg_put_info(from_attrs_err_to_txt(err));
662                         goto out;
663                 }
664         }
665
666         if (info->genlhdr->cmd == DRBD_ADM_PRIMARY)
667                 retcode = drbd_set_role(adm_ctx.mdev, R_PRIMARY, parms.assume_uptodate);
668         else
669                 retcode = drbd_set_role(adm_ctx.mdev, R_SECONDARY, 0);
670 out:
671         drbd_adm_finish(info, retcode);
672         return 0;
673 }
674
675 /* initializes the md.*_offset members, so we are able to find
676  * the on disk meta data */
677 static void drbd_md_set_sector_offsets(struct drbd_conf *mdev,
678                                        struct drbd_backing_dev *bdev)
679 {
680         sector_t md_size_sect = 0;
681         switch (bdev->dc.meta_dev_idx) {
682         default:
683                 /* v07 style fixed size indexed meta data */
684                 bdev->md.md_size_sect = MD_RESERVED_SECT;
685                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
686                 bdev->md.al_offset = MD_AL_OFFSET;
687                 bdev->md.bm_offset = MD_BM_OFFSET;
688                 break;
689         case DRBD_MD_INDEX_FLEX_EXT:
690                 /* just occupy the full device; unit: sectors */
691                 bdev->md.md_size_sect = drbd_get_capacity(bdev->md_bdev);
692                 bdev->md.md_offset = 0;
693                 bdev->md.al_offset = MD_AL_OFFSET;
694                 bdev->md.bm_offset = MD_BM_OFFSET;
695                 break;
696         case DRBD_MD_INDEX_INTERNAL:
697         case DRBD_MD_INDEX_FLEX_INT:
698                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
699                 /* al size is still fixed */
700                 bdev->md.al_offset = -MD_AL_SECTORS;
701                 /* we need (slightly less than) ~ this much bitmap sectors: */
702                 md_size_sect = drbd_get_capacity(bdev->backing_bdev);
703                 md_size_sect = ALIGN(md_size_sect, BM_SECT_PER_EXT);
704                 md_size_sect = BM_SECT_TO_EXT(md_size_sect);
705                 md_size_sect = ALIGN(md_size_sect, 8);
706
707                 /* plus the "drbd meta data super block",
708                  * and the activity log; */
709                 md_size_sect += MD_BM_OFFSET;
710
711                 bdev->md.md_size_sect = md_size_sect;
712                 /* bitmap offset is adjusted by 'super' block size */
713                 bdev->md.bm_offset   = -md_size_sect + MD_AL_OFFSET;
714                 break;
715         }
716 }
717
718 /* input size is expected to be in KB */
719 char *ppsize(char *buf, unsigned long long size)
720 {
721         /* Needs 9 bytes at max including trailing NUL:
722          * -1ULL ==> "16384 EB" */
723         static char units[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
724         int base = 0;
725         while (size >= 10000 && base < sizeof(units)-1) {
726                 /* shift + round */
727                 size = (size >> 10) + !!(size & (1<<9));
728                 base++;
729         }
730         sprintf(buf, "%u %cB", (unsigned)size, units[base]);
731
732         return buf;
733 }
734
735 /* there is still a theoretical deadlock when called from receiver
736  * on an D_INCONSISTENT R_PRIMARY:
737  *  remote READ does inc_ap_bio, receiver would need to receive answer
738  *  packet from remote to dec_ap_bio again.
739  *  receiver receive_sizes(), comes here,
740  *  waits for ap_bio_cnt == 0. -> deadlock.
741  * but this cannot happen, actually, because:
742  *  R_PRIMARY D_INCONSISTENT, and peer's disk is unreachable
743  *  (not connected, or bad/no disk on peer):
744  *  see drbd_fail_request_early, ap_bio_cnt is zero.
745  *  R_PRIMARY D_INCONSISTENT, and C_SYNC_TARGET:
746  *  peer may not initiate a resize.
747  */
748 /* Note these are not to be confused with
749  * drbd_adm_suspend_io/drbd_adm_resume_io,
750  * which are (sub) state changes triggered by admin (drbdsetup),
751  * and can be long lived.
752  * This changes an mdev->flag, is triggered by drbd internals,
753  * and should be short-lived. */
754 void drbd_suspend_io(struct drbd_conf *mdev)
755 {
756         set_bit(SUSPEND_IO, &mdev->flags);
757         if (drbd_suspended(mdev))
758                 return;
759         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_bio_cnt));
760 }
761
762 void drbd_resume_io(struct drbd_conf *mdev)
763 {
764         clear_bit(SUSPEND_IO, &mdev->flags);
765         wake_up(&mdev->misc_wait);
766 }
767
768 /**
769  * drbd_determine_dev_size() -  Sets the right device size obeying all constraints
770  * @mdev:       DRBD device.
771  *
772  * Returns 0 on success, negative return values indicate errors.
773  * You should call drbd_md_sync() after calling this function.
774  */
775 enum determine_dev_size drbd_determine_dev_size(struct drbd_conf *mdev, enum dds_flags flags) __must_hold(local)
776 {
777         sector_t prev_first_sect, prev_size; /* previous meta location */
778         sector_t la_size;
779         sector_t size;
780         char ppb[10];
781
782         int md_moved, la_size_changed;
783         enum determine_dev_size rv = unchanged;
784
785         /* race:
786          * application request passes inc_ap_bio,
787          * but then cannot get an AL-reference.
788          * this function later may wait on ap_bio_cnt == 0. -> deadlock.
789          *
790          * to avoid that:
791          * Suspend IO right here.
792          * still lock the act_log to not trigger ASSERTs there.
793          */
794         drbd_suspend_io(mdev);
795
796         /* no wait necessary anymore, actually we could assert that */
797         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
798
799         prev_first_sect = drbd_md_first_sector(mdev->ldev);
800         prev_size = mdev->ldev->md.md_size_sect;
801         la_size = mdev->ldev->md.la_size_sect;
802
803         /* TODO: should only be some assert here, not (re)init... */
804         drbd_md_set_sector_offsets(mdev, mdev->ldev);
805
806         size = drbd_new_dev_size(mdev, mdev->ldev, flags & DDSF_FORCED);
807
808         if (drbd_get_capacity(mdev->this_bdev) != size ||
809             drbd_bm_capacity(mdev) != size) {
810                 int err;
811                 err = drbd_bm_resize(mdev, size, !(flags & DDSF_NO_RESYNC));
812                 if (unlikely(err)) {
813                         /* currently there is only one error: ENOMEM! */
814                         size = drbd_bm_capacity(mdev)>>1;
815                         if (size == 0) {
816                                 dev_err(DEV, "OUT OF MEMORY! "
817                                     "Could not allocate bitmap!\n");
818                         } else {
819                                 dev_err(DEV, "BM resizing failed. "
820                                     "Leaving size unchanged at size = %lu KB\n",
821                                     (unsigned long)size);
822                         }
823                         rv = dev_size_error;
824                 }
825                 /* racy, see comments above. */
826                 drbd_set_my_capacity(mdev, size);
827                 mdev->ldev->md.la_size_sect = size;
828                 dev_info(DEV, "size = %s (%llu KB)\n", ppsize(ppb, size>>1),
829                      (unsigned long long)size>>1);
830         }
831         if (rv == dev_size_error)
832                 goto out;
833
834         la_size_changed = (la_size != mdev->ldev->md.la_size_sect);
835
836         md_moved = prev_first_sect != drbd_md_first_sector(mdev->ldev)
837                 || prev_size       != mdev->ldev->md.md_size_sect;
838
839         if (la_size_changed || md_moved) {
840                 int err;
841
842                 drbd_al_shrink(mdev); /* All extents inactive. */
843                 dev_info(DEV, "Writing the whole bitmap, %s\n",
844                          la_size_changed && md_moved ? "size changed and md moved" :
845                          la_size_changed ? "size changed" : "md moved");
846                 /* next line implicitly does drbd_suspend_io()+drbd_resume_io() */
847                 err = drbd_bitmap_io(mdev, &drbd_bm_write,
848                                 "size changed", BM_LOCKED_MASK);
849                 if (err) {
850                         rv = dev_size_error;
851                         goto out;
852                 }
853                 drbd_md_mark_dirty(mdev);
854         }
855
856         if (size > la_size)
857                 rv = grew;
858         if (size < la_size)
859                 rv = shrunk;
860 out:
861         lc_unlock(mdev->act_log);
862         wake_up(&mdev->al_wait);
863         drbd_resume_io(mdev);
864
865         return rv;
866 }
867
868 sector_t
869 drbd_new_dev_size(struct drbd_conf *mdev, struct drbd_backing_dev *bdev, int assume_peer_has_space)
870 {
871         sector_t p_size = mdev->p_size;   /* partner's disk size. */
872         sector_t la_size = bdev->md.la_size_sect; /* last agreed size. */
873         sector_t m_size; /* my size */
874         sector_t u_size = bdev->dc.disk_size; /* size requested by user. */
875         sector_t size = 0;
876
877         m_size = drbd_get_max_capacity(bdev);
878
879         if (mdev->state.conn < C_CONNECTED && assume_peer_has_space) {
880                 dev_warn(DEV, "Resize while not connected was forced by the user!\n");
881                 p_size = m_size;
882         }
883
884         if (p_size && m_size) {
885                 size = min_t(sector_t, p_size, m_size);
886         } else {
887                 if (la_size) {
888                         size = la_size;
889                         if (m_size && m_size < size)
890                                 size = m_size;
891                         if (p_size && p_size < size)
892                                 size = p_size;
893                 } else {
894                         if (m_size)
895                                 size = m_size;
896                         if (p_size)
897                                 size = p_size;
898                 }
899         }
900
901         if (size == 0)
902                 dev_err(DEV, "Both nodes diskless!\n");
903
904         if (u_size) {
905                 if (u_size > size)
906                         dev_err(DEV, "Requested disk size is too big (%lu > %lu)\n",
907                             (unsigned long)u_size>>1, (unsigned long)size>>1);
908                 else
909                         size = u_size;
910         }
911
912         return size;
913 }
914
915 /**
916  * drbd_check_al_size() - Ensures that the AL is of the right size
917  * @mdev:       DRBD device.
918  *
919  * Returns -EBUSY if current al lru is still used, -ENOMEM when allocation
920  * failed, and 0 on success. You should call drbd_md_sync() after you called
921  * this function.
922  */
923 static int drbd_check_al_size(struct drbd_conf *mdev, struct disk_conf *dc)
924 {
925         struct lru_cache *n, *t;
926         struct lc_element *e;
927         unsigned int in_use;
928         int i;
929
930         if (!expect(dc->al_extents >= DRBD_AL_EXTENTS_MIN))
931                 dc->al_extents = DRBD_AL_EXTENTS_MIN;
932
933         if (mdev->act_log &&
934             mdev->act_log->nr_elements == dc->al_extents)
935                 return 0;
936
937         in_use = 0;
938         t = mdev->act_log;
939         n = lc_create("act_log", drbd_al_ext_cache, AL_UPDATES_PER_TRANSACTION,
940                 dc->al_extents, sizeof(struct lc_element), 0);
941
942         if (n == NULL) {
943                 dev_err(DEV, "Cannot allocate act_log lru!\n");
944                 return -ENOMEM;
945         }
946         spin_lock_irq(&mdev->al_lock);
947         if (t) {
948                 for (i = 0; i < t->nr_elements; i++) {
949                         e = lc_element_by_index(t, i);
950                         if (e->refcnt)
951                                 dev_err(DEV, "refcnt(%d)==%d\n",
952                                     e->lc_number, e->refcnt);
953                         in_use += e->refcnt;
954                 }
955         }
956         if (!in_use)
957                 mdev->act_log = n;
958         spin_unlock_irq(&mdev->al_lock);
959         if (in_use) {
960                 dev_err(DEV, "Activity log still in use!\n");
961                 lc_destroy(n);
962                 return -EBUSY;
963         } else {
964                 if (t)
965                         lc_destroy(t);
966         }
967         drbd_md_mark_dirty(mdev); /* we changed mdev->act_log->nr_elemens */
968         return 0;
969 }
970
971 static void drbd_setup_queue_param(struct drbd_conf *mdev, unsigned int max_bio_size)
972 {
973         struct request_queue * const q = mdev->rq_queue;
974         int max_hw_sectors = max_bio_size >> 9;
975         int max_segments = 0;
976
977         if (get_ldev_if_state(mdev, D_ATTACHING)) {
978                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
979
980                 max_hw_sectors = min(queue_max_hw_sectors(b), max_bio_size >> 9);
981                 max_segments = mdev->ldev->dc.max_bio_bvecs;
982                 put_ldev(mdev);
983         }
984
985         blk_queue_logical_block_size(q, 512);
986         blk_queue_max_hw_sectors(q, max_hw_sectors);
987         /* This is the workaround for "bio would need to, but cannot, be split" */
988         blk_queue_max_segments(q, max_segments ? max_segments : BLK_MAX_SEGMENTS);
989         blk_queue_segment_boundary(q, PAGE_CACHE_SIZE-1);
990
991         if (get_ldev_if_state(mdev, D_ATTACHING)) {
992                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
993
994                 blk_queue_stack_limits(q, b);
995
996                 if (q->backing_dev_info.ra_pages != b->backing_dev_info.ra_pages) {
997                         dev_info(DEV, "Adjusting my ra_pages to backing device's (%lu -> %lu)\n",
998                                  q->backing_dev_info.ra_pages,
999                                  b->backing_dev_info.ra_pages);
1000                         q->backing_dev_info.ra_pages = b->backing_dev_info.ra_pages;
1001                 }
1002                 put_ldev(mdev);
1003         }
1004 }
1005
1006 void drbd_reconsider_max_bio_size(struct drbd_conf *mdev)
1007 {
1008         int now, new, local, peer;
1009
1010         now = queue_max_hw_sectors(mdev->rq_queue) << 9;
1011         local = mdev->local_max_bio_size; /* Eventually last known value, from volatile memory */
1012         peer = mdev->peer_max_bio_size; /* Eventually last known value, from meta data */
1013
1014         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1015                 local = queue_max_hw_sectors(mdev->ldev->backing_bdev->bd_disk->queue) << 9;
1016                 mdev->local_max_bio_size = local;
1017                 put_ldev(mdev);
1018         }
1019
1020         /* We may ignore peer limits if the peer is modern enough.
1021            Because new from 8.3.8 onwards the peer can use multiple
1022            BIOs for a single peer_request */
1023         if (mdev->state.conn >= C_CONNECTED) {
1024                 if (mdev->tconn->agreed_pro_version < 94)
1025                         peer = mdev->peer_max_bio_size;
1026                 else if (mdev->tconn->agreed_pro_version == 94)
1027                         peer = DRBD_MAX_SIZE_H80_PACKET;
1028                 else /* drbd 8.3.8 onwards */
1029                         peer = DRBD_MAX_BIO_SIZE;
1030         }
1031
1032         new = min_t(int, local, peer);
1033
1034         if (mdev->state.role == R_PRIMARY && new < now)
1035                 dev_err(DEV, "ASSERT FAILED new < now; (%d < %d)\n", new, now);
1036
1037         if (new != now)
1038                 dev_info(DEV, "max BIO size = %u\n", new);
1039
1040         drbd_setup_queue_param(mdev, new);
1041 }
1042
1043 /* Starts the worker thread */
1044 static void conn_reconfig_start(struct drbd_tconn *tconn)
1045 {
1046         drbd_thread_start(&tconn->worker);
1047         conn_flush_workqueue(tconn);
1048 }
1049
1050 /* if still unconfigured, stops worker again. */
1051 static void conn_reconfig_done(struct drbd_tconn *tconn)
1052 {
1053         spin_lock_irq(&tconn->req_lock);
1054         if (conn_all_vols_unconf(tconn))
1055                 drbd_thread_stop_nowait(&tconn->worker);
1056         spin_unlock_irq(&tconn->req_lock);
1057 }
1058
1059 /* Make sure IO is suspended before calling this function(). */
1060 static void drbd_suspend_al(struct drbd_conf *mdev)
1061 {
1062         int s = 0;
1063
1064         if (!lc_try_lock(mdev->act_log)) {
1065                 dev_warn(DEV, "Failed to lock al in drbd_suspend_al()\n");
1066                 return;
1067         }
1068
1069         drbd_al_shrink(mdev);
1070         spin_lock_irq(&mdev->tconn->req_lock);
1071         if (mdev->state.conn < C_CONNECTED)
1072                 s = !test_and_set_bit(AL_SUSPENDED, &mdev->flags);
1073         spin_unlock_irq(&mdev->tconn->req_lock);
1074         lc_unlock(mdev->act_log);
1075
1076         if (s)
1077                 dev_info(DEV, "Suspended AL updates\n");
1078 }
1079
1080
1081 static bool should_set_defaults(struct genl_info *info)
1082 {
1083         unsigned flags = ((struct drbd_genlmsghdr*)info->userhdr)->flags;
1084         return 0 != (flags & DRBD_GENL_F_SET_DEFAULTS);
1085 }
1086
1087 /* Maybe we should we generate these functions
1088  * from the drbd_genl.h magic as well?
1089  * That way we would not "accidentally forget" to add defaults here. */
1090
1091 #define RESET_ARRAY_FIELD(field) do { \
1092         memset(field, 0, sizeof(field)); \
1093         field ## _len = 0; \
1094 } while (0)
1095 void drbd_set_res_opts_default(struct res_opts *r)
1096 {
1097         RESET_ARRAY_FIELD(r->cpu_mask);
1098         r->on_no_data  = DRBD_ON_NO_DATA_DEF;
1099 }
1100
1101 static void drbd_set_net_conf_defaults(struct net_conf *nc)
1102 {
1103         /* Do NOT (re)set those fields marked as GENLA_F_INVARIANT
1104          * in drbd_genl.h, they can only be change with disconnect/reconnect */
1105         RESET_ARRAY_FIELD(nc->shared_secret);
1106
1107         RESET_ARRAY_FIELD(nc->cram_hmac_alg);
1108         RESET_ARRAY_FIELD(nc->integrity_alg);
1109         RESET_ARRAY_FIELD(nc->verify_alg);
1110         RESET_ARRAY_FIELD(nc->csums_alg);
1111 #undef RESET_ARRAY_FIELD
1112
1113         nc->wire_protocol = DRBD_PROTOCOL_DEF;
1114         nc->try_connect_int = DRBD_CONNECT_INT_DEF;
1115         nc->timeout = DRBD_TIMEOUT_DEF;
1116         nc->ping_int = DRBD_PING_INT_DEF;
1117         nc->ping_timeo = DRBD_PING_TIMEO_DEF;
1118         nc->sndbuf_size = DRBD_SNDBUF_SIZE_DEF;
1119         nc->rcvbuf_size = DRBD_RCVBUF_SIZE_DEF;
1120         nc->ko_count = DRBD_KO_COUNT_DEF;
1121         nc->max_buffers = DRBD_MAX_BUFFERS_DEF;
1122         nc->max_epoch_size = DRBD_MAX_EPOCH_SIZE_DEF;
1123         nc->unplug_watermark = DRBD_UNPLUG_WATERMARK_DEF;
1124         nc->after_sb_0p = DRBD_AFTER_SB_0P_DEF;
1125         nc->after_sb_1p = DRBD_AFTER_SB_1P_DEF;
1126         nc->after_sb_2p = DRBD_AFTER_SB_2P_DEF;
1127         nc->rr_conflict = DRBD_RR_CONFLICT_DEF;
1128         nc->on_congestion = DRBD_ON_CONGESTION_DEF;
1129         nc->cong_fill = DRBD_CONG_FILL_DEF;
1130         nc->cong_extents = DRBD_CONG_EXTENTS_DEF;
1131         nc->two_primaries = 0;
1132         nc->no_cork = 0;
1133         nc->always_asbp = 0;
1134         nc->use_rle = 0;
1135 }
1136
1137 static void drbd_set_disk_conf_defaults(struct disk_conf *dc)
1138 {
1139         /* Do NOT (re)set those fields marked as GENLA_F_INVARIANT
1140          * in drbd_genl.h, they can only be change with detach/reattach */
1141         dc->on_io_error = DRBD_ON_IO_ERROR_DEF;
1142         dc->fencing = DRBD_FENCING_DEF;
1143         dc->resync_rate = DRBD_RATE_DEF;
1144         dc->resync_after = DRBD_AFTER_DEF;
1145         dc->al_extents = DRBD_AL_EXTENTS_DEF;
1146         dc->c_plan_ahead = DRBD_C_PLAN_AHEAD_DEF;
1147         dc->c_delay_target = DRBD_C_DELAY_TARGET_DEF;
1148         dc->c_fill_target = DRBD_C_FILL_TARGET_DEF;
1149         dc->c_max_rate = DRBD_C_MAX_RATE_DEF;
1150         dc->c_min_rate = DRBD_C_MIN_RATE_DEF;
1151         dc->no_disk_barrier = 0;
1152         dc->no_disk_flush = 0;
1153         dc->no_disk_drain = 0;
1154         dc->no_md_flush = 0;
1155 }
1156
1157
1158 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info)
1159 {
1160         enum drbd_ret_code retcode;
1161         struct drbd_conf *mdev;
1162         struct disk_conf *new_disk_conf;
1163         int err, fifo_size;
1164         int *rs_plan_s = NULL;
1165
1166         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1167         if (!adm_ctx.reply_skb)
1168                 return retcode;
1169         if (retcode != NO_ERROR)
1170                 goto out;
1171
1172         mdev = adm_ctx.mdev;
1173
1174         /* we also need a disk
1175          * to change the options on */
1176         if (!get_ldev(mdev)) {
1177                 retcode = ERR_NO_DISK;
1178                 goto out;
1179         }
1180
1181 /* FIXME freeze IO, cluster wide.
1182  *
1183  * We should make sure no-one uses
1184  * some half-updated struct when we
1185  * assign it later. */
1186
1187         new_disk_conf = kmalloc(sizeof(*new_disk_conf), GFP_KERNEL);
1188         if (!new_disk_conf) {
1189                 retcode = ERR_NOMEM;
1190                 goto fail;
1191         }
1192
1193         memcpy(new_disk_conf, &mdev->ldev->dc, sizeof(*new_disk_conf));
1194         if (should_set_defaults(info))
1195                 drbd_set_disk_conf_defaults(new_disk_conf);
1196
1197         err = disk_conf_from_attrs_for_change(new_disk_conf, info);
1198         if (err) {
1199                 retcode = ERR_MANDATORY_TAG;
1200                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1201         }
1202
1203         if (!expect(new_disk_conf->resync_rate >= 1))
1204                 new_disk_conf->resync_rate = 1;
1205
1206         /* clip to allowed range */
1207         if (!expect(new_disk_conf->al_extents >= DRBD_AL_EXTENTS_MIN))
1208                 new_disk_conf->al_extents = DRBD_AL_EXTENTS_MIN;
1209         if (!expect(new_disk_conf->al_extents <= DRBD_AL_EXTENTS_MAX))
1210                 new_disk_conf->al_extents = DRBD_AL_EXTENTS_MAX;
1211
1212         /* most sanity checks done, try to assign the new sync-after
1213          * dependency.  need to hold the global lock in there,
1214          * to avoid a race in the dependency loop check. */
1215         retcode = drbd_alter_sa(mdev, new_disk_conf->resync_after);
1216         if (retcode != NO_ERROR)
1217                 goto fail;
1218
1219         fifo_size = (new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ;
1220         if (fifo_size != mdev->rs_plan_s.size && fifo_size > 0) {
1221                 rs_plan_s   = kzalloc(sizeof(int) * fifo_size, GFP_KERNEL);
1222                 if (!rs_plan_s) {
1223                         dev_err(DEV, "kmalloc of fifo_buffer failed");
1224                         retcode = ERR_NOMEM;
1225                         goto fail;
1226                 }
1227         }
1228
1229         if (fifo_size != mdev->rs_plan_s.size) {
1230                 kfree(mdev->rs_plan_s.values);
1231                 mdev->rs_plan_s.values = rs_plan_s;
1232                 mdev->rs_plan_s.size   = fifo_size;
1233                 mdev->rs_planed = 0;
1234                 rs_plan_s = NULL;
1235         }
1236
1237         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
1238         drbd_al_shrink(mdev);
1239         err = drbd_check_al_size(mdev, new_disk_conf);
1240         lc_unlock(mdev->act_log);
1241         wake_up(&mdev->al_wait);
1242
1243         if (err) {
1244                 retcode = ERR_NOMEM;
1245                 goto fail;
1246         }
1247
1248         /* FIXME
1249          * To avoid someone looking at a half-updated struct, we probably
1250          * should have a rw-semaphor on net_conf and disk_conf.
1251          */
1252         mdev->ldev->dc = *new_disk_conf;
1253
1254         drbd_md_sync(mdev);
1255
1256
1257         if (mdev->state.conn >= C_CONNECTED)
1258                 drbd_send_sync_param(mdev);
1259
1260  fail:
1261         put_ldev(mdev);
1262         kfree(new_disk_conf);
1263         kfree(rs_plan_s);
1264  out:
1265         drbd_adm_finish(info, retcode);
1266         return 0;
1267 }
1268
1269 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info)
1270 {
1271         struct drbd_conf *mdev;
1272         int err;
1273         enum drbd_ret_code retcode;
1274         enum determine_dev_size dd;
1275         sector_t max_possible_sectors;
1276         sector_t min_md_device_sectors;
1277         struct drbd_backing_dev *nbc = NULL; /* new_backing_conf */
1278         struct block_device *bdev;
1279         struct lru_cache *resync_lru = NULL;
1280         union drbd_state ns, os;
1281         enum drbd_state_rv rv;
1282         struct net_conf *nc;
1283         int cp_discovered = 0;
1284
1285         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1286         if (!adm_ctx.reply_skb)
1287                 return retcode;
1288         if (retcode != NO_ERROR)
1289                 goto finish;
1290
1291         mdev = adm_ctx.mdev;
1292         conn_reconfig_start(mdev->tconn);
1293
1294         /* if you want to reconfigure, please tear down first */
1295         if (mdev->state.disk > D_DISKLESS) {
1296                 retcode = ERR_DISK_CONFIGURED;
1297                 goto fail;
1298         }
1299         /* It may just now have detached because of IO error.  Make sure
1300          * drbd_ldev_destroy is done already, we may end up here very fast,
1301          * e.g. if someone calls attach from the on-io-error handler,
1302          * to realize a "hot spare" feature (not that I'd recommend that) */
1303         wait_event(mdev->misc_wait, !atomic_read(&mdev->local_cnt));
1304
1305         /* allocation not in the IO path, drbdsetup context */
1306         nbc = kzalloc(sizeof(struct drbd_backing_dev), GFP_KERNEL);
1307         if (!nbc) {
1308                 retcode = ERR_NOMEM;
1309                 goto fail;
1310         }
1311
1312         drbd_set_disk_conf_defaults(&nbc->dc);
1313
1314         err = disk_conf_from_attrs(&nbc->dc, info);
1315         if (err) {
1316                 retcode = ERR_MANDATORY_TAG;
1317                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1318                 goto fail;
1319         }
1320
1321         if ((int)nbc->dc.meta_dev_idx < DRBD_MD_INDEX_FLEX_INT) {
1322                 retcode = ERR_MD_IDX_INVALID;
1323                 goto fail;
1324         }
1325
1326         rcu_read_lock();
1327         nc = rcu_dereference(mdev->tconn->net_conf);
1328         if (nc) {
1329                 if (nbc->dc.fencing == FP_STONITH && nc->wire_protocol == DRBD_PROT_A) {
1330                         rcu_read_unlock();
1331                         retcode = ERR_STONITH_AND_PROT_A;
1332                         goto fail;
1333                 }
1334         }
1335         rcu_read_unlock();
1336
1337         bdev = blkdev_get_by_path(nbc->dc.backing_dev,
1338                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL, mdev);
1339         if (IS_ERR(bdev)) {
1340                 dev_err(DEV, "open(\"%s\") failed with %ld\n", nbc->dc.backing_dev,
1341                         PTR_ERR(bdev));
1342                 retcode = ERR_OPEN_DISK;
1343                 goto fail;
1344         }
1345         nbc->backing_bdev = bdev;
1346
1347         /*
1348          * meta_dev_idx >= 0: external fixed size, possibly multiple
1349          * drbd sharing one meta device.  TODO in that case, paranoia
1350          * check that [md_bdev, meta_dev_idx] is not yet used by some
1351          * other drbd minor!  (if you use drbd.conf + drbdadm, that
1352          * should check it for you already; but if you don't, or
1353          * someone fooled it, we need to double check here)
1354          */
1355         bdev = blkdev_get_by_path(nbc->dc.meta_dev,
1356                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL,
1357                                   ((int)nbc->dc.meta_dev_idx < 0) ?
1358                                   (void *)mdev : (void *)drbd_m_holder);
1359         if (IS_ERR(bdev)) {
1360                 dev_err(DEV, "open(\"%s\") failed with %ld\n", nbc->dc.meta_dev,
1361                         PTR_ERR(bdev));
1362                 retcode = ERR_OPEN_MD_DISK;
1363                 goto fail;
1364         }
1365         nbc->md_bdev = bdev;
1366
1367         if ((nbc->backing_bdev == nbc->md_bdev) !=
1368             (nbc->dc.meta_dev_idx == DRBD_MD_INDEX_INTERNAL ||
1369              nbc->dc.meta_dev_idx == DRBD_MD_INDEX_FLEX_INT)) {
1370                 retcode = ERR_MD_IDX_INVALID;
1371                 goto fail;
1372         }
1373
1374         resync_lru = lc_create("resync", drbd_bm_ext_cache,
1375                         1, 61, sizeof(struct bm_extent),
1376                         offsetof(struct bm_extent, lce));
1377         if (!resync_lru) {
1378                 retcode = ERR_NOMEM;
1379                 goto fail;
1380         }
1381
1382         /* RT - for drbd_get_max_capacity() DRBD_MD_INDEX_FLEX_INT */
1383         drbd_md_set_sector_offsets(mdev, nbc);
1384
1385         if (drbd_get_max_capacity(nbc) < nbc->dc.disk_size) {
1386                 dev_err(DEV, "max capacity %llu smaller than disk size %llu\n",
1387                         (unsigned long long) drbd_get_max_capacity(nbc),
1388                         (unsigned long long) nbc->dc.disk_size);
1389                 retcode = ERR_DISK_TO_SMALL;
1390                 goto fail;
1391         }
1392
1393         if ((int)nbc->dc.meta_dev_idx < 0) {
1394                 max_possible_sectors = DRBD_MAX_SECTORS_FLEX;
1395                 /* at least one MB, otherwise it does not make sense */
1396                 min_md_device_sectors = (2<<10);
1397         } else {
1398                 max_possible_sectors = DRBD_MAX_SECTORS;
1399                 min_md_device_sectors = MD_RESERVED_SECT * (nbc->dc.meta_dev_idx + 1);
1400         }
1401
1402         if (drbd_get_capacity(nbc->md_bdev) < min_md_device_sectors) {
1403                 retcode = ERR_MD_DISK_TO_SMALL;
1404                 dev_warn(DEV, "refusing attach: md-device too small, "
1405                      "at least %llu sectors needed for this meta-disk type\n",
1406                      (unsigned long long) min_md_device_sectors);
1407                 goto fail;
1408         }
1409
1410         /* Make sure the new disk is big enough
1411          * (we may currently be R_PRIMARY with no local disk...) */
1412         if (drbd_get_max_capacity(nbc) <
1413             drbd_get_capacity(mdev->this_bdev)) {
1414                 retcode = ERR_DISK_TO_SMALL;
1415                 goto fail;
1416         }
1417
1418         nbc->known_size = drbd_get_capacity(nbc->backing_bdev);
1419
1420         if (nbc->known_size > max_possible_sectors) {
1421                 dev_warn(DEV, "==> truncating very big lower level device "
1422                         "to currently maximum possible %llu sectors <==\n",
1423                         (unsigned long long) max_possible_sectors);
1424                 if ((int)nbc->dc.meta_dev_idx >= 0)
1425                         dev_warn(DEV, "==>> using internal or flexible "
1426                                       "meta data may help <<==\n");
1427         }
1428
1429         drbd_suspend_io(mdev);
1430         /* also wait for the last barrier ack. */
1431         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_pending_cnt) || drbd_suspended(mdev));
1432         /* and for any other previously queued work */
1433         drbd_flush_workqueue(mdev);
1434
1435         rv = _drbd_request_state(mdev, NS(disk, D_ATTACHING), CS_VERBOSE);
1436         retcode = rv;  /* FIXME: Type mismatch. */
1437         drbd_resume_io(mdev);
1438         if (rv < SS_SUCCESS)
1439                 goto fail;
1440
1441         if (!get_ldev_if_state(mdev, D_ATTACHING))
1442                 goto force_diskless;
1443
1444         drbd_md_set_sector_offsets(mdev, nbc);
1445
1446         if (!mdev->bitmap) {
1447                 if (drbd_bm_init(mdev)) {
1448                         retcode = ERR_NOMEM;
1449                         goto force_diskless_dec;
1450                 }
1451         }
1452
1453         retcode = drbd_md_read(mdev, nbc);
1454         if (retcode != NO_ERROR)
1455                 goto force_diskless_dec;
1456
1457         if (mdev->state.conn < C_CONNECTED &&
1458             mdev->state.role == R_PRIMARY &&
1459             (mdev->ed_uuid & ~((u64)1)) != (nbc->md.uuid[UI_CURRENT] & ~((u64)1))) {
1460                 dev_err(DEV, "Can only attach to data with current UUID=%016llX\n",
1461                     (unsigned long long)mdev->ed_uuid);
1462                 retcode = ERR_DATA_NOT_CURRENT;
1463                 goto force_diskless_dec;
1464         }
1465
1466         /* Since we are diskless, fix the activity log first... */
1467         if (drbd_check_al_size(mdev, &nbc->dc)) {
1468                 retcode = ERR_NOMEM;
1469                 goto force_diskless_dec;
1470         }
1471
1472         /* Prevent shrinking of consistent devices ! */
1473         if (drbd_md_test_flag(nbc, MDF_CONSISTENT) &&
1474             drbd_new_dev_size(mdev, nbc, 0) < nbc->md.la_size_sect) {
1475                 dev_warn(DEV, "refusing to truncate a consistent device\n");
1476                 retcode = ERR_DISK_TO_SMALL;
1477                 goto force_diskless_dec;
1478         }
1479
1480         if (!drbd_al_read_log(mdev, nbc)) {
1481                 retcode = ERR_IO_MD_DISK;
1482                 goto force_diskless_dec;
1483         }
1484
1485         /* Reset the "barriers don't work" bits here, then force meta data to
1486          * be written, to ensure we determine if barriers are supported. */
1487         if (nbc->dc.no_md_flush)
1488                 set_bit(MD_NO_FUA, &mdev->flags);
1489         else
1490                 clear_bit(MD_NO_FUA, &mdev->flags);
1491
1492         /* Point of no return reached.
1493          * Devices and memory are no longer released by error cleanup below.
1494          * now mdev takes over responsibility, and the state engine should
1495          * clean it up somewhere.  */
1496         D_ASSERT(mdev->ldev == NULL);
1497         mdev->ldev = nbc;
1498         mdev->resync = resync_lru;
1499         nbc = NULL;
1500         resync_lru = NULL;
1501
1502         mdev->write_ordering = WO_bdev_flush;
1503         drbd_bump_write_ordering(mdev, WO_bdev_flush);
1504
1505         if (drbd_md_test_flag(mdev->ldev, MDF_CRASHED_PRIMARY))
1506                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1507         else
1508                 clear_bit(CRASHED_PRIMARY, &mdev->flags);
1509
1510         if (drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1511             !(mdev->state.role == R_PRIMARY && mdev->tconn->susp_nod)) {
1512                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1513                 cp_discovered = 1;
1514         }
1515
1516         mdev->send_cnt = 0;
1517         mdev->recv_cnt = 0;
1518         mdev->read_cnt = 0;
1519         mdev->writ_cnt = 0;
1520
1521         drbd_reconsider_max_bio_size(mdev);
1522
1523         /* If I am currently not R_PRIMARY,
1524          * but meta data primary indicator is set,
1525          * I just now recover from a hard crash,
1526          * and have been R_PRIMARY before that crash.
1527          *
1528          * Now, if I had no connection before that crash
1529          * (have been degraded R_PRIMARY), chances are that
1530          * I won't find my peer now either.
1531          *
1532          * In that case, and _only_ in that case,
1533          * we use the degr-wfc-timeout instead of the default,
1534          * so we can automatically recover from a crash of a
1535          * degraded but active "cluster" after a certain timeout.
1536          */
1537         clear_bit(USE_DEGR_WFC_T, &mdev->flags);
1538         if (mdev->state.role != R_PRIMARY &&
1539              drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1540             !drbd_md_test_flag(mdev->ldev, MDF_CONNECTED_IND))
1541                 set_bit(USE_DEGR_WFC_T, &mdev->flags);
1542
1543         dd = drbd_determine_dev_size(mdev, 0);
1544         if (dd == dev_size_error) {
1545                 retcode = ERR_NOMEM_BITMAP;
1546                 goto force_diskless_dec;
1547         } else if (dd == grew)
1548                 set_bit(RESYNC_AFTER_NEG, &mdev->flags);
1549
1550         if (drbd_md_test_flag(mdev->ldev, MDF_FULL_SYNC)) {
1551                 dev_info(DEV, "Assuming that all blocks are out of sync "
1552                      "(aka FullSync)\n");
1553                 if (drbd_bitmap_io(mdev, &drbd_bmio_set_n_write,
1554                         "set_n_write from attaching", BM_LOCKED_MASK)) {
1555                         retcode = ERR_IO_MD_DISK;
1556                         goto force_diskless_dec;
1557                 }
1558         } else {
1559                 if (drbd_bitmap_io(mdev, &drbd_bm_read,
1560                         "read from attaching", BM_LOCKED_MASK)) {
1561                         retcode = ERR_IO_MD_DISK;
1562                         goto force_diskless_dec;
1563                 }
1564         }
1565
1566         if (cp_discovered) {
1567                 drbd_al_apply_to_bm(mdev);
1568                 if (drbd_bitmap_io(mdev, &drbd_bm_write,
1569                         "crashed primary apply AL", BM_LOCKED_MASK)) {
1570                         retcode = ERR_IO_MD_DISK;
1571                         goto force_diskless_dec;
1572                 }
1573         }
1574
1575         if (_drbd_bm_total_weight(mdev) == drbd_bm_bits(mdev))
1576                 drbd_suspend_al(mdev); /* IO is still suspended here... */
1577
1578         spin_lock_irq(&mdev->tconn->req_lock);
1579         os = drbd_read_state(mdev);
1580         ns = os;
1581         /* If MDF_CONSISTENT is not set go into inconsistent state,
1582            otherwise investigate MDF_WasUpToDate...
1583            If MDF_WAS_UP_TO_DATE is not set go into D_OUTDATED disk state,
1584            otherwise into D_CONSISTENT state.
1585         */
1586         if (drbd_md_test_flag(mdev->ldev, MDF_CONSISTENT)) {
1587                 if (drbd_md_test_flag(mdev->ldev, MDF_WAS_UP_TO_DATE))
1588                         ns.disk = D_CONSISTENT;
1589                 else
1590                         ns.disk = D_OUTDATED;
1591         } else {
1592                 ns.disk = D_INCONSISTENT;
1593         }
1594
1595         if (drbd_md_test_flag(mdev->ldev, MDF_PEER_OUT_DATED))
1596                 ns.pdsk = D_OUTDATED;
1597
1598         if ( ns.disk == D_CONSISTENT &&
1599             (ns.pdsk == D_OUTDATED || mdev->ldev->dc.fencing == FP_DONT_CARE))
1600                 ns.disk = D_UP_TO_DATE;
1601
1602         /* All tests on MDF_PRIMARY_IND, MDF_CONNECTED_IND,
1603            MDF_CONSISTENT and MDF_WAS_UP_TO_DATE must happen before
1604            this point, because drbd_request_state() modifies these
1605            flags. */
1606
1607         /* In case we are C_CONNECTED postpone any decision on the new disk
1608            state after the negotiation phase. */
1609         if (mdev->state.conn == C_CONNECTED) {
1610                 mdev->new_state_tmp.i = ns.i;
1611                 ns.i = os.i;
1612                 ns.disk = D_NEGOTIATING;
1613
1614                 /* We expect to receive up-to-date UUIDs soon.
1615                    To avoid a race in receive_state, free p_uuid while
1616                    holding req_lock. I.e. atomic with the state change */
1617                 kfree(mdev->p_uuid);
1618                 mdev->p_uuid = NULL;
1619         }
1620
1621         rv = _drbd_set_state(mdev, ns, CS_VERBOSE, NULL);
1622         spin_unlock_irq(&mdev->tconn->req_lock);
1623
1624         if (rv < SS_SUCCESS)
1625                 goto force_diskless_dec;
1626
1627         if (mdev->state.role == R_PRIMARY)
1628                 mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
1629         else
1630                 mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
1631
1632         drbd_md_mark_dirty(mdev);
1633         drbd_md_sync(mdev);
1634
1635         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
1636         put_ldev(mdev);
1637         conn_reconfig_done(mdev->tconn);
1638         drbd_adm_finish(info, retcode);
1639         return 0;
1640
1641  force_diskless_dec:
1642         put_ldev(mdev);
1643  force_diskless:
1644         drbd_force_state(mdev, NS(disk, D_FAILED));
1645         drbd_md_sync(mdev);
1646  fail:
1647         conn_reconfig_done(mdev->tconn);
1648         if (nbc) {
1649                 if (nbc->backing_bdev)
1650                         blkdev_put(nbc->backing_bdev,
1651                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1652                 if (nbc->md_bdev)
1653                         blkdev_put(nbc->md_bdev,
1654                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1655                 kfree(nbc);
1656         }
1657         lc_destroy(resync_lru);
1658
1659  finish:
1660         drbd_adm_finish(info, retcode);
1661         return 0;
1662 }
1663
1664 static int adm_detach(struct drbd_conf *mdev)
1665 {
1666         enum drbd_state_rv retcode;
1667         drbd_suspend_io(mdev); /* so no-one is stuck in drbd_al_begin_io */
1668         retcode = drbd_request_state(mdev, NS(disk, D_DISKLESS));
1669         wait_event(mdev->misc_wait,
1670                         mdev->state.disk != D_DISKLESS ||
1671                         !atomic_read(&mdev->local_cnt));
1672         drbd_resume_io(mdev);
1673         return retcode;
1674 }
1675
1676 /* Detaching the disk is a process in multiple stages.  First we need to lock
1677  * out application IO, in-flight IO, IO stuck in drbd_al_begin_io.
1678  * Then we transition to D_DISKLESS, and wait for put_ldev() to return all
1679  * internal references as well.
1680  * Only then we have finally detached. */
1681 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info)
1682 {
1683         enum drbd_ret_code retcode;
1684
1685         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1686         if (!adm_ctx.reply_skb)
1687                 return retcode;
1688         if (retcode != NO_ERROR)
1689                 goto out;
1690
1691         retcode = adm_detach(adm_ctx.mdev);
1692 out:
1693         drbd_adm_finish(info, retcode);
1694         return 0;
1695 }
1696
1697 static bool conn_resync_running(struct drbd_tconn *tconn)
1698 {
1699         struct drbd_conf *mdev;
1700         bool rv = false;
1701         int vnr;
1702
1703         rcu_read_lock();
1704         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1705                 if (mdev->state.conn == C_SYNC_SOURCE ||
1706                     mdev->state.conn == C_SYNC_TARGET ||
1707                     mdev->state.conn == C_PAUSED_SYNC_S ||
1708                     mdev->state.conn == C_PAUSED_SYNC_T) {
1709                         rv = true;
1710                         break;
1711                 }
1712         }
1713         rcu_read_unlock();
1714
1715         return rv;
1716 }
1717
1718 static bool conn_ov_running(struct drbd_tconn *tconn)
1719 {
1720         struct drbd_conf *mdev;
1721         bool rv = false;
1722         int vnr;
1723
1724         rcu_read_lock();
1725         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1726                 if (mdev->state.conn == C_VERIFY_S ||
1727                     mdev->state.conn == C_VERIFY_T) {
1728                         rv = true;
1729                         break;
1730                 }
1731         }
1732         rcu_read_unlock();
1733
1734         return rv;
1735 }
1736
1737 static enum drbd_ret_code
1738 _check_net_options(struct drbd_tconn *tconn, struct net_conf *old_conf, struct net_conf *new_conf)
1739 {
1740         struct drbd_conf *mdev;
1741         int i;
1742
1743         if (old_conf && tconn->agreed_pro_version < 100 &&
1744             tconn->cstate == C_WF_REPORT_PARAMS &&
1745             new_conf->wire_protocol != old_conf->wire_protocol)
1746                 return ERR_NEED_APV_100;
1747
1748         if (new_conf->two_primaries &&
1749             (new_conf->wire_protocol != DRBD_PROT_C))
1750                 return ERR_NOT_PROTO_C;
1751
1752         idr_for_each_entry(&tconn->volumes, mdev, i) {
1753                 if (get_ldev(mdev)) {
1754                         enum drbd_fencing_p fp = mdev->ldev->dc.fencing;
1755                         put_ldev(mdev);
1756                         if (new_conf->wire_protocol == DRBD_PROT_A && fp == FP_STONITH)
1757                                 return ERR_STONITH_AND_PROT_A;
1758                 }
1759                 if (mdev->state.role == R_PRIMARY && new_conf->want_lose)
1760                         return ERR_DISCARD;
1761         }
1762
1763         if (new_conf->on_congestion != OC_BLOCK && new_conf->wire_protocol != DRBD_PROT_A)
1764                 return ERR_CONG_NOT_PROTO_A;
1765
1766         return NO_ERROR;
1767 }
1768
1769 static enum drbd_ret_code
1770 check_net_options(struct drbd_tconn *tconn, struct net_conf *new_conf)
1771 {
1772         static enum drbd_ret_code rv;
1773         struct drbd_conf *mdev;
1774         int i;
1775
1776         rcu_read_lock();
1777         rv = _check_net_options(tconn, rcu_dereference(tconn->net_conf), new_conf);
1778         rcu_read_unlock();
1779
1780         /* tconn->volumes protected by genl_lock() here */
1781         idr_for_each_entry(&tconn->volumes, mdev, i) {
1782                 if (!mdev->bitmap) {
1783                         if(drbd_bm_init(mdev))
1784                                 return ERR_NOMEM;
1785                 }
1786         }
1787
1788         return rv;
1789 }
1790
1791 struct crypto {
1792         struct crypto_hash *verify_tfm;
1793         struct crypto_hash *csums_tfm;
1794         struct crypto_hash *cram_hmac_tfm;
1795         struct crypto_hash *integrity_tfm;
1796         struct crypto_hash *peer_integrity_tfm;
1797         void *int_dig_in;
1798         void *int_dig_vv;
1799 };
1800
1801 static int
1802 alloc_hash(struct crypto_hash **tfm, char *tfm_name, int err_alg)
1803 {
1804         if (!tfm_name[0])
1805                 return NO_ERROR;
1806
1807         *tfm = crypto_alloc_hash(tfm_name, 0, CRYPTO_ALG_ASYNC);
1808         if (IS_ERR(*tfm)) {
1809                 *tfm = NULL;
1810                 return err_alg;
1811         }
1812
1813         return NO_ERROR;
1814 }
1815
1816 static enum drbd_ret_code
1817 alloc_crypto(struct crypto *crypto, struct net_conf *new_conf)
1818 {
1819         char hmac_name[CRYPTO_MAX_ALG_NAME];
1820         enum drbd_ret_code rv;
1821         int hash_size;
1822
1823         rv = alloc_hash(&crypto->csums_tfm, new_conf->csums_alg,
1824                        ERR_CSUMS_ALG);
1825         if (rv != NO_ERROR)
1826                 return rv;
1827         rv = alloc_hash(&crypto->verify_tfm, new_conf->verify_alg,
1828                        ERR_VERIFY_ALG);
1829         if (rv != NO_ERROR)
1830                 return rv;
1831         rv = alloc_hash(&crypto->integrity_tfm, new_conf->integrity_alg,
1832                        ERR_INTEGRITY_ALG);
1833         if (rv != NO_ERROR)
1834                 return rv;
1835         rv = alloc_hash(&crypto->peer_integrity_tfm, new_conf->integrity_alg,
1836                        ERR_INTEGRITY_ALG);
1837         if (rv != NO_ERROR)
1838                 return rv;
1839         if (new_conf->cram_hmac_alg[0] != 0) {
1840                 snprintf(hmac_name, CRYPTO_MAX_ALG_NAME, "hmac(%s)",
1841                          new_conf->cram_hmac_alg);
1842
1843                 rv = alloc_hash(&crypto->cram_hmac_tfm, hmac_name,
1844                                ERR_AUTH_ALG);
1845         }
1846         if (crypto->integrity_tfm) {
1847                 hash_size = crypto_hash_digestsize(crypto->integrity_tfm);
1848                 crypto->int_dig_in = kmalloc(hash_size, GFP_KERNEL);
1849                 if (!crypto->int_dig_in)
1850                         return ERR_NOMEM;
1851                 crypto->int_dig_vv = kmalloc(hash_size, GFP_KERNEL);
1852                 if (!crypto->int_dig_vv)
1853                         return ERR_NOMEM;
1854         }
1855
1856         return rv;
1857 }
1858
1859 static void free_crypto(struct crypto *crypto)
1860 {
1861         kfree(crypto->int_dig_in);
1862         kfree(crypto->int_dig_vv);
1863         crypto_free_hash(crypto->cram_hmac_tfm);
1864         crypto_free_hash(crypto->integrity_tfm);
1865         crypto_free_hash(crypto->peer_integrity_tfm);
1866         crypto_free_hash(crypto->csums_tfm);
1867         crypto_free_hash(crypto->verify_tfm);
1868 }
1869
1870 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info)
1871 {
1872         enum drbd_ret_code retcode;
1873         struct drbd_tconn *tconn;
1874         struct net_conf *old_conf, *new_conf = NULL;
1875         int err;
1876         int ovr; /* online verify running */
1877         int rsr; /* re-sync running */
1878         struct crypto crypto = { };
1879
1880         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
1881         if (!adm_ctx.reply_skb)
1882                 return retcode;
1883         if (retcode != NO_ERROR)
1884                 goto out;
1885
1886         tconn = adm_ctx.tconn;
1887
1888         new_conf = kzalloc(sizeof(struct net_conf), GFP_KERNEL);
1889         if (!new_conf) {
1890                 retcode = ERR_NOMEM;
1891                 goto out;
1892         }
1893
1894         conn_reconfig_start(tconn);
1895
1896         mutex_lock(&tconn->net_conf_update);
1897         old_conf = tconn->net_conf;
1898
1899         if (!old_conf) {
1900                 drbd_msg_put_info("net conf missing, try connect");
1901                 retcode = ERR_INVALID_REQUEST;
1902                 goto fail;
1903         }
1904
1905         *new_conf = *old_conf;
1906         if (should_set_defaults(info))
1907                 drbd_set_net_conf_defaults(new_conf);
1908
1909         err = net_conf_from_attrs_for_change(new_conf, info);
1910         if (err) {
1911                 retcode = ERR_MANDATORY_TAG;
1912                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1913                 goto fail;
1914         }
1915
1916         retcode = check_net_options(tconn, new_conf);
1917         if (retcode != NO_ERROR)
1918                 goto fail;
1919
1920         /* re-sync running */
1921         rsr = conn_resync_running(tconn);
1922         if (rsr && strcmp(new_conf->csums_alg, old_conf->csums_alg)) {
1923                 retcode = ERR_CSUMS_RESYNC_RUNNING;
1924                 goto fail;
1925         }
1926
1927         /* online verify running */
1928         ovr = conn_ov_running(tconn);
1929         if (ovr && strcmp(new_conf->verify_alg, old_conf->verify_alg)) {
1930                 retcode = ERR_VERIFY_RUNNING;
1931                 goto fail;
1932         }
1933
1934         retcode = alloc_crypto(&crypto, new_conf);
1935         if (retcode != NO_ERROR)
1936                 goto fail;
1937
1938         rcu_assign_pointer(tconn->net_conf, new_conf);
1939
1940         if (!rsr) {
1941                 crypto_free_hash(tconn->csums_tfm);
1942                 tconn->csums_tfm = crypto.csums_tfm;
1943                 crypto.csums_tfm = NULL;
1944         }
1945         if (!ovr) {
1946                 crypto_free_hash(tconn->verify_tfm);
1947                 tconn->verify_tfm = crypto.verify_tfm;
1948                 crypto.verify_tfm = NULL;
1949         }
1950
1951         /* FIXME can not assign these so bluntly while we have ongoing IO */
1952         kfree(tconn->int_dig_in);
1953         tconn->int_dig_in = crypto.int_dig_in;
1954         kfree(tconn->int_dig_vv);
1955         tconn->int_dig_vv = crypto.int_dig_vv;
1956         crypto_free_hash(tconn->integrity_tfm);
1957         tconn->integrity_tfm = crypto.integrity_tfm;
1958         crypto_free_hash(tconn->peer_integrity_tfm);
1959         tconn->peer_integrity_tfm = crypto.peer_integrity_tfm;
1960
1961         /* FIXME Changing cram_hmac while the connection is established is useless */
1962         crypto_free_hash(tconn->cram_hmac_tfm);
1963         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
1964
1965         mutex_unlock(&tconn->net_conf_update);
1966         synchronize_rcu();
1967         kfree(old_conf);
1968
1969         if (tconn->cstate >= C_WF_REPORT_PARAMS)
1970                 drbd_send_sync_param(minor_to_mdev(conn_lowest_minor(tconn)));
1971
1972         goto done;
1973
1974  fail:
1975         mutex_unlock(&tconn->net_conf_update);
1976         free_crypto(&crypto);
1977         kfree(new_conf);
1978  done:
1979         conn_reconfig_done(tconn);
1980  out:
1981         drbd_adm_finish(info, retcode);
1982         return 0;
1983 }
1984
1985 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info)
1986 {
1987         struct drbd_conf *mdev;
1988         struct net_conf *old_conf, *new_conf = NULL;
1989         struct crypto crypto = { };
1990         struct drbd_tconn *oconn;
1991         struct drbd_tconn *tconn;
1992         struct sockaddr *new_my_addr, *new_peer_addr, *taken_addr;
1993         enum drbd_ret_code retcode;
1994         int i;
1995         int err;
1996
1997         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
1998         if (!adm_ctx.reply_skb)
1999                 return retcode;
2000         if (retcode != NO_ERROR)
2001                 goto out;
2002
2003         tconn = adm_ctx.tconn;
2004         conn_reconfig_start(tconn);
2005
2006         if (tconn->cstate > C_STANDALONE) {
2007                 retcode = ERR_NET_CONFIGURED;
2008                 goto fail;
2009         }
2010
2011         /* allocation not in the IO path, cqueue thread context */
2012         new_conf = kzalloc(sizeof(*new_conf), GFP_KERNEL);
2013         if (!new_conf) {
2014                 retcode = ERR_NOMEM;
2015                 goto fail;
2016         }
2017
2018         drbd_set_net_conf_defaults(new_conf);
2019
2020         err = net_conf_from_attrs(new_conf, info);
2021         if (err) {
2022                 retcode = ERR_MANDATORY_TAG;
2023                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2024                 goto fail;
2025         }
2026
2027         retcode = check_net_options(tconn, new_conf);
2028         if (retcode != NO_ERROR)
2029                 goto fail;
2030
2031         retcode = NO_ERROR;
2032
2033         new_my_addr = (struct sockaddr *)&new_conf->my_addr;
2034         new_peer_addr = (struct sockaddr *)&new_conf->peer_addr;
2035
2036         /* No need to take drbd_cfg_rwsem here.  All reconfiguration is
2037          * strictly serialized on genl_lock(). We are protected against
2038          * concurrent reconfiguration/addition/deletion */
2039         list_for_each_entry(oconn, &drbd_tconns, all_tconn) {
2040                 struct net_conf *nc;
2041                 if (oconn == tconn)
2042                         continue;
2043
2044                 rcu_read_lock();
2045                 nc = rcu_dereference(oconn->net_conf);
2046                 if (nc) {
2047                         taken_addr = (struct sockaddr *)&nc->my_addr;
2048                         if (new_conf->my_addr_len == nc->my_addr_len &&
2049                             !memcmp(new_my_addr, taken_addr, new_conf->my_addr_len))
2050                                 retcode = ERR_LOCAL_ADDR;
2051
2052                         taken_addr = (struct sockaddr *)&nc->peer_addr;
2053                         if (new_conf->peer_addr_len == nc->peer_addr_len &&
2054                             !memcmp(new_peer_addr, taken_addr, new_conf->peer_addr_len))
2055                                 retcode = ERR_PEER_ADDR;
2056                 }
2057                 rcu_read_unlock();
2058                 if (retcode != NO_ERROR)
2059                         goto fail;
2060         }
2061
2062         retcode = alloc_crypto(&crypto, new_conf);
2063         if (retcode != NO_ERROR)
2064                 goto fail;
2065
2066         ((char *)new_conf->shared_secret)[SHARED_SECRET_MAX-1] = 0;
2067
2068         conn_flush_workqueue(tconn);
2069
2070         mutex_lock(&tconn->net_conf_update);
2071         old_conf = tconn->net_conf;
2072         if (old_conf) {
2073                 retcode = ERR_NET_CONFIGURED;
2074                 mutex_unlock(&tconn->net_conf_update);
2075                 goto fail;
2076         }
2077         rcu_assign_pointer(tconn->net_conf, new_conf);
2078
2079         conn_free_crypto(tconn);
2080         tconn->int_dig_in = crypto.int_dig_in;
2081         tconn->int_dig_vv = crypto.int_dig_vv;
2082         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
2083         tconn->integrity_tfm = crypto.integrity_tfm;
2084         tconn->peer_integrity_tfm = crypto.peer_integrity_tfm;
2085         tconn->csums_tfm = crypto.csums_tfm;
2086         tconn->verify_tfm = crypto.verify_tfm;
2087
2088         mutex_unlock(&tconn->net_conf_update);
2089
2090         rcu_read_lock();
2091         idr_for_each_entry(&tconn->volumes, mdev, i) {
2092                 mdev->send_cnt = 0;
2093                 mdev->recv_cnt = 0;
2094         }
2095         rcu_read_unlock();
2096
2097         retcode = conn_request_state(tconn, NS(conn, C_UNCONNECTED), CS_VERBOSE);
2098
2099         conn_reconfig_done(tconn);
2100         drbd_adm_finish(info, retcode);
2101         return 0;
2102
2103 fail:
2104         free_crypto(&crypto);
2105         kfree(new_conf);
2106
2107         conn_reconfig_done(tconn);
2108 out:
2109         drbd_adm_finish(info, retcode);
2110         return 0;
2111 }
2112
2113 static enum drbd_state_rv conn_try_disconnect(struct drbd_tconn *tconn, bool force)
2114 {
2115         enum drbd_state_rv rv;
2116         if (force) {
2117                 spin_lock_irq(&tconn->req_lock);
2118                 rv = _conn_request_state(tconn, NS(conn, C_DISCONNECTING), CS_HARD);
2119                 spin_unlock_irq(&tconn->req_lock);
2120                 return rv;
2121         }
2122
2123         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING), 0);
2124
2125         switch (rv) {
2126         case SS_NOTHING_TO_DO:
2127         case SS_ALREADY_STANDALONE:
2128                 return SS_SUCCESS;
2129         case SS_PRIMARY_NOP:
2130                 /* Our state checking code wants to see the peer outdated. */
2131                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2132                                                         pdsk, D_OUTDATED), CS_VERBOSE);
2133                 break;
2134         case SS_CW_FAILED_BY_PEER:
2135                 /* The peer probably wants to see us outdated. */
2136                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2137                                                         disk, D_OUTDATED), 0);
2138                 if (rv == SS_IS_DISKLESS || rv == SS_LOWER_THAN_OUTDATED) {
2139                         conn_request_state(tconn, NS(conn, C_DISCONNECTING), CS_HARD);
2140                         rv = SS_SUCCESS;
2141                 }
2142                 break;
2143         default:;
2144                 /* no special handling necessary */
2145         }
2146
2147         return rv;
2148 }
2149
2150 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info)
2151 {
2152         struct disconnect_parms parms;
2153         struct drbd_tconn *tconn;
2154         enum drbd_state_rv rv;
2155         enum drbd_ret_code retcode;
2156         int err;
2157
2158         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
2159         if (!adm_ctx.reply_skb)
2160                 return retcode;
2161         if (retcode != NO_ERROR)
2162                 goto fail;
2163
2164         tconn = adm_ctx.tconn;
2165         memset(&parms, 0, sizeof(parms));
2166         if (info->attrs[DRBD_NLA_DISCONNECT_PARMS]) {
2167                 err = disconnect_parms_from_attrs(&parms, info);
2168                 if (err) {
2169                         retcode = ERR_MANDATORY_TAG;
2170                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2171                         goto fail;
2172                 }
2173         }
2174
2175         rv = conn_try_disconnect(tconn, parms.force_disconnect);
2176         if (rv < SS_SUCCESS)
2177                 goto fail;
2178
2179         /* No one else can reconfigure the network while I am here.
2180          * The state handling only uses drbd_thread_stop_nowait(),
2181          * we want to really wait here until the receiver is no more. */
2182         drbd_thread_stop(&tconn->receiver);
2183         if (wait_event_interruptible(tconn->ping_wait,
2184                                      tconn->cstate == C_STANDALONE)) {
2185                 retcode = ERR_INTR;
2186                 goto fail;
2187         }
2188
2189         retcode = NO_ERROR;
2190  fail:
2191         drbd_adm_finish(info, retcode);
2192         return 0;
2193 }
2194
2195 void resync_after_online_grow(struct drbd_conf *mdev)
2196 {
2197         int iass; /* I am sync source */
2198
2199         dev_info(DEV, "Resync of new storage after online grow\n");
2200         if (mdev->state.role != mdev->state.peer)
2201                 iass = (mdev->state.role == R_PRIMARY);
2202         else
2203                 iass = test_bit(DISCARD_CONCURRENT, &mdev->tconn->flags);
2204
2205         if (iass)
2206                 drbd_start_resync(mdev, C_SYNC_SOURCE);
2207         else
2208                 _drbd_request_state(mdev, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE + CS_SERIALIZE);
2209 }
2210
2211 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info)
2212 {
2213         struct resize_parms rs;
2214         struct drbd_conf *mdev;
2215         enum drbd_ret_code retcode;
2216         enum determine_dev_size dd;
2217         enum dds_flags ddsf;
2218         int err;
2219
2220         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2221         if (!adm_ctx.reply_skb)
2222                 return retcode;
2223         if (retcode != NO_ERROR)
2224                 goto fail;
2225
2226         memset(&rs, 0, sizeof(struct resize_parms));
2227         if (info->attrs[DRBD_NLA_RESIZE_PARMS]) {
2228                 err = resize_parms_from_attrs(&rs, info);
2229                 if (err) {
2230                         retcode = ERR_MANDATORY_TAG;
2231                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2232                         goto fail;
2233                 }
2234         }
2235
2236         mdev = adm_ctx.mdev;
2237         if (mdev->state.conn > C_CONNECTED) {
2238                 retcode = ERR_RESIZE_RESYNC;
2239                 goto fail;
2240         }
2241
2242         if (mdev->state.role == R_SECONDARY &&
2243             mdev->state.peer == R_SECONDARY) {
2244                 retcode = ERR_NO_PRIMARY;
2245                 goto fail;
2246         }
2247
2248         if (!get_ldev(mdev)) {
2249                 retcode = ERR_NO_DISK;
2250                 goto fail;
2251         }
2252
2253         if (rs.no_resync && mdev->tconn->agreed_pro_version < 93) {
2254                 retcode = ERR_NEED_APV_93;
2255                 goto fail;
2256         }
2257
2258         if (mdev->ldev->known_size != drbd_get_capacity(mdev->ldev->backing_bdev))
2259                 mdev->ldev->known_size = drbd_get_capacity(mdev->ldev->backing_bdev);
2260
2261         mdev->ldev->dc.disk_size = (sector_t)rs.resize_size;
2262         ddsf = (rs.resize_force ? DDSF_FORCED : 0) | (rs.no_resync ? DDSF_NO_RESYNC : 0);
2263         dd = drbd_determine_dev_size(mdev, ddsf);
2264         drbd_md_sync(mdev);
2265         put_ldev(mdev);
2266         if (dd == dev_size_error) {
2267                 retcode = ERR_NOMEM_BITMAP;
2268                 goto fail;
2269         }
2270
2271         if (mdev->state.conn == C_CONNECTED) {
2272                 if (dd == grew)
2273                         set_bit(RESIZE_PENDING, &mdev->flags);
2274
2275                 drbd_send_uuids(mdev);
2276                 drbd_send_sizes(mdev, 1, ddsf);
2277         }
2278
2279  fail:
2280         drbd_adm_finish(info, retcode);
2281         return 0;
2282 }
2283
2284 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info)
2285 {
2286         enum drbd_ret_code retcode;
2287         cpumask_var_t new_cpu_mask;
2288         struct drbd_tconn *tconn;
2289         int *rs_plan_s = NULL;
2290         struct res_opts res_opts;
2291         int err;
2292
2293         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
2294         if (!adm_ctx.reply_skb)
2295                 return retcode;
2296         if (retcode != NO_ERROR)
2297                 goto fail;
2298         tconn = adm_ctx.tconn;
2299
2300         if (!zalloc_cpumask_var(&new_cpu_mask, GFP_KERNEL)) {
2301                 retcode = ERR_NOMEM;
2302                 drbd_msg_put_info("unable to allocate cpumask");
2303                 goto fail;
2304         }
2305
2306         res_opts = tconn->res_opts;
2307         if (should_set_defaults(info))
2308                 drbd_set_res_opts_default(&res_opts);
2309
2310         err = res_opts_from_attrs(&res_opts, info);
2311         if (err) {
2312                 retcode = ERR_MANDATORY_TAG;
2313                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2314                 goto fail;
2315         }
2316
2317         /* silently ignore cpu mask on UP kernel */
2318         if (nr_cpu_ids > 1 && res_opts.cpu_mask[0] != 0) {
2319                 err = __bitmap_parse(res_opts.cpu_mask, 32, 0,
2320                                 cpumask_bits(new_cpu_mask), nr_cpu_ids);
2321                 if (err) {
2322                         conn_warn(tconn, "__bitmap_parse() failed with %d\n", err);
2323                         retcode = ERR_CPU_MASK_PARSE;
2324                         goto fail;
2325                 }
2326         }
2327
2328
2329         tconn->res_opts = res_opts;
2330
2331         if (!cpumask_equal(tconn->cpu_mask, new_cpu_mask)) {
2332                 cpumask_copy(tconn->cpu_mask, new_cpu_mask);
2333                 drbd_calc_cpu_mask(tconn);
2334                 tconn->receiver.reset_cpu_mask = 1;
2335                 tconn->asender.reset_cpu_mask = 1;
2336                 tconn->worker.reset_cpu_mask = 1;
2337         }
2338
2339 fail:
2340         kfree(rs_plan_s);
2341         free_cpumask_var(new_cpu_mask);
2342
2343         drbd_adm_finish(info, retcode);
2344         return 0;
2345 }
2346
2347 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info)
2348 {
2349         struct drbd_conf *mdev;
2350         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2351
2352         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2353         if (!adm_ctx.reply_skb)
2354                 return retcode;
2355         if (retcode != NO_ERROR)
2356                 goto out;
2357
2358         mdev = adm_ctx.mdev;
2359
2360         /* If there is still bitmap IO pending, probably because of a previous
2361          * resync just being finished, wait for it before requesting a new resync. */
2362         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2363
2364         retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T), CS_ORDERED);
2365
2366         if (retcode < SS_SUCCESS && retcode != SS_NEED_CONNECTION)
2367                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2368
2369         while (retcode == SS_NEED_CONNECTION) {
2370                 spin_lock_irq(&mdev->tconn->req_lock);
2371                 if (mdev->state.conn < C_CONNECTED)
2372                         retcode = _drbd_set_state(_NS(mdev, disk, D_INCONSISTENT), CS_VERBOSE, NULL);
2373                 spin_unlock_irq(&mdev->tconn->req_lock);
2374
2375                 if (retcode != SS_NEED_CONNECTION)
2376                         break;
2377
2378                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2379         }
2380
2381 out:
2382         drbd_adm_finish(info, retcode);
2383         return 0;
2384 }
2385
2386 static int drbd_bmio_set_susp_al(struct drbd_conf *mdev)
2387 {
2388         int rv;
2389
2390         rv = drbd_bmio_set_n_write(mdev);
2391         drbd_suspend_al(mdev);
2392         return rv;
2393 }
2394
2395 static int drbd_adm_simple_request_state(struct sk_buff *skb, struct genl_info *info,
2396                 union drbd_state mask, union drbd_state val)
2397 {
2398         enum drbd_ret_code retcode;
2399
2400         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2401         if (!adm_ctx.reply_skb)
2402                 return retcode;
2403         if (retcode != NO_ERROR)
2404                 goto out;
2405
2406         retcode = drbd_request_state(adm_ctx.mdev, mask, val);
2407 out:
2408         drbd_adm_finish(info, retcode);
2409         return 0;
2410 }
2411
2412 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info)
2413 {
2414         return drbd_adm_simple_request_state(skb, info, NS(conn, C_STARTING_SYNC_S));
2415 }
2416
2417 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info)
2418 {
2419         enum drbd_ret_code retcode;
2420
2421         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2422         if (!adm_ctx.reply_skb)
2423                 return retcode;
2424         if (retcode != NO_ERROR)
2425                 goto out;
2426
2427         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 1)) == SS_NOTHING_TO_DO)
2428                 retcode = ERR_PAUSE_IS_SET;
2429 out:
2430         drbd_adm_finish(info, retcode);
2431         return 0;
2432 }
2433
2434 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info)
2435 {
2436         union drbd_dev_state s;
2437         enum drbd_ret_code retcode;
2438
2439         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2440         if (!adm_ctx.reply_skb)
2441                 return retcode;
2442         if (retcode != NO_ERROR)
2443                 goto out;
2444
2445         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 0)) == SS_NOTHING_TO_DO) {
2446                 s = adm_ctx.mdev->state;
2447                 if (s.conn == C_PAUSED_SYNC_S || s.conn == C_PAUSED_SYNC_T) {
2448                         retcode = s.aftr_isp ? ERR_PIC_AFTER_DEP :
2449                                   s.peer_isp ? ERR_PIC_PEER_DEP : ERR_PAUSE_IS_CLEAR;
2450                 } else {
2451                         retcode = ERR_PAUSE_IS_CLEAR;
2452                 }
2453         }
2454
2455 out:
2456         drbd_adm_finish(info, retcode);
2457         return 0;
2458 }
2459
2460 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info)
2461 {
2462         return drbd_adm_simple_request_state(skb, info, NS(susp, 1));
2463 }
2464
2465 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info)
2466 {
2467         struct drbd_conf *mdev;
2468         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2469
2470         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2471         if (!adm_ctx.reply_skb)
2472                 return retcode;
2473         if (retcode != NO_ERROR)
2474                 goto out;
2475
2476         mdev = adm_ctx.mdev;
2477         if (test_bit(NEW_CUR_UUID, &mdev->flags)) {
2478                 drbd_uuid_new_current(mdev);
2479                 clear_bit(NEW_CUR_UUID, &mdev->flags);
2480         }
2481         drbd_suspend_io(mdev);
2482         retcode = drbd_request_state(mdev, NS3(susp, 0, susp_nod, 0, susp_fen, 0));
2483         if (retcode == SS_SUCCESS) {
2484                 if (mdev->state.conn < C_CONNECTED)
2485                         tl_clear(mdev->tconn);
2486                 if (mdev->state.disk == D_DISKLESS || mdev->state.disk == D_FAILED)
2487                         tl_restart(mdev->tconn, FAIL_FROZEN_DISK_IO);
2488         }
2489         drbd_resume_io(mdev);
2490
2491 out:
2492         drbd_adm_finish(info, retcode);
2493         return 0;
2494 }
2495
2496 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info)
2497 {
2498         return drbd_adm_simple_request_state(skb, info, NS(disk, D_OUTDATED));
2499 }
2500
2501 int nla_put_drbd_cfg_context(struct sk_buff *skb, const char *conn_name, unsigned vnr)
2502 {
2503         struct nlattr *nla;
2504         nla = nla_nest_start(skb, DRBD_NLA_CFG_CONTEXT);
2505         if (!nla)
2506                 goto nla_put_failure;
2507         if (vnr != VOLUME_UNSPECIFIED)
2508                 NLA_PUT_U32(skb, T_ctx_volume, vnr);
2509         NLA_PUT_STRING(skb, T_ctx_conn_name, conn_name);
2510         nla_nest_end(skb, nla);
2511         return 0;
2512
2513 nla_put_failure:
2514         if (nla)
2515                 nla_nest_cancel(skb, nla);
2516         return -EMSGSIZE;
2517 }
2518
2519 int nla_put_status_info(struct sk_buff *skb, struct drbd_conf *mdev,
2520                 const struct sib_info *sib)
2521 {
2522         struct state_info *si = NULL; /* for sizeof(si->member); */
2523         struct net_conf *nc;
2524         struct nlattr *nla;
2525         int got_ldev;
2526         int err = 0;
2527         int exclude_sensitive;
2528
2529         /* If sib != NULL, this is drbd_bcast_event, which anyone can listen
2530          * to.  So we better exclude_sensitive information.
2531          *
2532          * If sib == NULL, this is drbd_adm_get_status, executed synchronously
2533          * in the context of the requesting user process. Exclude sensitive
2534          * information, unless current has superuser.
2535          *
2536          * NOTE: for drbd_adm_get_status_all(), this is a netlink dump, and
2537          * relies on the current implementation of netlink_dump(), which
2538          * executes the dump callback successively from netlink_recvmsg(),
2539          * always in the context of the receiving process */
2540         exclude_sensitive = sib || !capable(CAP_SYS_ADMIN);
2541
2542         got_ldev = get_ldev(mdev);
2543
2544         /* We need to add connection name and volume number information still.
2545          * Minor number is in drbd_genlmsghdr. */
2546         if (nla_put_drbd_cfg_context(skb, mdev->tconn->name, mdev->vnr))
2547                 goto nla_put_failure;
2548
2549         if (res_opts_to_skb(skb, &mdev->tconn->res_opts, exclude_sensitive))
2550                 goto nla_put_failure;
2551
2552         if (got_ldev)
2553                 if (disk_conf_to_skb(skb, &mdev->ldev->dc, exclude_sensitive))
2554                         goto nla_put_failure;
2555
2556         rcu_read_lock();
2557         nc = rcu_dereference(mdev->tconn->net_conf);
2558         if (nc)
2559                 err = net_conf_to_skb(skb, nc, exclude_sensitive);
2560         rcu_read_unlock();
2561         if (err)
2562                 goto nla_put_failure;
2563
2564         nla = nla_nest_start(skb, DRBD_NLA_STATE_INFO);
2565         if (!nla)
2566                 goto nla_put_failure;
2567         NLA_PUT_U32(skb, T_sib_reason, sib ? sib->sib_reason : SIB_GET_STATUS_REPLY);
2568         NLA_PUT_U32(skb, T_current_state, mdev->state.i);
2569         NLA_PUT_U64(skb, T_ed_uuid, mdev->ed_uuid);
2570         NLA_PUT_U64(skb, T_capacity, drbd_get_capacity(mdev->this_bdev));
2571
2572         if (got_ldev) {
2573                 NLA_PUT_U32(skb, T_disk_flags, mdev->ldev->md.flags);
2574                 NLA_PUT(skb, T_uuids, sizeof(si->uuids), mdev->ldev->md.uuid);
2575                 NLA_PUT_U64(skb, T_bits_total, drbd_bm_bits(mdev));
2576                 NLA_PUT_U64(skb, T_bits_oos, drbd_bm_total_weight(mdev));
2577                 if (C_SYNC_SOURCE <= mdev->state.conn &&
2578                     C_PAUSED_SYNC_T >= mdev->state.conn) {
2579                         NLA_PUT_U64(skb, T_bits_rs_total, mdev->rs_total);
2580                         NLA_PUT_U64(skb, T_bits_rs_failed, mdev->rs_failed);
2581                 }
2582         }
2583
2584         if (sib) {
2585                 switch(sib->sib_reason) {
2586                 case SIB_SYNC_PROGRESS:
2587                 case SIB_GET_STATUS_REPLY:
2588                         break;
2589                 case SIB_STATE_CHANGE:
2590                         NLA_PUT_U32(skb, T_prev_state, sib->os.i);
2591                         NLA_PUT_U32(skb, T_new_state, sib->ns.i);
2592                         break;
2593                 case SIB_HELPER_POST:
2594                         NLA_PUT_U32(skb,
2595                                 T_helper_exit_code, sib->helper_exit_code);
2596                         /* fall through */
2597                 case SIB_HELPER_PRE:
2598                         NLA_PUT_STRING(skb, T_helper, sib->helper_name);
2599                         break;
2600                 }
2601         }
2602         nla_nest_end(skb, nla);
2603
2604         if (0)
2605 nla_put_failure:
2606                 err = -EMSGSIZE;
2607         if (got_ldev)
2608                 put_ldev(mdev);
2609         return err;
2610 }
2611
2612 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info)
2613 {
2614         enum drbd_ret_code retcode;
2615         int err;
2616
2617         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2618         if (!adm_ctx.reply_skb)
2619                 return retcode;
2620         if (retcode != NO_ERROR)
2621                 goto out;
2622
2623         err = nla_put_status_info(adm_ctx.reply_skb, adm_ctx.mdev, NULL);
2624         if (err) {
2625                 nlmsg_free(adm_ctx.reply_skb);
2626                 return err;
2627         }
2628 out:
2629         drbd_adm_finish(info, retcode);
2630         return 0;
2631 }
2632
2633 int get_one_status(struct sk_buff *skb, struct netlink_callback *cb)
2634 {
2635         struct drbd_conf *mdev;
2636         struct drbd_genlmsghdr *dh;
2637         struct drbd_tconn *pos = (struct drbd_tconn*)cb->args[0];
2638         struct drbd_tconn *tconn = NULL;
2639         struct drbd_tconn *tmp;
2640         unsigned volume = cb->args[1];
2641
2642         /* Open coded, deferred, iteration:
2643          * list_for_each_entry_safe(tconn, tmp, &drbd_tconns, all_tconn) {
2644          *      idr_for_each_entry(&tconn->volumes, mdev, i) {
2645          *        ...
2646          *      }
2647          * }
2648          * where tconn is cb->args[0];
2649          * and i is cb->args[1];
2650          *
2651          * cb->args[2] indicates if we shall loop over all resources,
2652          * or just dump all volumes of a single resource.
2653          *
2654          * This may miss entries inserted after this dump started,
2655          * or entries deleted before they are reached.
2656          *
2657          * We need to make sure the mdev won't disappear while
2658          * we are looking at it, and revalidate our iterators
2659          * on each iteration.
2660          */
2661
2662         /* synchronize with conn_create()/conn_destroy() */
2663         down_read(&drbd_cfg_rwsem);
2664         /* revalidate iterator position */
2665         list_for_each_entry(tmp, &drbd_tconns, all_tconn) {
2666                 if (pos == NULL) {
2667                         /* first iteration */
2668                         pos = tmp;
2669                         tconn = pos;
2670                         break;
2671                 }
2672                 if (tmp == pos) {
2673                         tconn = pos;
2674                         break;
2675                 }
2676         }
2677         if (tconn) {
2678 next_tconn:
2679                 mdev = idr_get_next(&tconn->volumes, &volume);
2680                 if (!mdev) {
2681                         /* No more volumes to dump on this tconn.
2682                          * Advance tconn iterator. */
2683                         pos = list_entry(tconn->all_tconn.next,
2684                                         struct drbd_tconn, all_tconn);
2685                         /* Did we dump any volume on this tconn yet? */
2686                         if (volume != 0) {
2687                                 /* If we reached the end of the list,
2688                                  * or only a single resource dump was requested,
2689                                  * we are done. */
2690                                 if (&pos->all_tconn == &drbd_tconns || cb->args[2])
2691                                         goto out;
2692                                 volume = 0;
2693                                 tconn = pos;
2694                                 goto next_tconn;
2695                         }
2696                 }
2697
2698                 dh = genlmsg_put(skb, NETLINK_CB(cb->skb).pid,
2699                                 cb->nlh->nlmsg_seq, &drbd_genl_family,
2700                                 NLM_F_MULTI, DRBD_ADM_GET_STATUS);
2701                 if (!dh)
2702                         goto out;
2703
2704                 if (!mdev) {
2705                         /* this is a tconn without a single volume */
2706                         dh->minor = -1U;
2707                         dh->ret_code = NO_ERROR;
2708                         if (nla_put_drbd_cfg_context(skb, tconn->name, VOLUME_UNSPECIFIED))
2709                                 genlmsg_cancel(skb, dh);
2710                         else
2711                                 genlmsg_end(skb, dh);
2712                         goto out;
2713                 }
2714
2715                 D_ASSERT(mdev->vnr == volume);
2716                 D_ASSERT(mdev->tconn == tconn);
2717
2718                 dh->minor = mdev_to_minor(mdev);
2719                 dh->ret_code = NO_ERROR;
2720
2721                 if (nla_put_status_info(skb, mdev, NULL)) {
2722                         genlmsg_cancel(skb, dh);
2723                         goto out;
2724                 }
2725                 genlmsg_end(skb, dh);
2726         }
2727
2728 out:
2729         up_read(&drbd_cfg_rwsem);
2730         /* where to start the next iteration */
2731         cb->args[0] = (long)pos;
2732         cb->args[1] = (pos == tconn) ? volume + 1 : 0;
2733
2734         /* No more tconns/volumes/minors found results in an empty skb.
2735          * Which will terminate the dump. */
2736         return skb->len;
2737 }
2738
2739 /*
2740  * Request status of all resources, or of all volumes within a single resource.
2741  *
2742  * This is a dump, as the answer may not fit in a single reply skb otherwise.
2743  * Which means we cannot use the family->attrbuf or other such members, because
2744  * dump is NOT protected by the genl_lock().  During dump, we only have access
2745  * to the incoming skb, and need to opencode "parsing" of the nlattr payload.
2746  *
2747  * Once things are setup properly, we call into get_one_status().
2748  */
2749 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb)
2750 {
2751         const unsigned hdrlen = GENL_HDRLEN + GENL_MAGIC_FAMILY_HDRSZ;
2752         struct nlattr *nla;
2753         const char *conn_name;
2754         struct drbd_tconn *tconn;
2755
2756         /* Is this a followup call? */
2757         if (cb->args[0]) {
2758                 /* ... of a single resource dump,
2759                  * and the resource iterator has been advanced already? */
2760                 if (cb->args[2] && cb->args[2] != cb->args[0])
2761                         return 0; /* DONE. */
2762                 goto dump;
2763         }
2764
2765         /* First call (from netlink_dump_start).  We need to figure out
2766          * which resource(s) the user wants us to dump. */
2767         nla = nla_find(nlmsg_attrdata(cb->nlh, hdrlen),
2768                         nlmsg_attrlen(cb->nlh, hdrlen),
2769                         DRBD_NLA_CFG_CONTEXT);
2770
2771         /* No explicit context given.  Dump all. */
2772         if (!nla)
2773                 goto dump;
2774         nla = nla_find_nested(nla, __nla_type(T_ctx_conn_name));
2775         /* context given, but no name present? */
2776         if (!nla)
2777                 return -EINVAL;
2778         conn_name = nla_data(nla);
2779         tconn = conn_get_by_name(conn_name);
2780
2781         if (!tconn)
2782                 return -ENODEV;
2783
2784         kref_put(&tconn->kref, &conn_destroy); /* get_one_status() (re)validates tconn by itself */
2785
2786         /* prime iterators, and set "filter" mode mark:
2787          * only dump this tconn. */
2788         cb->args[0] = (long)tconn;
2789         /* cb->args[1] = 0; passed in this way. */
2790         cb->args[2] = (long)tconn;
2791
2792 dump:
2793         return get_one_status(skb, cb);
2794 }
2795
2796 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info)
2797 {
2798         enum drbd_ret_code retcode;
2799         struct timeout_parms tp;
2800         int err;
2801
2802         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2803         if (!adm_ctx.reply_skb)
2804                 return retcode;
2805         if (retcode != NO_ERROR)
2806                 goto out;
2807
2808         tp.timeout_type =
2809                 adm_ctx.mdev->state.pdsk == D_OUTDATED ? UT_PEER_OUTDATED :
2810                 test_bit(USE_DEGR_WFC_T, &adm_ctx.mdev->flags) ? UT_DEGRADED :
2811                 UT_DEFAULT;
2812
2813         err = timeout_parms_to_priv_skb(adm_ctx.reply_skb, &tp);
2814         if (err) {
2815                 nlmsg_free(adm_ctx.reply_skb);
2816                 return err;
2817         }
2818 out:
2819         drbd_adm_finish(info, retcode);
2820         return 0;
2821 }
2822
2823 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info)
2824 {
2825         struct drbd_conf *mdev;
2826         enum drbd_ret_code retcode;
2827
2828         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2829         if (!adm_ctx.reply_skb)
2830                 return retcode;
2831         if (retcode != NO_ERROR)
2832                 goto out;
2833
2834         mdev = adm_ctx.mdev;
2835         if (info->attrs[DRBD_NLA_START_OV_PARMS]) {
2836                 /* resume from last known position, if possible */
2837                 struct start_ov_parms parms =
2838                         { .ov_start_sector = mdev->ov_start_sector };
2839                 int err = start_ov_parms_from_attrs(&parms, info);
2840                 if (err) {
2841                         retcode = ERR_MANDATORY_TAG;
2842                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2843                         goto out;
2844                 }
2845                 /* w_make_ov_request expects position to be aligned */
2846                 mdev->ov_start_sector = parms.ov_start_sector & ~BM_SECT_PER_BIT;
2847         }
2848         /* If there is still bitmap IO pending, e.g. previous resync or verify
2849          * just being finished, wait for it before requesting a new resync. */
2850         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2851         retcode = drbd_request_state(mdev,NS(conn,C_VERIFY_S));
2852 out:
2853         drbd_adm_finish(info, retcode);
2854         return 0;
2855 }
2856
2857
2858 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info)
2859 {
2860         struct drbd_conf *mdev;
2861         enum drbd_ret_code retcode;
2862         int skip_initial_sync = 0;
2863         int err;
2864         struct new_c_uuid_parms args;
2865
2866         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2867         if (!adm_ctx.reply_skb)
2868                 return retcode;
2869         if (retcode != NO_ERROR)
2870                 goto out_nolock;
2871
2872         mdev = adm_ctx.mdev;
2873         memset(&args, 0, sizeof(args));
2874         if (info->attrs[DRBD_NLA_NEW_C_UUID_PARMS]) {
2875                 err = new_c_uuid_parms_from_attrs(&args, info);
2876                 if (err) {
2877                         retcode = ERR_MANDATORY_TAG;
2878                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2879                         goto out_nolock;
2880                 }
2881         }
2882
2883         mutex_lock(mdev->state_mutex); /* Protects us against serialized state changes. */
2884
2885         if (!get_ldev(mdev)) {
2886                 retcode = ERR_NO_DISK;
2887                 goto out;
2888         }
2889
2890         /* this is "skip initial sync", assume to be clean */
2891         if (mdev->state.conn == C_CONNECTED && mdev->tconn->agreed_pro_version >= 90 &&
2892             mdev->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED && args.clear_bm) {
2893                 dev_info(DEV, "Preparing to skip initial sync\n");
2894                 skip_initial_sync = 1;
2895         } else if (mdev->state.conn != C_STANDALONE) {
2896                 retcode = ERR_CONNECTED;
2897                 goto out_dec;
2898         }
2899
2900         drbd_uuid_set(mdev, UI_BITMAP, 0); /* Rotate UI_BITMAP to History 1, etc... */
2901         drbd_uuid_new_current(mdev); /* New current, previous to UI_BITMAP */
2902
2903         if (args.clear_bm) {
2904                 err = drbd_bitmap_io(mdev, &drbd_bmio_clear_n_write,
2905                         "clear_n_write from new_c_uuid", BM_LOCKED_MASK);
2906                 if (err) {
2907                         dev_err(DEV, "Writing bitmap failed with %d\n",err);
2908                         retcode = ERR_IO_MD_DISK;
2909                 }
2910                 if (skip_initial_sync) {
2911                         drbd_send_uuids_skip_initial_sync(mdev);
2912                         _drbd_uuid_set(mdev, UI_BITMAP, 0);
2913                         drbd_print_uuids(mdev, "cleared bitmap UUID");
2914                         spin_lock_irq(&mdev->tconn->req_lock);
2915                         _drbd_set_state(_NS2(mdev, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
2916                                         CS_VERBOSE, NULL);
2917                         spin_unlock_irq(&mdev->tconn->req_lock);
2918                 }
2919         }
2920
2921         drbd_md_sync(mdev);
2922 out_dec:
2923         put_ldev(mdev);
2924 out:
2925         mutex_unlock(mdev->state_mutex);
2926 out_nolock:
2927         drbd_adm_finish(info, retcode);
2928         return 0;
2929 }
2930
2931 static enum drbd_ret_code
2932 drbd_check_conn_name(const char *name)
2933 {
2934         if (!name || !name[0]) {
2935                 drbd_msg_put_info("connection name missing");
2936                 return ERR_MANDATORY_TAG;
2937         }
2938         /* if we want to use these in sysfs/configfs/debugfs some day,
2939          * we must not allow slashes */
2940         if (strchr(name, '/')) {
2941                 drbd_msg_put_info("invalid connection name");
2942                 return ERR_INVALID_REQUEST;
2943         }
2944         return NO_ERROR;
2945 }
2946
2947 int drbd_adm_create_connection(struct sk_buff *skb, struct genl_info *info)
2948 {
2949         enum drbd_ret_code retcode;
2950
2951         retcode = drbd_adm_prepare(skb, info, 0);
2952         if (!adm_ctx.reply_skb)
2953                 return retcode;
2954         if (retcode != NO_ERROR)
2955                 goto out;
2956
2957         retcode = drbd_check_conn_name(adm_ctx.conn_name);
2958         if (retcode != NO_ERROR)
2959                 goto out;
2960
2961         if (adm_ctx.tconn) {
2962                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL) {
2963                         retcode = ERR_INVALID_REQUEST;
2964                         drbd_msg_put_info("connection exists");
2965                 }
2966                 /* else: still NO_ERROR */
2967                 goto out;
2968         }
2969
2970         if (!conn_create(adm_ctx.conn_name))
2971                 retcode = ERR_NOMEM;
2972 out:
2973         drbd_adm_finish(info, retcode);
2974         return 0;
2975 }
2976
2977 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info)
2978 {
2979         struct drbd_genlmsghdr *dh = info->userhdr;
2980         enum drbd_ret_code retcode;
2981
2982         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
2983         if (!adm_ctx.reply_skb)
2984                 return retcode;
2985         if (retcode != NO_ERROR)
2986                 goto out;
2987
2988         /* FIXME drop minor_count parameter, limit to MINORMASK */
2989         if (dh->minor >= minor_count) {
2990                 drbd_msg_put_info("requested minor out of range");
2991                 retcode = ERR_INVALID_REQUEST;
2992                 goto out;
2993         }
2994         if (adm_ctx.volume > DRBD_VOLUME_MAX) {
2995                 drbd_msg_put_info("requested volume id out of range");
2996                 retcode = ERR_INVALID_REQUEST;
2997                 goto out;
2998         }
2999
3000         /* drbd_adm_prepare made sure already
3001          * that mdev->tconn and mdev->vnr match the request. */
3002         if (adm_ctx.mdev) {
3003                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL)
3004                         retcode = ERR_MINOR_EXISTS;
3005                 /* else: still NO_ERROR */
3006                 goto out;
3007         }
3008
3009         down_write(&drbd_cfg_rwsem);
3010         retcode = conn_new_minor(adm_ctx.tconn, dh->minor, adm_ctx.volume);
3011         up_write(&drbd_cfg_rwsem);
3012 out:
3013         drbd_adm_finish(info, retcode);
3014         return 0;
3015 }
3016
3017 static enum drbd_ret_code adm_delete_minor(struct drbd_conf *mdev)
3018 {
3019         if (mdev->state.disk == D_DISKLESS &&
3020             /* no need to be mdev->state.conn == C_STANDALONE &&
3021              * we may want to delete a minor from a live replication group.
3022              */
3023             mdev->state.role == R_SECONDARY) {
3024                 drbd_delete_device(mdev);
3025                 return NO_ERROR;
3026         } else
3027                 return ERR_MINOR_CONFIGURED;
3028 }
3029
3030 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info)
3031 {
3032         enum drbd_ret_code retcode;
3033
3034         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
3035         if (!adm_ctx.reply_skb)
3036                 return retcode;
3037         if (retcode != NO_ERROR)
3038                 goto out;
3039
3040         down_write(&drbd_cfg_rwsem);
3041         retcode = adm_delete_minor(adm_ctx.mdev);
3042         up_write(&drbd_cfg_rwsem);
3043 out:
3044         drbd_adm_finish(info, retcode);
3045         return 0;
3046 }
3047
3048 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info)
3049 {
3050         enum drbd_ret_code retcode;
3051         enum drbd_state_rv rv;
3052         struct drbd_conf *mdev;
3053         unsigned i;
3054
3055         retcode = drbd_adm_prepare(skb, info, 0);
3056         if (!adm_ctx.reply_skb)
3057                 return retcode;
3058         if (retcode != NO_ERROR)
3059                 goto out;
3060
3061         if (!adm_ctx.tconn) {
3062                 retcode = ERR_CONN_NOT_KNOWN;
3063                 goto out;
3064         }
3065
3066         down_read(&drbd_cfg_rwsem);
3067         /* demote */
3068         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3069                 retcode = drbd_set_role(mdev, R_SECONDARY, 0);
3070                 if (retcode < SS_SUCCESS) {
3071                         drbd_msg_put_info("failed to demote");
3072                         goto out_unlock;
3073                 }
3074         }
3075
3076         /* disconnect */
3077         rv = conn_try_disconnect(adm_ctx.tconn, 0);
3078         if (rv < SS_SUCCESS) {
3079                 retcode = rv; /* enum type mismatch! */
3080                 drbd_msg_put_info("failed to disconnect");
3081                 goto out_unlock;
3082         }
3083
3084         /* Make sure the network threads have actually stopped,
3085          * state handling only does drbd_thread_stop_nowait(). */
3086         drbd_thread_stop(&adm_ctx.tconn->receiver);
3087
3088         /* detach */
3089         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3090                 rv = adm_detach(mdev);
3091                 if (rv < SS_SUCCESS) {
3092                         retcode = rv; /* enum type mismatch! */
3093                         drbd_msg_put_info("failed to detach");
3094                         goto out_unlock;
3095                 }
3096         }
3097         up_read(&drbd_cfg_rwsem);
3098
3099         /* delete volumes */
3100         down_write(&drbd_cfg_rwsem);
3101         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3102                 retcode = adm_delete_minor(mdev);
3103                 if (retcode != NO_ERROR) {
3104                         /* "can not happen" */
3105                         drbd_msg_put_info("failed to delete volume");
3106                         up_write(&drbd_cfg_rwsem);
3107                         goto out;
3108                 }
3109         }
3110
3111         /* delete connection */
3112         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3113                 drbd_thread_stop(&adm_ctx.tconn->worker);
3114                 list_del(&adm_ctx.tconn->all_tconn);
3115                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3116
3117                 retcode = NO_ERROR;
3118         } else {
3119                 /* "can not happen" */
3120                 retcode = ERR_CONN_IN_USE;
3121                 drbd_msg_put_info("failed to delete connection");
3122         }
3123
3124         up_write(&drbd_cfg_rwsem);
3125         goto out;
3126 out_unlock:
3127         up_read(&drbd_cfg_rwsem);
3128 out:
3129         drbd_adm_finish(info, retcode);
3130         return 0;
3131 }
3132
3133 int drbd_adm_delete_connection(struct sk_buff *skb, struct genl_info *info)
3134 {
3135         enum drbd_ret_code retcode;
3136
3137         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
3138         if (!adm_ctx.reply_skb)
3139                 return retcode;
3140         if (retcode != NO_ERROR)
3141                 goto out;
3142
3143         down_write(&drbd_cfg_rwsem);
3144         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3145                 list_del(&adm_ctx.tconn->all_tconn);
3146                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3147
3148                 retcode = NO_ERROR;
3149         } else {
3150                 retcode = ERR_CONN_IN_USE;
3151         }
3152         up_write(&drbd_cfg_rwsem);
3153
3154 out:
3155         drbd_adm_finish(info, retcode);
3156         return 0;
3157 }
3158
3159 void drbd_bcast_event(struct drbd_conf *mdev, const struct sib_info *sib)
3160 {
3161         static atomic_t drbd_genl_seq = ATOMIC_INIT(2); /* two. */
3162         struct sk_buff *msg;
3163         struct drbd_genlmsghdr *d_out;
3164         unsigned seq;
3165         int err = -ENOMEM;
3166
3167         seq = atomic_inc_return(&drbd_genl_seq);
3168         msg = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
3169         if (!msg)
3170                 goto failed;
3171
3172         err = -EMSGSIZE;
3173         d_out = genlmsg_put(msg, 0, seq, &drbd_genl_family, 0, DRBD_EVENT);
3174         if (!d_out) /* cannot happen, but anyways. */
3175                 goto nla_put_failure;
3176         d_out->minor = mdev_to_minor(mdev);
3177         d_out->ret_code = 0;
3178
3179         if (nla_put_status_info(msg, mdev, sib))
3180                 goto nla_put_failure;
3181         genlmsg_end(msg, d_out);
3182         err = drbd_genl_multicast_events(msg, 0);
3183         /* msg has been consumed or freed in netlink_broadcast() */
3184         if (err && err != -ESRCH)
3185                 goto failed;
3186
3187         return;
3188
3189 nla_put_failure:
3190         nlmsg_free(msg);
3191 failed:
3192         dev_err(DEV, "Error %d while broadcasting event. "
3193                         "Event seq:%u sib_reason:%u\n",
3194                         err, seq, sib->sib_reason);
3195 }